From 3f703c0d5315c1f2bde96191647360f79cd08a08 Mon Sep 17 00:00:00 2001 From: Ruben Bridgewater Date: Sat, 22 Nov 2025 15:44:32 +0900 Subject: [PATCH 1/5] Reapply "Script to migrate code" This reverts commit 93dbd4f2be4291ae3acfa4561f74e28d1b5f8281. --- scripts/codemods/chai-to-assert.js | 734 +++++++++++++++++++++++++++++ 1 file changed, 734 insertions(+) create mode 100644 scripts/codemods/chai-to-assert.js diff --git a/scripts/codemods/chai-to-assert.js b/scripts/codemods/chai-to-assert.js new file mode 100644 index 00000000000..99f7cf291f2 --- /dev/null +++ b/scripts/codemods/chai-to-assert.js @@ -0,0 +1,734 @@ +'use strict' + +/** + * Chai → node:assert/strict codemod + * - Rewrites common expect/assert patterns to Node's assert + * - Rewrites sinon-chai to sinon.assert + * - Inserts `const assert = require('node:assert/strict')` when needed + * - Skips Cypress browser e2e directories + * + * Usage: + * node scripts/codemods/chai-to-assert.js + */ + +const fs = require('fs') +const path = require('path') +const glob = require('glob') + +const ROOT = path.resolve(__dirname, '..', '..') + +/** @param {string} file */ +function read (file) { + return fs.readFileSync(file, 'utf8') +} + +/** @param {string} file @param {string} content */ +function write (file, content) { + fs.writeFileSync(file, content) +} + +/** @param {string} code */ +function ensureAssertImport (code) { + const hasStrict = /\bconst\s+assert\s*=\s*require\(['"](node:)?assert\/strict['"]\)/.test(code) + const hasAssert = /\bconst\s+assert\s*=\s*require\(['"](node:)?assert['"]\)/.test(code) + const hasESMStrict = /^\s*import\s+(?:\*\s+as\s+)?assert\s+from\s*['"](node:)?assert\/strict['"]/m.test(code) || + /^\s*import\s*\{\s*strict\s+as\s+assert\s*\}\s*from\s*['"](node:)?assert['"]/m.test(code) + const hasESMAssert = /^\s*import\s+(?:\*\s+as\s+)?assert\s+from\s*['"](node:)?assert['"]/m.test(code) + if (hasStrict || hasAssert || hasESMStrict || hasESMAssert) return code + + const useStrictMatch = code.match(/^(\s*'use strict'\s*;?\s*\n)/) + if (useStrictMatch) { + const idx = useStrictMatch[0].length + return code.slice(0, idx) + "const assert = require('node:assert/strict')\n\n" + code.slice(idx) + } + return "const assert = require('node:assert/strict')\n\n" + code +} + +// Import utilities +function getTopImportBlockRange (code) { + let idx = 0 + const useStrict = code.match(/^(\s*'use strict'\s*;?\s*\n)/) + if (useStrict) idx = useStrict[0].length + + const reFirst = /^(?:\s*(?:import\b|(?:const|let|var)\s+[^=]+?=\s*require\(['"][^'"]+['"]\))\s*(?:\n|$))/m + const m = code.slice(idx).match(reFirst) + if (!m || typeof m.index !== 'number') return null + const start = idx + m.index + + const lines = code.slice(start).split('\n') + let consumed = 0 + for (const line of lines) { + const isImport = /^\s*import\b/.test(line) + const isRequire = /^\s*(?:const|let|var)\s+[^=]+?=\s*require\(['"][^'"]+['"]\)\s*;?\s*$/.test(line) + const isBlank = /^\s*$/.test(line) + const isComment = /^\s*\/{2}/.test(line) + if (!(isImport || isRequire || isBlank || isComment)) break + consumed++ + } + const end = start + lines.slice(0, consumed).join('\n').length + return [start, end] +} + +function extractImportSpec (line) { + let m = line.match(/\brequire\(\s*['"]([^'"]+)['"]\s*\)/) + if (m) return m[1] + m = line.match(/\bfrom\s*['"]([^'"]+)['"]/) + if (m) return m[1] + m = line.match(/^\s*import\s*['"]([^'"]+)['"]/) + if (m) return m[1] + return null +} + +function isRelativeSpec (spec) { + return spec.startsWith('.') || spec.startsWith('/') +} + +function isNodeSpec (spec, builtinSet) { + if (spec.startsWith('node:')) return true + return builtinSet.has(spec) +} + +function rebuildImportsSortedByType (code) { + const range = getTopImportBlockRange(code) + if (!range) return code + const [start, end] = range + const block = code.slice(start, end) + const lines = block.split('\n') + const { builtinModules } = require('module') + const allBuiltins = new Set(builtinModules.concat(builtinModules.map(m => m.replace(/^node:/, '')))) + + const node = [] + const npm = [] + const rel = [] + for (const line of lines) { + const spec = extractImportSpec(line) + if (!spec) continue + if (isRelativeSpec(spec)) rel.push({ spec, line }) + else if (isNodeSpec(spec, allBuiltins)) node.push({ spec, line }) + else npm.push({ spec, line }) + } + node.sort((a, b) => a.spec.localeCompare(b.spec)) + npm.sort((a, b) => a.spec.localeCompare(b.spec)) + rel.sort((a, b) => a.spec.localeCompare(b.spec)) + + const pieces = [] + if (node.length) pieces.push(node.map(x => x.line).join('\n')) + if (npm.length) pieces.push(npm.map(x => x.line).join('\n')) + if (rel.length) pieces.push(rel.map(x => x.line).join('\n')) + const rebuilt = pieces.join('\n\n') + return code.slice(0, start) + rebuilt + code.slice(end) +} + +// Mocha helpers +function findMochaImports (code) { + const lines = code.split('\n') + const idxs = [] + for (let i = 0; i < lines.length; i++) { + const l = lines[i] + if (/^\s*(?:const|let|var)\s*\{[^}]*\}\s*=\s*require\(\s*['"]mocha['"]\s*\)\s*;?\s*$/.test(l)) idxs.push(i) + else if (/^\s*import\s*\{[^}]*\}\s*from\s*['"]mocha['"]\s*;?\s*$/.test(l)) idxs.push(i) + } + return idxs +} + +function getMochaSpecifiersFromLine (line) { + const m = line.match(/\{\s*([^}]*)\s*\}/) + if (!m) return [] + return m[1].split(',').map(s => s.trim()).filter(Boolean) +} + +function setMochaSpecifiersOnLine (line, names) { + const sorted = Array.from(new Set(names)).sort() + const replaced = line.replace(/\{\s*([^}]*)\s*\}/, '{ __PLACEHOLDER__ }') + return replaced.replace('__PLACEHOLDER__', sorted.join(', ')) +} + +function ensureMochaImportsIfNeeded (code) { + const idxs = findMochaImports(code) + if (idxs.length !== 1) return code + const usedNames = ['describe', 'context', 'it', 'specify', 'before', 'beforeEach', 'after', 'afterEach'] + const used = new Set() + for (const n of usedNames) { + const re = new RegExp('\\s' + n + '(?:\\.(?:only|skip))?\\(') + if (re.test(code)) used.add(n) + } + if (!used.size) return code + const lines = code.split('\n') + const i = idxs[0] + const current = getMochaSpecifiersFromLine(lines[i]) + const merged = Array.from(new Set([...current, ...used])) + lines[i] = setMochaSpecifiersOnLine(lines[i], merged) + return lines.join('\n') +} + +function removeChaiImportsWhenReplaced (code, { dropAssert, dropExpect }) { + let out = code + if (dropAssert) { + out = out.replace(/^\s*const\s+assert\s*=\s*require\(\s*['"]chai['"]\s*\)\.assert\s*;?\s*\n/mg, '') + out = out.replace(/^\s*const\s+{\s+assert\s+}\s*=\s*require\(\s*['"]chai['"]\s*\)\s*;?\s*\n/mg, '') + out = out.replace(/^\s*import\s*\{\s*assert\s*\}\s*from\s*['"]chai['"]\s*;?\s*\n/mg, '') + } + if (dropExpect) { + out = out.replace(/^\s*const\s+expect\s*=\s*require\(\s*['"]chai['"]\s*\)\.expect\s*;?\s*\n/mg, '') + out = out.replace(/^\s*const\s+{\s+expect\s+}\s*=\s*require\(\s*['"]chai['"]\s*\)\s*;?\s*\n/mg, '') + out = out.replace(/^\s*import\s*\{\s*expect\s*\}\s*from\s*['"]chai['"]\s*;?\s*\n/mg, '') + } + // const { expect, assert } = require('chai') + out = out.replace(/^(\s*const\s*\{)([^}]*)\}(\s*=\s*require\(\s*['"]chai['"]\s*\)\s*;?\s*\n)/mg, (m, a, inner, b) => { + const names = inner.split(',').map(s => s.trim()).filter(Boolean) + const filtered = names.filter(n => !(dropAssert && n === 'assert') && !(dropExpect && n === 'expect')) + if (!filtered.length) return '' + if (filtered.length === names.length) return m + return a + ' ' + filtered.join(', ') + ' }' + b + }) + // import { expect, assert } from 'chai' + out = out.replace(/^(\s*import\s*\{)([^}]*)\}(\s*from\s*['"]chai['"]\s*;?\s*\n)/mg, (m, a, inner, b) => { + const names = inner.split(',').map(s => s.trim()).filter(Boolean) + const filtered = names.filter(n => !(dropAssert && n === 'assert') && !(dropExpect && n === 'expect')) + if (!filtered.length) return '' + if (filtered.length === names.length) return m + return a + ' ' + filtered.join(', ') + ' }' + b + }) + return out +} + +function posixify (p) { + return p.replace(/\\/g, '/') +} + +function ensureAssertObjectContainsImport (code, file) { + if (!/\bassertObjectContains\(/.test(code)) return code + // If already imported somewhere from a helpers module, skip + const already = /^(?:\s*(?:const|let|var)\s*\{[^}]*\bassertObjectContains\b[^}]*\}\s*=\s*require\([^)]*helpers[^)]*\)|\s*import\s*\{[^}]*\bassertObjectContains\b[^}]*\}\s*from\s*['"][^'"]*helpers[^'"]*['"])\s*;?\s*$/m + if (already.test(code)) return code + + const helpersDir = path.join(ROOT, 'integration-tests', 'helpers') + const helpersIndexJs = path.join(helpersDir, 'index.js') + const helpersIndexTs = path.join(helpersDir, 'index.ts') + if (!fs.existsSync(helpersDir) && !fs.existsSync(helpersIndexJs) && !fs.existsSync(helpersIndexTs)) return code + + const fromDir = path.dirname(file) + let rel = posixify(path.relative(fromDir, helpersDir)) + if (!rel.startsWith('.')) rel = './' + rel + + const importLine = `const { assertObjectContains } = require('${rel}')\n` + const range = getTopImportBlockRange(code) + if (range) { + const [start, end] = range + const block = code.slice(start, end) + let newBlock = block + if (!block.endsWith('\n')) newBlock += '\n' + newBlock += importLine + return code.slice(0, start) + newBlock + code.slice(end) + } + const useStrictMatch = code.match(/^(\s*'use strict'\s*;?\s*\n)/) + if (useStrictMatch) { + const idx = useStrictMatch[0].length + return code.slice(0, idx) + importLine + code.slice(idx) + } + return importLine + code +} + +/** + * Escape a JS expression to a regex at runtime. + * Produces: new RegExp((EXPR).replace(/[.*+?^${}()|[\]\\]/g, '\\$&')) + */ +function wrapAsEscapedRegex (expr) { + return 'new RegExp((' + expr + ')' + + ".replace(/[.*+?^${}()|[\\]\\]/g, '\\$&'))" +} + +// Build a safe accessor using dot notation for identifier keys, or bracket for others. +// keyLiteral includes quotes (e.g., 'name' or "name"). For non-literals, fallback to bracket. +function buildAccessor (objExpr, keyLiteral) { + const k = (keyLiteral || '').trim() + if ((k.startsWith('"') && k.endsWith('"')) || (k.startsWith("'") && k.endsWith("'"))) { + const key = k.slice(1, -1) + const isIdentifier = /^[A-Za-z_][A-Za-z0-9_]*$/.test(key) + return isIdentifier ? `${objExpr}.${key}` : `${objExpr}[${k}]` + } + return `${objExpr}[${k}]` +} + +// Detect files using expect from Playwright and skip transforming them +function usesPlaywrightExpect (code) { + // import { expect } from '@playwright/test' + if (/^\s*import\s*\{[^}]*\bexpect\b[^}]*\}\s*from\s*["']@playwright\/test["']\s*;?\s*$/m.test(code)) return true + // const { expect } = require('@playwright/test') or let/var + if (/^\s*(?:const|let|var)\s*\{[^}]*\bexpect\b[^}]*\}\s*=\s*require\(\s*["']@playwright\/test["']\s*\)\s*;?\s*$/m.test(code)) return true + return false +} + +function hasChaiImport (code) { + if (/\brequire\(\s*["']chai["']\s*\)/.test(code)) return true + if (/\bfrom\s*["']chai["']/.test(code)) return true + if (/^\s*import\s*["']chai["']\s*;?\s*$/m.test(code)) return true + return false +} + +function isCiVisibilityPath (file) { + const p = file.replace(/\\/g, '/') + return p.includes('/integration-tests/ci-visibility/') +} + +function pruneUnusedChaiNamedImports (code) { + // Build a version without any chai import/require lines to check identifier usage + const body = code + .replace(/^\s*(?:const|let|var)\s+chai\s*=\s*require\(\s*["']chai["']\s*\)\s*;?\s*\n/mg, '') + .replace(/^\s*import\s+chai\s+from\s*["']chai["']\s*;?\s*\n/mg, '') + .replace(/^\s*import\s+chai\s*,\s*\{[^}]*\}\s*from\s*["']chai["']\s*;?\s*\n/mg, '') + .replace(/^\s*(?:const|let|var)\s*\{[^}]*\}\s*=\s*require\(\s*["']chai["']\s*\)\s*;?\s*\n/mg, '') + .replace(/^\s*import\s*\{[^}]*\}\s*from\s*["']chai["']\s*;?\s*\n/mg, '') + + function filterTokens (inner, isImport) { + const tokens = inner.split(',').map(s => s.trim()).filter(Boolean) + const kept = [] + for (const tok of tokens) { + let local = tok + if (isImport) { + const m = tok.match(/^(\w+)\s+as\s+(\w+)$/) + if (m) local = m[2] + } else { + const m = tok.match(/^(\w+)\s*:\s*(\w+)$/) + if (m) local = m[2] + } + if (new RegExp('\\b' + local + '\\b').test(body)) kept.push(tok) + } + return kept + } + + // Require destructuring + code = code.replace(/^(\s*(?:const|let|var)\s*\{)([^}]*)\}(\s*=\s*require\(\s*["']chai["']\s*\)\s*;?\s*\n)/mg, (m, a, inner, b) => { + const kept = filterTokens(inner, false) + if (!kept.length) return '' + return a + ' ' + kept.join(', ') + ' }' + b + }) + // Import destructuring + code = code.replace(/^(\s*import\s*\{)([^}]*)\}(\s*from\s*["']chai["']\s*;?\s*\n)/mg, (m, a, inner, b) => { + const kept = filterTokens(inner, true) + if (!kept.length) return '' + return a + ' ' + kept.join(', ') + ' }' + b + }) + + return code +} + +/** @param {string} code */ +function transform (code, file) { + let out = code + + // Skip files that import expect from Playwright + if (usesPlaywrightExpect(code)) return code + // Skip ci-visibility files unless they use chai + if (isCiVisibilityPath(file) && !hasChaiImport(code)) return code + + // Track assert usage/import state before transformation + const beforeNonChaiAssertCount = (code.match(/(^|[^.\w$])assert\./g) || []).length + const hasNodeAssertImportBefore = /\bconst\s+assert\s*=\s*require\(['"](node:)?assert(?:\/strict)?['"]\)/.test(code) || + /^\s*import\s+(?:\*\s+as\s+)?assert\s+from\s*['"](node:)?assert(?:\/strict)?['"]/m.test(code) || + /^\s*import\s*\{\s*strict\s+as\s+assert\s*\}\s*from\s*['"](node:)?assert['"]/m.test(code) + const hasAssertVariableBefore = /\b(?:const|let|var)\s+assert\s*=/.test(code) || /\bconst\s*\{[^}]*\bassert\b[^}]*\}\s*=\s*require\(\s*['"]chai['"]\s*\)/.test(code) || /\bimport\s*\{[^}]*\bassert\b[^}]*\}\s*from\s*['"]chai['"]/.test(code) + + // 0) Do not alter chai/sinon-chai imports or chai.use lines here; we only add assert when used. + + // 1) expect(...).to.be.fulfilled → await p (handled only when 'await expect(...)') + out = out.replace(/await\s+expect\(([^)]+)\)\.to\.be\.fulfilled/g, 'await $1') + + // 2) await expect(p).to.be.rejected[With(...)] + out = out.replace(/await\s+expect\(([^)]+)\)\.to\.be\.rejectedWith\(([^)]+)\)/g, + 'await assert.rejects($1, $2)') + out = out.replace(/await\s+expect\(([^)]+)\)\.to\.be\.rejected(?!With)/g, + 'await assert.rejects($1)') + + // 3) NaN + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.be\.NaN/g, 'assert.strictEqual($1, NaN)') + + // 6) Basic equality + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.deep\.(?:equal|eql)\(([^)]+)\)/g, 'assert.deepStrictEqual($1, $2)') + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.be\.deep\.(?:equal|eql)\(([^)]+)\)/g, 'assert.deepStrictEqual($1, $2)') + // eq/eql aliases + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.eq\(([^)]+)\)/g, 'assert.strictEqual($1, $2)') + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.eql\(([^)]+)\)/g, 'assert.deepStrictEqual($1, $2)') + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.(?:be\.)?(?:equal|equals)\(([^)]+)\)/g, 'assert.strictEqual($1, $2)') + // function-call aware equal/equals (balanced one-level parentheses) + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.not\.(?:be\.)?(?:equal|equals)\(([^)]+)\)/g, 'assert.notStrictEqual($1, $2)') + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.(?:to\.not|not\.to)\.(?:be\.)?(?:equal|equals)\(([^)]+)\)/g, 'assert.notStrictEqual($1, $2)') + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.(?:to\.not|not\.to)\.deep\.(?:equal|eql)\(([^)]+)\)/g, 'assert.notDeepStrictEqual($1, $2)') + // toBe / not.toBe (used in some chai setups too) + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.toBe\(([^)]+)\)/g, 'assert.strictEqual($1, $2)') + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.not\.toBe\(([^)]+)\)/g, 'assert.notStrictEqual($1, $2)') + // Jest toEqual / not.toEqual + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.toEqual\(([^)]+)\)/g, 'assert.deepStrictEqual($1, $2)') + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.not\.toEqual\(([^)]+)\)/g, 'assert.notDeepStrictEqual($1, $2)') + + // 4) Truthiness & types + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.be\.true/g, 'assert.strictEqual($1, true)') + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.be\.false/g, 'assert.strictEqual($1, false)') + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.be\.ok/g, 'assert.ok($1)') + // .to.not.undefined (property form) + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.not\.undefined\b/g, 'assert.notStrictEqual($1, undefined)') + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.be\.undefined/g, 'assert.strictEqual($1, undefined)') + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.be\.null/g, 'assert.strictEqual($1, null)') + // negatives: to.not / not.to + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.(?:to\.not|not\.to)\.be\.undefined/g, 'assert.notStrictEqual($1, undefined)') + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.(?:to\.not|not\.to)\.be\.null/g, 'assert.notStrictEqual($1, null)') + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.exist/g, 'assert.ok($1 != null)') + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.not\.exist/g, 'assert.ok($1 == null)') + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.be\.(?:an|a)\(['"]array['"]\)/g, 'assert.ok(Array.isArray($1))') + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.be\.(?:an|a)\(['"]object['"]\)/g, "assert.ok(typeof $1 === 'object' && $1 !== null)") + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.be\.(?:an|a)\(['"]string['"]\)/g, "assert.strictEqual(typeof $1, 'string')") + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.be\.(?:an|a)\(['"]number['"]\)/g, "assert.strictEqual(typeof $1, 'number')") + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.be\.(?:an|a)\(['"]boolean['"]\)/g, "assert.strictEqual(typeof $1, 'boolean')") + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.be\.(?:an|a)\(['"]bigint['"]\)/g, "assert.strictEqual(typeof $1, 'bigint')") + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.be\.(?:an|a)\(['"]function['"]\)/g, "assert.strictEqual(typeof $1, 'function')") + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.be\.(?:an|a)\(['"]array['"]\)\.and\.have\.length\(([^)]+)\)/g, + '(assert.ok(Array.isArray($1)), assert.strictEqual($1.length, $2))') + // instanceOf (Array special case first) + out = out.replace(/expect\(([^)]+)\)\.to\.be\.(?:instanceOf|instanceof)\(\s*Array\s*\)/g, 'assert.ok(Array.isArray($1))') + out = out.replace(/expect\(([^)]+)\)\.to\.not\.be\.(?:instanceOf|instanceof)\(\s*Array\s*\)/g, 'assert.ok(!Array.isArray($1))') + out = out.replace(/expect\(([^)]+)\)\.to\.be\.(?:instanceOf|instanceof)\(([^)]+)\)/g, 'assert.ok($1 instanceof $2)') + out = out.replace(/expect\(([^)]+)\)\.to\.not\.be\.(?:instanceOf|instanceof)\(([^)]+)\)/g, 'assert.ok(!($1 instanceof $2))') + + // 8) Regex + out = out.replace(/expect\(([^)]+)\)\.to\.match\(([^)]+)\)/g, 'assert.match($1, $2)') + out = out.replace(/expect\(([^)]+)\)\.to\.not\.match\(([^)]+)\)/g, 'assert.doesNotMatch($1, $2)') + // function-call aware regex + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.match\(([^)]+)\)/g, 'assert.match($1, $2)') + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.not\.match\(([^)]+)\)/g, 'assert.doesNotMatch($1, $2)') + + // 8.1) contain/include string literal or .contain alias → assert.match(haystack, escaped(needle)) + out = out.replace(/expect\(([^)]+)\)\.to\.(?:contain|include)\(\s*(['"][^'"]+['"])\s*\)/g, + (m, haystack, lit) => `assert.match(${haystack}, ${wrapAsEscapedRegex(lit)})`) + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.(?:contain|include)\(\s*(['"][^'"]+['"])\s*\)/g, + (m, haystack, lit) => `assert.match(${haystack}, ${wrapAsEscapedRegex(lit)})`) + out = out.replace(/expect\(([^)]+)\)\.to\.contain\(\s*(['"][^'"]+['"])\s*\)/g, + (m, haystack, lit) => `assert.match(${haystack}, ${wrapAsEscapedRegex(lit)})`) + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.contain\(\s*(['"][^'"]+['"])\s*\)/g, + (m, haystack, lit) => `assert.match(${haystack}, ${wrapAsEscapedRegex(lit)})`) + + // 8.2) include/contain with object literal → assertObjectContains (allowed everywhere) + out = out.replace(/expect\(([^)]+)\)\.to\.(?:contain|include)\(\s*(\{[^}]*\})\s*\)/g, 'assertObjectContains($1, $2)') + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.(?:contain|include)\(\s*(\{[^}]*\})\s*\)/g, 'assertObjectContains($1, $2)') + // 8.21) include(objectLiteral) without chain + out = out.replace(/expect\(([^)]+)\)\.to\.include\(\s*(\{[^}]*\})\s*\)/g, 'assertObjectContains($1, $2)') + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.include\(\s*(\{[^}]*\})\s*\)/g, 'assertObjectContains($1, $2)') + // 8.3) deep.include with object literal → assertObjectContains + out = out.replace(/expect\(([^)]+)\)\.to\.deep\.include\(\s*(\{[^}]*\})\s*\)/g, 'assertObjectContains($1, $2)') + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.deep\.include\(\s*(\{[^}]*\})\s*\)/g, 'assertObjectContains($1, $2)') + // Skip generic include/contain for safety otherwise + + // 10) property + // expect(obj).to.have.property('k').that.deep.equal(v) → deepStrictEqual(accessor, v) + out = out.replace(/expect\(([^)]+)\)\.to\.have\.property\((['"][^'"]+['"])\)\.that\.deep\.equal\(([^)]+)\)/g, + (m, obj, key, val) => `assert.deepStrictEqual(${buildAccessor(obj, key)}, ${val})`) + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.have\.property\((['"][^'"]+['"])\)\.that\.deep\.equal\(([^)]+)\)/g, + (m, obj, key, val) => `assert.deepStrictEqual(${buildAccessor(obj, key)}, ${val})`) + // expect(obj).to.have.property('k').that.equal(v) → strictEqual(accessor, v) + out = out.replace(/expect\(([^)]+)\)\.to\.have\.property\((['"][^'"]+['"])\)\.that\.equal\(([^)]+)\)/g, + (m, obj, key, val) => `assert.strictEqual(${buildAccessor(obj, key)}, ${val})`) + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.have\.property\((['"][^'"]+['"])\)\.that\.equal\(([^)]+)\)/g, + (m, obj, key, val) => `assert.strictEqual(${buildAccessor(obj, key)}, ${val})`) + // expect(obj).to.have.property('k').that.match(/re/) → match(accessor, /re/) + out = out.replace(/expect\(([^)]+)\)\.to\.have\.property\((['"][^'"]+['"])\)\.that\.match\(([^)]+)\)/g, + (m, obj, key, re) => `assert.match(${buildAccessor(obj, key)}, ${re})`) + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.have\.property\((['"][^'"]+['"])\)\.that\.match\(([^)]+)\)/g, + (m, obj, key, re) => `assert.match(${buildAccessor(obj, key)}, ${re})`) + // // Handle leftover chains after hasOwn conversion + // out = out.replace(/assert\.ok\(Object\.hasOwn\(([^,]+),\s*(['"][^'"]+['"])\)\)\.that\.deep\.equal\(([^)]+)\)/g, + // (m, obj, key, val) => `assert.deepStrictEqual(${buildAccessor(obj, key)}, ${val})`) + // out = out.replace(/assert\.ok\(Object\.hasOwn\(([^,]+),\s*(['"][^'"]+['"])\)\)\.that\.equal\(([^)]+)\)/g, + // (m, obj, key, val) => `assert.strictEqual(${buildAccessor(obj, key)}, ${val})`) + // out = out.replace(/assert\.ok\(Object\.hasOwn\(([^,]+),\s*(['"][^'"]+['"])\)\)\.that\.match\(([^)]+)\)/g, + // (m, obj, key, re) => `assert.match(${buildAccessor(obj, key)}, ${re})`) + // expect(obj).to.have.property('k', v) → assert.strictEqual(accessor, v) + out = out.replace(/expect\(([^)]+)\)\.to\.have\.property\((['"][^'"]+['"]),\s*([^)]+)\)/g, + (m, obj, key, val) => `assert.strictEqual(${buildAccessor(obj, key)}, ${val})`) + // variable key: expect(obj).to.have.property(KEY, v) + out = out.replace(/expect\(([^)]+)\)\.to\.have\.property\(([^,'")]+),\s*([^)]+)\)/g, 'assert.strictEqual($1[$2], $3)') + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.have\.property\(([^,'")]+),\s*([^)]+)\)/g, 'assert.strictEqual($1[$2], $3)') + // expect(obj).to.have.property('k') → assert.ok(Object.hasOwn(obj, 'k')) (preserve key quoting rules) + out = out.replace(/expect\(([^)]+)\)\.to\.have\.property\(([^,)]+)\)/g, + 'assert.ok(Object.hasOwn($1, $2))') + // variable key presence: expect(obj).to.have.property(KEY) + out = out.replace(/expect\(([^)]+)\)\.to\.have\.property\(([^,)]+)\)/g, 'assert.ok(Object.hasOwn($1, $2))') + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.have\.property\(([^,)]+)\)/g, 'assert.ok(Object.hasOwn($1, $2))') + // not.have.property literal keys + out = out.replace(/expect\(([^)]+)\)\.to\.not\.have\.property\(([^,)]+)\)/g, + 'assert.ok(!Object.hasOwn($1, $2))') + out = out.replace(/expect\(([^)]+)\)\.not\.to\.have\.property\(([^,)]+)\)/g, + 'assert.ok(!Object.hasOwn($1, $2))') + // ownProperty alias (literal keys) + out = out.replace(/expect\(([^)]+)\)\.to\.have\.ownProperty\(([^,)]+)\)/g, + 'assert.ok(Object.hasOwn($1, $2))') + out = out.replace(/expect\(([^)]+)\)\.to\.not\.have\.ownProperty\(([^,)]+)\)/g, + 'assert.ok(!Object.hasOwn($1, $2))') + out = out.replace(/expect\(([^)]+)\)\.not\.to\.have\.ownProperty\(([^,)]+)\)/g, + 'assert.ok(!Object.hasOwn($1, $2))') + + // 11) lengthOf + out = out.replace(/expect\(([^)]+)\)\.to\.(?:have\.)?lengthOf\(([^)]+)\)/g, + 'assert.strictEqual($1.length, $2)') + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.(?:have\.)?lengthOf\(([^)]+)\)/g, + 'assert.strictEqual($1.length, $2)') + // length alias (chai): .length(n) + out = out.replace(/expect\(([^)]+)\)\.to\.(?:have\.)?length\(([^)]+)\)/g, + 'assert.strictEqual($1.length, $2)') + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.(?:have\.)?length\(([^)]+)\)/g, + 'assert.strictEqual($1.length, $2)') + // have.length.at.least/at.most + out = out.replace(/expect\(([^)]+)\)\.to\.have\.length\.at\.least\(([^)]+)\)/g, 'assert.ok($1.length >= $2)') + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.have\.length\.at\.least\(([^)]+)\)/g, 'assert.ok($1.length >= $2)') + out = out.replace(/expect\(([^)]+)\)\.to\.have\.length\.at\.most\(([^)]+)\)/g, 'assert.ok($1.length <= $2)') + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.have\.length\.at\.most\(([^)]+)\)/g, 'assert.ok($1.length <= $2)') + // have.lengthOf.at.least/at.most + out = out.replace(/expect\(([^)]+)\)\.to\.have\.lengthOf\.at\.least\(([^)]+)\)/g, 'assert.ok($1.length >= $2)') + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.have\.lengthOf\.at\.least\(([^)]+)\)/g, 'assert.ok($1.length >= $2)') + out = out.replace(/expect\(([^)]+)\)\.to\.have\.lengthOf\.at\.most\(([^)]+)\)/g, 'assert.ok($1.length <= $2)') + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.have\.lengthOf\.at\.most\(([^)]+)\)/g, 'assert.ok($1.length <= $2)') + // property(...).that.length(Of)?(n) + out = out.replace(/expect\(([^)]+)\)\.to\.have\.property\((['"][^'"]+['"])\)\.that\.(?:have\.)?length(?:Of)?\(([^)]+)\)/g, + (m, obj, key, val) => `assert.strictEqual(${buildAccessor(obj, key)}.length, ${val})`) + + // 12) Comparisons + out = out.replace(/expect\(([^)]+)\)\.to\.be\.above\(([^)]+)\)/g, 'assert.ok($1 > $2)') + out = out.replace(/expect\(([^)]+)\)\.to\.be\.at\.least\(([^)]+)\)/g, 'assert.ok($1 >= $2)') + out = out.replace(/expect\(([^)]+)\)\.to\.be\.below\(([^)]+)\)/g, 'assert.ok($1 < $2)') + out = out.replace(/expect\(([^)]+)\)\.to\.be\.at\.most\(([^)]+)\)/g, 'assert.ok($1 <= $2)') + out = out.replace(/expect\(([^)]+)\)\.to\.be\.(?:lessThan|lt)\(([^)]+)\)/g, 'assert.ok($1 < $2)') + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.be\.(?:lessThan|lt)\(([^)]+)\)/g, 'assert.ok($1 < $2)') + out = out.replace(/expect\(([^)]+)\)\.to\.be\.(?:greaterThan|gt)\(([^)]+)\)/g, 'assert.ok($1 > $2)') + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.be\.(?:greaterThan|gt)\(([^)]+)\)/g, 'assert.ok($1 > $2)') + out = out.replace(/expect\(([^)]+)\)\.to\.be\.(?:gte)\(([^)]+)\)/g, 'assert.ok($1 >= $2)') + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.be\.(?:gte)\(([^)]+)\)/g, 'assert.ok($1 >= $2)') + out = out.replace(/expect\(([^)]+)\)\.to\.be\.(?:lte)\(([^)]+)\)/g, 'assert.ok($1 <= $2)') + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.be\.(?:lte)\(([^)]+)\)/g, 'assert.ok($1 <= $2)') + out = out.replace(/expect\(([^)]+)\)\.to\.be\.closeTo\(([^,]+),\s*([^)]+)\)/g, + 'assert.ok(Math.abs(($1) - ($2)) <= ($3))') + + // 12) Throws + out = out.replace(/expect\(([^)]+)\)\.to\.throw\(\s*\)/g, 'assert.throws($1)') + out = out.replace(/expect\(([^)]+)\)\.to\.throw\(([^)]+)\)/g, 'assert.throws($1, $2)') + out = out.replace(/expect\(([^)]+)\)\.to\.not\.throw\(\s*\)/g, 'assert.doesNotThrow($1)') + // function-call aware subject for throw + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.throw\(\s*\)/g, 'assert.throws($1)') + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.throw\(([^)]+)\)/g, 'assert.throws($1, $2)') + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.not\.throw\(\s*\)/g, 'assert.doesNotThrow($1)') + + // Bare hasOwnProperty truthiness: expect(obj.hasOwnProperty('k')) → assert.ok(obj.hasOwnProperty('k')) + out = out.replace(/expect\(([^)]+?\.hasOwnProperty\([^)]*\))\)\s*(?!\.)/g, 'assert.ok($1)') + + // 13) Leave custom chai profile assertions as-is + + // 14) sinon-chai → sinon.assert + out = out.replace(/expect\(([^)]+)\)\.to\.have\.been\.calledOnce\b/g, 'sinon.assert.calledOnce($1)') + out = out.replace(/expect\(([^)]+)\)\.to\.be\.calledOnce\b/g, 'sinon.assert.calledOnce($1)') + out = out.replace(/expect\(([^)]+)\)\.to\.have\.been\.calledTwice\b/g, 'sinon.assert.calledTwice($1)') + out = out.replace(/expect\(([^)]+)\)\.to\.have\.been\.calledThrice\b/g, 'sinon.assert.calledThrice($1)') + out = out.replace(/expect\(([^)]+)\)\.to\.have\.been\.called\b/g, 'sinon.assert.called($1)') + out = out.replace(/expect\(([^)]+)\)\.to\.have\.been\.notCalled\b/g, 'sinon.assert.notCalled($1)') + out = out.replace(/expect\(([^)]+)\)\.(?:to\.not|not\.to)\.have\.been\.called\b/g, 'sinon.assert.notCalled($1)') + // also support: to.be.called + out = out.replace(/expect\(([^)]+)\)\.to\.be\.called\b/g, 'sinon.assert.called($1)') + out = out.replace(/expect\(([^)]+)\)\.to\.have\.been\.calledWithExactly\(([^)]+)\)/g, + 'sinon.assert.calledWithExactly($1, $2)') + out = out.replace(/expect\(([^)]+)\)\.to\.have\.been\.calledWithMatch\(([^)]+)\)/g, + 'sinon.assert.calledWithMatch($1, $2)') + out = out.replace(/expect\(([^)]+)\)\.to\.have\.been\.calledWith\(([^)]+)\)/g, + 'sinon.assert.calledWith($1, $2)') + out = out.replace(/expect\(([^)]+)\)\.to\.have\.been\.calledOnceWithExactly\(\s*\)/g, + 'sinon.assert.calledOnce($1)') + // calledOnceWith(Exactly) with args + out = out.replace(/expect\(([^)]+)\)\.to\.have\.been\.calledOnceWithExactly\(([^)]*)\)/g, + 'sinon.assert.calledOnceWithExactly($1, $2)') + out = out.replace(/expect\(([^)]+)\)\.to\.have\.been\.calledOnceWith\(([^)]*)\)/g, + 'sinon.assert.calledOnceWithExactly($1, $2)') + // negative calledWith variants + out = out.replace(/expect\(([^)]+)\)\.to\.not\.have\.been\.calledWith\(([^)]+)\)/g, 'sinon.assert.neverCalledWith($1, $2)') + out = out.replace(/expect\(([^)]+)\)\.not\.to\.have\.been\.calledWith\(([^)]+)\)/g, 'sinon.assert.neverCalledWith($1, $2)') + out = out.replace(/expect\(([^)]+)\)\.to\.not\.have\.been\.calledWithMatch\(([^)]+)\)/g, 'sinon.assert.neverCalledWithMatch($1, $2)') + out = out.replace(/expect\(([^)]+)\)\.not\.to\.have\.been\.calledWithMatch\(([^)]+)\)/g, 'sinon.assert.neverCalledWithMatch($1, $2)') + + // 15) chai.assert style minimal mapping + out = out.replace(/chai\.assert\.deepEqual\(([^)]+)\)/g, 'assert.deepStrictEqual($1)') + out = out.replace(/chai\.assert\.equal\(([^)]+)\)/g, 'assert.strictEqual($1)') + + // 16) Insert Node assert only when safe. Otherwise, skip touching this file. + const afterNonChaiAssertCount = (out.match(/(^|[^.\w$])assert\./g) || []).length + const didReplaceAssert = afterNonChaiAssertCount > beforeNonChaiAssertCount + const hasNodeAssertImportAfter = /\bconst\s+assert\s*=\s*require\(['"](node:)?assert(?:\/strict)?['"]\)/.test(out) || + /^\s*import\s+(?:\*\s+as\s+)?assert\s+from\s*['"](node:)?assert(?:\/strict)?['"]/m.test(out) || + /^\s*import\s*\{\s*strict\s+as\s+assert\s*\}\s*from\s*['"](node:)?assert['"]/m.test(out) + const needsNodeAssertImport = /(^|[^.\w$])assert\./.test(out) && !hasNodeAssertImportAfter + + let insertedNodeAssert = false + if (needsNodeAssertImport) { + if (hasAssertVariableBefore && !hasNodeAssertImportBefore) { + if (beforeNonChaiAssertCount > 0 && !didReplaceAssert) { + return code + } + if (beforeNonChaiAssertCount > 0) { + return code + } + } + out = ensureAssertImport(out) + insertedNodeAssert = true + } + + // 17) deepEqualWithMockValues direct assertion mapping (keep plugin wiring lines) + out = out.replace(/expect\(([^)]+)\)\.to\.deep(?:\.deep)?EqualWithMockValues\(([^)]+)\)/g, 'deepEqualWithMockValues($1, $2)') + + // 18) Fix concatenations caused by missing newline after assert import + out = out.replace(/(const\s+assert\s*=\s*require\(['"]node:assert\/strict['"]\))([^\n])/g, '$1\n$2') + + // 19) Prefer strict assert if both imported; remove non-strict when strict present + if (/require\(['"]node:assert\/strict['"]\)/.test(out)) { + out = out.replace(/^\s*const\s+assert\s*=\s*require\(['"]node:assert['"]\)\s*;?\s*\n/mg, '') + } + + // 19.5) Multi-line tolerant variants for common patterns (allow whitespace/newlines around dots) + // Await rejected + out = out.replace(/await\s+expect\(((?:[^()]|\([^()]*\))+?)\)\s*\.\s*to\s*\.\s*be\s*\.\s*rejectedWith\(([^)]+)\)/gs, + 'await assert.rejects($1, $2)') + out = out.replace(/await\s+expect\(((?:[^()]|\([^()]*\))+?)\)\s*\.\s*to\s*\.\s*be\s*\.\s*rejected(?!With)/gs, + 'await assert.rejects($1)') + // Equality + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\s*\.\s*to\s*\.\s*deep\s*\.\s*(?:equal|eql)\(([^)]+)\)/gs, 'assert.deepStrictEqual($1, $2)') + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\s*\.\s*to\s*\.\s*(?:be\s*\.\s*)?(?:equal|equals)\(([^)]+)\)/gs, 'assert.strictEqual($1, $2)') + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\s*\.\s*(?:to\s*\.\s*not|not\s*\.\s*to)\s*\.\s*(?:be\s*\.\s*)?(?:equal|equals)\(([^)]+)\)/gs, 'assert.notStrictEqual($1, $2)') + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\s*\.\s*(?:to\s*\.\s*not|not\s*\.\s*to)\s*\.\s*deep\s*\.\s*(?:equal|eql)\(([^)]+)\)/gs, 'assert.notDeepStrictEqual($1, $2)') + // Truthiness + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\s*\.\s*to\s*\.\s*be\s*\.\s*true\b/gs, 'assert.strictEqual($1, true)') + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\s*\.\s*to\s*\.\s*be\s*\.\s*false\b/gs, 'assert.strictEqual($1, false)') + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\s*\.\s*to\s*\.\s*be\s*\.\s*ok\b/gs, 'assert.ok($1)') + // Existence and types + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\s*\.\s*to\s*\.\s*exist\b/gs, 'assert.ok($1 != null)') + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\s*\.\s*to\s*\.\s*not\s*\.\s*exist\b/gs, 'assert.ok($1 == null)') + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\s*\.\s*to\s*\.\s*be\s*\.\s*(?:an|a)\(\s*['"]array['"]\s*\)/gs, 'assert.ok(Array.isArray($1))') + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\s*\.\s*to\s*\.\s*be\s*\.\s*(?:an|a)\(\s*['"]object['"]\s*\)/gs, "(assert.strictEqual(typeof $1, 'object'), assert.notStrictEqual($1, null))") + // Regex matching + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\s*\.\s*to\s*\.\s*match\(([^)]+)\)/gs, 'assert.match($1, $2)') + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\s*\.\s*to\s*\.\s*not\s*\.\s*match\(([^)]+)\)/gs, 'assert.doesNotMatch($1, $2)') + // Include/contain object literal + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\s*\.\s*to\s*\.\s*(?:contain|include)\(\s*(\{[^}]*\})\s*\)/gs, 'assertObjectContains($1, $2)') + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\s*\.\s*to\s*\.\s*deep\s*\.\s*include\(\s*(\{[^}]*\})\s*\)/gs, 'assertObjectContains($1, $2)') + // Throws + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\s*\.\s*to\s*\.\s*throw\(\s*\)/gs, 'assert.throws($1)') + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\s*\.\s*to\s*\.\s*throw\(([^)]+)\)/gs, 'assert.throws($1, $2)') + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\s*\.\s*to\s*\.\s*not\s*\.\s*throw\(\s*\)/gs, 'assert.doesNotThrow($1)') + + // 20) On full replacement, remove chai assert import and chai expect if unused + const expectStillUsed = /(?:^|[^\w$])expect\s*(\(|\.)/.test(out) + const chaiAssertCallsRemain = /\bchai\.assert\./.test(out) + if (!expectStillUsed || !chaiAssertCallsRemain) { + out = removeChaiImportsWhenReplaced(out, { dropAssert: !chaiAssertCallsRemain, dropExpect: !expectStillUsed }) + } + + // 21) If we introduced Node assert calls, fix mocha imports and sort imports by type + if (didReplaceAssert && (insertedNodeAssert || hasNodeAssertImportBefore)) { + out = ensureMochaImportsIfNeeded(out) + out = rebuildImportsSortedByType(out) + } + + // 22) If we inserted node:assert but no assert usages remain, remove the import we added + if (insertedNodeAssert && !/\bassert\./.test(out)) { + out = out.replace(/^[\t ]*const\s+assert\s*=\s*require\(['"]node:assert\/strict['"]\)\s*\n?\n?/m, '') + } + + // 23) Remove unused default chai import/require if chai.* is no longer used + { + // Build a version without any chai import/require lines to check for real usage + const outNoChaiImports = out + .replace(/^\s*(?:const|let|var)\s+chai\s*=\s*require\(\s*['"]chai['"]\s*\)\s*;?\s*\n/mg, '') + .replace(/^\s*import\s+chai\s+from\s*['"]chai['"]\s*;?\s*\n/mg, '') + .replace(/^\s*import\s+chai\s*,\s*\{([^}]*)\}\s*from\s*(['"]chai['"])\s*;?\s*\n/mg, + (m, names, from) => { + const inner = names.split(',').map(s => s.trim()).filter(Boolean) + if (!inner.length) return '' + return `import { ${inner.join(', ')} } from ${from}\n` + }) + .replace(/^\s*import\s*\{\s*\}\s*from\s*['"]chai['"]\s*;?\s*\n/mg, '') + .replace(/^\s*(?:const|let|var)\s*\{\s*\}\s*=\s*require\(\s*['"]chai['"]\s*\)\s*;?\s*\n/mg, '') + const chaiUsed = /\bchai\s*(?:[.[(])/.test(outNoChaiImports) + if (!chaiUsed) { + // Drop const/let/var chai = require('chai') + out = out.replace(/^\s*(?:const|let|var)\s+chai\s*=\s*require\(\s*['"]chai['"]\s*\)\s*;?\s*\n/mg, '') + // Drop import chai from 'chai' + out = out.replace(/^\s*import\s+chai\s+from\s*['"]chai['"]\s*;?\s*\n/mg, '') + // Convert 'import chai, { names } from' → 'import { names } from' + out = out.replace(/^\s*import\s+chai\s*,\s*\{([^}]*)\}\s*from\s*(['"]chai['"])\s*;?\s*\n/mg, + (m, names, from) => { + const inner = names.split(',').map(s => s.trim()).filter(Boolean) + if (!inner.length) return '' + return `import { ${inner.join(', ')} } from ${from}\n` + }) + // Remove empty named-only chai imports if any + out = out.replace(/^\s*import\s*\{\s*\}\s*from\s*['"]chai['"]\s*;?\s*\n/mg, '') + // Remove empty named-only chai requires if any + out = out.replace(/^\s*(?:const|let|var)\s*\{\s*\}\s*=\s*require\(\s*['"]chai['"]\s*\)\s*;?\s*\n/mg, '') + } + } + + // 24) Prune unused named chai imports/requires (destructuring) + out = pruneUnusedChaiNamedImports(out) + + return out +} + +function isBrowserCypress (file) { + const p = file.replace(/\\/g, '/') + return p.includes('/integration-tests/cypress/e2e/') || p.endsWith('.cy.js') || p.endsWith('.cy.ts') +} + +function main () { + const patterns = [ + 'packages/**/test/**/*.js', + 'integration-tests/**/*.js' + ] + const files = patterns.flatMap((pat) => glob.sync(path.join(ROOT, pat), { nodir: true })) + let changed = 0 + const reverted = [] + for (const file of files) { + if (isBrowserCypress(file)) continue + const before = read(file) + let after = transform(before, file) + + // If assertObjectContains is used, inject proper import path + if (/\bassertObjectContains\(/.test(after)) { + after = ensureAssertObjectContainsImport(after, file) + } + + if (after !== before) { + // Attempt to repair any broken destructured chai imports due to edge spacing + after = after.replace(/^(\s*(?:const|let|var)\s*\{[^}]*)(=\s*require\(\s*["']chai["']\s*\))/mg, + (m, head, tail) => head.trimEnd() + ' } ' + tail) + after = after.replace(/^(\s*import\s*\{[^}]*)(\s*from\s*["']chai["'][^\n]*\n)/mg, + (m, head, tail) => head.trimEnd() + ' } ' + tail) + + // Syntax validation: revert on failure; skip for ESM + const isLikelyESM = /^\s*(?:import|export)\s/m.test(after) + if (!isLikelyESM) { + try { + // eslint-disable-next-line no-new-func + Function(after) + } catch (e) { + reverted.push(file) + continue + } + } + write(file, after) + changed++ + } + } + // eslint-disable-next-line no-console + console.log('chai-to-assert: updated', changed, 'files') + if (reverted.length) { + // eslint-disable-next-line no-console + console.log('chai-to-assert: reverted due to syntax errors in:') + // eslint-disable-next-line no-console + for (const f of reverted) console.log(' - ' + f) + } +} + +if (require.main === module) { + main() +} From f2f668cfe6240959e15ec5ab98d9262c28044867 Mon Sep 17 00:00:00 2001 From: Ruben Bridgewater Date: Thu, 27 Nov 2025 01:12:21 +0900 Subject: [PATCH 2/5] fixup! update script --- scripts/codemods/chai-to-assert.js | 124 +++++++++++++++++++++++++++-- 1 file changed, 119 insertions(+), 5 deletions(-) diff --git a/scripts/codemods/chai-to-assert.js b/scripts/codemods/chai-to-assert.js index 99f7cf291f2..bf4861f66c9 100644 --- a/scripts/codemods/chai-to-assert.js +++ b/scripts/codemods/chai-to-assert.js @@ -238,6 +238,63 @@ function wrapAsEscapedRegex (expr) { ".replace(/[.*+?^${}()|[\\]\\]/g, '\\$&'))" } +// -------- Helpers to format long assert lines (wrap args if >120 chars) -------- +function splitTopLevelArgs (s) { + const out = [] + let buf = '' + let p = 0; let b = 0; let c = 0 + let inS = false; let inD = false; let inT = false + for (let i = 0; i < s.length; i++) { + const ch = s[i] + const prev = i > 0 ? s[i - 1] : '' + if (inS) { buf += ch; if (ch === '\'' && prev !== '\\') inS = false; continue } + if (inD) { buf += ch; if (ch === '"' && prev !== '\\') inD = false; continue } + if (inT) { + buf += ch + if (ch === '`' && prev !== '\\') inT = false + else if (ch === '{' && prev === '$') c++ + else if (ch === '}' && c > 0) c-- + continue + } + if (ch === '\'') { inS = true; buf += ch; continue } + if (ch === '"') { inD = true; buf += ch; continue } + if (ch === '`') { inT = true; buf += ch; continue } + if (ch === '(') { p++; buf += ch; continue } + if (ch === ')') { p--; buf += ch; continue } + if (ch === '[') { b++; buf += ch; continue } + if (ch === ']') { b--; buf += ch; continue } + if (ch === '{') { c++; buf += ch; continue } + if (ch === '}') { c--; buf += ch; continue } + if (ch === ',' && p === 0 && b === 0 && c === 0) { out.push(buf.trim()); buf = ''; continue } + buf += ch + } + if (buf.trim()) out.push(buf.trim()) + return out +} + +function formatLongAssertCalls (code) { + const lines = code.split('\n') + // keep indexable form for potential future use + const out = [] + for (const line of lines) { + if (line.length <= 120) { out.push(line); continue } + const m = line.match(/^(\s*)(assert\.\w+)\((.*)\)\s*;?\s*$/) + if (!m) { out.push(line); continue } + const indent = m[1] || '' + const head = m[2] + const inner = m[3] || '' + const args = splitTopLevelArgs(inner) + if (args.length === 0) { out.push(line); continue } + if (args.length === 1) { + out.push(`${indent}${head}(\n${indent} ${args[0]}\n${indent})`) + } else { + const formatted = args.map(a => `${indent} ${a}`).join(',\n') + out.push(`${indent}${head}(\n${formatted}\n${indent})`) + } + } + return out.join('\n') +} + // Build a safe accessor using dot notation for identifier keys, or bracket for others. // keyLiteral includes quotes (e.g., 'name' or "name"). For non-literals, fallback to bracket. function buildAccessor (objExpr, keyLiteral) { @@ -266,11 +323,50 @@ function hasChaiImport (code) { return false } -function isCiVisibilityPath (file) { - const p = file.replace(/\\/g, '/') - return p.includes('/integration-tests/ci-visibility/') +// Skip files that import/require an 'expect' symbol from a non-chai module +function usesNonChaiExpect (code) { + // import { expect } from 'x' + const reNamed = /^\s*import\s*\{([^}]*\bexpect\b[^}]*)\}\s*from\s*['"]([^'"]+)['"]\s*;?/mg + let m + while ((m = reNamed.exec(code)) !== null) { + const mod = m[2] + if (!/^chai(?:\/|$)?/.test(mod)) return true + } + // import expect from 'x' + const reDef = /^\s*import\s+(\w+)\s+from\s*['"]([^'"]+)['"]\s*;?/mg + while ((m = reDef.exec(code)) !== null) { + const name = m[1]; const mod = m[2] + if (name === 'expect' && !/^chai(?:\/|$)?/.test(mod)) return true + } + // import * as expect from 'x' + const reNs = /^\s*import\s+\*\s+as\s+(\w+)\s+from\s*['"]([^'"]+)['"]\s*;?/mg + while ((m = reNs.exec(code)) !== null) { + const name = m[1]; const mod = m[2] + if (name === 'expect' && !/^chai(?:\/|$)?/.test(mod)) return true + } + // const { expect } = require('x') + const reReqNamed = /^\s*(?:const|let|var)\s*\{([^}]*\bexpect\b[^}]*)\}\s*=\s*require\(\s*['"]([^'"]+)['"]\s*\)\s*;?/mg + while ((m = reReqNamed.exec(code)) !== null) { + const mod = m[2] + if (!/^chai(?:\/|$)?/.test(mod)) return true + } + // const expect = require('x') + const reReqDef = /^\s*(?:const|let|var)\s*(\w+)\s*=\s*require\(\s*['"]([^'"]+)['"]\s*\)\s*;?/mg + while ((m = reReqDef.exec(code)) !== null) { + const name = m[1]; const mod = m[2] + if (name === 'expect' && !/^chai(?:\/|$)?/.test(mod)) return true + } + // const expect = require('x').something (non-chai) + const reReqProp = /^\s*(?:const|let|var)\s*(\w+)\s*=\s*require\(\s*['"]([^'"]+)['"]\s*\)\.\s*([A-Za-z_$][\w$]*)/mg + while ((m = reReqProp.exec(code)) !== null) { + const name = m[1]; const mod = m[2]; const prop = m[3] + if (name === 'expect' && !(/^chai(?:\/|$)?/.test(mod) && prop === 'expect')) return true + } + return false } +// isCiVisibilityPath removed – not needed after chai-only guard + function pruneUnusedChaiNamedImports (code) { // Build a version without any chai import/require lines to check identifier usage const body = code @@ -319,8 +415,12 @@ function transform (code, file) { // Skip files that import expect from Playwright if (usesPlaywrightExpect(code)) return code - // Skip ci-visibility files unless they use chai - if (isCiVisibilityPath(file) && !hasChaiImport(code)) return code + // Skip files that import/require an 'expect' symbol from a non-chai module + if (usesNonChaiExpect(code)) return code + // Only process files that import/require chai, OR that contain assert.* helpers we can convert, OR expect() usage + const hasAssertHelpers = /\bassert\.(?:exists|notExists|hasAllKeys|isTrue|isFalse|isUndefined|isDefined|isNull|isNotNull|isArray|isObject|isString|isNumber|isBoolean|isBigInt|isFunction|isBelow|isAbove|isAtLeast|isAtMost|instanceOf|notInstanceOf|istanceOf|lengthOf|notLengthOf|property|notProperty|propertyVal|notPropertyVal|include|notInclude|deepInclude|match|notMatch|sameMembers|sameDeepMembers|isEmpty|isNotEmpty)\(/.test(code) + const hasExpect = /(?:^|[^\w$])expect\s*(\(|\.)/.test(code) + if (!hasChaiImport(code) && !hasAssertHelpers && !hasExpect) return code // Track assert usage/import state before transformation const beforeNonChaiAssertCount = (code.match(/(^|[^.\w$])assert\./g) || []).length @@ -671,6 +771,8 @@ function transform (code, file) { // 24) Prune unused named chai imports/requires (destructuring) out = pruneUnusedChaiNamedImports(out) + // Format long assert lines to multiple lines when > 120 chars + out = formatLongAssertCalls(out) return out } @@ -687,9 +789,15 @@ function main () { const files = patterns.flatMap((pat) => glob.sync(path.join(ROOT, pat), { nodir: true })) let changed = 0 const reverted = [] + const ignored = [] for (const file of files) { if (isBrowserCypress(file)) continue const before = read(file) + // Early skip if the file imports an 'expect' symbol from a non-chai module + if (usesNonChaiExpect(before)) { + ignored.push(file) + continue + } let after = transform(before, file) // If assertObjectContains is used, inject proper import path @@ -721,6 +829,12 @@ function main () { } // eslint-disable-next-line no-console console.log('chai-to-assert: updated', changed, 'files') + if (ignored.length) { + // eslint-disable-next-line no-console + console.log('chai-to-assert: ignored files due to non-chai expect imports:') + // eslint-disable-next-line no-console + for (const f of ignored) console.log(' - ' + f) + } if (reverted.length) { // eslint-disable-next-line no-console console.log('chai-to-assert: reverted due to syntax errors in:') From 28bec712b3704690dce63615665462e2a675e97d Mon Sep 17 00:00:00 2001 From: Ruben Bridgewater Date: Sun, 23 Nov 2025 01:23:53 +0900 Subject: [PATCH 3/5] test: rewrite lots of chai calls to use Node.js assert instead --- integration-tests/aiguard/index.spec.js | 8 +- .../appsec/data-collection.spec.js | 6 +- integration-tests/appsec/graphql.spec.js | 30 +- integration-tests/appsec/iast-esbuild.spec.js | 11 +- .../iast-stack-traces-with-sourcemaps.spec.js | 24 +- .../appsec/iast.esm-security-controls.spec.js | 28 +- integration-tests/appsec/iast.esm.spec.js | 12 +- integration-tests/appsec/index.spec.js | 17 +- integration-tests/appsec/multer.spec.js | 21 +- .../appsec/response-headers.spec.js | 8 +- .../appsec/standalone-asm.spec.js | 104 +- .../appsec/trace-tagging.spec.js | 12 +- .../support/steps.js | 8 +- .../automatic-log-submission-test.js | 7 +- .../parallel-test-hit-breakpoint-1.js | 8 +- .../parallel-test-hit-breakpoint-2.js | 5 +- .../test-hit-breakpoint.js | 10 +- .../test-not-hit-breakpoint.js | 8 +- .../features-selenium/support/steps.js | 10 +- .../ci-visibility/git-cache.spec.js | 61 +- .../jest-bad-import-test-pass-2.js | 4 +- .../jest-bad-import-test-pass.js | 4 +- .../jest-bad-import-test.js | 4 +- .../jest-bad-import-test-pass-2.js | 4 +- .../jest-bad-import-test-pass.js | 4 +- .../jest-bad-import/jest-bad-import-test.js | 4 +- .../jest-fast-check/jest-no-fast-check.js | 4 +- .../ci-visibility/jest-flaky/flaky-fails.js | 4 +- .../ci-visibility/jest-flaky/flaky-passes.js | 6 +- .../non-dependency-mock-test-2.js | 12 +- .../non-dependency-mock-test-3.js | 4 +- .../non-dependency-mock-test-4.js | 4 +- .../non-dependency-mock-test-5.js | 4 +- .../non-dependency-mock-test-6.js | 4 +- .../non-dependency-mock-test.js | 4 +- .../jest-plugin-tests/jest-inject-globals.js | 4 +- .../jest-plugin-tests/jest-test.js | 34 +- .../ci-visibility/jest/failing-test.js | 7 +- .../ci-visibility/jest/mocked-test.js | 4 +- .../mocha-plugin-tests/active-span-hooks.js | 13 +- .../mocha-plugin-tests/async-fail.js | 5 +- .../mocha-plugin-tests/async-pass.js | 5 +- .../mocha-plugin-tests/done-fail-badly.js | 5 +- .../mocha-plugin-tests/done-fail.js | 5 +- .../mocha-plugin-tests/done-pass.js | 5 +- .../mocha-plugin-tests/failing.js | 5 +- .../mocha-plugin-tests/hook-async-error.js | 15 +- .../mocha-plugin-tests/hook-sync-error.js | 5 +- .../mocha-plugin-tests/parameterized.js | 6 +- .../mocha-plugin-tests/passing.js | 11 +- .../mocha-plugin-tests/promise-fail.js | 5 +- .../mocha-plugin-tests/promise-pass.js | 5 +- .../mocha-plugin-tests/retries.js | 7 +- .../mocha-plugin-tests/skip-describe.js | 7 +- .../mocha-plugin-tests/skipping.js | 9 +- .../suite-level-fail-after-each.js | 7 +- .../suite-level-fail-skip-describe.js | 11 +- .../suite-level-fail-test.js | 11 +- .../mocha-plugin-tests/suite-level-pass.js | 9 +- .../ci-visibility/office-addin-mock/test.js | 6 +- .../sharding-test/sharding-test-1.js | 5 +- .../sharding-test/sharding-test-2.js | 5 +- .../sharding-test/sharding-test-3.js | 5 +- .../sharding-test/sharding-test-4.js | 5 +- .../sharding-test/sharding-test-5.js | 5 +- .../subproject/subproject-test.js | 9 +- .../ci-visibility/test-api-manual.spec.js | 9 +- .../test-custom-tags/custom-tags.js | 7 +- .../mocha-parameterized.js | 6 +- .../occasionally-failing-test.js | 5 +- .../skipped-and-todo-test.js | 7 +- .../test-parameterized.js | 5 +- .../test-early-flake-detection/test.js | 5 +- .../weird-test-names.js | 7 +- .../eventually-passing-test.js | 5 +- .../test-impacted-test/test-impacted-1.js | 7 +- .../test-impacted-test/test-impacted-2.js | 7 +- .../test-management/test-attempt-to-fix-1.js | 11 +- .../test-management/test-attempt-to-fix-2.js | 5 +- .../test-management/test-disabled-1.js | 5 +- .../test-management/test-disabled-2.js | 5 +- .../test-management/test-quarantine-1.js | 7 +- .../test-management/test-quarantine-2.js | 7 +- .../test-nested-hooks/test-nested-hooks.js | 7 +- .../test-optimization-startup.spec.js | 19 +- .../support/steps.js | 8 +- .../test-parsing-error/parsing-error-2.js | 4 +- .../test-parsing-error/parsing-error.js | 4 +- .../test-total-code-coverage/test-run.js | 6 +- .../test-total-code-coverage/test-skipped.js | 6 +- .../test/ci-visibility-test-2.js | 6 +- .../ci-visibility/test/ci-visibility-test.js | 6 +- .../test/efd-parallel/ci-visibility-test-2.js | 4 +- .../test/efd-parallel/ci-visibility-test-3.js | 4 +- .../test/efd-parallel/ci-visibility-test-4.js | 4 +- .../test/efd-parallel/ci-visibility-test.js | 4 +- .../ci-visibility/test/fail-test.js | 5 +- .../ci-visibility/test/selenium-test.js | 8 +- .../unskippable-test/test-to-run.js | 5 +- .../unskippable-test/test-to-skip.js | 5 +- .../unskippable-test/test-unskippable.js | 7 +- integration-tests/cucumber/cucumber.spec.js | 709 +++++------ integration-tests/cypress/cypress.spec.js | 587 +++++---- integration-tests/debugger/redact.spec.js | 2 +- .../snapshot-global-sample-rate.spec.js | 8 +- .../debugger/snapshot-pruning.spec.js | 4 +- integration-tests/debugger/snapshot.spec.js | 40 +- .../debugger/source-map-support.spec.js | 8 +- integration-tests/debugger/template.spec.js | 4 +- integration-tests/debugger/unreffed.spec.js | 2 +- integration-tests/helpers/fake-agent.js | 2 + integration-tests/jest/jest.spec.js | 1118 ++++++++-------- integration-tests/mocha/mocha.spec.js | 1125 ++++++++--------- .../openfeature-exposure-events.spec.js | 77 +- integration-tests/opentelemetry-logs.spec.js | 2 +- integration-tests/opentelemetry.spec.js | 7 +- integration-tests/pino.spec.js | 3 +- integration-tests/remote_config.spec.js | 8 +- integration-tests/selenium/selenium.spec.js | 17 +- integration-tests/startup.spec.js | 51 +- integration-tests/vitest/vitest.spec.js | 393 +++--- .../test/body-parser.spec.js | 3 +- .../test/express-mongo-sanitize.spec.js | 6 +- .../test/express.spec.js | 3 +- .../test/helpers/check-require-cache.spec.js | 3 +- .../test/helpers/router-helper.spec.js | 7 +- .../test/multer.spec.js | 2 +- .../test/mysql2.spec.js | 102 +- .../test/passport-http.spec.js | 2 +- .../test/passport-local.spec.js | 2 +- .../datadog-instrumentations/test/pg.spec.js | 18 +- .../test/integration-test/client.spec.js | 7 +- .../test/integration-test/client.spec.js | 8 +- .../test/integration-test/client.spec.js | 8 +- .../test/integration-test/client.spec.js | 7 +- .../datadog-plugin-apollo/test/index.spec.js | 5 +- .../test/integration-test/client.spec.js | 8 +- .../datadog-plugin-aws-sdk/test/s3.spec.js | 3 +- .../datadog-plugin-aws-sdk/test/sqs.spec.js | 12 +- .../test/integration-test/client.spec.js | 8 +- .../test/integration-test/client.spec.js | 62 +- .../eventhubs-test/eventhubs.spec.js | 7 +- .../integration-test/http-test/client.spec.js | 11 +- .../servicebus-test/servicebus.spec.js | 7 +- .../test/integration-test/client.spec.js | 126 +- .../test/integration-test/client.spec.js | 8 +- .../test/index.spec.js | 104 +- .../test/scrub-cmd-params.spec.js | 16 +- .../test/integration-test/client.spec.js | 8 +- .../test/integration-test/client.spec.js | 8 +- .../test/index.spec.js | 5 +- .../test/integration-test/client.spec.js | 8 +- .../test/integration-test/client.spec.js | 8 +- .../test/index.spec.js | 22 +- .../test/integration-test/client.spec.js | 8 +- .../test/code_origin.spec.js | 9 +- .../test/integration-test/client.spec.js | 21 +- .../test/code_origin.spec.js | 13 +- .../test/integration-test/client.spec.js | 15 +- .../test/integration-test/client.spec.js | 8 +- .../test/index.spec.js | 5 +- .../test/integration-test/client.spec.js | 8 +- .../test/index.spec.js | 5 +- .../test/integration-test/client.spec.js | 8 +- .../test/esm-test/esm.spec.js | 11 +- .../datadog-plugin-graphql/test/index.spec.js | 8 +- .../test/integration-test/client.spec.js | 8 +- .../test/integration-test/client.spec.js | 7 +- .../datadog-plugin-grpc/test/server.spec.js | 6 +- .../datadog-plugin-hapi/test/index.spec.js | 3 +- .../test/integration-test/client.spec.js | 12 +- .../test/integration-test/client.spec.js | 13 +- .../test/integration-test/client.spec.js | 8 +- .../test/integration-test/client.spec.js | 8 +- .../datadog-plugin-jest/test/util.spec.js | 8 +- .../test/integration-test/client.spec.js | 8 +- .../datadog-plugin-koa/test/index.spec.js | 10 +- .../test/integration-test/client.spec.js | 8 +- .../test/integration-test/client.spec.js | 8 +- .../test/integration-test/client.spec.js | 8 +- .../test/integration-test/client.spec.js | 8 +- .../test/integration-test/client.spec.js | 8 +- .../test/integration-test/client.spec.js | 8 +- .../test/integration-test/client.spec.js | 8 +- .../test/integration-test/client.spec.js | 12 +- .../test/integration-test/client.spec.js | 8 +- .../test/integration-test/client.spec.js | 8 +- .../test/integration-test/client.spec.js | 8 +- .../datadog-plugin-net/test/index.spec.js | 8 +- .../test/integration-test/client.spec.js | 8 +- .../datadog-plugin-openai/test/index.spec.js | 51 +- .../test/integration-test/client.spec.js | 8 +- .../test/index.spec.js | 12 +- .../test/integration-test/client.spec.js | 8 +- .../test/integration-test/client.spec.js | 8 +- .../test/integration-test/client.spec.js | 7 +- .../datadog-plugin-pino/test/index.spec.js | 86 +- .../datadog-plugin-prisma/test/index.spec.js | 6 +- .../test/integration-test/client.spec.js | 8 +- .../test/integration-test/client.spec.js | 8 +- .../datadog-plugin-rhea/test/index.spec.js | 90 +- .../test/integration-test/client.spec.js | 8 +- .../test/integration-test/client.spec.js | 8 +- .../datadog-plugin-sharedb/test/index.spec.js | 9 +- .../test/integration-test/client.spec.js | 8 +- .../test/integration-test/client.spec.js | 7 +- .../datadog-plugin-winston/test/index.spec.js | 80 +- packages/datadog-plugin-ws/test/index.spec.js | 4 +- packages/datadog-shimmer/test/shimmer.spec.js | 26 +- packages/dd-trace/test/aiguard/index.spec.js | 5 +- .../test/appsec/api_security_sampler.spec.js | 86 +- ...cker-fingerprinting.express.plugin.spec.js | 16 +- ...cker-fingerprinting.fastify.plugin.spec.js | 16 +- ...ingerprinting.passport-http.plugin.spec.js | 16 +- ...ngerprinting.passport-local.plugin.spec.js | 16 +- .../appsec/attacker-fingerprinting.spec.js | 20 +- .../dd-trace/test/appsec/blocking.spec.js | 4 +- .../hardcoded-password-analyzer.spec.js | 19 +- .../hardcoded-secret-analyzer.spec.js | 33 +- ...p-injection-analyzer.ldapjs.plugin.spec.js | 3 +- ...l-injection-analyzer.mysql2.plugin.spec.js | 7 +- .../analyzers/sql-injection-analyzer.spec.js | 2 +- .../unvalidated-redirect-analyzer.spec.js | 16 +- .../analyzers/vulnerability-analyzer.spec.js | 2 +- .../iast/code_injection.integration.spec.js | 13 +- .../test/appsec/iast/iast-context.spec.js | 10 +- .../test/appsec/iast/iast-plugin.spec.js | 10 +- .../dd-trace/test/appsec/iast/index.spec.js | 13 +- .../overhead-controller.integration.spec.js | 9 +- .../appsec/iast/overhead-controller.spec.js | 45 +- .../test/appsec/iast/path-line.spec.js | 3 +- .../iast/security-controls/parser.spec.js | 5 +- .../appsec/iast/taint-tracking/plugin.spec.js | 4 +- .../taint-tracking/rewriter-telemetry.spec.js | 2 +- .../iast/taint-tracking/rewriter.spec.js | 18 +- .../iast/taint-tracking/secure-marks.spec.js | 10 +- .../taint-tracking-impl.spec.js | 9 +- .../taint-tracking-operations.spec.js | 59 +- .../taint-tracking.lodash.plugin.spec.js | 3 +- .../appsec/iast/telemetry/iast-metric.spec.js | 10 +- .../test/appsec/iast/telemetry/index.spec.js | 4 +- .../appsec/iast/telemetry/namespaces.spec.js | 6 +- .../appsec/iast/telemetry/span-tags.spec.js | 12 +- .../appsec/iast/telemetry/verbosity.spec.js | 8 +- packages/dd-trace/test/appsec/iast/utils.js | 33 +- .../iast/vulnerability-reporter.spec.js | 16 +- .../appsec/index.body-parser.plugin.spec.js | 5 +- .../test/appsec/index.fastify.plugin.spec.js | 101 +- packages/dd-trace/test/appsec/index.spec.js | 2 +- .../command_injection.integration.spec.js | 21 +- .../test/appsec/rasp/fs-plugin.spec.js | 48 +- .../appsec/rasp/lfi.express.plugin.spec.js | 3 +- .../lfi.integration.express.plugin.spec.js | 8 +- .../rasp/rasp-metrics.integration.spec.js | 20 +- .../rasp/rasp_blocking.fastify.plugin.spec.js | 3 +- ...ql_injection.integration.pg.plugin.spec.js | 16 +- .../rasp/sql_injection.mysql2.plugin.spec.js | 3 +- .../appsec/rasp/ssrf.express.plugin.spec.js | 5 +- packages/dd-trace/test/appsec/rasp/utils.js | 14 +- .../dd-trace/test/appsec/reporter.spec.js | 8 +- .../dd-trace/test/appsec/rule_manager.spec.js | 55 +- .../sdk/track_event-integration.spec.js | 11 +- .../sdk/user_blocking-integration.spec.js | 3 +- .../dd-trace/test/appsec/sdk/utils.spec.js | 25 +- .../dd-trace/test/appsec/stack_trace.spec.js | 34 +- .../test/appsec/telemetry/rasp.spec.js | 25 +- .../test/appsec/telemetry/waf.spec.js | 170 +-- .../appsec/waf-metrics.integration.spec.js | 34 +- .../dd-trace/test/appsec/waf/index.spec.js | 8 +- packages/dd-trace/test/azure_metadata.spec.js | 4 +- .../dynamic-instrumentation.spec.js | 12 +- .../ci-visibility/encode/json-encoder.spec.js | 4 +- .../exporters/agent-proxy/agent-proxy.spec.js | 6 +- .../exporters/agentless/exporter.spec.js | 40 +- .../exporters/ci-visibility-exporter.spec.js | 164 +-- .../exporters/git/git_metadata.spec.js | 100 +- .../data_streams_checkpointer.spec.js | 18 +- .../test/datastreams/encoding.spec.js | 10 +- .../test/datastreams/processor.spec.js | 6 +- .../devtools_client/json-buffer.spec.js | 3 +- .../debugger/devtools_client/send.spec.js | 10 +- .../snapshot/complex-types.spec.js | 102 +- .../snapshot/max-collection-size.spec.js | 18 +- .../snapshot/max-field-count-scopes.spec.js | 7 +- .../snapshot/max-field-count.spec.js | 10 +- .../snapshot/max-reference-depth.spec.js | 19 +- .../snapshot/primitives.spec.js | 22 +- .../snapshot/redaction.spec.js | 54 +- .../devtools_client/snapshot/scopes.spec.js | 16 +- .../snapshot/time-budget.spec.js | 12 +- .../devtools_client/source-maps.spec.js | 5 +- packages/dd-trace/test/encode/0.5.spec.js | 154 +-- .../encode/coverage-ci-visibility.spec.js | 52 +- .../common/agent-info-exporter.spec.js | 22 +- .../test/external-logger/index.spec.js | 8 +- .../dd-trace/test/git_metadata_tagger.spec.js | 6 +- packages/dd-trace/test/lambda/index.spec.js | 9 +- .../dd-trace/test/llmobs/sdk/index.spec.js | 16 +- .../test/llmobs/span_processor.spec.js | 57 +- packages/dd-trace/test/llmobs/tagger.spec.js | 3 +- packages/dd-trace/test/llmobs/util.spec.js | 13 +- packages/dd-trace/test/log.spec.js | 9 +- .../flagging_provider_timeout.spec.js | 50 +- .../dd-trace/test/openfeature/noop.spec.js | 10 +- .../opentelemetry/context_manager.spec.js | 20 +- .../dd-trace/test/opentelemetry/span.spec.js | 4 +- .../test/opentelemetry/tracer.spec.js | 10 +- .../opentelemetry/tracer_provider.spec.js | 8 +- .../test/opentracing/propagation/log.spec.js | 4 +- .../opentracing/propagation/text_map.spec.js | 421 +++--- .../propagation/tracestate.spec.js | 6 +- .../dd-trace/test/opentracing/span.spec.js | 10 +- .../dd-trace/test/opentracing/tracer.spec.js | 6 +- packages/dd-trace/test/plugin_manager.spec.js | 4 +- .../dd-trace/test/plugins/log_plugin.spec.js | 4 +- .../dd-trace/test/plugins/outbound.spec.js | 10 +- .../test/plugins/plugin-structure.spec.js | 4 +- .../dd-trace/test/plugins/tracing.spec.js | 4 +- .../test/plugins/util/ip_extractor.spec.js | 6 +- .../dd-trace/test/plugins/util/llm.spec.js | 8 +- .../plugins/util/test-environment.spec.js | 6 +- .../dd-trace/test/plugins/util/test.spec.js | 8 +- .../dd-trace/test/plugins/util/web.spec.js | 12 +- .../dd-trace/test/priority_sampler.spec.js | 6 +- .../dd-trace/test/profiling/config.spec.js | 62 +- .../dd-trace/test/profiling/profiler.spec.js | 2 +- .../test/profiling/profilers/space.spec.js | 4 +- .../test/remote_config/manager.spec.js | 8 +- packages/dd-trace/test/sampler.spec.js | 12 +- packages/dd-trace/test/sampling_rule.spec.js | 14 +- packages/dd-trace/test/scope.spec.js | 6 +- packages/dd-trace/test/span_format.spec.js | 14 +- packages/dd-trace/test/span_processor.spec.js | 34 +- .../dd-trace/test/standalone/index.spec.js | 54 +- .../dd-trace/test/standalone/product.spec.js | 14 +- .../test/standalone/tracesource.spec.js | 14 +- .../tracesource_priority_sampler.spec.js | 4 +- packages/dd-trace/test/tagger.spec.js | 6 +- .../dd-trace/test/telemetry/endpoints.spec.js | 57 +- .../dd-trace/test/telemetry/index.spec.js | 8 +- .../test/telemetry/logs/index.spec.js | 16 +- .../test/telemetry/logs/log-collector.spec.js | 4 +- .../dd-trace/test/telemetry/metrics.spec.js | 8 +- packages/dd-trace/test/tracer.spec.js | 4 +- packages/dd-trace/test/util.spec.js | 10 +- scripts/codemods/chai-to-assert.js | 543 +++++++- 346 files changed, 5265 insertions(+), 4901 deletions(-) diff --git a/integration-tests/aiguard/index.spec.js b/integration-tests/aiguard/index.spec.js index 885c5098d55..94a8e42dad0 100644 --- a/integration-tests/aiguard/index.spec.js +++ b/integration-tests/aiguard/index.spec.js @@ -3,12 +3,12 @@ const assert = require('node:assert/strict') const path = require('path') -const { expect } = require('chai') const { after, afterEach, before, beforeEach, describe, it } = require('mocha') const { sandboxCwd, useSandbox, FakeAgent, spawnProc } = require('../helpers') const startApiMock = require('./api-mock') const { executeRequest } = require('./util') +const { assertObjectContains } = require('../helpers') describe('AIGuard SDK integration tests', () => { let cwd, appFile, agent, proc, api, url @@ -63,11 +63,11 @@ describe('AIGuard SDK integration tests', () => { const response = await executeRequest(`${url}${endpoint}`, 'GET', headers) if (blocking && action !== 'ALLOW') { assert.strictEqual(response.status, 403) - expect(response.body).to.contain(reason) + assertObjectContains(response.body, reason) } else { assert.strictEqual(response.status, 200) - expect(response.body).to.have.nested.property('action', action) - expect(response.body).to.have.nested.property('reason', reason) + assert.strictEqual(response.body?.action, action) + assert.strictEqual(response.body?.reason, reason) } await agent.assertMessageReceived(({ headers, payload }) => { const span = payload[0].find(span => span.name === 'ai_guard') diff --git a/integration-tests/appsec/data-collection.spec.js b/integration-tests/appsec/data-collection.spec.js index a9e477e09f7..96f2ea8615e 100644 --- a/integration-tests/appsec/data-collection.spec.js +++ b/integration-tests/appsec/data-collection.spec.js @@ -1,6 +1,6 @@ 'use strict' -const { assert } = require('chai') +const assert = require('node:assert/strict') const path = require('path') const Axios = require('axios') @@ -55,7 +55,7 @@ describe('ASM Data collection', () => { requestHeaders.length ) requestHeaders.forEach((headerName) => { - assert.property(payload[0][0].meta, `http.request.headers.${headerName}`) + assert.ok(Object.hasOwn(payload[0][0].meta, `http.request.headers.${headerName}`)) }) // Response headers @@ -64,7 +64,7 @@ describe('ASM Data collection', () => { responseHeaders.length ) responseHeaders.forEach((headerName) => { - assert.property(payload[0][0].meta, `http.response.headers.${headerName}`) + assert.ok(Object.hasOwn(payload[0][0].meta, `http.response.headers.${headerName}`)) }) }) } diff --git a/integration-tests/appsec/graphql.spec.js b/integration-tests/appsec/graphql.spec.js index bac12b22ff1..6b7900e94c1 100644 --- a/integration-tests/appsec/graphql.spec.js +++ b/integration-tests/appsec/graphql.spec.js @@ -1,6 +1,6 @@ 'use strict' -const { assert } = require('chai') +const assert = require('node:assert/strict') const path = require('path') const axios = require('axios') @@ -38,15 +38,15 @@ describe('graphql', () => { it('should not report any attack', async () => { const agentPromise = agent.assertMessageReceived(({ headers, payload }) => { - assert.propertyVal(headers, 'host', `127.0.0.1:${agent.port}`) - assert.isArray(payload) + assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.ok(Array.isArray(payload)) assert.strictEqual(payload.length, 2) // Apollo server 5 is using Node.js http server instead of express - assert.propertyVal(payload[1][0], 'name', 'web.request') - assert.propertyVal(payload[1][0].metrics, '_dd.appsec.enabled', 1) - assert.property(payload[1][0].metrics, '_dd.appsec.waf.duration') - assert.notProperty(payload[1][0].meta, '_dd.appsec.event') - assert.notProperty(payload[1][0].meta, '_dd.appsec.json') + assert.strictEqual(payload[1][0]['name'], 'web.request') + assert.strictEqual(payload[1][0].metrics['_dd.appsec.enabled'], 1) + assert.ok(Object.hasOwn(payload[1][0].metrics, '_dd.appsec.waf.duration')) + assert.ok(!Object.hasOwn(payload[1][0].meta, '_dd.appsec.event')) + assert.ok(!Object.hasOwn(payload[1][0].meta, '_dd.appsec.json')) }) await axios({ @@ -100,15 +100,15 @@ describe('graphql', () => { } const agentPromise = agent.assertMessageReceived(({ headers, payload }) => { - assert.propertyVal(headers, 'host', `127.0.0.1:${agent.port}`) - assert.isArray(payload) + assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.ok(Array.isArray(payload)) assert.strictEqual(payload.length, 2) // Apollo server 5 is using Node.js http server instead of express - assert.propertyVal(payload[1][0], 'name', 'web.request') - assert.propertyVal(payload[1][0].metrics, '_dd.appsec.enabled', 1) - assert.property(payload[1][0].metrics, '_dd.appsec.waf.duration') - assert.propertyVal(payload[1][0].meta, 'appsec.event', 'true') - assert.property(payload[1][0].meta, '_dd.appsec.json') + assert.strictEqual(payload[1][0]['name'], 'web.request') + assert.strictEqual(payload[1][0].metrics['_dd.appsec.enabled'], 1) + assert.ok(Object.hasOwn(payload[1][0].metrics, '_dd.appsec.waf.duration')) + assert.strictEqual(payload[1][0].meta['appsec.event'], 'true') + assert.ok(Object.hasOwn(payload[1][0].meta, '_dd.appsec.json')) assert.deepStrictEqual(JSON.parse(payload[1][0].meta['_dd.appsec.json']), result) }) diff --git a/integration-tests/appsec/iast-esbuild.spec.js b/integration-tests/appsec/iast-esbuild.spec.js index 9730d5b5ca5..ee27a868c90 100644 --- a/integration-tests/appsec/iast-esbuild.spec.js +++ b/integration-tests/appsec/iast-esbuild.spec.js @@ -1,7 +1,8 @@ 'use strict' +const assert = require('node:assert/strict') + const Axios = require('axios') -const { assert } = require('chai') const childProcess = require('child_process') const fs = require('fs') const path = require('path') @@ -34,7 +35,7 @@ describe('esbuild support for IAST', () => { return agent.assertMessageReceived(({ payload }) => { const spans = payload.flatMap(p => p.filter(span => span.name === 'express.request')) spans.forEach(span => { - assert.property(span.meta, '_dd.iast.json') + assert.ok(Object.hasOwn(span.meta, '_dd.iast.json')) const spanIastData = JSON.parse(span.meta['_dd.iast.json']) assert.strictEqual(spanIastData.vulnerabilities[0].type, 'COMMAND_INJECTION') assert.strictEqual(spanIastData.vulnerabilities[0].location.path, expectedPath) @@ -43,8 +44,8 @@ describe('esbuild support for IAST', () => { } const ddStack = msgpack.decode(span.meta_struct['_dd.stack']) - assert.property(ddStack.vulnerability[0], 'frames') - assert.isNotEmpty(ddStack.vulnerability[0].frames) + assert.ok(Object.hasOwn(ddStack.vulnerability[0], 'frames')) + assert.ok(ddStack.vulnerability[0].frames.length > 0) }) }, null, 1, true) } @@ -53,7 +54,7 @@ describe('esbuild support for IAST', () => { return agent.assertMessageReceived(({ payload }) => { const spans = payload.flatMap(p => p.filter(span => span.name === 'express.request')) spans.forEach(span => { - assert.notProperty(span.meta, '_dd.iast.json') + assert.ok(!Object.hasOwn(span.meta, '_dd.iast.json')) }) }, null, 1, true) } diff --git a/integration-tests/appsec/iast-stack-traces-with-sourcemaps.spec.js b/integration-tests/appsec/iast-stack-traces-with-sourcemaps.spec.js index 4029e9031b8..e4818bdc1e9 100644 --- a/integration-tests/appsec/iast-stack-traces-with-sourcemaps.spec.js +++ b/integration-tests/appsec/iast-stack-traces-with-sourcemaps.spec.js @@ -1,11 +1,11 @@ 'use strict' +const assert = require('node:assert/strict') + const { sandboxCwd, useSandbox, spawnProc, FakeAgent } = require('../helpers') const childProcess = require('child_process') const path = require('path') const Axios = require('axios') -const { assert } = require('chai') - describe('IAST stack traces and vulnerabilities with sourcemaps', () => { let axios, cwd, appDir, appFile, agent, proc @@ -49,13 +49,13 @@ describe('IAST stack traces and vulnerabilities with sourcemaps', () => { it('should detect correct stack trace in unnamed function', async () => { const response = await axios.get('/rewritten/stack-trace-from-unnamed-function') - assert.include(response.data, '/rewritten-routes.ts:7:13') + assert.ok(response.data.includes('/rewritten-routes.ts:7:13')) }) it('should detect correct stack trace in named function', async () => { const response = await axios.get('/rewritten/stack-trace-from-named-function') - assert.include(response.data, '/rewritten-routes.ts:11:13') + assert.ok(response.data.includes('/rewritten-routes.ts:11:13')) }) it('should detect vulnerability in the correct location', async () => { @@ -64,14 +64,14 @@ describe('IAST stack traces and vulnerabilities with sourcemaps', () => { await agent.assertMessageReceived(({ payload }) => { const spans = payload.flatMap(p => p.filter(span => span.name === 'express.request')) spans.forEach(span => { - assert.property(span.meta, '_dd.iast.json') + assert.ok(Object.hasOwn(span.meta, '_dd.iast.json')) const iastJsonObject = JSON.parse(span.meta['_dd.iast.json']) - assert.isTrue(iastJsonObject.vulnerabilities.some(vulnerability => { + assert.strictEqual(iastJsonObject.vulnerabilities.some(vulnerability => { return vulnerability.type === 'WEAK_HASH' && vulnerability.location.path === 'appsec/iast-stack-traces-ts-with-sourcemaps/rewritten-routes.ts' && vulnerability.location.line === 15 - })) + }), true) }) }, null, 1, true) }) @@ -81,13 +81,13 @@ describe('IAST stack traces and vulnerabilities with sourcemaps', () => { it('should detect correct stack trace in unnamed function', async () => { const response = await axios.get('/not-rewritten/stack-trace-from-unnamed-function') - assert.include(response.data, '/not-rewritten-routes.ts:7:13') + assert.ok(response.data.includes('/not-rewritten-routes.ts:7:13')) }) it('should detect correct stack trace in named function', async () => { const response = await axios.get('/not-rewritten/stack-trace-from-named-function') - assert.include(response.data, '/not-rewritten-routes.ts:11:13') + assert.ok(response.data.includes('/not-rewritten-routes.ts:11:13')) }) it('should detect vulnerability in the correct location', async () => { @@ -96,14 +96,14 @@ describe('IAST stack traces and vulnerabilities with sourcemaps', () => { await agent.assertMessageReceived(({ payload }) => { const spans = payload.flatMap(p => p.filter(span => span.name === 'express.request')) spans.forEach(span => { - assert.property(span.meta, '_dd.iast.json') + assert.ok(Object.hasOwn(span.meta, '_dd.iast.json')) const iastJsonObject = JSON.parse(span.meta['_dd.iast.json']) - assert.isTrue(iastJsonObject.vulnerabilities.some(vulnerability => { + assert.strictEqual(iastJsonObject.vulnerabilities.some(vulnerability => { return vulnerability.type === 'WEAK_HASH' && vulnerability.location.path === 'appsec/iast-stack-traces-ts-with-sourcemaps/not-rewritten-routes.ts' && vulnerability.location.line === 15 - })) + }), true) }) }, null, 1, true) }) diff --git a/integration-tests/appsec/iast.esm-security-controls.spec.js b/integration-tests/appsec/iast.esm-security-controls.spec.js index d35c174a8db..cfe9b924e84 100644 --- a/integration-tests/appsec/iast.esm-security-controls.spec.js +++ b/integration-tests/appsec/iast.esm-security-controls.spec.js @@ -1,10 +1,10 @@ 'use strict' +const assert = require('node:assert/strict') + const { sandboxCwd, useSandbox, spawnProc, FakeAgent } = require('../helpers') const path = require('path') const Axios = require('axios') -const { assert } = require('chai') - describe('ESM Security controls', () => { let axios, cwd, appFile, agent, proc @@ -51,8 +51,8 @@ describe('ESM Security controls', () => { await agent.assertMessageReceived(({ payload }) => { const spans = payload.flatMap(p => p.filter(span => span.name === 'express.request')) spans.forEach(span => { - assert.property(span.meta, '_dd.iast.json') - assert.include(span.meta['_dd.iast.json'], '"COMMAND_INJECTION"') + assert.ok(Object.hasOwn(span.meta, '_dd.iast.json')) + assert.ok(span.meta['_dd.iast.json'].includes('"COMMAND_INJECTION"')) }) }, null, 1, true) }) @@ -63,8 +63,8 @@ describe('ESM Security controls', () => { await agent.assertMessageReceived(({ payload }) => { const spans = payload.flatMap(p => p.filter(span => span.name === 'express.request')) spans.forEach(span => { - assert.notProperty(span.meta, '_dd.iast.json') - assert.property(span.metrics, '_dd.iast.telemetry.suppressed.vulnerabilities.command_injection') + assert.ok(!Object.hasOwn(span.meta, '_dd.iast.json')) + assert.ok(Object.hasOwn(span.metrics, '_dd.iast.telemetry.suppressed.vulnerabilities.command_injection')) }) }, null, 1, true) }) @@ -75,8 +75,8 @@ describe('ESM Security controls', () => { await agent.assertMessageReceived(({ payload }) => { const spans = payload.flatMap(p => p.filter(span => span.name === 'express.request')) spans.forEach(span => { - assert.notProperty(span.meta, '_dd.iast.json') - assert.property(span.metrics, '_dd.iast.telemetry.suppressed.vulnerabilities.command_injection') + assert.ok(!Object.hasOwn(span.meta, '_dd.iast.json')) + assert.ok(Object.hasOwn(span.metrics, '_dd.iast.telemetry.suppressed.vulnerabilities.command_injection')) }) }, null, 1, true) }) @@ -87,8 +87,8 @@ describe('ESM Security controls', () => { await agent.assertMessageReceived(({ payload }) => { const spans = payload.flatMap(p => p.filter(span => span.name === 'express.request')) spans.forEach(span => { - assert.property(span.meta, '_dd.iast.json') - assert.include(span.meta['_dd.iast.json'], '"COMMAND_INJECTION"') + assert.ok(Object.hasOwn(span.meta, '_dd.iast.json')) + assert.ok(span.meta['_dd.iast.json'].includes('"COMMAND_INJECTION"')) }) }, null, 1, true) }) @@ -99,8 +99,8 @@ describe('ESM Security controls', () => { await agent.assertMessageReceived(({ payload }) => { const spans = payload.flatMap(p => p.filter(span => span.name === 'express.request')) spans.forEach(span => { - assert.notProperty(span.meta, '_dd.iast.json') - assert.property(span.metrics, '_dd.iast.telemetry.suppressed.vulnerabilities.command_injection') + assert.ok(!Object.hasOwn(span.meta, '_dd.iast.json')) + assert.ok(Object.hasOwn(span.metrics, '_dd.iast.telemetry.suppressed.vulnerabilities.command_injection')) }) }, null, 1, true) }) @@ -111,8 +111,8 @@ describe('ESM Security controls', () => { await agent.assertMessageReceived(({ payload }) => { const spans = payload.flatMap(p => p.filter(span => span.name === 'express.request')) spans.forEach(span => { - assert.notProperty(span.meta, '_dd.iast.json') - assert.property(span.metrics, '_dd.iast.telemetry.suppressed.vulnerabilities.command_injection') + assert.ok(!Object.hasOwn(span.meta, '_dd.iast.json')) + assert.ok(Object.hasOwn(span.metrics, '_dd.iast.telemetry.suppressed.vulnerabilities.command_injection')) }) }, null, 1, true) }) diff --git a/integration-tests/appsec/iast.esm.spec.js b/integration-tests/appsec/iast.esm.spec.js index 86318007a11..a2acdefd1eb 100644 --- a/integration-tests/appsec/iast.esm.spec.js +++ b/integration-tests/appsec/iast.esm.spec.js @@ -1,10 +1,10 @@ 'use strict' +const assert = require('node:assert/strict') + const { sandboxCwd, useSandbox, spawnProc, FakeAgent } = require('../helpers') const path = require('path') const Axios = require('axios') -const { assert } = require('chai') - describe('ESM', () => { let axios, cwd, appFile, agent, proc @@ -64,8 +64,8 @@ describe('ESM', () => { await agent.assertMessageReceived(({ payload }) => { verifySpan(payload, span => { - assert.property(span.meta, '_dd.iast.json') - assert.include(span.meta['_dd.iast.json'], '"COMMAND_INJECTION"') + assert.ok(Object.hasOwn(span.meta, '_dd.iast.json')) + assert.ok(span.meta['_dd.iast.json'].includes('"COMMAND_INJECTION"')) }) }, null, 1, true) }) @@ -75,8 +75,8 @@ describe('ESM', () => { await agent.assertMessageReceived(({ payload }) => { verifySpan(payload, span => { - assert.property(span.meta, '_dd.iast.json') - assert.include(span.meta['_dd.iast.json'], '"COMMAND_INJECTION"') + assert.ok(Object.hasOwn(span.meta, '_dd.iast.json')) + assert.ok(span.meta['_dd.iast.json'].includes('"COMMAND_INJECTION"')) }) }, null, 1, true) }) diff --git a/integration-tests/appsec/index.spec.js b/integration-tests/appsec/index.spec.js index e78bce17934..4fc6c939b69 100644 --- a/integration-tests/appsec/index.spec.js +++ b/integration-tests/appsec/index.spec.js @@ -1,8 +1,9 @@ 'use strict' +const assert = require('node:assert/strict') + const path = require('path') const Axios = require('axios') -const { assert } = require('chai') const msgpack = require('@msgpack/msgpack') const { sandboxCwd, useSandbox, FakeAgent, spawnProc } = require('../helpers') @@ -49,18 +50,18 @@ describe('RASP', () => { async function assertExploitDetected () { await agent.assertMessageReceived(({ headers, payload }) => { - assert.property(payload[0][0].meta, '_dd.appsec.json') - assert.include(payload[0][0].meta['_dd.appsec.json'], '"test-rule-id-2"') + assert.ok(Object.hasOwn(payload[0][0].meta, '_dd.appsec.json')) + assert.ok(payload[0][0].meta['_dd.appsec.json'].includes('"test-rule-id-2"')) }) } async function assertBodyReported (expectedBody, truncated) { await agent.assertMessageReceived(({ headers, payload }) => { - assert.property(payload[0][0].meta_struct, 'http.request.body') + assert.ok(Object.hasOwn(payload[0][0].meta_struct, 'http.request.body')) assert.deepStrictEqual(msgpack.decode(payload[0][0].meta_struct['http.request.body']), expectedBody) if (truncated) { - assert.property(payload[0][0].meta, '_dd.appsec.rasp.request_body_size.exceeded') + assert.ok(Object.hasOwn(payload[0][0].meta, '_dd.appsec.rasp.request_body_size.exceeded')) } }) } @@ -338,8 +339,8 @@ describe('RASP', () => { } // not blocked - assert.notEqual(response.status, 418) - assert.notEqual(response.status, 403) + assert.notStrictEqual(response.status, 418) + assert.notStrictEqual(response.status, 403) await assertExploitDetected() }) }) @@ -399,7 +400,7 @@ describe('RASP', () => { } await agent.assertMessageReceived(({ headers, payload }) => { - assert.notProperty(payload[0][0].meta_struct, 'http.request.body') + assert.ok(!Object.hasOwn(payload[0][0].meta_struct, 'http.request.body')) }) } }) diff --git a/integration-tests/appsec/multer.spec.js b/integration-tests/appsec/multer.spec.js index cde9d931e1c..75f6580d1e8 100644 --- a/integration-tests/appsec/multer.spec.js +++ b/integration-tests/appsec/multer.spec.js @@ -1,7 +1,8 @@ 'use strict' +const assert = require('node:assert/strict') + const axios = require('axios') -const { assert } = require('chai') const { describe, it, beforeEach, afterEach, before } = require('mocha') const path = require('node:path') @@ -51,7 +52,7 @@ describe('multer', () => { const res = await axios.post(proc.url, form) - assert.equal(res.data, 'DONE') + assert.strictEqual(res.data, 'DONE') }) it('should block the request when attack is detected', async () => { @@ -63,7 +64,7 @@ describe('multer', () => { return Promise.reject(new Error('Request should not return 200')) } catch (e) { - assert.equal(e.response.status, 403) + assert.strictEqual(e.response.status, 403) } }) }) @@ -75,7 +76,7 @@ describe('multer', () => { const res = await axios.post(`${proc.url}/no-middleware`, form) - assert.equal(res.data, 'DONE') + assert.strictEqual(res.data, 'DONE') }) it('should block the request when attack is detected', async () => { @@ -87,7 +88,7 @@ describe('multer', () => { return Promise.reject(new Error('Request should not return 200')) } catch (e) { - assert.equal(e.response.status, 403) + assert.strictEqual(e.response.status, 403) } }) }) @@ -95,18 +96,18 @@ describe('multer', () => { describe('IAST', () => { function assertCmdInjection ({ payload }) { - assert.isArray(payload) + assert.ok(Array.isArray(payload)) assert.strictEqual(payload.length, 1) - assert.isArray(payload[0]) + assert.ok(Array.isArray(payload[0])) const { meta } = payload[0][0] - assert.property(meta, '_dd.iast.json') + assert.ok(Object.hasOwn(meta, '_dd.iast.json')) const iastJson = JSON.parse(meta['_dd.iast.json']) - assert.isTrue(iastJson.vulnerabilities.some(v => v.type === 'COMMAND_INJECTION')) - assert.isTrue(iastJson.sources.some(s => s.origin === 'http.request.body')) + assert.strictEqual(iastJson.vulnerabilities.some(v => v.type === 'COMMAND_INJECTION'), true) + assert.strictEqual(iastJson.sources.some(s => s.origin === 'http.request.body'), true) } describe('using middleware', () => { diff --git a/integration-tests/appsec/response-headers.spec.js b/integration-tests/appsec/response-headers.spec.js index f8dff7ab7fb..ec76a946da1 100644 --- a/integration-tests/appsec/response-headers.spec.js +++ b/integration-tests/appsec/response-headers.spec.js @@ -1,6 +1,6 @@ 'use strict' -const { assert } = require('chai') +const assert = require('node:assert/strict') const path = require('path') const Axios = require('axios') @@ -68,7 +68,7 @@ describe('Headers collection - Fastify', () => { requestHeaders.length ) requestHeaders.forEach((headerName) => { - assert.property(payload[0][0].meta, `http.request.headers.${headerName}`) + assert.ok(Object.hasOwn(payload[0][0].meta, `http.request.headers.${headerName}`)) }) // Response headers @@ -77,10 +77,10 @@ describe('Headers collection - Fastify', () => { responseHeaders.length ) responseHeaders.forEach((headerName) => { - assert.property(payload[0][0].meta, `http.response.headers.${headerName}`) + assert.ok(Object.hasOwn(payload[0][0].meta, `http.response.headers.${headerName}`)) }) }, 30000, 10, true) - assert.isTrue(fastifyRequestReceived) + assert.strictEqual(fastifyRequestReceived, true) }) }) diff --git a/integration-tests/appsec/standalone-asm.spec.js b/integration-tests/appsec/standalone-asm.spec.js index 715d8e5cc8b..382b796a6db 100644 --- a/integration-tests/appsec/standalone-asm.spec.js +++ b/integration-tests/appsec/standalone-asm.spec.js @@ -1,6 +1,6 @@ 'use strict' -const { assert } = require('chai') +const assert = require('node:assert/strict') const path = require('path') const { @@ -24,17 +24,17 @@ describe('Standalone ASM', () => { }) function assertKeep ({ meta, metrics }) { - assert.propertyVal(meta, '_dd.p.ts', '02') + assert.strictEqual(meta['_dd.p.ts'], '02') - assert.propertyVal(metrics, '_sampling_priority_v1', USER_KEEP) - assert.propertyVal(metrics, '_dd.apm.enabled', 0) + assert.strictEqual(metrics['_sampling_priority_v1'], USER_KEEP) + assert.strictEqual(metrics['_dd.apm.enabled'], 0) } function assertDrop ({ meta, metrics }) { - assert.notProperty(meta, '_dd.p.ts') + assert.ok(!Object.hasOwn(meta, '_dd.p.ts')) - assert.propertyVal(metrics, '_sampling_priority_v1', AUTO_REJECT) - assert.propertyVal(metrics, '_dd.apm.enabled', 0) + assert.strictEqual(metrics['_sampling_priority_v1'], AUTO_REJECT) + assert.strictEqual(metrics['_dd.apm.enabled'], 0) } async function doWarmupRequests (procOrUrl, number = 3) { @@ -67,10 +67,10 @@ describe('Standalone ASM', () => { // first req initializes the waf and reports the first appsec event adding manual.keep tag it('should send correct headers and tags on first req', async () => { return curlAndAssertMessage(agent, proc, ({ headers, payload }) => { - assert.propertyVal(headers, 'datadog-client-computed-stats', 'yes') - assert.isArray(payload) + assert.strictEqual(headers['datadog-client-computed-stats'], 'yes') + assert.ok(Array.isArray(payload)) assert.strictEqual(payload.length, 1) - assert.isArray(payload[0]) + assert.ok(Array.isArray(payload[0])) // express.request + router.middleware x 2 assert.strictEqual(payload[0].length, 3) @@ -81,8 +81,8 @@ describe('Standalone ASM', () => { it('should keep fifth req because RateLimiter allows 1 req/min', async () => { const promise = curlAndAssertMessage(agent, proc, ({ headers, payload }) => { - assert.propertyVal(headers, 'datadog-client-computed-stats', 'yes') - assert.isArray(payload) + assert.strictEqual(headers['datadog-client-computed-stats'], 'yes') + assert.ok(Array.isArray(payload)) if (payload.length === 4) { assertKeep(payload[0][0]) assertDrop(payload[1][0]) @@ -92,15 +92,15 @@ describe('Standalone ASM', () => { // req after a minute } else { const fifthReq = payload[0] - assert.isArray(fifthReq) + assert.ok(Array.isArray(fifthReq)) assert.strictEqual(fifthReq.length, 3) const { meta, metrics } = fifthReq[0] - assert.notProperty(meta, 'manual.keep') - assert.notProperty(meta, '_dd.p.ts') + assert.ok(!Object.hasOwn(meta, 'manual.keep')) + assert.ok(!Object.hasOwn(meta, '_dd.p.ts')) - assert.propertyVal(metrics, '_sampling_priority_v1', AUTO_KEEP) - assert.propertyVal(metrics, '_dd.apm.enabled', 0) + assert.strictEqual(metrics['_sampling_priority_v1'], AUTO_KEEP) + assert.strictEqual(metrics['_dd.apm.enabled'], 0) } }, 70000, 2) @@ -121,8 +121,8 @@ describe('Standalone ASM', () => { const urlAttack = proc.url + '?query=1 or 1=1' return curlAndAssertMessage(agent, urlAttack, ({ headers, payload }) => { - assert.propertyVal(headers, 'datadog-client-computed-stats', 'yes') - assert.isArray(payload) + assert.strictEqual(headers['datadog-client-computed-stats'], 'yes') + assert.ok(Array.isArray(payload)) assert.strictEqual(payload.length, 4) assertKeep(payload[3][0]) @@ -134,8 +134,8 @@ describe('Standalone ASM', () => { const url = proc.url + '/login?user=test' return curlAndAssertMessage(agent, url, ({ headers, payload }) => { - assert.propertyVal(headers, 'datadog-client-computed-stats', 'yes') - assert.isArray(payload) + assert.strictEqual(headers['datadog-client-computed-stats'], 'yes') + assert.ok(Array.isArray(payload)) assert.strictEqual(payload.length, 4) assertKeep(payload[3][0]) @@ -147,8 +147,8 @@ describe('Standalone ASM', () => { const url = proc.url + '/sdk' return curlAndAssertMessage(agent, url, ({ headers, payload }) => { - assert.propertyVal(headers, 'datadog-client-computed-stats', 'yes') - assert.isArray(payload) + assert.strictEqual(headers['datadog-client-computed-stats'], 'yes') + assert.ok(Array.isArray(payload)) assert.strictEqual(payload.length, 4) assertKeep(payload[3][0]) @@ -160,14 +160,14 @@ describe('Standalone ASM', () => { const url = proc.url + '/vulnerableHash' return curlAndAssertMessage(agent, url, ({ headers, payload }) => { - assert.propertyVal(headers, 'datadog-client-computed-stats', 'yes') - assert.isArray(payload) + assert.strictEqual(headers['datadog-client-computed-stats'], 'yes') + assert.ok(Array.isArray(payload)) assert.strictEqual(payload.length, 4) const expressReq4 = payload[3][0] assertKeep(expressReq4) - assert.property(expressReq4.meta, '_dd.iast.json') - assert.propertyVal(expressReq4.metrics, '_dd.iast.enabled', 1) + assert.ok(Object.hasOwn(expressReq4.meta, '_dd.iast.json')) + assert.strictEqual(expressReq4.metrics['_dd.iast.enabled'], 1) }) }) @@ -195,8 +195,8 @@ describe('Standalone ASM', () => { const url = `${proc.url}/propagation-after-drop-and-call-sdk?port=${port2}` return curlAndAssertMessage(agent, url, ({ headers, payload }) => { - assert.propertyVal(headers, 'datadog-client-computed-stats', 'yes') - assert.isArray(payload) + assert.strictEqual(headers['datadog-client-computed-stats'], 'yes') + assert.ok(Array.isArray(payload)) const innerReq = payload.find(p => p[0].resource === 'GET /sdk') assert.notStrictEqual(innerReq, undefined) @@ -212,8 +212,8 @@ describe('Standalone ASM', () => { const url = `${proc.url}/propagation-with-event?port=${port2}` return curlAndAssertMessage(agent, url, ({ headers, payload }) => { - assert.propertyVal(headers, 'datadog-client-computed-stats', 'yes') - assert.isArray(payload) + assert.strictEqual(headers['datadog-client-computed-stats'], 'yes') + assert.ok(Array.isArray(payload)) const innerReq = payload.find(p => p[0].resource === 'GET /down') assert.notStrictEqual(innerReq, undefined) @@ -227,12 +227,12 @@ describe('Standalone ASM', () => { const url = `${proc.url}/propagation-without-event?port=${port2}` return curlAndAssertMessage(agent, url, ({ headers, payload }) => { - assert.propertyVal(headers, 'datadog-client-computed-stats', 'yes') - assert.isArray(payload) + assert.strictEqual(headers['datadog-client-computed-stats'], 'yes') + assert.ok(Array.isArray(payload)) const innerReq = payload.find(p => p[0].resource === 'GET /down') assert.notStrictEqual(innerReq, undefined) - assert.notProperty(innerReq[0].meta, '_dd.p.other') + assert.ok(!Object.hasOwn(innerReq[0].meta, '_dd.p.other')) }, undefined, undefined, true) }) @@ -241,12 +241,12 @@ describe('Standalone ASM', () => { const url = `${proc.url}/propagation-with-event?port=${port2}` return curlAndAssertMessage(agent, url, ({ headers, payload }) => { - assert.propertyVal(headers, 'datadog-client-computed-stats', 'yes') - assert.isArray(payload) + assert.strictEqual(headers['datadog-client-computed-stats'], 'yes') + assert.ok(Array.isArray(payload)) const innerReq = payload.find(p => p[0].resource === 'GET /down') assert.notStrictEqual(innerReq, undefined) - assert.property(innerReq[0].meta, '_dd.p.other') + assert.ok(Object.hasOwn(innerReq[0].meta, '_dd.p.other')) }, undefined, undefined, true) }) }) @@ -274,8 +274,8 @@ describe('Standalone ASM', () => { it('should keep fifth req because of api security sampler', async () => { const promise = curlAndAssertMessage(agent, proc, ({ headers, payload }) => { - assert.propertyVal(headers, 'datadog-client-computed-stats', 'yes') - assert.isArray(payload) + assert.strictEqual(headers['datadog-client-computed-stats'], 'yes') + assert.ok(Array.isArray(payload)) if (payload.length === 4) { assertKeep(payload[0][0]) assertDrop(payload[1][0]) @@ -285,7 +285,7 @@ describe('Standalone ASM', () => { // req after 30s } else { const fifthReq = payload[0] - assert.isArray(fifthReq) + assert.ok(Array.isArray(fifthReq)) assert.strictEqual(fifthReq.length, 3) assertKeep(fifthReq[0]) } @@ -323,19 +323,19 @@ describe('Standalone ASM', () => { it('should not add standalone related tags in iast events', () => { const url = proc.url + '/vulnerableHash' return curlAndAssertMessage(agent, url, ({ headers, payload }) => { - assert.notProperty(headers, 'datadog-client-computed-stats') - assert.isArray(payload) + assert.ok(!Object.hasOwn(headers, 'datadog-client-computed-stats')) + assert.ok(Array.isArray(payload)) assert.strictEqual(payload.length, 1) - assert.isArray(payload[0]) + assert.ok(Array.isArray(payload[0])) // express.request + router.middleware x 2 assert.strictEqual(payload[0].length, 3) const { meta, metrics } = payload[0][0] - assert.property(meta, '_dd.iast.json') // WEAK_HASH and XCONTENTTYPE_HEADER_MISSING reported + assert.ok(Object.hasOwn(meta, '_dd.iast.json')) // WEAK_HASH and XCONTENTTYPE_HEADER_MISSING reported - assert.notProperty(meta, '_dd.p.ts') - assert.notProperty(metrics, '_dd.apm.enabled') + assert.ok(!Object.hasOwn(meta, '_dd.p.ts')) + assert.ok(!Object.hasOwn(metrics, '_dd.apm.enabled')) }) }) @@ -343,19 +343,19 @@ describe('Standalone ASM', () => { const urlAttack = proc.url + '?query=1 or 1=1' return curlAndAssertMessage(agent, urlAttack, ({ headers, payload }) => { - assert.notProperty(headers, 'datadog-client-computed-stats') - assert.isArray(payload) + assert.ok(!Object.hasOwn(headers, 'datadog-client-computed-stats')) + assert.ok(Array.isArray(payload)) assert.strictEqual(payload.length, 1) - assert.isArray(payload[0]) + assert.ok(Array.isArray(payload[0])) // express.request + router.middleware x 2 assert.strictEqual(payload[0].length, 3) const { meta, metrics } = payload[0][0] - assert.property(meta, '_dd.appsec.json') // crs-942-100 triggered + assert.ok(Object.hasOwn(meta, '_dd.appsec.json')) // crs-942-100 triggered - assert.notProperty(meta, '_dd.p.ts') - assert.notProperty(metrics, '_dd.apm.enabled') + assert.ok(!Object.hasOwn(meta, '_dd.p.ts')) + assert.ok(!Object.hasOwn(metrics, '_dd.apm.enabled')) }) }) }) diff --git a/integration-tests/appsec/trace-tagging.spec.js b/integration-tests/appsec/trace-tagging.spec.js index 497c7b454f9..6cdd9dd069d 100644 --- a/integration-tests/appsec/trace-tagging.spec.js +++ b/integration-tests/appsec/trace-tagging.spec.js @@ -1,6 +1,6 @@ 'use strict' -const { assert } = require('chai') +const assert = require('node:assert/strict') const path = require('path') const Axios = require('axios') @@ -48,9 +48,9 @@ describe('ASM Trace Tagging rules', () => { await axios.get('/', { headers: { 'User-Agent': 'TraceTaggingTest/v1' } }) await agent.assertMessageReceived(({ _, payload }) => { - assert.property(payload[0][0].meta, '_dd.appsec.trace.agent') + assert.ok(Object.hasOwn(payload[0][0].meta, '_dd.appsec.trace.agent')) assert.strictEqual(payload[0][0].meta['_dd.appsec.trace.agent'], 'TraceTaggingTest/v1') - assert.property(payload[0][0].metrics, '_dd.appsec.trace.integer') + assert.ok(Object.hasOwn(payload[0][0].metrics, '_dd.appsec.trace.integer')) assert.strictEqual(payload[0][0].metrics['_dd.appsec.trace.integer'], 1234) }) }) @@ -81,13 +81,13 @@ describe('ASM Trace Tagging rules', () => { fastifyRequestReceived = true - assert.property(payload[0][0].meta, '_dd.appsec.trace.agent') + assert.ok(Object.hasOwn(payload[0][0].meta, '_dd.appsec.trace.agent')) assert.strictEqual(payload[0][0].meta['_dd.appsec.trace.agent'], 'TraceTaggingTest/v1') - assert.property(payload[0][0].metrics, '_dd.appsec.trace.integer') + assert.ok(Object.hasOwn(payload[0][0].metrics, '_dd.appsec.trace.integer')) assert.strictEqual(payload[0][0].metrics['_dd.appsec.trace.integer'], 1234) }, 30000, 10, true) - assert.isTrue(fastifyRequestReceived) + assert.strictEqual(fastifyRequestReceived, true) }) }) }) diff --git a/integration-tests/ci-visibility/automatic-log-submission-cucumber/support/steps.js b/integration-tests/ci-visibility/automatic-log-submission-cucumber/support/steps.js index 90f3d25aa6e..759d1a18589 100644 --- a/integration-tests/ci-visibility/automatic-log-submission-cucumber/support/steps.js +++ b/integration-tests/ci-visibility/automatic-log-submission-cucumber/support/steps.js @@ -1,14 +1,14 @@ 'use strict' -const { expect } = require('chai') +const assert = require('node:assert/strict') + const { When, Then } = require('@cucumber/cucumber') const logger = require('./logger') const sum = require('./sum') - Then('I should have made a log', async function () { - expect(true).to.equal(true) - expect(sum(1, 2)).to.equal(3) + assert.strictEqual(true, true) + assert.strictEqual(sum(1, 2), 3) }) When('we run a test', async function () { diff --git a/integration-tests/ci-visibility/automatic-log-submission/automatic-log-submission-test.js b/integration-tests/ci-visibility/automatic-log-submission/automatic-log-submission-test.js index 6a557c46119..97b6eb30300 100644 --- a/integration-tests/ci-visibility/automatic-log-submission/automatic-log-submission-test.js +++ b/integration-tests/ci-visibility/automatic-log-submission/automatic-log-submission-test.js @@ -1,15 +1,14 @@ 'use strict' -const { expect } = require('chai') +const assert = require('node:assert/strict') const logger = require('./logger') const sum = require('./sum') - describe('test', () => { it('should return true', () => { logger.log('info', 'Hello simple log!') - expect(true).to.be.true - expect(sum(1, 2)).to.equal(3) + assert.strictEqual(true, true) + assert.strictEqual(sum(1, 2), 3) }) }) diff --git a/integration-tests/ci-visibility/dynamic-instrumentation/parallel-test-hit-breakpoint-1.js b/integration-tests/ci-visibility/dynamic-instrumentation/parallel-test-hit-breakpoint-1.js index c0ae5658f0c..9d12396f8aa 100644 --- a/integration-tests/ci-visibility/dynamic-instrumentation/parallel-test-hit-breakpoint-1.js +++ b/integration-tests/ci-visibility/dynamic-instrumentation/parallel-test-hit-breakpoint-1.js @@ -1,14 +1,14 @@ 'use strict' -const sum = require('./dependency') -const { expect } = require('chai') +const assert = require('node:assert/strict') +const sum = require('./dependency') describe('dynamic-instrumentation', () => { it('retries with DI', function () { - expect(sum(11, 3)).to.equal(14) + assert.strictEqual(sum(11, 3), 14) }) it('is not retried', () => { - expect(1 + 2).to.equal(3) + assert.strictEqual(1 + 2, 3) }) }) diff --git a/integration-tests/ci-visibility/dynamic-instrumentation/parallel-test-hit-breakpoint-2.js b/integration-tests/ci-visibility/dynamic-instrumentation/parallel-test-hit-breakpoint-2.js index b5f7d04415a..12e687ff613 100644 --- a/integration-tests/ci-visibility/dynamic-instrumentation/parallel-test-hit-breakpoint-2.js +++ b/integration-tests/ci-visibility/dynamic-instrumentation/parallel-test-hit-breakpoint-2.js @@ -1,9 +1,8 @@ 'use strict' -const { expect } = require('chai') - +const assert = require('node:assert/strict') describe('dynamic-instrumentation 2', () => { it('is not retried', () => { - expect(1 + 2).to.equal(3) + assert.strictEqual(1 + 2, 3) }) }) diff --git a/integration-tests/ci-visibility/dynamic-instrumentation/test-hit-breakpoint.js b/integration-tests/ci-visibility/dynamic-instrumentation/test-hit-breakpoint.js index c57f8ffb357..1be2d27d21a 100644 --- a/integration-tests/ci-visibility/dynamic-instrumentation/test-hit-breakpoint.js +++ b/integration-tests/ci-visibility/dynamic-instrumentation/test-hit-breakpoint.js @@ -1,21 +1,21 @@ 'use strict' -const sum = require('./dependency') -const { expect } = require('chai') +const assert = require('node:assert/strict') +const sum = require('./dependency') let count = 0 describe('dynamic-instrumentation', () => { it('retries with DI', function () { if (process.env.TEST_SHOULD_PASS_AFTER_RETRY && count++ === 1) { // Passes after a retry if TEST_SHOULD_PASS_AFTER_RETRY is passed - expect(sum(1, 3)).to.equal(4) + assert.strictEqual(sum(1, 3), 4) } else { - expect(sum(11, 3)).to.equal(14) + assert.strictEqual(sum(11, 3), 14) } }) it('is not retried', () => { - expect(1 + 2).to.equal(3) + assert.strictEqual(1 + 2, 3) }) }) diff --git a/integration-tests/ci-visibility/dynamic-instrumentation/test-not-hit-breakpoint.js b/integration-tests/ci-visibility/dynamic-instrumentation/test-not-hit-breakpoint.js index eb0fd470c75..2408a0e2aeb 100644 --- a/integration-tests/ci-visibility/dynamic-instrumentation/test-not-hit-breakpoint.js +++ b/integration-tests/ci-visibility/dynamic-instrumentation/test-not-hit-breakpoint.js @@ -1,17 +1,17 @@ 'use strict' -const sum = require('./dependency') -const { expect } = require('chai') +const assert = require('node:assert/strict') +const sum = require('./dependency') let count = 0 describe('dynamic-instrumentation', () => { it('retries with DI', function () { const willFail = count++ === 0 if (willFail) { - expect(sum(11, 3)).to.equal(14) // only throws the first time + assert.strictEqual(sum(11, 3), 14) // only throws the first time } else { - expect(sum(1, 2)).to.equal(3) + assert.strictEqual(sum(1, 2), 3) } }) }) diff --git a/integration-tests/ci-visibility/features-selenium/support/steps.js b/integration-tests/ci-visibility/features-selenium/support/steps.js index 2e2052cdc72..77c54b105b2 100644 --- a/integration-tests/ci-visibility/features-selenium/support/steps.js +++ b/integration-tests/ci-visibility/features-selenium/support/steps.js @@ -1,10 +1,10 @@ 'use strict' -const { expect } = require('chai') +const assert = require('node:assert/strict') + +const { When, Then, Before, After } = require('@cucumber/cucumber') const { By, Builder } = require('selenium-webdriver') const chrome = require('selenium-webdriver/chrome') -const { When, Then, Before, After } = require('@cucumber/cucumber') - let driver let title let helloWorldText @@ -22,8 +22,8 @@ After(async function () { }) Then('I should have run selenium', async function () { - expect(title).to.equal('Hello World') - expect(helloWorldText).to.equal('Hello World') + assert.strictEqual(title, 'Hello World') + assert.strictEqual(helloWorldText, 'Hello World') }) When('we run selenium', async function () { diff --git a/integration-tests/ci-visibility/git-cache.spec.js b/integration-tests/ci-visibility/git-cache.spec.js index d7513429f55..24bd1894598 100644 --- a/integration-tests/ci-visibility/git-cache.spec.js +++ b/integration-tests/ci-visibility/git-cache.spec.js @@ -1,12 +1,13 @@ 'use strict' -const { expect } = require('chai') +const { execSync } = require('child_process') const fs = require('fs') -const path = require('path') +const assert = require('node:assert/strict') const os = require('os') -const { execSync } = require('child_process') +const path = require('path') const { sandboxCwd, useSandbox } = require('../helpers') +const { assertObjectContains } = require('../helpers') const FIXED_COMMIT_MESSAGE = 'Test commit message for caching' const GET_COMMIT_MESSAGE_COMMAND_ARGS = ['log', '-1', '--pretty=format:%s'] @@ -72,29 +73,29 @@ describe('git-cache integration tests', () => { const firstResult = gitCache.cachedExec('git', GET_COMMIT_MESSAGE_COMMAND_ARGS) const firstResultStr = firstResult.toString().trim() - expect(firstResultStr).to.equal(FIXED_COMMIT_MESSAGE) + assert.strictEqual(firstResultStr, FIXED_COMMIT_MESSAGE) const cacheKey = gitCache.getCacheKey('git', GET_COMMIT_MESSAGE_COMMAND_ARGS) const cacheFilePath = gitCache.getCacheFilePath(cacheKey) - expect(fs.existsSync(cacheFilePath)).to.be.true + assert.strictEqual(fs.existsSync(cacheFilePath), true) const cachedContent = fs.readFileSync(cacheFilePath, 'utf8') - expect(cachedContent).to.equal(firstResultStr) + assert.strictEqual(cachedContent, firstResultStr) }) it('should return cached results when git is unavailable', function () { const firstResult = gitCache.cachedExec('git', GET_COMMIT_MESSAGE_COMMAND_ARGS).toString().trim() - expect(firstResult).to.equal(FIXED_COMMIT_MESSAGE) + assert.strictEqual(firstResult, FIXED_COMMIT_MESSAGE) const cacheKey = gitCache.getCacheKey('git', GET_COMMIT_MESSAGE_COMMAND_ARGS) const cacheFilePath = gitCache.getCacheFilePath(cacheKey) - expect(fs.existsSync(cacheFilePath)).to.be.true + assert.strictEqual(fs.existsSync(cacheFilePath), true) removeGitFromPath() const secondResult = gitCache.cachedExec('git', GET_COMMIT_MESSAGE_COMMAND_ARGS).toString().trim() - expect(secondResult).to.equal(firstResult) + assert.strictEqual(secondResult, firstResult) let secondError try { @@ -102,9 +103,9 @@ describe('git-cache integration tests', () => { } catch (error) { secondError = error } - expect(secondError).to.be.an('error') - expect(secondError.code).to.equal('ENOENT') - expect(secondError.message).to.include('git') + assert.ok(secondError instanceof Error) + assert.strictEqual(secondError.code, 'ENOENT') + assertObjectContains(secondError.message, 'git') }) it('should cache git command failures and throw the same error on subsequent calls', function () { @@ -117,14 +118,14 @@ describe('git-cache integration tests', () => { firstError = error } - expect(firstError).to.be.an('error') + assert.ok(firstError instanceof Error) const cacheKey = gitCache.getCacheKey('git', gitArgs) const cacheFilePath = gitCache.getCacheFilePath(cacheKey) - expect(fs.existsSync(cacheFilePath)).to.be.true + assert.strictEqual(fs.existsSync(cacheFilePath), true) const cachedData = fs.readFileSync(cacheFilePath, 'utf8') - expect(cachedData).to.include('__GIT_COMMAND_FAILED__') + assertObjectContains(cachedData, '__GIT_COMMAND_FAILED__') removeGitFromPath() @@ -136,11 +137,11 @@ describe('git-cache integration tests', () => { secondError = error } - expect(secondError).to.be.an('error') - expect(secondError.message).to.equal(firstError.message) - expect(secondError.code).to.equal(firstError.code) - expect(secondError.status).to.equal(firstError.status) - expect(secondError.errno).to.equal(firstError.errno) + assert.ok(secondError instanceof Error) + assert.strictEqual(secondError.message, firstError.message) + assert.strictEqual(secondError.code, firstError.code) + assert.strictEqual(secondError.status, firstError.status) + assert.strictEqual(secondError.errno, firstError.errno) }) it('should not cache when DD_EXPERIMENTAL_TEST_OPT_GIT_CACHE_ENABLED is not set to true', function () { @@ -151,11 +152,11 @@ describe('git-cache integration tests', () => { const firstResult = disabledGitCache.cachedExec('git', GET_COMMIT_MESSAGE_COMMAND_ARGS) const firstResultStr = firstResult.toString().trim() - expect(firstResultStr).to.equal(FIXED_COMMIT_MESSAGE) + assert.strictEqual(firstResultStr, FIXED_COMMIT_MESSAGE) const cacheKey = disabledGitCache.getCacheKey('git', GET_COMMIT_MESSAGE_COMMAND_ARGS) const cacheFilePath = disabledGitCache.getCacheFilePath(cacheKey) - expect(fs.existsSync(cacheFilePath)).to.be.false + assert.strictEqual(fs.existsSync(cacheFilePath), false) removeGitFromPath() @@ -166,9 +167,9 @@ describe('git-cache integration tests', () => { secondError = error } - expect(secondError).to.be.an('error') - expect(secondError.code).to.equal('ENOENT') - expect(secondError.message).to.include('git') + assert.ok(secondError instanceof Error) + assert.strictEqual(secondError.code, 'ENOENT') + assertObjectContains(secondError.message, 'git') }) context('invalid DD_EXPERIMENTAL_TEST_OPT_GIT_CACHE_DIR', () => { @@ -180,11 +181,11 @@ describe('git-cache integration tests', () => { const firstResult = invalidDirGitCache.cachedExec('git', GET_COMMIT_MESSAGE_COMMAND_ARGS) const firstResultStr = firstResult.toString().trim() - expect(firstResultStr).to.equal(FIXED_COMMIT_MESSAGE) + assert.strictEqual(firstResultStr, FIXED_COMMIT_MESSAGE) const cacheKey = invalidDirGitCache.getCacheKey('git', GET_COMMIT_MESSAGE_COMMAND_ARGS) const cacheFilePath = invalidDirGitCache.getCacheFilePath(cacheKey) - expect(fs.existsSync(cacheFilePath)).to.be.false + assert.strictEqual(fs.existsSync(cacheFilePath), false) removeGitFromPath() @@ -195,9 +196,9 @@ describe('git-cache integration tests', () => { secondError = error } - expect(secondError).to.be.an('error') - expect(secondError.code).to.equal('ENOENT') - expect(secondError.message).to.include('git') + assert.ok(secondError instanceof Error) + assert.strictEqual(secondError.code, 'ENOENT') + assertObjectContains(secondError.message, 'git') } it('set to a file', () => { diff --git a/integration-tests/ci-visibility/jest-bad-import-torn-down/jest-bad-import-test-pass-2.js b/integration-tests/ci-visibility/jest-bad-import-torn-down/jest-bad-import-test-pass-2.js index c2b27bc2b49..e9fed73447e 100644 --- a/integration-tests/ci-visibility/jest-bad-import-torn-down/jest-bad-import-test-pass-2.js +++ b/integration-tests/ci-visibility/jest-bad-import-torn-down/jest-bad-import-test-pass-2.js @@ -1,5 +1,7 @@ 'use strict' +const assert = require('node:assert/strict') + it('works', () => { - expect(true).toBe(true) + assert.strictEqual(true, true) }) diff --git a/integration-tests/ci-visibility/jest-bad-import-torn-down/jest-bad-import-test-pass.js b/integration-tests/ci-visibility/jest-bad-import-torn-down/jest-bad-import-test-pass.js index c2b27bc2b49..e9fed73447e 100644 --- a/integration-tests/ci-visibility/jest-bad-import-torn-down/jest-bad-import-test-pass.js +++ b/integration-tests/ci-visibility/jest-bad-import-torn-down/jest-bad-import-test-pass.js @@ -1,5 +1,7 @@ 'use strict' +const assert = require('node:assert/strict') + it('works', () => { - expect(true).toBe(true) + assert.strictEqual(true, true) }) diff --git a/integration-tests/ci-visibility/jest-bad-import-torn-down/jest-bad-import-test.js b/integration-tests/ci-visibility/jest-bad-import-torn-down/jest-bad-import-test.js index f79ced29d1e..99898f15961 100644 --- a/integration-tests/ci-visibility/jest-bad-import-torn-down/jest-bad-import-test.js +++ b/integration-tests/ci-visibility/jest-bad-import-torn-down/jest-bad-import-test.js @@ -1,10 +1,12 @@ 'use strict' +const assert = require('node:assert/strict') + afterAll(() => { process.nextTick(() => { require('./off-timing-import.js') }) }) it('will fail', () => { - expect(true).toBe(true) + assert.strictEqual(true, true) }) diff --git a/integration-tests/ci-visibility/jest-bad-import/jest-bad-import-test-pass-2.js b/integration-tests/ci-visibility/jest-bad-import/jest-bad-import-test-pass-2.js index c2b27bc2b49..e9fed73447e 100644 --- a/integration-tests/ci-visibility/jest-bad-import/jest-bad-import-test-pass-2.js +++ b/integration-tests/ci-visibility/jest-bad-import/jest-bad-import-test-pass-2.js @@ -1,5 +1,7 @@ 'use strict' +const assert = require('node:assert/strict') + it('works', () => { - expect(true).toBe(true) + assert.strictEqual(true, true) }) diff --git a/integration-tests/ci-visibility/jest-bad-import/jest-bad-import-test-pass.js b/integration-tests/ci-visibility/jest-bad-import/jest-bad-import-test-pass.js index c2b27bc2b49..e9fed73447e 100644 --- a/integration-tests/ci-visibility/jest-bad-import/jest-bad-import-test-pass.js +++ b/integration-tests/ci-visibility/jest-bad-import/jest-bad-import-test-pass.js @@ -1,5 +1,7 @@ 'use strict' +const assert = require('node:assert/strict') + it('works', () => { - expect(true).toBe(true) + assert.strictEqual(true, true) }) diff --git a/integration-tests/ci-visibility/jest-bad-import/jest-bad-import-test.js b/integration-tests/ci-visibility/jest-bad-import/jest-bad-import-test.js index 6606a96cc54..dd2e858c9a3 100644 --- a/integration-tests/ci-visibility/jest-bad-import/jest-bad-import-test.js +++ b/integration-tests/ci-visibility/jest-bad-import/jest-bad-import-test.js @@ -1,9 +1,11 @@ 'use strict' +const assert = require('node:assert/strict') + it('will fail', () => { setTimeout(() => { const sum = require('./off-timing-import.js') - expect(sum(1, 2)).toBe(3) + assert.strictEqual(sum(1, 2), 3) }, 0) }) diff --git a/integration-tests/ci-visibility/jest-fast-check/jest-no-fast-check.js b/integration-tests/ci-visibility/jest-fast-check/jest-no-fast-check.js index d51323d6336..baee3d62949 100644 --- a/integration-tests/ci-visibility/jest-fast-check/jest-no-fast-check.js +++ b/integration-tests/ci-visibility/jest-fast-check/jest-no-fast-check.js @@ -1,7 +1,9 @@ 'use strict' +const assert = require('node:assert/strict') + describe('fast check with seed', () => { it('should include seed (with seed=12)', () => { - expect(1 + 2).toEqual(3) + assert.deepStrictEqual(1 + 2, 3) }) }) diff --git a/integration-tests/ci-visibility/jest-flaky/flaky-fails.js b/integration-tests/ci-visibility/jest-flaky/flaky-fails.js index 63bc4640188..c48bd85b369 100644 --- a/integration-tests/ci-visibility/jest-flaky/flaky-fails.js +++ b/integration-tests/ci-visibility/jest-flaky/flaky-fails.js @@ -1,7 +1,9 @@ 'use strict' +const assert = require('node:assert/strict') + describe('test-flaky-test-retries', () => { it('can retry failed tests', () => { - expect(1).toEqual(2) + assert.deepStrictEqual(1, 2) }) }) diff --git a/integration-tests/ci-visibility/jest-flaky/flaky-passes.js b/integration-tests/ci-visibility/jest-flaky/flaky-passes.js index e00c0c61762..3e08ee07a59 100644 --- a/integration-tests/ci-visibility/jest-flaky/flaky-passes.js +++ b/integration-tests/ci-visibility/jest-flaky/flaky-passes.js @@ -1,13 +1,15 @@ 'use strict' +const assert = require('node:assert/strict') + let counter = 0 describe('test-flaky-test-retries', () => { it('can retry flaky tests', () => { - expect(++counter).toEqual(3) + assert.deepStrictEqual(++counter, 3) }) it('will not retry passed tests', () => { - expect(3).toEqual(3) + assert.deepStrictEqual(3, 3) }) }) diff --git a/integration-tests/ci-visibility/jest-package-mock/non-dependency-mock-test-2.js b/integration-tests/ci-visibility/jest-package-mock/non-dependency-mock-test-2.js index 428151cac4f..5df557962c0 100644 --- a/integration-tests/ci-visibility/jest-package-mock/non-dependency-mock-test-2.js +++ b/integration-tests/ci-visibility/jest-package-mock/non-dependency-mock-test-2.js @@ -1,11 +1,13 @@ 'use strict' -// This is to check that the actual package is loaded, to make sure -// that the scenario is the same as the one that was failing. -// Doing it in one of the test suites is enough, as the failure was -// when calling jest.mock('some-package') +const assert = require('node:assert/strict') + + + + + const hello = jest.requireActual('some-package') test('hello function returns correct greeting', () => { - expect(hello()).toBe('Hello, world!') + assert.strictEqual(hello(), 'Hello, world!') }) diff --git a/integration-tests/ci-visibility/jest-package-mock/non-dependency-mock-test-3.js b/integration-tests/ci-visibility/jest-package-mock/non-dependency-mock-test-3.js index b4ce095d9bf..38c64e0f74e 100644 --- a/integration-tests/ci-visibility/jest-package-mock/non-dependency-mock-test-3.js +++ b/integration-tests/ci-visibility/jest-package-mock/non-dependency-mock-test-3.js @@ -1,7 +1,9 @@ 'use strict' +const assert = require('node:assert/strict') + const hello = require('some-package') test('hello function returns correct greeting', () => { - expect(hello()).toBe('Hello, mocked world!') + assert.strictEqual(hello(), 'Hello, mocked world!') }) diff --git a/integration-tests/ci-visibility/jest-package-mock/non-dependency-mock-test-4.js b/integration-tests/ci-visibility/jest-package-mock/non-dependency-mock-test-4.js index b4ce095d9bf..38c64e0f74e 100644 --- a/integration-tests/ci-visibility/jest-package-mock/non-dependency-mock-test-4.js +++ b/integration-tests/ci-visibility/jest-package-mock/non-dependency-mock-test-4.js @@ -1,7 +1,9 @@ 'use strict' +const assert = require('node:assert/strict') + const hello = require('some-package') test('hello function returns correct greeting', () => { - expect(hello()).toBe('Hello, mocked world!') + assert.strictEqual(hello(), 'Hello, mocked world!') }) diff --git a/integration-tests/ci-visibility/jest-package-mock/non-dependency-mock-test-5.js b/integration-tests/ci-visibility/jest-package-mock/non-dependency-mock-test-5.js index b4ce095d9bf..38c64e0f74e 100644 --- a/integration-tests/ci-visibility/jest-package-mock/non-dependency-mock-test-5.js +++ b/integration-tests/ci-visibility/jest-package-mock/non-dependency-mock-test-5.js @@ -1,7 +1,9 @@ 'use strict' +const assert = require('node:assert/strict') + const hello = require('some-package') test('hello function returns correct greeting', () => { - expect(hello()).toBe('Hello, mocked world!') + assert.strictEqual(hello(), 'Hello, mocked world!') }) diff --git a/integration-tests/ci-visibility/jest-package-mock/non-dependency-mock-test-6.js b/integration-tests/ci-visibility/jest-package-mock/non-dependency-mock-test-6.js index b4ce095d9bf..38c64e0f74e 100644 --- a/integration-tests/ci-visibility/jest-package-mock/non-dependency-mock-test-6.js +++ b/integration-tests/ci-visibility/jest-package-mock/non-dependency-mock-test-6.js @@ -1,7 +1,9 @@ 'use strict' +const assert = require('node:assert/strict') + const hello = require('some-package') test('hello function returns correct greeting', () => { - expect(hello()).toBe('Hello, mocked world!') + assert.strictEqual(hello(), 'Hello, mocked world!') }) diff --git a/integration-tests/ci-visibility/jest-package-mock/non-dependency-mock-test.js b/integration-tests/ci-visibility/jest-package-mock/non-dependency-mock-test.js index b4ce095d9bf..38c64e0f74e 100644 --- a/integration-tests/ci-visibility/jest-package-mock/non-dependency-mock-test.js +++ b/integration-tests/ci-visibility/jest-package-mock/non-dependency-mock-test.js @@ -1,7 +1,9 @@ 'use strict' +const assert = require('node:assert/strict') + const hello = require('some-package') test('hello function returns correct greeting', () => { - expect(hello()).toBe('Hello, mocked world!') + assert.strictEqual(hello(), 'Hello, mocked world!') }) diff --git a/integration-tests/ci-visibility/jest-plugin-tests/jest-inject-globals.js b/integration-tests/ci-visibility/jest-plugin-tests/jest-inject-globals.js index 99b14736416..04c7c72ca69 100644 --- a/integration-tests/ci-visibility/jest-plugin-tests/jest-inject-globals.js +++ b/integration-tests/ci-visibility/jest-plugin-tests/jest-inject-globals.js @@ -1,9 +1,11 @@ 'use strict' +const assert = require('node:assert/strict') + const { describe, it, expect } = require('@jest/globals') describe('jest-inject-globals', () => { it('will be run', () => { - expect(true).toEqual(true) + assert.deepStrictEqual(true, true) }) }) diff --git a/integration-tests/ci-visibility/jest-plugin-tests/jest-test.js b/integration-tests/ci-visibility/jest-plugin-tests/jest-test.js index 8046535038b..32a5f86d876 100644 --- a/integration-tests/ci-visibility/jest-plugin-tests/jest-test.js +++ b/integration-tests/ci-visibility/jest-plugin-tests/jest-test.js @@ -1,9 +1,11 @@ 'use strict' const http = require('http') +const assert = require('node:assert/strict') const tracer = require('dd-trace') + const ENDPOINT_URL = process.env.DD_CIVISIBILITY_AGENTLESS_URL || `http://127.0.0.1:${process.env.DD_TRACE_AGENT_PORT}` @@ -11,15 +13,15 @@ describe('jest-test-suite', () => { jest.setTimeout(400) it('tracer and active span are available', () => { - expect(global._ddtrace).not.toEqual(undefined) + assert.notDeepStrictEqual(global._ddtrace, undefined) const testSpan = tracer.scope().active() - expect(testSpan).not.toEqual(null) + assert.notDeepStrictEqual(testSpan, null) testSpan.setTag('test.add.stuff', 'stuff') }) it('done', (done) => { setTimeout(() => { - expect(100).toEqual(100) + assert.deepStrictEqual(100, 100) done() }, 50) }) @@ -27,7 +29,7 @@ describe('jest-test-suite', () => { it('done fail', (done) => { setTimeout(() => { try { - expect(100).toEqual(200) + assert.deepStrictEqual(100, 200) done() } catch (e) { done(e) @@ -37,14 +39,14 @@ describe('jest-test-suite', () => { it('done fail uncaught', (done) => { setTimeout(() => { - expect(100).toEqual(200) + assert.deepStrictEqual(100, 200) done() }, 50) }) it('can do integration http', (done) => { const req = http.request(`${ENDPOINT_URL}/info`, { agent: false }, (res) => { - expect(res.statusCode).toEqual(200) + assert.deepStrictEqual(res.statusCode, 200) done() }) req.end() @@ -53,17 +55,17 @@ describe('jest-test-suite', () => { if (jest.retryTimes) { const parameters = [[1, 2, 3], [2, 3, 5]] it.each(parameters)('can do parameterized test', (a, b, expected) => { - expect(a + b).toEqual(expected) + assert.deepStrictEqual(a + b, expected) // They are not modified by dd-trace reading the parameters - expect(parameters[0]).toEqual([1, 2, 3]) - expect(parameters[1]).toEqual([2, 3, 5]) + assert.deepStrictEqual(parameters[0], [1, 2, 3]) + assert.deepStrictEqual(parameters[1], [2, 3, 5]) }) } it('promise passes', () => { return new Promise((resolve) => setTimeout(() => { - expect(100).toEqual(100) + assert.deepStrictEqual(100, 100) resolve() }, 50) ) @@ -72,7 +74,7 @@ describe('jest-test-suite', () => { it('promise fails', () => { return new Promise((resolve) => setTimeout(() => { - expect(100).toEqual(200) + assert.deepStrictEqual(100, 200) resolve() }, 50) ) @@ -82,18 +84,18 @@ describe('jest-test-suite', () => { it('timeout', () => { return new Promise((resolve) => setTimeout(() => { - expect(100).toEqual(100) + assert.deepStrictEqual(100, 100) resolve() }, 300) ) }, 200) it('passes', () => { - expect(true).toEqual(true) + assert.deepStrictEqual(true, true) }) it('fails', () => { - expect(true).toEqual(false) + assert.deepStrictEqual(true, false) }) // eslint-disable-next-line mocha/handle-done-callback it('does not crash with missing stack', (done) => { @@ -105,7 +107,7 @@ describe('jest-test-suite', () => { }) it.skip('skips', () => { - expect(100).toEqual(100) + assert.deepStrictEqual(100, 100) }) it.todo('skips todo') }) @@ -117,7 +119,7 @@ if (jest.retryTimes) { let retryAttempt = 0 it('can retry', () => { - expect(retryAttempt++).toEqual(2) + assert.deepStrictEqual(retryAttempt++, 2) }) }) } diff --git a/integration-tests/ci-visibility/jest/failing-test.js b/integration-tests/ci-visibility/jest/failing-test.js index 9a9201fe1f7..6d713411836 100644 --- a/integration-tests/ci-visibility/jest/failing-test.js +++ b/integration-tests/ci-visibility/jest/failing-test.js @@ -1,13 +1,12 @@ 'use strict' -const { expect } = require('chai') - +const assert = require('node:assert/strict') describe('failing', () => { it.failing('can report failed tests', () => { - expect(1 + 2).to.equal(4) + assert.strictEqual(1 + 2, 4) }) it.failing('can report failing tests as failures', () => { - expect(1 + 2).to.equal(3) // this passes but it should fail! So the test.status should be fail + assert.strictEqual(1 + 2, 3) // this passes but it should fail! So the test.status should be fail }) }) diff --git a/integration-tests/ci-visibility/jest/mocked-test.js b/integration-tests/ci-visibility/jest/mocked-test.js index fbba0e62e1d..b3a5a2f0527 100644 --- a/integration-tests/ci-visibility/jest/mocked-test.js +++ b/integration-tests/ci-visibility/jest/mocked-test.js @@ -1,7 +1,9 @@ 'use strict' +const assert = require('node:assert/strict') + jest.mock('../test/sum.js') test('adds 1 + 2 to equal 3', () => { - expect(1 + 2).toBe(3) + assert.strictEqual(1 + 2, 3) }) diff --git a/integration-tests/ci-visibility/mocha-plugin-tests/active-span-hooks.js b/integration-tests/ci-visibility/mocha-plugin-tests/active-span-hooks.js index dccc56e256c..0e66b3a14c7 100644 --- a/integration-tests/ci-visibility/mocha-plugin-tests/active-span-hooks.js +++ b/integration-tests/ci-visibility/mocha-plugin-tests/active-span-hooks.js @@ -1,16 +1,15 @@ 'use strict' -const { expect } = require('chai') - +const assert = require('node:assert/strict') let currentTestTraceId describe('mocha-active-span-in-hooks', function () { before(() => { - expect(global._ddtrace.scope().active()).to.equal(null) + assert.strictEqual(global._ddtrace.scope().active(), null) }) after(() => { - expect(global._ddtrace.scope().active()).to.equal(null) + assert.strictEqual(global._ddtrace.scope().active(), null) }) beforeEach(() => { @@ -18,14 +17,14 @@ describe('mocha-active-span-in-hooks', function () { }) afterEach(() => { - expect(currentTestTraceId).to.equal(global._ddtrace.scope().active().context().toTraceId()) + assert.strictEqual(currentTestTraceId, global._ddtrace.scope().active().context().toTraceId()) }) it('first test', () => { - expect(currentTestTraceId).to.equal(global._ddtrace.scope().active().context().toTraceId()) + assert.strictEqual(currentTestTraceId, global._ddtrace.scope().active().context().toTraceId()) }) it('second test', () => { - expect(currentTestTraceId).to.equal(global._ddtrace.scope().active().context().toTraceId()) + assert.strictEqual(currentTestTraceId, global._ddtrace.scope().active().context().toTraceId()) }) }) diff --git a/integration-tests/ci-visibility/mocha-plugin-tests/async-fail.js b/integration-tests/ci-visibility/mocha-plugin-tests/async-fail.js index 88698671cef..8e0097eb5dc 100644 --- a/integration-tests/ci-visibility/mocha-plugin-tests/async-fail.js +++ b/integration-tests/ci-visibility/mocha-plugin-tests/async-fail.js @@ -1,12 +1,11 @@ 'use strict' -const { expect } = require('chai') - +const assert = require('node:assert/strict') describe('mocha-test-async-fail', () => { it('can do failed async tests', async () => { await new Promise(resolve => { setTimeout(resolve, 100) }) - expect(true).to.equal(false) + assert.strictEqual(true, false) }) }) diff --git a/integration-tests/ci-visibility/mocha-plugin-tests/async-pass.js b/integration-tests/ci-visibility/mocha-plugin-tests/async-pass.js index 8660312ac98..3841dfc62ff 100644 --- a/integration-tests/ci-visibility/mocha-plugin-tests/async-pass.js +++ b/integration-tests/ci-visibility/mocha-plugin-tests/async-pass.js @@ -1,12 +1,11 @@ 'use strict' -const { expect } = require('chai') - +const assert = require('node:assert/strict') describe('mocha-test-async-pass', () => { it('can do passed async tests', async () => { await new Promise(resolve => { setTimeout(resolve, 100) }) - expect(true).to.equal(true) + assert.strictEqual(true, true) }) }) diff --git a/integration-tests/ci-visibility/mocha-plugin-tests/done-fail-badly.js b/integration-tests/ci-visibility/mocha-plugin-tests/done-fail-badly.js index ae21c2b1358..ce43ce3e4c8 100644 --- a/integration-tests/ci-visibility/mocha-plugin-tests/done-fail-badly.js +++ b/integration-tests/ci-visibility/mocha-plugin-tests/done-fail-badly.js @@ -1,11 +1,10 @@ 'use strict' -const { expect } = require('chai') - +const assert = require('node:assert/strict') describe('mocha-test-done-fail', () => { it('can do badly setup failed tests with done', (done) => { setTimeout(() => { - expect(true).to.equal(false) + assert.strictEqual(true, false) done() }, 100) }) diff --git a/integration-tests/ci-visibility/mocha-plugin-tests/done-fail.js b/integration-tests/ci-visibility/mocha-plugin-tests/done-fail.js index 485875cfd6f..38b964bd8b7 100644 --- a/integration-tests/ci-visibility/mocha-plugin-tests/done-fail.js +++ b/integration-tests/ci-visibility/mocha-plugin-tests/done-fail.js @@ -1,12 +1,11 @@ 'use strict' -const { expect } = require('chai') - +const assert = require('node:assert/strict') describe('mocha-test-done-fail', () => { it('can do failed tests with done', (done) => { setTimeout(() => { try { - expect(true).to.equal(false) + assert.strictEqual(true, false) done() } catch (e) { done(e) diff --git a/integration-tests/ci-visibility/mocha-plugin-tests/done-pass.js b/integration-tests/ci-visibility/mocha-plugin-tests/done-pass.js index 6d3969526a0..edeb067654d 100644 --- a/integration-tests/ci-visibility/mocha-plugin-tests/done-pass.js +++ b/integration-tests/ci-visibility/mocha-plugin-tests/done-pass.js @@ -1,12 +1,11 @@ 'use strict' -const { expect } = require('chai') - +const assert = require('node:assert/strict') describe('mocha-test-done-pass', () => { it('can do passed tests with done', (done) => { setTimeout(() => { try { - expect(true).to.equal(true) + assert.strictEqual(true, true) done() } catch (e) { done(e) diff --git a/integration-tests/ci-visibility/mocha-plugin-tests/failing.js b/integration-tests/ci-visibility/mocha-plugin-tests/failing.js index 44247c88089..3a2261560a3 100644 --- a/integration-tests/ci-visibility/mocha-plugin-tests/failing.js +++ b/integration-tests/ci-visibility/mocha-plugin-tests/failing.js @@ -1,9 +1,8 @@ 'use strict' -const { expect } = require('chai') - +const assert = require('node:assert/strict') describe('mocha-test-fail', () => { it('can fail', () => { - expect(true).to.equal(false) + assert.strictEqual(true, false) }) }) diff --git a/integration-tests/ci-visibility/mocha-plugin-tests/hook-async-error.js b/integration-tests/ci-visibility/mocha-plugin-tests/hook-async-error.js index 2017fd3911b..44d7bfa872c 100644 --- a/integration-tests/ci-visibility/mocha-plugin-tests/hook-async-error.js +++ b/integration-tests/ci-visibility/mocha-plugin-tests/hook-async-error.js @@ -1,14 +1,13 @@ 'use strict' -const { expect } = require('chai') - +const assert = require('node:assert/strict') describe('mocha-fail-before-all', function () { before((done) => { done(new Error('this should not stop execution')) }) it('will not be reported because it will not run', () => { - expect(true).to.equal(true) + assert.strictEqual(true, true) }) }) @@ -20,7 +19,7 @@ describe('mocha-fail-hook-async', function () { }) it('will run but be reported as failed', () => { - expect(true).to.equal(true) + assert.strictEqual(true, true) }) }) @@ -30,7 +29,7 @@ describe('mocha-fail-hook-async-other', function () { }) it('will run and be reported as passed', () => { - expect(true).to.equal(true) + assert.strictEqual(true, true) }) }) @@ -42,7 +41,7 @@ describe('mocha-fail-hook-async-other-before', function () { }) it('will not run and be reported as failed', () => { - expect(true).to.equal(true) + assert.strictEqual(true, true) }) }) @@ -59,7 +58,7 @@ describe('mocha-fail-hook-async-other-second-after', function () { }) it('will run and be reported as failed', () => { - expect(true).to.equal(true) + assert.strictEqual(true, true) }) }) @@ -69,6 +68,6 @@ describe('mocha-fail-test-after-each-passes', function () { }) it('will fail and be reported as failed', () => { - expect(true).to.equal(false) + assert.strictEqual(true, false) }) }) diff --git a/integration-tests/ci-visibility/mocha-plugin-tests/hook-sync-error.js b/integration-tests/ci-visibility/mocha-plugin-tests/hook-sync-error.js index 928dac52896..fb531c43dca 100644 --- a/integration-tests/ci-visibility/mocha-plugin-tests/hook-sync-error.js +++ b/integration-tests/ci-visibility/mocha-plugin-tests/hook-sync-error.js @@ -1,7 +1,6 @@ 'use strict' -const { expect } = require('chai') - +const assert = require('node:assert/strict') describe('mocha-fail-hook-sync', () => { beforeEach(() => { const value = '' @@ -9,6 +8,6 @@ describe('mocha-fail-hook-sync', () => { }) it('will not run but be reported as failed', () => { - expect(true).to.equal(true) + assert.strictEqual(true, true) }) }) diff --git a/integration-tests/ci-visibility/mocha-plugin-tests/parameterized.js b/integration-tests/ci-visibility/mocha-plugin-tests/parameterized.js index e5b811007ac..8583c85e302 100644 --- a/integration-tests/ci-visibility/mocha-plugin-tests/parameterized.js +++ b/integration-tests/ci-visibility/mocha-plugin-tests/parameterized.js @@ -1,10 +1,10 @@ 'use strict' -const { expect } = require('chai') -const forEach = require('mocha-each') +const assert = require('node:assert/strict') +const forEach = require('mocha-each') describe('mocha-parameterized', () => { forEach([[1, 2, 3]]).it('can do parameterized', (left, right, expected) => { - expect(left + right).to.equal(expected) + assert.strictEqual(left + right, expected) }) }) diff --git a/integration-tests/ci-visibility/mocha-plugin-tests/passing.js b/integration-tests/ci-visibility/mocha-plugin-tests/passing.js index cd72b5e9244..6deddb9b28b 100644 --- a/integration-tests/ci-visibility/mocha-plugin-tests/passing.js +++ b/integration-tests/ci-visibility/mocha-plugin-tests/passing.js @@ -1,23 +1,22 @@ 'use strict' -const { expect } = require('chai') - +const assert = require('node:assert/strict') describe('mocha-test-pass', () => { it('can pass', () => { - expect(true).to.equal(true) + assert.strictEqual(true, true) }) it('can pass two', () => { - expect(true).to.equal(true) + assert.strictEqual(true, true) }) }) describe('mocha-test-pass-two', () => { it('can pass', () => { - expect(true).to.equal(true) + assert.strictEqual(true, true) }) it('can pass two', () => { - expect(true).to.equal(true) + assert.strictEqual(true, true) }) }) diff --git a/integration-tests/ci-visibility/mocha-plugin-tests/promise-fail.js b/integration-tests/ci-visibility/mocha-plugin-tests/promise-fail.js index 3da477c204d..f9cec459600 100644 --- a/integration-tests/ci-visibility/mocha-plugin-tests/promise-fail.js +++ b/integration-tests/ci-visibility/mocha-plugin-tests/promise-fail.js @@ -1,13 +1,12 @@ 'use strict' -const { expect } = require('chai') - +const assert = require('node:assert/strict') describe('mocha-test-promise-fail', () => { it('can do failed promise tests', () => { return new Promise((resolve, reject) => { setTimeout(() => { try { - expect(true).to.equal(false) + assert.strictEqual(true, false) resolve() } catch (e) { reject(e) diff --git a/integration-tests/ci-visibility/mocha-plugin-tests/promise-pass.js b/integration-tests/ci-visibility/mocha-plugin-tests/promise-pass.js index 4101e84a26b..e07d4c578ba 100644 --- a/integration-tests/ci-visibility/mocha-plugin-tests/promise-pass.js +++ b/integration-tests/ci-visibility/mocha-plugin-tests/promise-pass.js @@ -1,12 +1,11 @@ 'use strict' -const { expect } = require('chai') - +const assert = require('node:assert/strict') describe('mocha-test-promise-pass', () => { it('can do passed promise tests', () => { return new Promise((resolve) => { setTimeout(() => { - expect(true).to.equal(true) + assert.strictEqual(true, true) resolve() }, 100) }) diff --git a/integration-tests/ci-visibility/mocha-plugin-tests/retries.js b/integration-tests/ci-visibility/mocha-plugin-tests/retries.js index 330988323f8..dac3f6d39f3 100644 --- a/integration-tests/ci-visibility/mocha-plugin-tests/retries.js +++ b/integration-tests/ci-visibility/mocha-plugin-tests/retries.js @@ -1,17 +1,16 @@ 'use strict' -const { expect } = require('chai') - +const assert = require('node:assert/strict') let attempt = 0 describe('mocha-test-retries', function () { this.retries(4) it('will be retried and pass', () => { - expect(attempt++).to.equal(2) + assert.strictEqual(attempt++, 2) }) it('will be retried and fail', () => { - expect(attempt++).to.equal(8) + assert.strictEqual(attempt++, 8) }) }) diff --git a/integration-tests/ci-visibility/mocha-plugin-tests/skip-describe.js b/integration-tests/ci-visibility/mocha-plugin-tests/skip-describe.js index 5513c9c8087..07bd0f00098 100644 --- a/integration-tests/ci-visibility/mocha-plugin-tests/skip-describe.js +++ b/integration-tests/ci-visibility/mocha-plugin-tests/skip-describe.js @@ -1,19 +1,18 @@ 'use strict' -const { expect } = require('chai') - +const assert = require('node:assert/strict') describe('mocha-test-skip-describe', () => { before(function () { this.skip() }) it('will be skipped', () => { - expect(true).to.equal(true) + assert.strictEqual(true, true) }) }) describe('mocha-test-skip-describe-pass', () => { it('will pass', function () { - expect(true).to.equal(true) + assert.strictEqual(true, true) }) }) diff --git a/integration-tests/ci-visibility/mocha-plugin-tests/skipping.js b/integration-tests/ci-visibility/mocha-plugin-tests/skipping.js index 34cbcc1d549..edb63eee69b 100644 --- a/integration-tests/ci-visibility/mocha-plugin-tests/skipping.js +++ b/integration-tests/ci-visibility/mocha-plugin-tests/skipping.js @@ -1,20 +1,19 @@ 'use strict' -const { expect } = require('chai') - +const assert = require('node:assert/strict') describe('mocha-test-skip', () => { it.skip('can skip', () => { - expect(true).to.equal(false) + assert.strictEqual(true, false) }) }) describe('mocha-test-skip-different', () => { it.skip('can skip too', () => { - expect(true).to.equal(false) + assert.strictEqual(true, false) }) it.skip('can skip twice', () => { - expect(true).to.equal(false) + assert.strictEqual(true, false) }) }) diff --git a/integration-tests/ci-visibility/mocha-plugin-tests/suite-level-fail-after-each.js b/integration-tests/ci-visibility/mocha-plugin-tests/suite-level-fail-after-each.js index 5f8b4c11193..6523a9b0f11 100644 --- a/integration-tests/ci-visibility/mocha-plugin-tests/suite-level-fail-after-each.js +++ b/integration-tests/ci-visibility/mocha-plugin-tests/suite-level-fail-after-each.js @@ -1,10 +1,9 @@ 'use strict' -const { expect } = require('chai') - +const assert = require('node:assert/strict') describe('mocha-test-suite-level-pass', function () { it('will pass', () => { - expect(2).to.equal(2) + assert.strictEqual(2, 2) }) }) @@ -14,6 +13,6 @@ describe('mocha-test-suite-level-fail', function () { }) it('will pass', () => { - expect(2).to.equal(2) + assert.strictEqual(2, 2) }) }) diff --git a/integration-tests/ci-visibility/mocha-plugin-tests/suite-level-fail-skip-describe.js b/integration-tests/ci-visibility/mocha-plugin-tests/suite-level-fail-skip-describe.js index 08cb1479c90..7db8d7f5d69 100644 --- a/integration-tests/ci-visibility/mocha-plugin-tests/suite-level-fail-skip-describe.js +++ b/integration-tests/ci-visibility/mocha-plugin-tests/suite-level-fail-skip-describe.js @@ -1,23 +1,22 @@ 'use strict' -const { expect } = require('chai') - +const assert = require('node:assert/strict') describe('mocha-test-suite-level-fail', function () { it('will pass', () => { - expect(2).to.equal(2) + assert.strictEqual(2, 2) }) it('will fail', () => { - expect(2).to.equal(8) + assert.strictEqual(2, 8) }) }) describe.skip('mocha-test-suite-level-skip', function () { it('will pass', () => { - expect(2).to.equal(2) + assert.strictEqual(2, 2) }) it('will fail', () => { - expect(2).to.equal(8) + assert.strictEqual(2, 8) }) }) diff --git a/integration-tests/ci-visibility/mocha-plugin-tests/suite-level-fail-test.js b/integration-tests/ci-visibility/mocha-plugin-tests/suite-level-fail-test.js index 7d777cb5542..695533042c6 100644 --- a/integration-tests/ci-visibility/mocha-plugin-tests/suite-level-fail-test.js +++ b/integration-tests/ci-visibility/mocha-plugin-tests/suite-level-fail-test.js @@ -1,23 +1,22 @@ 'use strict' -const { expect } = require('chai') - +const assert = require('node:assert/strict') describe('mocha-test-suite-level-fail', function () { it('will pass', () => { - expect(2).to.equal(2) + assert.strictEqual(2, 2) }) it('will fail', () => { - expect(2).to.equal(8) + assert.strictEqual(2, 8) }) }) describe('mocha-test-suite-level-pass', function () { it('will pass', () => { - expect(2).to.equal(2) + assert.strictEqual(2, 2) }) it.skip('will skip', () => { - expect(2).to.equal(2) + assert.strictEqual(2, 2) }) }) diff --git a/integration-tests/ci-visibility/mocha-plugin-tests/suite-level-pass.js b/integration-tests/ci-visibility/mocha-plugin-tests/suite-level-pass.js index 716940e6069..bb0e389d1f1 100644 --- a/integration-tests/ci-visibility/mocha-plugin-tests/suite-level-pass.js +++ b/integration-tests/ci-visibility/mocha-plugin-tests/suite-level-pass.js @@ -1,19 +1,18 @@ 'use strict' -const { expect } = require('chai') - +const assert = require('node:assert/strict') describe('mocha-test-suite-level-fail', function () { it('will pass', () => { - expect(2).to.equal(2) + assert.strictEqual(2, 2) }) }) describe.skip('mocha-test-suite-level-skip', function () { it('will pass', () => { - expect(2).to.equal(2) + assert.strictEqual(2, 2) }) it('will fail', () => { - expect(2).to.equal(8) + assert.strictEqual(2, 8) }) }) diff --git a/integration-tests/ci-visibility/office-addin-mock/test.js b/integration-tests/ci-visibility/office-addin-mock/test.js index 5d40e2fad6f..0ec8218aff6 100644 --- a/integration-tests/ci-visibility/office-addin-mock/test.js +++ b/integration-tests/ci-visibility/office-addin-mock/test.js @@ -1,8 +1,8 @@ 'use strict' -const sum = require('./dependency') -const { expect } = require('chai') +const assert = require('node:assert/strict') +const sum = require('./dependency') test('can sum', () => { - expect(sum(1, 2)).to.equal(3) + assert.strictEqual(sum(1, 2), 3) }) diff --git a/integration-tests/ci-visibility/sharding-test/sharding-test-1.js b/integration-tests/ci-visibility/sharding-test/sharding-test-1.js index 0a26a920193..3490957122d 100644 --- a/integration-tests/ci-visibility/sharding-test/sharding-test-1.js +++ b/integration-tests/ci-visibility/sharding-test/sharding-test-1.js @@ -1,9 +1,8 @@ 'use strict' -const { expect } = require('chai') - +const assert = require('node:assert/strict') describe('sharding test 1', () => { it('can report tests', () => { - expect(1 + 2).to.equal(3) + assert.strictEqual(1 + 2, 3) }) }) diff --git a/integration-tests/ci-visibility/sharding-test/sharding-test-2.js b/integration-tests/ci-visibility/sharding-test/sharding-test-2.js index 2381beb5939..380a43db236 100644 --- a/integration-tests/ci-visibility/sharding-test/sharding-test-2.js +++ b/integration-tests/ci-visibility/sharding-test/sharding-test-2.js @@ -1,9 +1,8 @@ 'use strict' -const { expect } = require('chai') - +const assert = require('node:assert/strict') describe('sharding test 2', () => { it('can report tests', () => { - expect(1 + 2).to.equal(3) + assert.strictEqual(1 + 2, 3) }) }) diff --git a/integration-tests/ci-visibility/sharding-test/sharding-test-3.js b/integration-tests/ci-visibility/sharding-test/sharding-test-3.js index 60757fa3df9..e9219819fcc 100644 --- a/integration-tests/ci-visibility/sharding-test/sharding-test-3.js +++ b/integration-tests/ci-visibility/sharding-test/sharding-test-3.js @@ -1,9 +1,8 @@ 'use strict' -const { expect } = require('chai') - +const assert = require('node:assert/strict') describe('sharding test 3', () => { it('can report tests', () => { - expect(1 + 2).to.equal(3) + assert.strictEqual(1 + 2, 3) }) }) diff --git a/integration-tests/ci-visibility/sharding-test/sharding-test-4.js b/integration-tests/ci-visibility/sharding-test/sharding-test-4.js index 90330b62a74..e06bf5348bf 100644 --- a/integration-tests/ci-visibility/sharding-test/sharding-test-4.js +++ b/integration-tests/ci-visibility/sharding-test/sharding-test-4.js @@ -1,9 +1,8 @@ 'use strict' -const { expect } = require('chai') - +const assert = require('node:assert/strict') describe('sharding test 4', () => { it('can report tests', () => { - expect(1 + 2).to.equal(3) + assert.strictEqual(1 + 2, 3) }) }) diff --git a/integration-tests/ci-visibility/sharding-test/sharding-test-5.js b/integration-tests/ci-visibility/sharding-test/sharding-test-5.js index 4b56d06cd79..b8b39b175d7 100644 --- a/integration-tests/ci-visibility/sharding-test/sharding-test-5.js +++ b/integration-tests/ci-visibility/sharding-test/sharding-test-5.js @@ -1,9 +1,8 @@ 'use strict' -const { expect } = require('chai') - +const assert = require('node:assert/strict') describe('sharding test 5', () => { it('can report tests', () => { - expect(1 + 2).to.equal(3) + assert.strictEqual(1 + 2, 3) }) }) diff --git a/integration-tests/ci-visibility/subproject/subproject-test.js b/integration-tests/ci-visibility/subproject/subproject-test.js index 021028a4dbb..23a0dbb92eb 100644 --- a/integration-tests/ci-visibility/subproject/subproject-test.js +++ b/integration-tests/ci-visibility/subproject/subproject-test.js @@ -1,12 +1,13 @@ 'use strict' -// TODO: It shouldn't be necessary to disable n/no-extraneous-require - Research -// eslint-disable-next-line n/no-extraneous-require -const { expect } = require('chai') +const assert = require('node:assert/strict') + const dependency = require('./dependency') + + describe('subproject-test', () => { it('can run', () => { - expect(dependency(1, 2)).to.equal(3) + assert.strictEqual(dependency(1, 2), 3) }) }) diff --git a/integration-tests/ci-visibility/test-api-manual.spec.js b/integration-tests/ci-visibility/test-api-manual.spec.js index 46ecb2b02f9..4329b3cba54 100644 --- a/integration-tests/ci-visibility/test-api-manual.spec.js +++ b/integration-tests/ci-visibility/test-api-manual.spec.js @@ -1,9 +1,8 @@ 'use strict' -const { exec } = require('child_process') - -const { assert } = require('chai') +const assert = require('node:assert/strict') +const { exec } = require('child_process') const { sandboxCwd, useSandbox, @@ -54,10 +53,10 @@ describe('test-api-manual', () => { const passedTest = testEvents.find( test => test.content.resource === 'ci-visibility/test-api-manual/test.fake.js.first test will pass' ) - assert.propertyVal(passedTest.content.meta, 'test.custom.tag', 'custom.value') + assert.strictEqual(passedTest.content.meta['test.custom.tag'], 'custom.value') const customSpan = events.find(event => event.type === 'span') - assert.propertyVal(customSpan.content, 'resource', 'custom.span') + assert.strictEqual(customSpan.content['resource'], 'custom.span') }).catch(done) childProcess = exec( diff --git a/integration-tests/ci-visibility/test-custom-tags/custom-tags.js b/integration-tests/ci-visibility/test-custom-tags/custom-tags.js index c6a7d1a5bc7..0c81bacb762 100644 --- a/integration-tests/ci-visibility/test-custom-tags/custom-tags.js +++ b/integration-tests/ci-visibility/test-custom-tags/custom-tags.js @@ -1,9 +1,10 @@ 'use strict' -const { expect } = require('chai') -const sum = require('../test/sum') +const assert = require('node:assert/strict') + const tracer = require('dd-trace') +const sum = require('../test/sum') describe('test optimization custom tags', () => { beforeEach(() => { const testSpan = tracer.scope().active() @@ -13,7 +14,7 @@ describe('test optimization custom tags', () => { it('can report tests', () => { const testSpan = tracer.scope().active() testSpan.setTag('custom_tag.it', 'true') - expect(sum(1, 2)).to.equal(3) + assert.strictEqual(sum(1, 2), 3) }) afterEach(() => { diff --git a/integration-tests/ci-visibility/test-early-flake-detection/mocha-parameterized.js b/integration-tests/ci-visibility/test-early-flake-detection/mocha-parameterized.js index ed9f2c34a38..ad4698deb28 100644 --- a/integration-tests/ci-visibility/test-early-flake-detection/mocha-parameterized.js +++ b/integration-tests/ci-visibility/test-early-flake-detection/mocha-parameterized.js @@ -1,10 +1,10 @@ 'use strict' -const { expect } = require('chai') -const forEach = require('mocha-each') +const assert = require('node:assert/strict') +const forEach = require('mocha-each') describe('parameterized', () => { forEach(['parameter 1', 'parameter 2']).it('test %s', (value) => { - expect(value.startsWith('parameter')).to.be.true + assert.strictEqual(value.startsWith('parameter'), true) }) }) diff --git a/integration-tests/ci-visibility/test-early-flake-detection/occasionally-failing-test.js b/integration-tests/ci-visibility/test-early-flake-detection/occasionally-failing-test.js index e444b98034a..749ed6f238c 100644 --- a/integration-tests/ci-visibility/test-early-flake-detection/occasionally-failing-test.js +++ b/integration-tests/ci-visibility/test-early-flake-detection/occasionally-failing-test.js @@ -1,11 +1,10 @@ 'use strict' -const { expect } = require('chai') - +const assert = require('node:assert/strict') let globalCounter = 0 describe('fail', () => { it('occasionally fails', () => { - expect((globalCounter++) % 2).to.equal(0) + assert.strictEqual((globalCounter++) % 2, 0) }) }) diff --git a/integration-tests/ci-visibility/test-early-flake-detection/skipped-and-todo-test.js b/integration-tests/ci-visibility/test-early-flake-detection/skipped-and-todo-test.js index 395dfd2ef66..f4783e4e901 100644 --- a/integration-tests/ci-visibility/test-early-flake-detection/skipped-and-todo-test.js +++ b/integration-tests/ci-visibility/test-early-flake-detection/skipped-and-todo-test.js @@ -1,10 +1,9 @@ 'use strict' -const { expect } = require('chai') - +const assert = require('node:assert/strict') describe('ci visibility', () => { it('can report tests', () => { - expect(1 + 2).to.equal(3) + assert.strictEqual(1 + 2, 3) }) // only run for jest tests if (typeof jest !== 'undefined') { @@ -12,6 +11,6 @@ describe('ci visibility', () => { } it.skip('skip will not be retried', () => { - expect(1 + 2).to.equal(4) + assert.strictEqual(1 + 2, 4) }) }) diff --git a/integration-tests/ci-visibility/test-early-flake-detection/test-parameterized.js b/integration-tests/ci-visibility/test-early-flake-detection/test-parameterized.js index 0c95a1a57b3..a4d3099f719 100644 --- a/integration-tests/ci-visibility/test-early-flake-detection/test-parameterized.js +++ b/integration-tests/ci-visibility/test-early-flake-detection/test-parameterized.js @@ -1,9 +1,8 @@ 'use strict' -const { expect } = require('chai') - +const assert = require('node:assert/strict') describe('parameterized', () => { test.each(['parameter 1', 'parameter 2'])('test %s', (value) => { - expect(value.startsWith('parameter')).toEqual(true) + assert.deepStrictEqual(value.startsWith('parameter'), true) }) }) diff --git a/integration-tests/ci-visibility/test-early-flake-detection/test.js b/integration-tests/ci-visibility/test-early-flake-detection/test.js index 3a708c06b8f..53de41a3938 100644 --- a/integration-tests/ci-visibility/test-early-flake-detection/test.js +++ b/integration-tests/ci-visibility/test-early-flake-detection/test.js @@ -1,9 +1,8 @@ 'use strict' -const { expect } = require('chai') - +const assert = require('node:assert/strict') describe('ci visibility', () => { it('can report tests', () => { - expect(1 + 2).to.equal(3) + assert.strictEqual(1 + 2, 3) }) }) diff --git a/integration-tests/ci-visibility/test-early-flake-detection/weird-test-names.js b/integration-tests/ci-visibility/test-early-flake-detection/weird-test-names.js index 755dff5c50d..4dd562db02f 100644 --- a/integration-tests/ci-visibility/test-early-flake-detection/weird-test-names.js +++ b/integration-tests/ci-visibility/test-early-flake-detection/weird-test-names.js @@ -1,13 +1,12 @@ 'use strict' -const { expect } = require('chai') - +const assert = require('node:assert/strict') it('no describe can do stuff', () => { - expect(1).to.equal(1) + assert.strictEqual(1, 1) }) describe('describe ', () => { it('trailing space ', () => { - expect(1).to.equal(1) + assert.strictEqual(1, 1) }) }) diff --git a/integration-tests/ci-visibility/test-flaky-test-retries/eventually-passing-test.js b/integration-tests/ci-visibility/test-flaky-test-retries/eventually-passing-test.js index e4c3b90f2e1..bc0d02b7df2 100644 --- a/integration-tests/ci-visibility/test-flaky-test-retries/eventually-passing-test.js +++ b/integration-tests/ci-visibility/test-flaky-test-retries/eventually-passing-test.js @@ -1,11 +1,10 @@ 'use strict' -const { expect } = require('chai') - +const assert = require('node:assert/strict') let counter = 0 describe('test-flaky-test-retries', () => { it('can retry failed tests', () => { - expect(++counter).to.equal(3) + assert.strictEqual(++counter, 3) }) }) diff --git a/integration-tests/ci-visibility/test-impacted-test/test-impacted-1.js b/integration-tests/ci-visibility/test-impacted-test/test-impacted-1.js index 5a696c4f0cb..783efc7bc2b 100644 --- a/integration-tests/ci-visibility/test-impacted-test/test-impacted-1.js +++ b/integration-tests/ci-visibility/test-impacted-test/test-impacted-1.js @@ -1,13 +1,12 @@ 'use strict' -const { expect } = require('chai') - +const assert = require('node:assert/strict') describe('impacted tests', () => { it('can pass normally', () => { - expect(1 + 2).to.equal(3) + assert.strictEqual(1 + 2, 3) }) it('can fail', () => { - expect(1 + 2).to.equal(4) + assert.strictEqual(1 + 2, 4) }) }) diff --git a/integration-tests/ci-visibility/test-impacted-test/test-impacted-2.js b/integration-tests/ci-visibility/test-impacted-test/test-impacted-2.js index aadc8ae4272..8d510c8ce75 100644 --- a/integration-tests/ci-visibility/test-impacted-test/test-impacted-2.js +++ b/integration-tests/ci-visibility/test-impacted-test/test-impacted-2.js @@ -1,13 +1,12 @@ 'use strict' -const { expect } = require('chai') - +const assert = require('node:assert/strict') describe('impacted tests 2', () => { it('can pass normally', () => { - expect(1 + 2).to.equal(3) + assert.strictEqual(1 + 2, 3) }) it('can fail', () => { - expect(1 + 2).to.equal(4) + assert.strictEqual(1 + 2, 4) }) }) diff --git a/integration-tests/ci-visibility/test-management/test-attempt-to-fix-1.js b/integration-tests/ci-visibility/test-management/test-attempt-to-fix-1.js index f6f1d0585da..36ff9c5cd80 100644 --- a/integration-tests/ci-visibility/test-management/test-attempt-to-fix-1.js +++ b/integration-tests/ci-visibility/test-management/test-attempt-to-fix-1.js @@ -1,7 +1,6 @@ 'use strict' -const { expect } = require('chai') - +const assert = require('node:assert/strict') let numAttempts = 0 describe('attempt to fix tests', () => { @@ -9,15 +8,15 @@ describe('attempt to fix tests', () => { // eslint-disable-next-line no-console console.log('I am running when attempt to fix') // to check if this is being run if (process.env.SHOULD_ALWAYS_PASS) { - expect(1 + 2).to.equal(3) + assert.strictEqual(1 + 2, 3) } else if (process.env.SHOULD_FAIL_SOMETIMES) { if (numAttempts++ % 2 === 0) { - expect(1 + 2).to.equal(3) + assert.strictEqual(1 + 2, 3) } else { - expect(1 + 2).to.equal(4) + assert.strictEqual(1 + 2, 4) } } else { - expect(1 + 2).to.equal(4) + assert.strictEqual(1 + 2, 4) } }) }) diff --git a/integration-tests/ci-visibility/test-management/test-attempt-to-fix-2.js b/integration-tests/ci-visibility/test-management/test-attempt-to-fix-2.js index cb3a60f8ade..a2a7920c9b2 100644 --- a/integration-tests/ci-visibility/test-management/test-attempt-to-fix-2.js +++ b/integration-tests/ci-visibility/test-management/test-attempt-to-fix-2.js @@ -1,11 +1,10 @@ 'use strict' -const { expect } = require('chai') - +const assert = require('node:assert/strict') describe('attempt to fix tests 2', () => { it('can attempt to fix a test', () => { // eslint-disable-next-line no-console console.log('I am running when attempt to fix 2') // to check if this is being run - expect(1 + 2).to.equal(3) + assert.strictEqual(1 + 2, 3) }) }) diff --git a/integration-tests/ci-visibility/test-management/test-disabled-1.js b/integration-tests/ci-visibility/test-management/test-disabled-1.js index 6a0dc33232f..3b7c8787a9d 100644 --- a/integration-tests/ci-visibility/test-management/test-disabled-1.js +++ b/integration-tests/ci-visibility/test-management/test-disabled-1.js @@ -1,11 +1,10 @@ 'use strict' -const { expect } = require('chai') - +const assert = require('node:assert/strict') describe('disable tests', () => { it('can disable a test', () => { // eslint-disable-next-line no-console console.log('I am running') // to check if this is being run - expect(1 + 2).to.equal(4) + assert.strictEqual(1 + 2, 4) }) }) diff --git a/integration-tests/ci-visibility/test-management/test-disabled-2.js b/integration-tests/ci-visibility/test-management/test-disabled-2.js index 7435a1d2b10..643455b20a5 100644 --- a/integration-tests/ci-visibility/test-management/test-disabled-2.js +++ b/integration-tests/ci-visibility/test-management/test-disabled-2.js @@ -1,9 +1,8 @@ 'use strict' -const { expect } = require('chai') - +const assert = require('node:assert/strict') describe('disable tests 2', () => { it('can disable a test', () => { - expect(1 + 2).to.equal(3) + assert.strictEqual(1 + 2, 3) }) }) diff --git a/integration-tests/ci-visibility/test-management/test-quarantine-1.js b/integration-tests/ci-visibility/test-management/test-quarantine-1.js index 2ad8a7963e7..6971e33d5d3 100644 --- a/integration-tests/ci-visibility/test-management/test-quarantine-1.js +++ b/integration-tests/ci-visibility/test-management/test-quarantine-1.js @@ -1,15 +1,14 @@ 'use strict' -const { expect } = require('chai') - +const assert = require('node:assert/strict') describe('quarantine tests', () => { it('can quarantine a test', () => { // eslint-disable-next-line no-console console.log('I am running when quarantined') // to check if this is being run - expect(1 + 2).to.equal(4) + assert.strictEqual(1 + 2, 4) }) it('can pass normally', () => { - expect(1 + 2).to.equal(3) + assert.strictEqual(1 + 2, 3) }) }) diff --git a/integration-tests/ci-visibility/test-management/test-quarantine-2.js b/integration-tests/ci-visibility/test-management/test-quarantine-2.js index 8d3816454d0..b6930c20262 100644 --- a/integration-tests/ci-visibility/test-management/test-quarantine-2.js +++ b/integration-tests/ci-visibility/test-management/test-quarantine-2.js @@ -1,13 +1,12 @@ 'use strict' -const { expect } = require('chai') - +const assert = require('node:assert/strict') describe('quarantine tests 2', () => { it('can quarantine a test', () => { - expect(1 + 2).to.equal(3) + assert.strictEqual(1 + 2, 3) }) it('can pass normally', () => { - expect(1 + 2).to.equal(3) + assert.strictEqual(1 + 2, 3) }) }) diff --git a/integration-tests/ci-visibility/test-nested-hooks/test-nested-hooks.js b/integration-tests/ci-visibility/test-nested-hooks/test-nested-hooks.js index 2bcfa0b7f65..6ebc7f67876 100644 --- a/integration-tests/ci-visibility/test-nested-hooks/test-nested-hooks.js +++ b/integration-tests/ci-visibility/test-nested-hooks/test-nested-hooks.js @@ -1,7 +1,6 @@ 'use strict' -const { expect } = require('chai') - +const assert = require('node:assert/strict') let globalAttempts = 0 describe('describe', function () { @@ -21,7 +20,7 @@ describe('describe', function () { // eslint-disable-next-line no-console console.log('is not nested') try { - expect(process.env.SHOULD_FAIL ? globalAttempts++ : 1).to.equal(1) + assert.strictEqual(process.env.SHOULD_FAIL ? globalAttempts++ : 1, 1) done() } catch (error) { done(error) @@ -42,7 +41,7 @@ describe('describe', function () { it('nested test with retries', function () { // eslint-disable-next-line no-console console.log('nested test with retries') - expect(0).to.equal(0) + assert.strictEqual(0, 0) }) }) }) diff --git a/integration-tests/ci-visibility/test-optimization-startup.spec.js b/integration-tests/ci-visibility/test-optimization-startup.spec.js index ce3fc51b7ce..8d0ac6f5474 100644 --- a/integration-tests/ci-visibility/test-optimization-startup.spec.js +++ b/integration-tests/ci-visibility/test-optimization-startup.spec.js @@ -1,10 +1,9 @@ 'use strict' +const assert = require('node:assert/strict') + const { exec } = require('child_process') const { once } = require('events') - -const { assert } = require('chai') - const { sandboxCwd, useSandbox } = require('../helpers') const { FakeCiVisIntake } = require('../ci-visibility-intake') @@ -56,7 +55,7 @@ describe('test optimization startup', () => { once(childProcess.stderr, 'end') ]) - assert.include(processOutput, 'dd-trace is not initialized in a package manager') + assert.ok(processOutput.includes('dd-trace is not initialized in a package manager')) }) }) @@ -86,8 +85,8 @@ describe('test optimization startup', () => { once(childProcess.stderr, 'end') ]) - assert.include(processOutput, 'hello!') - assert.notInclude(processOutput, 'dd-trace is not initialized in a package manager') + assert.ok(processOutput.includes('hello!')) + assert.ok(!processOutput.includes('dd-trace is not initialized in a package manager')) }) it('fails if DD_API_KEY is not set when in a non test worker', async () => { @@ -117,8 +116,8 @@ describe('test optimization startup', () => { once(childProcess.stderr, 'end') ]) - assert.include(processOutput, 'hello!') - assert.include(processOutput, 'dd-trace will not be initialized') + assert.ok(processOutput.includes('hello!')) + assert.ok(processOutput.includes('dd-trace will not be initialized')) }) it('does not fail if DD_API_KEY is not set when in a test worker', async () => { @@ -149,7 +148,7 @@ describe('test optimization startup', () => { once(childProcess.stderr, 'end') ]) - assert.include(processOutput, 'hello!') - assert.notInclude(processOutput, 'dd-trace will not be initialized') + assert.ok(processOutput.includes('hello!')) + assert.ok(!processOutput.includes('dd-trace will not be initialized')) }) }) diff --git a/integration-tests/ci-visibility/test-optimization-wrong-init-cucumber/support/steps.js b/integration-tests/ci-visibility/test-optimization-wrong-init-cucumber/support/steps.js index aeb2afcde3d..60ca39f6327 100644 --- a/integration-tests/ci-visibility/test-optimization-wrong-init-cucumber/support/steps.js +++ b/integration-tests/ci-visibility/test-optimization-wrong-init-cucumber/support/steps.js @@ -1,9 +1,9 @@ 'use strict' -const tracer = require('dd-trace') -const { Given, When, Then } = require('@cucumber/cucumber') -const { expect } = require('chai') +const assert = require('node:assert/strict') +const { Given, When, Then } = require('@cucumber/cucumber') +const tracer = require('dd-trace') let num1, num2, result Given('I have two numbers {int} and {int}', function (first, second) { @@ -17,5 +17,5 @@ When('I add them together', function () { }) Then('the result should be {int}', function (expected) { - expect(result).to.equal(expected) + assert.strictEqual(result, expected) }) diff --git a/integration-tests/ci-visibility/test-parsing-error/parsing-error-2.js b/integration-tests/ci-visibility/test-parsing-error/parsing-error-2.js index bb43f645de4..b55bb87eb6f 100644 --- a/integration-tests/ci-visibility/test-parsing-error/parsing-error-2.js +++ b/integration-tests/ci-visibility/test-parsing-error/parsing-error-2.js @@ -1,9 +1,11 @@ 'use strict' +const assert = require('node:assert/strict') + const { expect } = require('chao') describe('test-parsing-error-2', () => { it('can report tests', () => { - expect(1 + 2).to.equal(3) + assert.strictEqual(1 + 2, 3) }) }) diff --git a/integration-tests/ci-visibility/test-parsing-error/parsing-error.js b/integration-tests/ci-visibility/test-parsing-error/parsing-error.js index 9ede9a25a37..f7d79b911ed 100644 --- a/integration-tests/ci-visibility/test-parsing-error/parsing-error.js +++ b/integration-tests/ci-visibility/test-parsing-error/parsing-error.js @@ -1,9 +1,11 @@ 'use strict' +const assert = require('node:assert/strict') + const { expect } = require('chao') describe('test-parsing-error', () => { it('can report tests', () => { - expect(1 + 2).to.equal(3) + assert.strictEqual(1 + 2, 3) }) }) diff --git a/integration-tests/ci-visibility/test-total-code-coverage/test-run.js b/integration-tests/ci-visibility/test-total-code-coverage/test-run.js index 6b6d2b5a4eb..838710a2449 100644 --- a/integration-tests/ci-visibility/test-total-code-coverage/test-run.js +++ b/integration-tests/ci-visibility/test-total-code-coverage/test-run.js @@ -1,10 +1,10 @@ 'use strict' -const { expect } = require('chai') -const sum = require('./used-dependency') +const assert = require('node:assert/strict') +const sum = require('./used-dependency') describe('test-run', () => { it('can report tests', () => { - expect(sum(1, 2)).to.equal(3) + assert.strictEqual(sum(1, 2), 3) }) }) diff --git a/integration-tests/ci-visibility/test-total-code-coverage/test-skipped.js b/integration-tests/ci-visibility/test-total-code-coverage/test-skipped.js index 3367eab54e0..9fcc000c82a 100644 --- a/integration-tests/ci-visibility/test-total-code-coverage/test-skipped.js +++ b/integration-tests/ci-visibility/test-total-code-coverage/test-skipped.js @@ -1,10 +1,10 @@ 'use strict' -const { expect } = require('chai') -const sum = require('./unused-dependency') +const assert = require('node:assert/strict') +const sum = require('./unused-dependency') describe('test-skipped', () => { it('can report tests', () => { - expect(sum(1, 2)).to.equal(3) + assert.strictEqual(sum(1, 2), 3) }) }) diff --git a/integration-tests/ci-visibility/test/ci-visibility-test-2.js b/integration-tests/ci-visibility/test/ci-visibility-test-2.js index f6edf100993..527690a12ce 100644 --- a/integration-tests/ci-visibility/test/ci-visibility-test-2.js +++ b/integration-tests/ci-visibility/test/ci-visibility-test-2.js @@ -1,10 +1,10 @@ 'use strict' -const { expect } = require('chai') -const sum = require('./sum') +const assert = require('node:assert/strict') +const sum = require('./sum') describe('ci visibility 2', () => { it('can report tests 2', () => { - expect(sum(1, 2)).to.equal(3) + assert.strictEqual(sum(1, 2), 3) }) }) diff --git a/integration-tests/ci-visibility/test/ci-visibility-test.js b/integration-tests/ci-visibility/test/ci-visibility-test.js index 9ce350498f9..0790a04acb8 100644 --- a/integration-tests/ci-visibility/test/ci-visibility-test.js +++ b/integration-tests/ci-visibility/test/ci-visibility-test.js @@ -1,10 +1,10 @@ 'use strict' -const { expect } = require('chai') -const sum = require('./sum') +const assert = require('node:assert/strict') +const sum = require('./sum') describe('ci visibility', () => { it('can report tests', () => { - expect(sum(1, 2)).to.equal(3) + assert.strictEqual(sum(1, 2), 3) }) }) diff --git a/integration-tests/ci-visibility/test/efd-parallel/ci-visibility-test-2.js b/integration-tests/ci-visibility/test/efd-parallel/ci-visibility-test-2.js index 2bbefae4ef0..8420b7d71ac 100644 --- a/integration-tests/ci-visibility/test/efd-parallel/ci-visibility-test-2.js +++ b/integration-tests/ci-visibility/test/efd-parallel/ci-visibility-test-2.js @@ -1,9 +1,11 @@ 'use strict' +const assert = require('node:assert/strict') + const sum = require('../sum') describe('ci visibility 2', () => { it('can report tests 2', () => { - expect(sum(1, 2)).toEqual(3) + assert.deepStrictEqual(sum(1, 2), 3) }) }) diff --git a/integration-tests/ci-visibility/test/efd-parallel/ci-visibility-test-3.js b/integration-tests/ci-visibility/test/efd-parallel/ci-visibility-test-3.js index e904010e679..18e3f89b90a 100644 --- a/integration-tests/ci-visibility/test/efd-parallel/ci-visibility-test-3.js +++ b/integration-tests/ci-visibility/test/efd-parallel/ci-visibility-test-3.js @@ -1,9 +1,11 @@ 'use strict' +const assert = require('node:assert/strict') + const sum = require('../sum') describe('ci visibility 3', () => { it('can report tests 3', () => { - expect(sum(1, 2)).toEqual(3) + assert.deepStrictEqual(sum(1, 2), 3) }) }) diff --git a/integration-tests/ci-visibility/test/efd-parallel/ci-visibility-test-4.js b/integration-tests/ci-visibility/test/efd-parallel/ci-visibility-test-4.js index 6d282bfd992..577be5b6557 100644 --- a/integration-tests/ci-visibility/test/efd-parallel/ci-visibility-test-4.js +++ b/integration-tests/ci-visibility/test/efd-parallel/ci-visibility-test-4.js @@ -1,9 +1,11 @@ 'use strict' +const assert = require('node:assert/strict') + const sum = require('../sum') describe('ci visibility 4', () => { it('can report tests 4', () => { - expect(sum(1, 2)).toEqual(3) + assert.deepStrictEqual(sum(1, 2), 3) }) }) diff --git a/integration-tests/ci-visibility/test/efd-parallel/ci-visibility-test.js b/integration-tests/ci-visibility/test/efd-parallel/ci-visibility-test.js index fba87f0ea98..b192019d261 100644 --- a/integration-tests/ci-visibility/test/efd-parallel/ci-visibility-test.js +++ b/integration-tests/ci-visibility/test/efd-parallel/ci-visibility-test.js @@ -1,9 +1,11 @@ 'use strict' +const assert = require('node:assert/strict') + const sum = require('../sum') describe('ci visibility', () => { it('can report tests', () => { - expect(sum(1, 2)).toEqual(3) + assert.deepStrictEqual(sum(1, 2), 3) }) }) diff --git a/integration-tests/ci-visibility/test/fail-test.js b/integration-tests/ci-visibility/test/fail-test.js index c6be99aa6f3..c0fbfbf685a 100644 --- a/integration-tests/ci-visibility/test/fail-test.js +++ b/integration-tests/ci-visibility/test/fail-test.js @@ -1,9 +1,8 @@ 'use strict' -const { expect } = require('chai') - +const assert = require('node:assert/strict') describe('fail', () => { it('can report failed tests', () => { - expect(1 + 2).to.equal(4) + assert.strictEqual(1 + 2, 4) }) }) diff --git a/integration-tests/ci-visibility/test/selenium-test.js b/integration-tests/ci-visibility/test/selenium-test.js index 45a2bf00432..c0581fbbfae 100644 --- a/integration-tests/ci-visibility/test/selenium-test.js +++ b/integration-tests/ci-visibility/test/selenium-test.js @@ -1,9 +1,9 @@ 'use strict' +const assert = require('node:assert/strict') + const { By, Builder } = require('selenium-webdriver') const chrome = require('selenium-webdriver/chrome') -const { expect } = require('chai') - const options = new chrome.Options() options.addArguments('--headless') @@ -19,7 +19,7 @@ describe('selenium', function () { await driver.get(process.env.WEB_APP_URL) const title = await driver.getTitle() - expect(title).to.equal('Hello World') + assert.strictEqual(title, 'Hello World') await driver.manage().setTimeouts({ implicit: 500 }) @@ -27,7 +27,7 @@ describe('selenium', function () { const value = await helloWorld.getText() - expect(value).to.equal('Hello World') + assert.strictEqual(value, 'Hello World') }) afterEach(async () => await driver.quit()) diff --git a/integration-tests/ci-visibility/unskippable-test/test-to-run.js b/integration-tests/ci-visibility/unskippable-test/test-to-run.js index 40326d2276a..d20cf9e8cec 100644 --- a/integration-tests/ci-visibility/unskippable-test/test-to-run.js +++ b/integration-tests/ci-visibility/unskippable-test/test-to-run.js @@ -1,9 +1,8 @@ 'use strict' -const { expect } = require('chai') - +const assert = require('node:assert/strict') describe('test-to-run', () => { it('can report tests', () => { - expect(1 + 2).to.equal(3) + assert.strictEqual(1 + 2, 3) }) }) diff --git a/integration-tests/ci-visibility/unskippable-test/test-to-skip.js b/integration-tests/ci-visibility/unskippable-test/test-to-skip.js index 54223246967..ed28293926c 100644 --- a/integration-tests/ci-visibility/unskippable-test/test-to-skip.js +++ b/integration-tests/ci-visibility/unskippable-test/test-to-skip.js @@ -1,9 +1,8 @@ 'use strict' -const { expect } = require('chai') - +const assert = require('node:assert/strict') describe('test-to-skip', () => { it('can report tests', () => { - expect(1 + 2).to.equal(3) + assert.strictEqual(1 + 2, 3) }) }) diff --git a/integration-tests/ci-visibility/unskippable-test/test-unskippable.js b/integration-tests/ci-visibility/unskippable-test/test-unskippable.js index d52db2bd893..1dabec4d0cb 100644 --- a/integration-tests/ci-visibility/unskippable-test/test-unskippable.js +++ b/integration-tests/ci-visibility/unskippable-test/test-unskippable.js @@ -1,3 +1,5 @@ +const assert = require('node:assert/strict') + /** Some comment */ /* eslint-disable jsdoc/valid-types */ /** @@ -5,11 +7,8 @@ */ /* Some other comment */ 'use strict' - -const { expect } = require('chai') - describe('test-unskippable', () => { it('can report tests', () => { - expect(1 + 2).to.equal(3) + assert.strictEqual(1 + 2, 3) }) }) diff --git a/integration-tests/cucumber/cucumber.spec.js b/integration-tests/cucumber/cucumber.spec.js index 63defa591e7..e246e5b4675 100644 --- a/integration-tests/cucumber/cucumber.spec.js +++ b/integration-tests/cucumber/cucumber.spec.js @@ -1,11 +1,12 @@ 'use strict' +const assert = require('node:assert/strict') + const { once } = require('node:events') const { exec, execSync } = require('child_process') - -const { assert } = require('chai') const fs = require('fs') const path = require('path') +const { assertObjectContains } = require('../helpers') const { sandboxCwd, @@ -190,73 +191,57 @@ describe(`cucumber@${version} commonJS`, () => { testSpans.forEach(testSpan => { const testName = testSpan.meta[TEST_NAME] - assert.propertyVal(testSpan.meta, 'language', 'javascript') - assert.propertyVal(testSpan.meta, 'service', 'cucumber-test-service') + assert.strictEqual(testSpan.meta['language'], 'javascript') + assert.strictEqual(testSpan.meta['service'], 'cucumber-test-service') const { status } = testInfoByTestName[testName] - assert.propertyVal(testSpan.meta, TEST_STATUS, status, - `Expected status for ${testName} to be ${status}` - ) - assert.propertyVal(testSpan.meta, TEST_TYPE, 'test') - assert.propertyVal(testSpan.meta, TEST_FRAMEWORK, 'cucumber') - assert.propertyVal(testSpan.meta, ORIGIN_KEY, CI_APP_ORIGIN) - assert.propertyVal(testSpan.meta, COMPONENT, 'cucumber') - assert.propertyVal(testSpan.metrics, SAMPLING_PRIORITY, AUTO_KEEP) - assert.exists(testSpan.meta[TEST_FRAMEWORK_VERSION]) - assert.propertyVal( - testSpan.meta, - TEST_CODE_OWNERS, - JSON.stringify(['@datadog-dd-trace-js']) - ) - assert.propertyVal( - testSpan.meta, - TEST_SUITE, - 'ci-visibility/cucumber-plugin-tests/features/simple.feature' - ) - assert.propertyVal( - testSpan.meta, - TEST_SOURCE_FILE, - 'ci-visibility/cucumber-plugin-tests/features/simple.feature' - ) - assert.exists(testSpan.metrics[TEST_SOURCE_START]) - assert.equal(testSpan.type, 'test') - assert.equal(testSpan.name, 'cucumber.test') - assert.equal(testSpan.parent_id.toString(), '0') + assert.strictEqual(testSpan.meta[TEST_STATUS], status, + `Expected status for ${testName} to be ${status}`) + assert.strictEqual(testSpan.meta[TEST_TYPE], 'test') + assert.strictEqual(testSpan.meta[TEST_FRAMEWORK], 'cucumber') + assert.strictEqual(testSpan.meta[ORIGIN_KEY], CI_APP_ORIGIN) + assert.strictEqual(testSpan.meta[COMPONENT], 'cucumber') + assert.strictEqual(testSpan.metrics[SAMPLING_PRIORITY], AUTO_KEEP) + assert.ok(testSpan.meta[TEST_FRAMEWORK_VERSION] != null) + assert.strictEqual(testSpan.meta[TEST_CODE_OWNERS], JSON.stringify(['@datadog-dd-trace-js'])) + assert.strictEqual(testSpan.meta[TEST_SUITE], 'ci-visibility/cucumber-plugin-tests/features/simple.feature') + assert.strictEqual(testSpan.meta[TEST_SOURCE_FILE], 'ci-visibility/cucumber-plugin-tests/features/simple.feature') + assert.ok(testSpan.metrics[TEST_SOURCE_START] != null) + assert.strictEqual(testSpan.type, 'test') + assert.strictEqual(testSpan.name, 'cucumber.test') + assert.strictEqual(testSpan.parent_id.toString(), '0') if (testName === 'integration scenario') { const endpointUrl = envVars.DD_CIVISIBILITY_AGENTLESS_URL || `http://127.0.0.1:${envVars.DD_TRACE_AGENT_PORT}` const httpSpan = spans.find(span => span.name === 'http.request') - assert.propertyVal(httpSpan.meta, ORIGIN_KEY, CI_APP_ORIGIN, 'HTTP span should have the correct origin') - assert.propertyVal(httpSpan.meta, - 'http.url', - `${endpointUrl}/info`, - 'HTTP span should have the correct url' - ) + assert.strictEqual(httpSpan.meta[ORIGIN_KEY], CI_APP_ORIGIN, 'HTTP span should have the correct origin') + assert.strictEqual(httpSpan.meta['http.url'], `${endpointUrl}/info`, + 'HTTP span should have the correct url') const parentCucumberStep = spans.find(span => span.meta['cucumber.step'] === 'integration') - assert.equal(httpSpan.parent_id.toString(), parentCucumberStep.span_id.toString(), + assert.strictEqual(httpSpan.parent_id.toString(), parentCucumberStep.span_id.toString(), 'HTTP span should be child of the cucumber step span') } if (testName === 'not implemented scenario') { const notImplementedStepSpan = spans.find(span => span.meta['cucumber.step'] === 'not-implemented') - assert.propertyVal(notImplementedStepSpan.meta, TEST_SKIP_REASON, 'not implemented') + assert.strictEqual(notImplementedStepSpan.meta[TEST_SKIP_REASON], 'not implemented') } if (testName === 'fail scenario') { - assert.propertyVal(testSpan.meta, ERROR_TYPE, 'Error') + assert.strictEqual(testSpan.meta[ERROR_TYPE], 'Error') const errorMessage = testSpan.meta[ERROR_MESSAGE] - assert.include(errorMessage, 'AssertionError') - assert.include(errorMessage, 'datadog') - assert.include(errorMessage, 'godatad') - assert.exists(testSpan.meta[ERROR_STACK]) + assert.ok(errorMessage.includes('AssertionError')) + assert.ok(errorMessage.includes('datadog')) + assert.ok(errorMessage.includes('godatad')) + assert.ok(testSpan.meta[ERROR_STACK] != null) } if (testName === 'hooks fail') { - assert.propertyVal(testSpan.meta, ERROR_TYPE, 'Error') + assert.strictEqual(testSpan.meta[ERROR_TYPE], 'Error') const errorMessage = testSpan.meta[ERROR_MESSAGE] - assert.include(errorMessage, 'TypeError: Cannot set') - assert.include(errorMessage, 'of undefined') - assert.include(errorMessage, 'boom') - assert.exists(testSpan.meta[ERROR_STACK]) + assert.ok(errorMessage.includes('TypeError: Cannot set')) + assert.ok(errorMessage.includes('of undefined')) + assert.ok(errorMessage.includes('boom')) + assert.ok(testSpan.meta[ERROR_STACK] != null) } const testSteps = spans.filter( @@ -265,15 +250,11 @@ describe(`cucumber@${version} commonJS`, () => { const { steps } = testInfoByTestName[testName] steps.forEach(({ name, stepStatus }) => { const stepSpan = testSteps.find(span => span.meta['cucumber.step'] === name) - assert.exists(stepSpan, `Test ${testName} should have a step span for ${name}`) - assert.propertyVal( - stepSpan.meta, - 'step.status', - stepStatus, - `Test ${testName} should have step ${name} with status ${stepStatus}` - ) - assert.propertyVal(stepSpan.meta, COMPONENT, 'cucumber') - assert.notPropertyVal(stepSpan, 'type', 'test') + assert.ok(stepSpan != null) + assert.strictEqual(stepSpan.meta['step.status'], stepStatus, + `Test ${testName} should have step ${name} with status ${stepStatus}`) + assert.strictEqual(stepSpan.meta[COMPONENT], 'cucumber') + assert.notStrictEqual(stepSpan['type'], 'test') }) }) }) @@ -323,7 +304,7 @@ describe(`cucumber@${version} commonJS`, () => { const metadataDicts = payloads.flatMap(({ payload }) => payload.metadata) metadataDicts.forEach(metadata => { for (const testLevel of TEST_LEVEL_EVENT_TYPES) { - assert.equal(metadata[testLevel][TEST_SESSION_NAME], 'my-test-session') + assert.strictEqual(metadata[testLevel][TEST_SESSION_NAME], 'my-test-session') } }) @@ -340,25 +321,22 @@ describe(`cucumber@${version} commonJS`, () => { const { content: testModuleEventContent } = testModuleEvent if (runMode === 'parallel') { - assert.equal(testSessionEventContent.meta[CUCUMBER_IS_PARALLEL], 'true') + assert.strictEqual(testSessionEventContent.meta[CUCUMBER_IS_PARALLEL], 'true') } - assert.exists(testSessionEventContent.test_session_id) - assert.exists(testSessionEventContent.meta[TEST_COMMAND]) - assert.exists(testSessionEventContent.meta[TEST_TOOLCHAIN]) - assert.equal(testSessionEventContent.resource.startsWith('test_session.'), true) - assert.equal(testSessionEventContent.meta[TEST_STATUS], 'fail') - - assert.exists(testModuleEventContent.test_session_id) - assert.exists(testModuleEventContent.test_module_id) - assert.exists(testModuleEventContent.meta[TEST_COMMAND]) - assert.exists(testModuleEventContent.meta[TEST_MODULE]) - assert.equal(testModuleEventContent.resource.startsWith('test_module.'), true) - assert.equal(testModuleEventContent.meta[TEST_STATUS], 'fail') - assert.equal( - testModuleEventContent.test_session_id.toString(10), - testSessionEventContent.test_session_id.toString(10) - ) + assert.ok(testSessionEventContent.test_session_id != null) + assert.ok(testSessionEventContent.meta[TEST_COMMAND] != null) + assert.ok(testSessionEventContent.meta[TEST_TOOLCHAIN] != null) + assert.strictEqual(testSessionEventContent.resource.startsWith('test_session.'), true) + assert.strictEqual(testSessionEventContent.meta[TEST_STATUS], 'fail') + + assert.ok(testModuleEventContent.test_session_id != null) + assert.ok(testModuleEventContent.test_module_id != null) + assert.ok(testModuleEventContent.meta[TEST_COMMAND] != null) + assert.ok(testModuleEventContent.meta[TEST_MODULE] != null) + assert.strictEqual(testModuleEventContent.resource.startsWith('test_module.'), true) + assert.strictEqual(testModuleEventContent.meta[TEST_STATUS], 'fail') + assert.strictEqual(testModuleEventContent.test_session_id.toString(10), testSessionEventContent.test_session_id.toString(10)) assert.includeMembers(testSuiteEvents.map(suite => suite.content.resource), [ `test_suite.${featuresPath}farewell.feature`, @@ -378,14 +356,14 @@ describe(`cucumber@${version} commonJS`, () => { test_session_id: testSessionId } }) => { - assert.exists(meta[TEST_COMMAND]) - assert.exists(meta[TEST_MODULE]) - assert.exists(testSuiteId) - assert.equal(testModuleId.toString(10), testModuleEventContent.test_module_id.toString(10)) - assert.equal(testSessionId.toString(10), testSessionEventContent.test_session_id.toString(10)) - assert.isTrue(meta[TEST_SOURCE_FILE].startsWith(featuresPath)) - assert.equal(metrics[TEST_SOURCE_START], 1) - assert.exists(metrics[DD_HOST_CPU_COUNT]) + assert.ok(meta[TEST_COMMAND] != null) + assert.ok(meta[TEST_MODULE] != null) + assert.ok(testSuiteId != null) + assert.strictEqual(testModuleId.toString(10), testModuleEventContent.test_module_id.toString(10)) + assert.strictEqual(testSessionId.toString(10), testSessionEventContent.test_session_id.toString(10)) + assert.strictEqual(meta[TEST_SOURCE_FILE].startsWith(featuresPath), true) + assert.strictEqual(metrics[TEST_SOURCE_START], 1) + assert.ok(metrics[DD_HOST_CPU_COUNT] != null) }) assert.includeMembers(testEvents.map(test => test.content.resource), [ @@ -412,31 +390,31 @@ describe(`cucumber@${version} commonJS`, () => { test_session_id: testSessionId } }) => { - assert.exists(meta[TEST_COMMAND]) - assert.exists(meta[TEST_MODULE]) - assert.exists(testSuiteId) - assert.equal(testModuleId.toString(10), testModuleEventContent.test_module_id.toString(10)) - assert.equal(testSessionId.toString(10), testSessionEventContent.test_session_id.toString(10)) - assert.equal(meta[TEST_SOURCE_FILE].startsWith('ci-visibility/features'), true) - assert.equal(meta[DD_TEST_IS_USER_PROVIDED_SERVICE], 'false') + assert.ok(meta[TEST_COMMAND] != null) + assert.ok(meta[TEST_MODULE] != null) + assert.ok(testSuiteId != null) + assert.strictEqual(testModuleId.toString(10), testModuleEventContent.test_module_id.toString(10)) + assert.strictEqual(testSessionId.toString(10), testSessionEventContent.test_session_id.toString(10)) + assert.strictEqual(meta[TEST_SOURCE_FILE].startsWith('ci-visibility/features'), true) + assert.strictEqual(meta[DD_TEST_IS_USER_PROVIDED_SERVICE], 'false') // Can read DD_TAGS - assert.propertyVal(meta, 'test.customtag', 'customvalue') - assert.propertyVal(meta, 'test.customtag2', 'customvalue2') + assert.strictEqual(meta['test.customtag'], 'customvalue') + assert.strictEqual(meta['test.customtag2'], 'customvalue2') if (runMode === 'parallel') { - assert.propertyVal(meta, CUCUMBER_IS_PARALLEL, 'true') + assert.strictEqual(meta[CUCUMBER_IS_PARALLEL], 'true') } - assert.exists(metrics[DD_HOST_CPU_COUNT]) + assert.ok(metrics[DD_HOST_CPU_COUNT] != null) if (!meta[TEST_NAME].includes('Say skip')) { - assert.propertyVal(meta, 'custom_tag.before', 'hello before') - assert.propertyVal(meta, 'custom_tag.after', 'hello after') + assert.strictEqual(meta['custom_tag.before'], 'hello before') + assert.strictEqual(meta['custom_tag.after'], 'hello after') } }) stepEvents.forEach(stepEvent => { - assert.equal(stepEvent.content.name, 'cucumber.step') - assert.property(stepEvent.content.meta, 'cucumber.step') + assert.strictEqual(stepEvent.content.name, 'cucumber.step') + assert.ok(Object.hasOwn(stepEvent.content.meta, 'cucumber.step')) if (stepEvent.content.meta['cucumber.step'] === 'the greeter says greetings') { - assert.propertyVal(stepEvent.content.meta, 'custom_tag.when', 'hello when') + assert.strictEqual(stepEvent.content.meta['custom_tag.when'], 'hello when') } }) }, 5000) @@ -476,11 +454,11 @@ describe(`cucumber@${version} commonJS`, () => { eventsRequestPromise ]).then(([searchCommitRequest, packfileRequest, eventsRequest]) => { if (isAgentless) { - assert.propertyVal(searchCommitRequest.headers, 'dd-api-key', '1') - assert.propertyVal(packfileRequest.headers, 'dd-api-key', '1') + assert.strictEqual(searchCommitRequest.headers['dd-api-key'], '1') + assert.strictEqual(packfileRequest.headers['dd-api-key'], '1') } else { - assert.notProperty(searchCommitRequest.headers, 'dd-api-key') - assert.notProperty(packfileRequest.headers, 'dd-api-key') + assert.ok(!Object.hasOwn(searchCommitRequest.headers, 'dd-api-key')) + assert.ok(!Object.hasOwn(packfileRequest.headers, 'dd-api-key')) } const eventTypes = eventsRequest.payload.events.map(event => event.type) @@ -488,7 +466,7 @@ describe(`cucumber@${version} commonJS`, () => { const numSuites = eventTypes.reduce( (acc, type) => type === 'test_suite_end' ? acc + 1 : acc, 0 ) - assert.equal(numSuites, 2) + assert.strictEqual(numSuites, 2) done() }).catch(done) @@ -517,19 +495,19 @@ describe(`cucumber@${version} commonJS`, () => { ]).then(([libraryConfigRequest, codeCovRequest, eventsRequest]) => { const [coveragePayload] = codeCovRequest.payload if (isAgentless) { - assert.propertyVal(libraryConfigRequest.headers, 'dd-api-key', '1') - assert.propertyVal(codeCovRequest.headers, 'dd-api-key', '1') + assert.strictEqual(libraryConfigRequest.headers['dd-api-key'], '1') + assert.strictEqual(codeCovRequest.headers['dd-api-key'], '1') } else { - assert.notProperty(libraryConfigRequest.headers, 'dd-api-key') - assert.notProperty(codeCovRequest.headers, 'dd-api-key', '1') + assert.ok(!Object.hasOwn(libraryConfigRequest.headers, 'dd-api-key')) + assert.ok(!Object.hasOwn(codeCovRequest.headers, 'dd-api-key')) } - assert.propertyVal(coveragePayload, 'name', 'coverage1') - assert.propertyVal(coveragePayload, 'filename', 'coverage1.msgpack') - assert.propertyVal(coveragePayload, 'type', 'application/msgpack') - assert.include(coveragePayload.content, { + assert.strictEqual(coveragePayload['name'], 'coverage1') + assert.strictEqual(coveragePayload['filename'], 'coverage1.msgpack') + assert.strictEqual(coveragePayload['type'], 'application/msgpack') + assert.ok(coveragePayload.content.includes({ version: 2 - }) + })) const allCoverageFiles = codeCovRequest.payload .flatMap(coverage => coverage.content.coverages) .flatMap(file => file.files) @@ -541,26 +519,23 @@ describe(`cucumber@${version} commonJS`, () => { `${featuresPath}greetings.feature` ]) // steps is twice because there are two suites using it - assert.equal( - allCoverageFiles.filter(file => file === `${featuresPath}support/steps.${fileExtension}`).length, - 2 - ) - assert.exists(coveragePayload.content.coverages[0].test_session_id) - assert.exists(coveragePayload.content.coverages[0].test_suite_id) + assert.strictEqual(allCoverageFiles.filter(file => file === `${featuresPath}support/steps.${fileExtension}`).length, 2) + assert.ok(coveragePayload.content.coverages[0].test_session_id != null) + assert.ok(coveragePayload.content.coverages[0].test_suite_id != null) const testSession = eventsRequest .payload .events .find(event => event.type === 'test_session_end') .content - assert.exists(testSession.metrics[TEST_CODE_COVERAGE_LINES_PCT]) + assert.ok(testSession.metrics[TEST_CODE_COVERAGE_LINES_PCT] != null) const eventTypes = eventsRequest.payload.events.map(event => event.type) assert.includeMembers(eventTypes, ['test', 'test_suite_end', 'test_module_end', 'test_session_end']) const numSuites = eventTypes.reduce( (acc, type) => type === 'test_suite_end' ? acc + 1 : acc, 0 ) - assert.equal(numSuites, 2) + assert.strictEqual(numSuites, 2) }).catch(done) childProcess = exec( @@ -579,7 +554,7 @@ describe(`cucumber@${version} commonJS`, () => { }) childProcess.on('exit', () => { // check that reported coverage is still the same - assert.include(testOutput, 'Lines : 100%') + assert.ok(testOutput.includes('Lines : 100%')) done() }) }) @@ -600,14 +575,14 @@ describe(`cucumber@${version} commonJS`, () => { const eventTypes = payload.events.map(event => event.type) assert.includeMembers(eventTypes, ['test', 'test_session_end', 'test_module_end', 'test_suite_end']) const testSession = payload.events.find(event => event.type === 'test_session_end').content - assert.propertyVal(testSession.meta, TEST_ITR_TESTS_SKIPPED, 'false') - assert.propertyVal(testSession.meta, TEST_CODE_COVERAGE_ENABLED, 'false') - assert.propertyVal(testSession.meta, TEST_ITR_SKIPPING_ENABLED, 'false') - assert.exists(testSession.metrics[TEST_CODE_COVERAGE_LINES_PCT]) + assert.strictEqual(testSession.meta[TEST_ITR_TESTS_SKIPPED], 'false') + assert.strictEqual(testSession.meta[TEST_CODE_COVERAGE_ENABLED], 'false') + assert.strictEqual(testSession.meta[TEST_ITR_SKIPPING_ENABLED], 'false') + assert.ok(testSession.metrics[TEST_CODE_COVERAGE_LINES_PCT] != null) const testModule = payload.events.find(event => event.type === 'test_module_end').content - assert.propertyVal(testModule.meta, TEST_ITR_TESTS_SKIPPED, 'false') - assert.propertyVal(testModule.meta, TEST_CODE_COVERAGE_ENABLED, 'false') - assert.propertyVal(testModule.meta, TEST_ITR_SKIPPING_ENABLED, 'false') + assert.strictEqual(testModule.meta[TEST_ITR_TESTS_SKIPPED], 'false') + assert.strictEqual(testModule.meta[TEST_CODE_COVERAGE_ENABLED], 'false') + assert.strictEqual(testModule.meta[TEST_ITR_SKIPPING_ENABLED], 'false') }, ({ url }) => url.endsWith('/api/v2/citestcycle')).then(() => done()).catch(done) childProcess = exec( @@ -641,46 +616,46 @@ describe(`cucumber@${version} commonJS`, () => { ]).then(([skippableRequest, coverageRequest, eventsRequest]) => { const [coveragePayload] = coverageRequest.payload if (isAgentless) { - assert.propertyVal(skippableRequest.headers, 'dd-api-key', '1') - assert.propertyVal(coverageRequest.headers, 'dd-api-key', '1') - assert.propertyVal(eventsRequest.headers, 'dd-api-key', '1') + assert.strictEqual(skippableRequest.headers['dd-api-key'], '1') + assert.strictEqual(coverageRequest.headers['dd-api-key'], '1') + assert.strictEqual(eventsRequest.headers['dd-api-key'], '1') } else { - assert.notProperty(skippableRequest.headers, 'dd-api-key', '1') - assert.notProperty(coverageRequest.headers, 'dd-api-key', '1') - assert.notProperty(eventsRequest.headers, 'dd-api-key', '1') + assert.ok(!Object.hasOwn(skippableRequest.headers, 'dd-api-key')) + assert.ok(!Object.hasOwn(coverageRequest.headers, 'dd-api-key')) + assert.ok(!Object.hasOwn(eventsRequest.headers, 'dd-api-key')) } - assert.propertyVal(coveragePayload, 'name', 'coverage1') - assert.propertyVal(coveragePayload, 'filename', 'coverage1.msgpack') - assert.propertyVal(coveragePayload, 'type', 'application/msgpack') + assert.strictEqual(coveragePayload['name'], 'coverage1') + assert.strictEqual(coveragePayload['filename'], 'coverage1.msgpack') + assert.strictEqual(coveragePayload['type'], 'application/msgpack') const eventTypes = eventsRequest.payload.events.map(event => event.type) const skippedSuite = eventsRequest.payload.events.find(event => event.content.resource === `test_suite.${featuresPath}farewell.feature` ).content - assert.propertyVal(skippedSuite.meta, TEST_STATUS, 'skip') - assert.propertyVal(skippedSuite.meta, TEST_SKIPPED_BY_ITR, 'true') + assert.strictEqual(skippedSuite.meta[TEST_STATUS], 'skip') + assert.strictEqual(skippedSuite.meta[TEST_SKIPPED_BY_ITR], 'true') assert.includeMembers(eventTypes, ['test', 'test_suite_end', 'test_module_end', 'test_session_end']) const numSuites = eventTypes.reduce( (acc, type) => type === 'test_suite_end' ? acc + 1 : acc, 0 ) - assert.equal(numSuites, 2) + assert.strictEqual(numSuites, 2) const testSession = eventsRequest .payload.events.find(event => event.type === 'test_session_end').content - assert.propertyVal(testSession.meta, TEST_ITR_TESTS_SKIPPED, 'true') - assert.propertyVal(testSession.meta, TEST_CODE_COVERAGE_ENABLED, 'true') - assert.propertyVal(testSession.meta, TEST_ITR_SKIPPING_ENABLED, 'true') - assert.propertyVal(testSession.meta, TEST_ITR_SKIPPING_TYPE, 'suite') - assert.propertyVal(testSession.metrics, TEST_ITR_SKIPPING_COUNT, 1) + assert.strictEqual(testSession.meta[TEST_ITR_TESTS_SKIPPED], 'true') + assert.strictEqual(testSession.meta[TEST_CODE_COVERAGE_ENABLED], 'true') + assert.strictEqual(testSession.meta[TEST_ITR_SKIPPING_ENABLED], 'true') + assert.strictEqual(testSession.meta[TEST_ITR_SKIPPING_TYPE], 'suite') + assert.strictEqual(testSession.metrics[TEST_ITR_SKIPPING_COUNT], 1) const testModule = eventsRequest .payload.events.find(event => event.type === 'test_module_end').content - assert.propertyVal(testModule.meta, TEST_ITR_TESTS_SKIPPED, 'true') - assert.propertyVal(testModule.meta, TEST_CODE_COVERAGE_ENABLED, 'true') - assert.propertyVal(testModule.meta, TEST_ITR_SKIPPING_ENABLED, 'true') - assert.propertyVal(testModule.meta, TEST_ITR_SKIPPING_TYPE, 'suite') - assert.propertyVal(testModule.metrics, TEST_ITR_SKIPPING_COUNT, 1) + assert.strictEqual(testModule.meta[TEST_ITR_TESTS_SKIPPED], 'true') + assert.strictEqual(testModule.meta[TEST_CODE_COVERAGE_ENABLED], 'true') + assert.strictEqual(testModule.meta[TEST_ITR_SKIPPING_ENABLED], 'true') + assert.strictEqual(testModule.meta[TEST_ITR_SKIPPING_TYPE], 'suite') + assert.strictEqual(testModule.metrics[TEST_ITR_SKIPPING_COUNT], 1) done() }).catch(done) @@ -716,15 +691,15 @@ describe(`cucumber@${version} commonJS`, () => { const numSuites = eventTypes.reduce( (acc, type) => type === 'test_suite_end' ? acc + 1 : acc, 0 ) - assert.equal(numSuites, 2) + assert.strictEqual(numSuites, 2) const testSession = payload.events.find(event => event.type === 'test_session_end').content - assert.propertyVal(testSession.meta, TEST_ITR_TESTS_SKIPPED, 'false') - assert.propertyVal(testSession.meta, TEST_CODE_COVERAGE_ENABLED, 'true') - assert.propertyVal(testSession.meta, TEST_ITR_SKIPPING_ENABLED, 'true') + assert.strictEqual(testSession.meta[TEST_ITR_TESTS_SKIPPED], 'false') + assert.strictEqual(testSession.meta[TEST_CODE_COVERAGE_ENABLED], 'true') + assert.strictEqual(testSession.meta[TEST_ITR_SKIPPING_ENABLED], 'true') const testModule = payload.events.find(event => event.type === 'test_module_end').content - assert.propertyVal(testModule.meta, TEST_ITR_TESTS_SKIPPED, 'false') - assert.propertyVal(testModule.meta, TEST_CODE_COVERAGE_ENABLED, 'true') - assert.propertyVal(testModule.meta, TEST_ITR_SKIPPING_ENABLED, 'true') + assert.strictEqual(testModule.meta[TEST_ITR_TESTS_SKIPPED], 'false') + assert.strictEqual(testModule.meta[TEST_CODE_COVERAGE_ENABLED], 'true') + assert.strictEqual(testModule.meta[TEST_ITR_SKIPPING_ENABLED], 'true') }, ({ url }) => url.endsWith('/api/v2/citestcycle')).then(() => done()).catch(done) childProcess = exec( @@ -763,7 +738,7 @@ describe(`cucumber@${version} commonJS`, () => { const numSuites = eventTypes.reduce( (acc, type) => type === 'test_suite_end' ? acc + 1 : acc, 0 ) - assert.equal(numSuites, 2) + assert.strictEqual(numSuites, 2) }, ({ url }) => url.endsWith('/api/v2/citestcycle')).then(() => done()).catch(done) childProcess = exec( @@ -803,15 +778,15 @@ describe(`cucumber@${version} commonJS`, () => { const events = payloads.flatMap(({ payload }) => payload.events) const suites = events.filter(event => event.type === 'test_suite_end') - assert.equal(suites.length, 2) + assert.strictEqual(suites.length, 2) const testSession = events.find(event => event.type === 'test_session_end').content const testModule = events.find(event => event.type === 'test_session_end').content - assert.propertyVal(testSession.meta, TEST_ITR_UNSKIPPABLE, 'true') - assert.propertyVal(testSession.meta, TEST_ITR_FORCED_RUN, 'true') - assert.propertyVal(testModule.meta, TEST_ITR_UNSKIPPABLE, 'true') - assert.propertyVal(testModule.meta, TEST_ITR_FORCED_RUN, 'true') + assert.strictEqual(testSession.meta[TEST_ITR_UNSKIPPABLE], 'true') + assert.strictEqual(testSession.meta[TEST_ITR_FORCED_RUN], 'true') + assert.strictEqual(testModule.meta[TEST_ITR_UNSKIPPABLE], 'true') + assert.strictEqual(testModule.meta[TEST_ITR_FORCED_RUN], 'true') const skippedSuite = suites.find( event => event.content.resource === 'test_suite.ci-visibility/features/farewell.feature' @@ -820,13 +795,13 @@ describe(`cucumber@${version} commonJS`, () => { event => event.content.resource === 'test_suite.ci-visibility/features/greetings.feature' ).content - assert.propertyVal(skippedSuite.meta, TEST_STATUS, 'skip') - assert.notProperty(skippedSuite.meta, TEST_ITR_UNSKIPPABLE) - assert.notProperty(skippedSuite.meta, TEST_ITR_FORCED_RUN) + assert.strictEqual(skippedSuite.meta[TEST_STATUS], 'skip') + assert.ok(!Object.hasOwn(skippedSuite.meta, TEST_ITR_UNSKIPPABLE)) + assert.ok(!Object.hasOwn(skippedSuite.meta, TEST_ITR_FORCED_RUN)) - assert.propertyVal(forcedToRunSuite.meta, TEST_STATUS, 'fail') - assert.propertyVal(forcedToRunSuite.meta, TEST_ITR_UNSKIPPABLE, 'true') - assert.propertyVal(forcedToRunSuite.meta, TEST_ITR_FORCED_RUN, 'true') + assert.strictEqual(forcedToRunSuite.meta[TEST_STATUS], 'fail') + assert.strictEqual(forcedToRunSuite.meta[TEST_ITR_UNSKIPPABLE], 'true') + assert.strictEqual(forcedToRunSuite.meta[TEST_ITR_FORCED_RUN], 'true') }, 25000) childProcess = exec( @@ -866,15 +841,15 @@ describe(`cucumber@${version} commonJS`, () => { const events = payloads.flatMap(({ payload }) => payload.events) const suites = events.filter(event => event.type === 'test_suite_end') - assert.equal(suites.length, 2) + assert.strictEqual(suites.length, 2) const testSession = events.find(event => event.type === 'test_session_end').content const testModule = events.find(event => event.type === 'test_session_end').content - assert.propertyVal(testSession.meta, TEST_ITR_UNSKIPPABLE, 'true') - assert.notProperty(testSession.meta, TEST_ITR_FORCED_RUN) - assert.propertyVal(testModule.meta, TEST_ITR_UNSKIPPABLE, 'true') - assert.notProperty(testModule.meta, TEST_ITR_FORCED_RUN) + assert.strictEqual(testSession.meta[TEST_ITR_UNSKIPPABLE], 'true') + assert.ok(!Object.hasOwn(testSession.meta, TEST_ITR_FORCED_RUN)) + assert.strictEqual(testModule.meta[TEST_ITR_UNSKIPPABLE], 'true') + assert.ok(!Object.hasOwn(testModule.meta, TEST_ITR_FORCED_RUN)) const skippedSuite = suites.find( event => event.content.resource === 'test_suite.ci-visibility/features/farewell.feature' @@ -883,13 +858,13 @@ describe(`cucumber@${version} commonJS`, () => { event => event.content.resource === 'test_suite.ci-visibility/features/greetings.feature' ) - assert.propertyVal(skippedSuite.content.meta, TEST_STATUS, 'skip') - assert.notProperty(skippedSuite.content.meta, TEST_ITR_UNSKIPPABLE) - assert.notProperty(skippedSuite.content.meta, TEST_ITR_FORCED_RUN) + assert.strictEqual(skippedSuite.content.meta[TEST_STATUS], 'skip') + assert.ok(!Object.hasOwn(skippedSuite.content.meta, TEST_ITR_UNSKIPPABLE)) + assert.ok(!Object.hasOwn(skippedSuite.content.meta, TEST_ITR_FORCED_RUN)) - assert.propertyVal(failedSuite.content.meta, TEST_STATUS, 'fail') - assert.propertyVal(failedSuite.content.meta, TEST_ITR_UNSKIPPABLE, 'true') - assert.notProperty(failedSuite.content.meta, TEST_ITR_FORCED_RUN) + assert.strictEqual(failedSuite.content.meta[TEST_STATUS], 'fail') + assert.strictEqual(failedSuite.content.meta[TEST_ITR_UNSKIPPABLE], 'true') + assert.ok(!Object.hasOwn(failedSuite.content.meta, TEST_ITR_FORCED_RUN)) }, 25000) childProcess = exec( @@ -919,15 +894,15 @@ describe(`cucumber@${version} commonJS`, () => { .gatherPayloadsMaxTimeout(({ url }) => url.endsWith('/api/v2/citestcycle'), (payloads) => { const events = payloads.flatMap(({ payload }) => payload.events) const testSession = events.find(event => event.type === 'test_session_end').content - assert.propertyVal(testSession.meta, TEST_ITR_TESTS_SKIPPED, 'false') - assert.propertyVal(testSession.meta, TEST_CODE_COVERAGE_ENABLED, 'true') - assert.propertyVal(testSession.meta, TEST_ITR_SKIPPING_ENABLED, 'true') - assert.propertyVal(testSession.metrics, TEST_ITR_SKIPPING_COUNT, 0) + assert.strictEqual(testSession.meta[TEST_ITR_TESTS_SKIPPED], 'false') + assert.strictEqual(testSession.meta[TEST_CODE_COVERAGE_ENABLED], 'true') + assert.strictEqual(testSession.meta[TEST_ITR_SKIPPING_ENABLED], 'true') + assert.strictEqual(testSession.metrics[TEST_ITR_SKIPPING_COUNT], 0) const testModule = events.find(event => event.type === 'test_module_end').content - assert.propertyVal(testModule.meta, TEST_ITR_TESTS_SKIPPED, 'false') - assert.propertyVal(testModule.meta, TEST_CODE_COVERAGE_ENABLED, 'true') - assert.propertyVal(testModule.meta, TEST_ITR_SKIPPING_ENABLED, 'true') - assert.propertyVal(testModule.metrics, TEST_ITR_SKIPPING_COUNT, 0) + assert.strictEqual(testModule.meta[TEST_ITR_TESTS_SKIPPED], 'false') + assert.strictEqual(testModule.meta[TEST_CODE_COVERAGE_ENABLED], 'true') + assert.strictEqual(testModule.meta[TEST_ITR_SKIPPING_ENABLED], 'true') + assert.strictEqual(testModule.metrics[TEST_ITR_SKIPPING_COUNT], 0) }, 25000) childProcess = exec( @@ -1002,7 +977,7 @@ describe(`cucumber@${version} commonJS`, () => { const events = payloads.flatMap(({ payload }) => payload.events) const testSuites = events.filter(event => event.type === 'test_suite_end').map(event => event.content) testSuites.forEach(testSuite => { - assert.equal(testSuite.itr_correlation_id, itrCorrelationId) + assert.strictEqual(testSuite.itr_correlation_id, itrCorrelationId) }) }, 25000) @@ -1087,28 +1062,25 @@ describe(`cucumber@${version} commonJS`, () => { const events = payloads.flatMap(({ payload }) => payload.events) const testSession = events.find(event => event.type === 'test_session_end').content - assert.propertyVal(testSession.meta, TEST_EARLY_FLAKE_ENABLED, 'true') + assert.strictEqual(testSession.meta[TEST_EARLY_FLAKE_ENABLED], 'true') const tests = events.filter(event => event.type === 'test').map(event => event.content) const newTests = tests.filter(test => test.resource === 'ci-visibility/features/farewell.feature.Say whatever' ) newTests.forEach(test => { - assert.propertyVal(test.meta, TEST_IS_NEW, 'true') + assert.strictEqual(test.meta[TEST_IS_NEW], 'true') }) const retriedTests = newTests.filter(test => test.meta[TEST_IS_RETRY] === 'true') // all but one has been retried - assert.equal( - newTests.length - 1, - retriedTests.length - ) - assert.equal(retriedTests.length, NUM_RETRIES_EFD) + assert.strictEqual(newTests.length - 1, retriedTests.length) + assert.strictEqual(retriedTests.length, NUM_RETRIES_EFD) retriedTests.forEach(test => { - assert.propertyVal(test.meta, TEST_RETRY_REASON, TEST_RETRY_REASON_TYPES.efd) + assert.strictEqual(test.meta[TEST_RETRY_REASON], TEST_RETRY_REASON_TYPES.efd) }) // Test name does not change newTests.forEach(test => { - assert.equal(test.meta[TEST_NAME], 'Say whatever') + assert.strictEqual(test.meta[TEST_NAME], 'Say whatever') }) }) childProcess = exec( @@ -1142,18 +1114,18 @@ describe(`cucumber@${version} commonJS`, () => { .gatherPayloadsMaxTimeout(({ url }) => url.endsWith('/api/v2/citestcycle'), (payloads) => { const events = payloads.flatMap(({ payload }) => payload.events) const testSession = events.find(event => event.type === 'test_session_end').content - assert.notProperty(testSession.meta, TEST_EARLY_FLAKE_ENABLED) + assert.ok(!Object.hasOwn(testSession.meta, TEST_EARLY_FLAKE_ENABLED)) const tests = events.filter(event => event.type === 'test').map(event => event.content) const newTests = tests.filter(test => test.meta[TEST_IS_NEW] === 'true' ) // new tests are detected but not retried - assert.equal(newTests.length, 1) + assert.strictEqual(newTests.length, 1) const retriedTests = tests.filter(test => test.meta[TEST_IS_RETRY] === 'true' ) - assert.equal(retriedTests.length, 0) + assert.strictEqual(retriedTests.length, 0) }) // cucumber.ci-visibility/features/farewell.feature.Say whatever will be considered new receiver.setKnownTests({ @@ -1199,24 +1171,24 @@ describe(`cucumber@${version} commonJS`, () => { const events = payloads.flatMap(({ payload }) => payload.events) const testSession = events.find(event => event.type === 'test_session_end').content - assert.propertyVal(testSession.meta, TEST_EARLY_FLAKE_ENABLED, 'true') + assert.strictEqual(testSession.meta[TEST_EARLY_FLAKE_ENABLED], 'true') const tests = events.filter(event => event.type === 'test').map(event => event.content) const testSuites = events.filter(event => event.type === 'test_suite_end').map(event => event.content) tests.forEach(test => { - assert.propertyVal(test.meta, TEST_IS_NEW, 'true') + assert.strictEqual(test.meta[TEST_IS_NEW], 'true') }) // All test suites pass, even though there are failed tests testSuites.forEach(testSuite => { - assert.propertyVal(testSuite.meta, TEST_STATUS, 'pass') + assert.strictEqual(testSuite.meta[TEST_STATUS], 'pass') }) const failedAttempts = tests.filter(test => test.meta[TEST_STATUS] === 'fail') const passedAttempts = tests.filter(test => test.meta[TEST_STATUS] === 'pass') // (1 original run + 3 retries) / 2 - assert.equal(failedAttempts.length, 2) - assert.equal(passedAttempts.length, 2) + assert.strictEqual(failedAttempts.length, 2) + assert.strictEqual(passedAttempts.length, 2) }) childProcess = exec( @@ -1228,7 +1200,7 @@ describe(`cucumber@${version} commonJS`, () => { } ) childProcess.on('exit', (exitCode) => { - assert.equal(exitCode, 0) + assert.strictEqual(exitCode, 0) eventsPromise.then(() => { done() }).catch(done) @@ -1260,14 +1232,14 @@ describe(`cucumber@${version} commonJS`, () => { const events = payloads.flatMap(({ payload }) => payload.events) const testSession = events.find(event => event.type === 'test_session_end').content - assert.propertyVal(testSession.meta, TEST_EARLY_FLAKE_ENABLED, 'true') + assert.strictEqual(testSession.meta[TEST_EARLY_FLAKE_ENABLED], 'true') const tests = events.filter(event => event.type === 'test').map(event => event.content) const skippedNewTest = tests.filter(test => test.resource === 'ci-visibility/features/greetings.feature.Say skip' ) // not retried - assert.equal(skippedNewTest.length, 1) + assert.strictEqual(skippedNewTest.length, 1) }) childProcess = exec( @@ -1305,14 +1277,14 @@ describe(`cucumber@${version} commonJS`, () => { const events = payloads.flatMap(({ payload }) => payload.events) const testSession = events.find(event => event.type === 'test_session_end').content - assert.notProperty(testSession.meta, TEST_EARLY_FLAKE_ENABLED) + assert.ok(!Object.hasOwn(testSession.meta, TEST_EARLY_FLAKE_ENABLED)) const tests = events.filter(event => event.type === 'test').map(event => event.content) - assert.equal(tests.length, 6) + assert.strictEqual(tests.length, 6) const newTests = tests.filter(test => test.meta[TEST_IS_NEW] === 'true' ) - assert.equal(newTests.length, 0) + assert.strictEqual(newTests.length, 0) }) childProcess = exec( @@ -1352,16 +1324,16 @@ describe(`cucumber@${version} commonJS`, () => { const events = payloads.flatMap(({ payload }) => payload.events) const testSession = events.find(event => event.type === 'test_session_end').content - assert.notProperty(testSession.meta, TEST_EARLY_FLAKE_ENABLED) - assert.propertyVal(testSession.meta, TEST_EARLY_FLAKE_ABORT_REASON, 'faulty') + assert.ok(!Object.hasOwn(testSession.meta, TEST_EARLY_FLAKE_ENABLED)) + assert.strictEqual(testSession.meta[TEST_EARLY_FLAKE_ABORT_REASON], 'faulty') const tests = events.filter(event => event.type === 'test').map(event => event.content) const newTests = tests.filter(test => test.meta[TEST_IS_NEW] === 'true') - assert.equal(newTests.length, 0) + assert.strictEqual(newTests.length, 0) const retriedTests = newTests.filter(test => test.meta[TEST_IS_RETRY] === 'true') - assert.equal(retriedTests.length, 0) + assert.strictEqual(retriedTests.length, 0) }) childProcess = exec( @@ -1405,15 +1377,15 @@ describe(`cucumber@${version} commonJS`, () => { const events = payloads.flatMap(({ payload }) => payload.events) const testSession = events.find(event => event.type === 'test_session_end').content - assert.notProperty(testSession.meta, TEST_EARLY_FLAKE_ENABLED) + assert.ok(!Object.hasOwn(testSession.meta, TEST_EARLY_FLAKE_ENABLED)) const tests = events.filter(event => event.type === 'test').map(event => event.content) // no new tests detected const newTests = tests.filter(test => test.meta[TEST_IS_NEW] === 'true') - assert.equal(newTests.length, 0) + assert.strictEqual(newTests.length, 0) // no retries const retriedTests = newTests.filter(test => test.meta[TEST_IS_RETRY] === 'true') - assert.equal(retriedTests.length, 0) + assert.strictEqual(retriedTests.length, 0) }) childProcess = exec( @@ -1459,8 +1431,8 @@ describe(`cucumber@${version} commonJS`, () => { const events = payloads.flatMap(({ payload }) => payload.events) const testSession = events.find(event => event.type === 'test_session_end').content - assert.propertyVal(testSession.meta, TEST_EARLY_FLAKE_ENABLED, 'true') - assert.propertyVal(testSession.meta, CUCUMBER_IS_PARALLEL, 'true') + assert.strictEqual(testSession.meta[TEST_EARLY_FLAKE_ENABLED], 'true') + assert.strictEqual(testSession.meta[CUCUMBER_IS_PARALLEL], 'true') const tests = events.filter(event => event.type === 'test').map(event => event.content) @@ -1468,18 +1440,15 @@ describe(`cucumber@${version} commonJS`, () => { test.resource === 'ci-visibility/features/farewell.feature.Say whatever' ) newTests.forEach(test => { - assert.propertyVal(test.meta, TEST_IS_NEW, 'true') + assert.strictEqual(test.meta[TEST_IS_NEW], 'true') // Test name does not change - assert.propertyVal(test.meta, TEST_NAME, 'Say whatever') - assert.propertyVal(test.meta, CUCUMBER_IS_PARALLEL, 'true') + assert.strictEqual(test.meta[TEST_NAME], 'Say whatever') + assert.strictEqual(test.meta[CUCUMBER_IS_PARALLEL], 'true') }) const retriedTests = newTests.filter(test => test.meta[TEST_IS_RETRY] === 'true') // all but one has been retried - assert.equal( - newTests.length - 1, - retriedTests.length - ) - assert.equal(retriedTests.length, NUM_RETRIES_EFD) + assert.strictEqual(newTests.length - 1, retriedTests.length) + assert.strictEqual(retriedTests.length, NUM_RETRIES_EFD) }) childProcess = exec( @@ -1519,28 +1488,28 @@ describe(`cucumber@${version} commonJS`, () => { const events = payloads.flatMap(({ payload }) => payload.events) const testSession = events.find(event => event.type === 'test_session_end').content - assert.propertyVal(testSession.meta, TEST_EARLY_FLAKE_ENABLED, 'true') - assert.propertyVal(testSession.meta, CUCUMBER_IS_PARALLEL, 'true') + assert.strictEqual(testSession.meta[TEST_EARLY_FLAKE_ENABLED], 'true') + assert.strictEqual(testSession.meta[CUCUMBER_IS_PARALLEL], 'true') const tests = events.filter(event => event.type === 'test').map(event => event.content) const testSuites = events .filter(event => event.type === 'test_suite_end').map(event => event.content) tests.forEach(test => { - assert.propertyVal(test.meta, TEST_IS_NEW, 'true') - assert.propertyVal(test.meta, CUCUMBER_IS_PARALLEL, 'true') + assert.strictEqual(test.meta[TEST_IS_NEW], 'true') + assert.strictEqual(test.meta[CUCUMBER_IS_PARALLEL], 'true') }) // All test suites pass, even though there are failed tests testSuites.forEach(testSuite => { - assert.propertyVal(testSuite.meta, TEST_STATUS, 'pass') + assert.strictEqual(testSuite.meta[TEST_STATUS], 'pass') }) const failedAttempts = tests.filter(test => test.meta[TEST_STATUS] === 'fail') const passedAttempts = tests.filter(test => test.meta[TEST_STATUS] === 'pass') // (1 original run + 3 retries) / 2 - assert.equal(failedAttempts.length, 2) - assert.equal(passedAttempts.length, 2) + assert.strictEqual(failedAttempts.length, 2) + assert.strictEqual(passedAttempts.length, 2) }) childProcess = exec( @@ -1553,7 +1522,7 @@ describe(`cucumber@${version} commonJS`, () => { ) childProcess.on('exit', (exitCode) => { - assert.equal(exitCode, 0) + assert.strictEqual(exitCode, 0) eventsPromise.then(() => { done() }).catch(done) @@ -1586,17 +1555,17 @@ describe(`cucumber@${version} commonJS`, () => { const events = payloads.flatMap(({ payload }) => payload.events) const testSession = events.find(event => event.type === 'test_session_end').content - assert.notProperty(testSession.meta, TEST_EARLY_FLAKE_ENABLED) - assert.propertyVal(testSession.meta, TEST_EARLY_FLAKE_ABORT_REASON, 'faulty') - assert.propertyVal(testSession.meta, CUCUMBER_IS_PARALLEL, 'true') + assert.ok(!Object.hasOwn(testSession.meta, TEST_EARLY_FLAKE_ENABLED)) + assert.strictEqual(testSession.meta[TEST_EARLY_FLAKE_ABORT_REASON], 'faulty') + assert.strictEqual(testSession.meta[CUCUMBER_IS_PARALLEL], 'true') const tests = events.filter(event => event.type === 'test').map(event => event.content) const newTests = tests.filter(test => test.meta[TEST_IS_NEW] === 'true') - assert.equal(newTests.length, 0) + assert.strictEqual(newTests.length, 0) const retriedTests = newTests.filter(test => test.meta[TEST_IS_RETRY] === 'true') - assert.equal(retriedTests.length, 0) + assert.strictEqual(retriedTests.length, 0) }) childProcess = exec( @@ -1640,15 +1609,15 @@ describe(`cucumber@${version} commonJS`, () => { const events = payloads.flatMap(({ payload }) => payload.events) const testSession = events.find(event => event.type === 'test_session_end').content - assert.propertyVal(testSession.meta, TEST_EARLY_FLAKE_ENABLED, 'true') - assert.propertyVal(testSession.meta, CUCUMBER_IS_PARALLEL, 'true') + assert.strictEqual(testSession.meta[TEST_EARLY_FLAKE_ENABLED], 'true') + assert.strictEqual(testSession.meta[CUCUMBER_IS_PARALLEL], 'true') const tests = events.filter(event => event.type === 'test').map(event => event.content) const skippedNewTest = tests.filter(test => test.resource === 'ci-visibility/features/greetings.feature.Say skip' ) // not retried - assert.equal(skippedNewTest.length, 1) + assert.strictEqual(skippedNewTest.length, 1) }) childProcess = exec( @@ -1691,17 +1660,17 @@ describe(`cucumber@${version} commonJS`, () => { const events = payloads.flatMap(({ payload }) => payload.events) const testSession = events.find(event => event.type === 'test_session_end').content - assert.notProperty(testSession.meta, TEST_EARLY_FLAKE_ENABLED) - assert.propertyVal(testSession.meta, TEST_EARLY_FLAKE_ABORT_REASON, 'faulty') - assert.propertyVal(testSession.meta, CUCUMBER_IS_PARALLEL, 'true') + assert.ok(!Object.hasOwn(testSession.meta, TEST_EARLY_FLAKE_ENABLED)) + assert.strictEqual(testSession.meta[TEST_EARLY_FLAKE_ABORT_REASON], 'faulty') + assert.strictEqual(testSession.meta[CUCUMBER_IS_PARALLEL], 'true') const tests = events.filter(event => event.type === 'test').map(event => event.content) const newTests = tests.filter(test => test.meta[TEST_IS_NEW] === 'true') - assert.equal(newTests.length, 0) + assert.strictEqual(newTests.length, 0) const retriedTests = newTests.filter(test => test.meta[TEST_IS_RETRY] === 'true') - assert.equal(retriedTests.length, 0) + assert.strictEqual(retriedTests.length, 0) }) childProcess = exec( @@ -1741,17 +1710,17 @@ describe(`cucumber@${version} commonJS`, () => { const tests = events.filter(event => event.type === 'test').map(event => event.content) // 2 failures and 1 passed attempt - assert.equal(tests.length, 3) + assert.strictEqual(tests.length, 3) const failedTests = tests.filter(test => test.meta[TEST_STATUS] === 'fail') - assert.equal(failedTests.length, 2) + assert.strictEqual(failedTests.length, 2) const passedTests = tests.filter(test => test.meta[TEST_STATUS] === 'pass') - assert.equal(passedTests.length, 1) + assert.strictEqual(passedTests.length, 1) // All but the first one are retries const retriedTests = tests.filter(test => test.meta[TEST_IS_RETRY] === 'true') - assert.equal(retriedTests.length, 2) - assert.equal(retriedTests.filter( + assert.strictEqual(retriedTests.length, 2) + assert.strictEqual(retriedTests.filter( test => test.meta[TEST_RETRY_REASON] === TEST_RETRY_REASON_TYPES.atr ).length, 2) }) @@ -1789,12 +1758,12 @@ describe(`cucumber@${version} commonJS`, () => { const tests = events.filter(event => event.type === 'test').map(event => event.content) - assert.equal(tests.length, 1) + assert.strictEqual(tests.length, 1) const retriedTests = tests.filter( test => test.meta[TEST_RETRY_REASON] === TEST_RETRY_REASON_TYPES.atr ) - assert.equal(retriedTests.length, 0) + assert.strictEqual(retriedTests.length, 0) }) childProcess = exec( @@ -1834,18 +1803,18 @@ describe(`cucumber@${version} commonJS`, () => { const tests = events.filter(event => event.type === 'test').map(event => event.content) // 2 failures - assert.equal(tests.length, 2) + assert.strictEqual(tests.length, 2) const failedTests = tests.filter(test => test.meta[TEST_STATUS] === 'fail') - assert.equal(failedTests.length, 2) + assert.strictEqual(failedTests.length, 2) const passedTests = tests.filter(test => test.meta[TEST_STATUS] === 'pass') - assert.equal(passedTests.length, 0) + assert.strictEqual(passedTests.length, 0) // All but the first one are retries const retriedTests = tests.filter( test => test.meta[TEST_RETRY_REASON] === TEST_RETRY_REASON_TYPES.atr ) - assert.equal(retriedTests.length, 1) + assert.strictEqual(retriedTests.length, 1) }) childProcess = exec( @@ -1884,7 +1853,7 @@ describe(`cucumber@${version} commonJS`, () => { test => test.meta[TEST_RETRY_REASON] === TEST_RETRY_REASON_TYPES.atr ) - assert.equal(retriedTests.length, 1) + assert.strictEqual(retriedTests.length, 1) const [retriedTest] = retriedTests const hasDebugTags = Object.keys(retriedTest.meta) @@ -1892,7 +1861,7 @@ describe(`cucumber@${version} commonJS`, () => { property.startsWith(DI_DEBUG_ERROR_PREFIX) || property === DI_ERROR_DEBUG_INFO_CAPTURED ) - assert.isFalse(hasDebugTags) + assert.strictEqual(hasDebugTags, false) }) const logsPromise = receiver .gatherPayloadsMaxTimeout(({ url }) => url === logsEndpoint, (payloads) => { @@ -1935,14 +1904,14 @@ describe(`cucumber@${version} commonJS`, () => { test => test.meta[TEST_RETRY_REASON] === TEST_RETRY_REASON_TYPES.atr ) - assert.equal(retriedTests.length, 1) + assert.strictEqual(retriedTests.length, 1) const [retriedTest] = retriedTests const hasDebugTags = Object.keys(retriedTest.meta) .some(property => property.startsWith(DI_DEBUG_ERROR_PREFIX) || property === DI_ERROR_DEBUG_INFO_CAPTURED ) - assert.isFalse(hasDebugTags) + assert.strictEqual(hasDebugTags, false) }) const logsPromise = receiver .gatherPayloadsMaxTimeout(({ url }) => url === logsEndpoint, (payloads) => { @@ -1986,19 +1955,17 @@ describe(`cucumber@${version} commonJS`, () => { test => test.meta[TEST_RETRY_REASON] === TEST_RETRY_REASON_TYPES.atr ) - assert.equal(retriedTests.length, 1) + assert.strictEqual(retriedTests.length, 1) const [retriedTest] = retriedTests - assert.propertyVal(retriedTest.meta, DI_ERROR_DEBUG_INFO_CAPTURED, 'true') + assert.strictEqual(retriedTest.meta[DI_ERROR_DEBUG_INFO_CAPTURED], 'true') - assert.isTrue( - retriedTest.meta[`${DI_DEBUG_ERROR_PREFIX}.0.${DI_DEBUG_ERROR_FILE_SUFFIX}`] - .endsWith('ci-visibility/features-di/support/sum.js') - ) - assert.equal(retriedTest.metrics[`${DI_DEBUG_ERROR_PREFIX}.0.${DI_DEBUG_ERROR_LINE_SUFFIX}`], 6) + assert.strictEqual(retriedTest.meta[`${DI_DEBUG_ERROR_PREFIX}.0.${DI_DEBUG_ERROR_FILE_SUFFIX}`] + .endsWith('ci-visibility/features-di/support/sum.js'), true) + assert.strictEqual(retriedTest.metrics[`${DI_DEBUG_ERROR_PREFIX}.0.${DI_DEBUG_ERROR_LINE_SUFFIX}`], 6) const snapshotIdKey = `${DI_DEBUG_ERROR_PREFIX}.0.${DI_DEBUG_ERROR_SNAPSHOT_ID_SUFFIX}` - assert.exists(retriedTest.meta[snapshotIdKey]) + assert.ok(retriedTest.meta[snapshotIdKey] != null) snapshotIdByTest = retriedTest.meta[snapshotIdKey] spanIdByTest = retriedTest.span_id.toString() @@ -2008,11 +1975,11 @@ describe(`cucumber@${version} commonJS`, () => { const logsPromise = receiver .gatherPayloadsMaxTimeout(({ url }) => url === logsEndpoint, (payloads) => { const [{ logMessage: [diLog] }] = payloads - assert.deepInclude(diLog, { + assertObjectContains(diLog, { ddsource: 'dd_debugger', level: 'error' }) - assert.equal(diLog.debugger.snapshot.language, 'javascript') + assert.strictEqual(diLog.debugger.snapshot.language, 'javascript') assert.deepInclude(diLog.debugger.snapshot.captures.lines['6'].locals, { a: { type: 'number', @@ -2051,9 +2018,9 @@ describe(`cucumber@${version} commonJS`, () => { childProcess.on('exit', () => { Promise.all([eventsPromise, logsPromise]).then(() => { - assert.equal(snapshotIdByTest, snapshotIdByLog) - assert.equal(spanIdByTest, spanIdByLog) - assert.equal(traceIdByTest, traceIdByLog) + assert.strictEqual(snapshotIdByTest, snapshotIdByLog) + assert.strictEqual(spanIdByTest, spanIdByLog) + assert.strictEqual(traceIdByTest, traceIdByLog) done() }).catch(done) }) @@ -2074,7 +2041,7 @@ describe(`cucumber@${version} commonJS`, () => { test => test.meta[TEST_RETRY_REASON] === TEST_RETRY_REASON_TYPES.atr ) - assert.equal(retriedTests.length, 1) + assert.strictEqual(retriedTests.length, 1) const [retriedTest] = retriedTests const hasDebugTags = Object.keys(retriedTest.meta) @@ -2082,7 +2049,7 @@ describe(`cucumber@${version} commonJS`, () => { property.startsWith(DI_DEBUG_ERROR_PREFIX) || property === DI_ERROR_DEBUG_INFO_CAPTURED ) - assert.isFalse(hasDebugTags) + assert.strictEqual(hasDebugTags, false) }) const logsPromise = receiver .gatherPayloadsMaxTimeout(({ url }) => url.endsWith('/api/v2/logs'), (payloads) => { @@ -2102,7 +2069,7 @@ describe(`cucumber@${version} commonJS`, () => { childProcess.on('exit', (exitCode) => { Promise.all([eventsPromise, logsPromise]).then(() => { - assert.equal(exitCode, 0) + assert.strictEqual(exitCode, 0) done() }).catch(done) }) @@ -2119,9 +2086,9 @@ describe(`cucumber@${version} commonJS`, () => { const test = events.find(event => event.type === 'test').content const testSuite = events.find(event => event.type === 'test_suite_end').content // The test is in a subproject - assert.notEqual(test.meta[TEST_SOURCE_FILE], test.meta[TEST_SUITE]) - assert.equal(test.meta[TEST_CODE_OWNERS], JSON.stringify(['@datadog-dd-trace-js'])) - assert.equal(testSuite.meta[TEST_CODE_OWNERS], JSON.stringify(['@datadog-dd-trace-js'])) + assert.notStrictEqual(test.meta[TEST_SOURCE_FILE], test.meta[TEST_SUITE]) + assert.strictEqual(test.meta[TEST_CODE_OWNERS], JSON.stringify(['@datadog-dd-trace-js'])) + assert.strictEqual(testSuite.meta[TEST_CODE_OWNERS], JSON.stringify(['@datadog-dd-trace-js'])) }) childProcess = exec( @@ -2185,11 +2152,8 @@ describe(`cucumber@${version} commonJS`, () => { linesPctMatch = testOutput.match(linesPctMatchRegex) linesPctFromNyc = linesPctMatch ? Number(linesPctMatch[1]) : null - assert.equal( - linesPctFromNyc, - codeCoverageWithUntestedFiles, - 'nyc --all output does not match the reported coverage' - ) + assert.strictEqual(linesPctFromNyc, codeCoverageWithUntestedFiles, + 'nyc --all output does not match the reported coverage') // reset test output for next test session testOutput = '' @@ -2230,14 +2194,11 @@ describe(`cucumber@${version} commonJS`, () => { linesPctMatch = testOutput.match(linesPctMatchRegex) linesPctFromNyc = linesPctMatch ? Number(linesPctMatch[1]) : null - assert.equal( - linesPctFromNyc, - codeCoverageWithoutUntestedFiles, - 'nyc output does not match the reported coverage (no --all flag)' - ) + assert.strictEqual(linesPctFromNyc, codeCoverageWithoutUntestedFiles, + 'nyc output does not match the reported coverage (no --all flag)') eventsPromise.then(() => { - assert.isAbove(codeCoverageWithoutUntestedFiles, codeCoverageWithUntestedFiles) + assert.ok(codeCoverageWithoutUntestedFiles > codeCoverageWithUntestedFiles) done() }).catch(done) }) @@ -2266,14 +2227,14 @@ describe(`cucumber@${version} commonJS`, () => { const events = payloads.flatMap(({ payload }) => payload.events) const testSession = events.find(event => event.type === 'test_session_end').content - assert.notProperty(testSession.meta, TEST_EARLY_FLAKE_ENABLED) + assert.ok(!Object.hasOwn(testSession.meta, TEST_EARLY_FLAKE_ENABLED)) const tests = events.filter(event => event.type === 'test').map(event => event.content) // new tests detected but not retried const newTests = tests.filter(test => test.meta[TEST_IS_NEW] === 'true') - assert.equal(newTests.length, 1) + assert.strictEqual(newTests.length, 1) const retriedTests = newTests.filter(test => test.meta[TEST_IS_RETRY] === 'true') - assert.equal(retriedTests.length, 0) + assert.strictEqual(retriedTests.length, 0) }) childProcess = exec( @@ -2300,7 +2261,7 @@ describe(`cucumber@${version} commonJS`, () => { const tests = events.filter(event => event.type === 'test').map(event => event.content) tests.forEach(test => { - assert.equal(test.meta[DD_TEST_IS_USER_PROVIDED_SERVICE], 'true') + assert.strictEqual(test.meta[DD_TEST_IS_USER_PROVIDED_SERVICE], 'true') }) }) @@ -2357,9 +2318,9 @@ describe(`cucumber@${version} commonJS`, () => { const testSession = events.find(event => event.type === 'test_session_end').content if (isAttemptToFix) { - assert.propertyVal(testSession.meta, TEST_MANAGEMENT_ENABLED, 'true') + assert.strictEqual(testSession.meta[TEST_MANAGEMENT_ENABLED], 'true') } else { - assert.notProperty(testSession.meta, TEST_MANAGEMENT_ENABLED) + assert.ok(!Object.hasOwn(testSession.meta, TEST_MANAGEMENT_ENABLED)) } const retriedTests = tests.filter( @@ -2368,9 +2329,9 @@ describe(`cucumber@${version} commonJS`, () => { if (isAttemptToFix) { // 3 retries + 1 initial run - assert.equal(retriedTests.length, 4) + assert.strictEqual(retriedTests.length, 4) } else { - assert.equal(retriedTests.length, 1) + assert.strictEqual(retriedTests.length, 1) } for (let i = 0; i < retriedTests.length; i++) { @@ -2378,41 +2339,38 @@ describe(`cucumber@${version} commonJS`, () => { const isLastAttempt = i === retriedTests.length - 1 const test = retriedTests[i] - assert.equal( - test.resource, - 'ci-visibility/features-test-management/attempt-to-fix.feature.Say attempt to fix' - ) + assert.strictEqual(test.resource, 'ci-visibility/features-test-management/attempt-to-fix.feature.Say attempt to fix') if (isDisabled) { - assert.propertyVal(test.meta, TEST_MANAGEMENT_IS_DISABLED, 'true') + assert.strictEqual(test.meta[TEST_MANAGEMENT_IS_DISABLED], 'true') } else if (isQuarantined) { - assert.propertyVal(test.meta, TEST_MANAGEMENT_IS_QUARANTINED, 'true') + assert.strictEqual(test.meta[TEST_MANAGEMENT_IS_QUARANTINED], 'true') } else { - assert.notProperty(test.meta, TEST_MANAGEMENT_IS_DISABLED) - assert.notProperty(test.meta, TEST_MANAGEMENT_IS_QUARANTINED) + assert.ok(!Object.hasOwn(test.meta, TEST_MANAGEMENT_IS_DISABLED)) + assert.ok(!Object.hasOwn(test.meta, TEST_MANAGEMENT_IS_QUARANTINED)) } if (isAttemptToFix) { - assert.propertyVal(test.meta, TEST_MANAGEMENT_IS_ATTEMPT_TO_FIX, 'true') + assert.strictEqual(test.meta[TEST_MANAGEMENT_IS_ATTEMPT_TO_FIX], 'true') if (!isFirstAttempt) { - assert.propertyVal(test.meta, TEST_IS_RETRY, 'true') - assert.propertyVal(test.meta, TEST_RETRY_REASON, TEST_RETRY_REASON_TYPES.atf) + assert.strictEqual(test.meta[TEST_IS_RETRY], 'true') + assert.strictEqual(test.meta[TEST_RETRY_REASON], TEST_RETRY_REASON_TYPES.atf) } if (isLastAttempt) { if (shouldFailSometimes) { - assert.propertyVal(test.meta, TEST_MANAGEMENT_ATTEMPT_TO_FIX_PASSED, 'false') - assert.notProperty(test.meta, TEST_HAS_FAILED_ALL_RETRIES) + assert.strictEqual(test.meta[TEST_MANAGEMENT_ATTEMPT_TO_FIX_PASSED], 'false') + assert.ok(!Object.hasOwn(test.meta, TEST_HAS_FAILED_ALL_RETRIES)) } else if (shouldAlwaysPass) { - assert.propertyVal(test.meta, TEST_MANAGEMENT_ATTEMPT_TO_FIX_PASSED, 'true') + assert.strictEqual(test.meta[TEST_MANAGEMENT_ATTEMPT_TO_FIX_PASSED], 'true') } else { - assert.propertyVal(test.meta, TEST_MANAGEMENT_ATTEMPT_TO_FIX_PASSED, 'false') - assert.propertyVal(test.meta, TEST_HAS_FAILED_ALL_RETRIES, 'true') + assert.strictEqual(test.meta[TEST_MANAGEMENT_ATTEMPT_TO_FIX_PASSED], 'false') + assert.strictEqual(test.meta[TEST_HAS_FAILED_ALL_RETRIES], 'true') } } } else { - assert.notProperty(test.meta, TEST_MANAGEMENT_IS_ATTEMPT_TO_FIX) - assert.notProperty(test.meta, TEST_IS_RETRY) - assert.notProperty(test.meta, TEST_RETRY_REASON) + assert.ok(!Object.hasOwn(test.meta, TEST_MANAGEMENT_IS_ATTEMPT_TO_FIX)) + assert.ok(!Object.hasOwn(test.meta, TEST_IS_RETRY)) + assert.ok(!Object.hasOwn(test.meta, TEST_RETRY_REASON)) } } }) @@ -2454,11 +2412,11 @@ describe(`cucumber@${version} commonJS`, () => { childProcess.on('exit', exitCode => { testAssertions.then(() => { - assert.include(stdout, 'I am running') + assert.ok(stdout.includes('I am running')) if (isQuarantined || isDisabled || shouldAlwaysPass) { - assert.equal(exitCode, 0) + assert.strictEqual(exitCode, 0) } else { - assert.equal(exitCode, 1) + assert.strictEqual(exitCode, 1) } done() }).catch(done) @@ -2575,21 +2533,21 @@ describe(`cucumber@${version} commonJS`, () => { const testSession = events.find(event => event.type === 'test_session_end').content if (isDisabling) { - assert.propertyVal(testSession.meta, TEST_MANAGEMENT_ENABLED, 'true') - assert.propertyVal(testSession.meta, TEST_STATUS, 'pass') + assert.strictEqual(testSession.meta[TEST_MANAGEMENT_ENABLED], 'true') + assert.strictEqual(testSession.meta[TEST_STATUS], 'pass') } else { - assert.notProperty(testSession.meta, TEST_MANAGEMENT_ENABLED) - assert.propertyVal(testSession.meta, TEST_STATUS, 'fail') + assert.ok(!Object.hasOwn(testSession.meta, TEST_MANAGEMENT_ENABLED)) + assert.strictEqual(testSession.meta[TEST_STATUS], 'fail') } - assert.equal(tests.resource, 'ci-visibility/features-test-management/disabled.feature.Say disabled') + assert.strictEqual(tests.resource, 'ci-visibility/features-test-management/disabled.feature.Say disabled') if (isDisabling) { - assert.equal(tests.meta[TEST_STATUS], 'skip') - assert.propertyVal(tests.meta, TEST_MANAGEMENT_IS_DISABLED, 'true') + assert.strictEqual(tests.meta[TEST_STATUS], 'skip') + assert.strictEqual(tests.meta[TEST_MANAGEMENT_IS_DISABLED], 'true') } else { - assert.equal(tests.meta[TEST_STATUS], 'fail') - assert.notProperty(tests.meta, TEST_MANAGEMENT_IS_DISABLED) + assert.strictEqual(tests.meta[TEST_STATUS], 'fail') + assert.ok(!Object.hasOwn(tests.meta, TEST_MANAGEMENT_IS_DISABLED)) } }) @@ -2616,11 +2574,11 @@ describe(`cucumber@${version} commonJS`, () => { childProcess.on('exit', exitCode => { testAssertionsPromise.then(() => { if (isDisabling) { - assert.notInclude(stdout, 'I am running') - assert.equal(exitCode, 0) + assert.ok(!stdout.includes('I am running')) + assert.strictEqual(exitCode, 0) } else { - assert.include(stdout, 'I am running') - assert.equal(exitCode, 1) + assert.ok(stdout.includes('I am running')) + assert.strictEqual(exitCode, 1) } done() }).catch(done) @@ -2673,19 +2631,18 @@ describe(`cucumber@${version} commonJS`, () => { const testSession = events.find(event => event.type === 'test_session_end').content if (isQuarantining) { - assert.propertyVal(testSession.meta, TEST_MANAGEMENT_ENABLED, 'true') + assert.strictEqual(testSession.meta[TEST_MANAGEMENT_ENABLED], 'true') } else { - assert.notProperty(testSession.meta, TEST_MANAGEMENT_ENABLED) + assert.ok(!Object.hasOwn(testSession.meta, TEST_MANAGEMENT_ENABLED)) } - assert.equal(failedTest.resource, - 'ci-visibility/features-test-management/quarantine.feature.Say quarantine') + assert.strictEqual(failedTest.resource, 'ci-visibility/features-test-management/quarantine.feature.Say quarantine') - assert.equal(failedTest.meta[TEST_STATUS], 'fail') + assert.strictEqual(failedTest.meta[TEST_STATUS], 'fail') if (isQuarantining) { - assert.propertyVal(failedTest.meta, TEST_MANAGEMENT_IS_QUARANTINED, 'true') + assert.strictEqual(failedTest.meta[TEST_MANAGEMENT_IS_QUARANTINED], 'true') } else { - assert.notProperty(failedTest.meta, TEST_MANAGEMENT_IS_QUARANTINED) + assert.ok(!Object.hasOwn(failedTest.meta, TEST_MANAGEMENT_IS_QUARANTINED)) } }) @@ -2711,12 +2668,12 @@ describe(`cucumber@${version} commonJS`, () => { childProcess.on('exit', exitCode => { testAssertionsPromise.then(() => { // Regardless of whether the test is quarantined or not, it will be run - assert.include(stdout, 'I am running as quarantine') + assert.ok(stdout.includes('I am running as quarantine')) if (isQuarantining) { // even though a test fails, the exit code is 1 because the test is quarantined - assert.equal(exitCode, 0) + assert.strictEqual(exitCode, 0) } else { - assert.equal(exitCode, 1) + assert.strictEqual(exitCode, 1) } done() }).catch(done) @@ -2754,10 +2711,10 @@ describe(`cucumber@${version} commonJS`, () => { .gatherPayloadsMaxTimeout(({ url }) => url.endsWith('/api/v2/citestcycle'), (payloads) => { const events = payloads.flatMap(({ payload }) => payload.events) const testSession = events.find(event => event.type === 'test_session_end').content - assert.notProperty(testSession.meta, TEST_MANAGEMENT_ENABLED) + assert.ok(!Object.hasOwn(testSession.meta, TEST_MANAGEMENT_ENABLED)) const tests = events.filter(event => event.type === 'test').map(event => event.content) // it is not retried - assert.equal(tests.length, 1) + assert.strictEqual(tests.length, 1) }) childProcess = exec( @@ -2785,7 +2742,7 @@ describe(`cucumber@${version} commonJS`, () => { once(childProcess.stderr, 'end'), eventsPromise ]) - assert.include(testOutput, 'Test management tests could not be fetched') + assert.ok(testOutput.includes('Test management tests could not be fetched')) }) }) @@ -2804,22 +2761,22 @@ describe(`cucumber@${version} commonJS`, () => { .gatherPayloadsMaxTimeout(({ url }) => url.endsWith('/api/v2/citestcycle'), payloads => { const metadataDicts = payloads.flatMap(({ payload }) => payload.metadata) - assert.isNotEmpty(metadataDicts) + assert.ok(metadataDicts.length > 0) metadataDicts.forEach(metadata => { if (runMode === 'parallel') { - assert.equal(metadata.test[DD_CAPABILITIES_TEST_IMPACT_ANALYSIS], undefined) + assert.strictEqual(metadata.test[DD_CAPABILITIES_TEST_IMPACT_ANALYSIS], undefined) } else { - assert.equal(metadata.test[DD_CAPABILITIES_TEST_IMPACT_ANALYSIS], '1') + assert.strictEqual(metadata.test[DD_CAPABILITIES_TEST_IMPACT_ANALYSIS], '1') } - assert.equal(metadata.test[DD_CAPABILITIES_EARLY_FLAKE_DETECTION], '1') - assert.equal(metadata.test[DD_CAPABILITIES_AUTO_TEST_RETRIES], '1') - assert.equal(metadata.test[DD_CAPABILITIES_IMPACTED_TESTS], '1') - assert.equal(metadata.test[DD_CAPABILITIES_TEST_MANAGEMENT_QUARANTINE], '1') - assert.equal(metadata.test[DD_CAPABILITIES_TEST_MANAGEMENT_DISABLE], '1') - assert.equal(metadata.test[DD_CAPABILITIES_TEST_MANAGEMENT_ATTEMPT_TO_FIX], '5') - assert.equal(metadata.test[DD_CAPABILITIES_FAILED_TEST_REPLAY], '1') + assert.strictEqual(metadata.test[DD_CAPABILITIES_EARLY_FLAKE_DETECTION], '1') + assert.strictEqual(metadata.test[DD_CAPABILITIES_AUTO_TEST_RETRIES], '1') + assert.strictEqual(metadata.test[DD_CAPABILITIES_IMPACTED_TESTS], '1') + assert.strictEqual(metadata.test[DD_CAPABILITIES_TEST_MANAGEMENT_QUARANTINE], '1') + assert.strictEqual(metadata.test[DD_CAPABILITIES_TEST_MANAGEMENT_DISABLE], '1') + assert.strictEqual(metadata.test[DD_CAPABILITIES_TEST_MANAGEMENT_ATTEMPT_TO_FIX], '5') + assert.strictEqual(metadata.test[DD_CAPABILITIES_FAILED_TEST_REPLAY], '1') // capabilities logic does not overwrite test session name - assert.equal(metadata.test[TEST_SESSION_NAME], 'my-test-session-name') + assert.strictEqual(metadata.test[TEST_SESSION_NAME], 'my-test-session-name') }) }) @@ -2885,9 +2842,9 @@ describe(`cucumber@${version} commonJS`, () => { const testSession = events.find(event => event.type === 'test_session_end').content if (isEfd) { - assert.propertyVal(testSession.meta, TEST_EARLY_FLAKE_ENABLED, 'true') + assert.strictEqual(testSession.meta[TEST_EARLY_FLAKE_ENABLED], 'true') } else { - assert.notProperty(testSession.meta, TEST_EARLY_FLAKE_ENABLED) + assert.ok(!Object.hasOwn(testSession.meta, TEST_EARLY_FLAKE_ENABLED)) } const resourceNames = tests.map(span => span.resource) @@ -2911,27 +2868,27 @@ describe(`cucumber@${version} commonJS`, () => { ) if (isEfd) { - assert.equal(impactedTests.length, NUM_RETRIES + 1) // Retries + original test + assert.strictEqual(impactedTests.length, NUM_RETRIES + 1) // Retries + original test } else { - assert.equal(impactedTests.length, 1) + assert.strictEqual(impactedTests.length, 1) } for (const impactedTest of impactedTests) { if (isModified) { - assert.propertyVal(impactedTest.meta, TEST_IS_MODIFIED, 'true') + assert.strictEqual(impactedTest.meta[TEST_IS_MODIFIED], 'true') } else { - assert.notProperty(impactedTest.meta, TEST_IS_MODIFIED) + assert.ok(!Object.hasOwn(impactedTest.meta, TEST_IS_MODIFIED)) } if (isNew) { - assert.propertyVal(impactedTest.meta, TEST_IS_NEW, 'true') + assert.strictEqual(impactedTest.meta[TEST_IS_NEW], 'true') } else { - assert.notProperty(impactedTest.meta, TEST_IS_NEW) + assert.ok(!Object.hasOwn(impactedTest.meta, TEST_IS_NEW)) } } if (isEfd) { const retriedTests = tests.filter(test => test.meta[TEST_IS_RETRY] === 'true') - assert.equal(retriedTests.length, NUM_RETRIES) + assert.strictEqual(retriedTests.length, NUM_RETRIES) let retriedTestNew = 0 let retriedTestsWithReason = 0 retriedTests.forEach(test => { @@ -2942,8 +2899,8 @@ describe(`cucumber@${version} commonJS`, () => { retriedTestsWithReason++ } }) - assert.equal(retriedTestNew, isNew ? NUM_RETRIES : 0) - assert.equal(retriedTestsWithReason, NUM_RETRIES) + assert.strictEqual(retriedTestNew, isNew ? NUM_RETRIES : 0) + assert.strictEqual(retriedTestsWithReason, NUM_RETRIES) } }) diff --git a/integration-tests/cypress/cypress.spec.js b/integration-tests/cypress/cypress.spec.js index 71e75fc576f..4bbd36d2ecf 100644 --- a/integration-tests/cypress/cypress.spec.js +++ b/integration-tests/cypress/cypress.spec.js @@ -1,14 +1,14 @@ 'use strict' -const semver = require('semver') +const assert = require('node:assert/strict') +const { exec, execSync } = require('node:child_process') const { once } = require('node:events') -const http = require('http') -const { exec, execSync } = require('child_process') -const path = require('path') -const fs = require('fs') - -const { assert } = require('chai') +const fs = require('node:fs') +const http = require('node:http') +const path = require('node:path') +const { promisify } = require('node:util') +const semver = require('semver') const { sandboxCwd, useSandbox, @@ -67,6 +67,8 @@ const { DD_HOST_CPU_COUNT } = require('../../packages/dd-trace/src/plugins/util/ const { ERROR_MESSAGE, ERROR_TYPE, COMPONENT } = require('../../packages/dd-trace/src/constants') const { DD_MAJOR, NODE_MAJOR } = require('../../version') +const execPromise = promisify(exec) + const RECEIVER_STOP_TIMEOUT = 20000 const version = process.env.CYPRESS_VERSION const hookFile = 'dd-trace/loader-hook.mjs' @@ -222,48 +224,48 @@ moduleTypes.forEach(({ span.resource === 'cypress/e2e/basic-fail.js.basic fail suite can fail' ) - assert.exists(passedTestSpan, 'passed test span should exist') - assert.equal(passedTestSpan.name, 'cypress.test') - assert.equal(passedTestSpan.resource, 'cypress/e2e/basic-pass.js.basic pass suite can pass') - assert.equal(passedTestSpan.type, 'test') - assert.equal(passedTestSpan.meta[TEST_STATUS], 'pass') - assert.equal(passedTestSpan.meta[TEST_NAME], 'basic pass suite can pass') - assert.equal(passedTestSpan.meta[TEST_SUITE], 'cypress/e2e/basic-pass.js') - assert.equal(passedTestSpan.meta[TEST_FRAMEWORK], 'cypress') - assert.equal(passedTestSpan.meta[TEST_TYPE], 'browser') - assert.exists(passedTestSpan.meta[TEST_SOURCE_FILE]) - assert.include(passedTestSpan.meta[TEST_SOURCE_FILE], 'cypress/e2e/basic-pass.js') - assert.exists(passedTestSpan.meta[TEST_FRAMEWORK_VERSION]) - assert.exists(passedTestSpan.meta[COMPONENT]) - assert.exists(passedTestSpan.metrics[TEST_SOURCE_START]) - assert.equal(passedTestSpan.meta[TEST_CODE_OWNERS], JSON.stringify(['@datadog-dd-trace-js'])) - assert.equal(passedTestSpan.meta.customTag, 'customValue') - assert.equal(passedTestSpan.meta.addTagsBeforeEach, 'customBeforeEach') - assert.equal(passedTestSpan.meta.addTagsAfterEach, 'customAfterEach') - - assert.exists(failedTestSpan, 'failed test span should exist') - assert.equal(failedTestSpan.name, 'cypress.test') - assert.equal(failedTestSpan.resource, 'cypress/e2e/basic-fail.js.basic fail suite can fail') - assert.equal(failedTestSpan.type, 'test') - assert.equal(failedTestSpan.meta[TEST_STATUS], 'fail') - assert.equal(failedTestSpan.meta[TEST_NAME], 'basic fail suite can fail') - assert.equal(failedTestSpan.meta[TEST_SUITE], 'cypress/e2e/basic-fail.js') - assert.equal(failedTestSpan.meta[TEST_FRAMEWORK], 'cypress') - assert.equal(failedTestSpan.meta[TEST_TYPE], 'browser') - assert.exists(failedTestSpan.meta[TEST_SOURCE_FILE]) - assert.include(failedTestSpan.meta[TEST_SOURCE_FILE], 'cypress/e2e/basic-fail.js') - assert.exists(failedTestSpan.meta[TEST_FRAMEWORK_VERSION]) - assert.exists(failedTestSpan.meta[COMPONENT]) - assert.exists(failedTestSpan.meta[ERROR_MESSAGE]) - assert.include(failedTestSpan.meta[ERROR_MESSAGE], 'expected') - assert.exists(failedTestSpan.meta[ERROR_TYPE]) - assert.exists(failedTestSpan.metrics[TEST_SOURCE_START]) - assert.equal(passedTestSpan.meta[TEST_CODE_OWNERS], JSON.stringify(['@datadog-dd-trace-js'])) - assert.equal(failedTestSpan.meta.customTag, 'customValue') - assert.equal(failedTestSpan.meta.addTagsBeforeEach, 'customBeforeEach') - assert.equal(failedTestSpan.meta.addTagsAfterEach, 'customAfterEach') + assert.ok(passedTestSpan != null) + assert.strictEqual(passedTestSpan.name, 'cypress.test') + assert.strictEqual(passedTestSpan.resource, 'cypress/e2e/basic-pass.js.basic pass suite can pass') + assert.strictEqual(passedTestSpan.type, 'test') + assert.strictEqual(passedTestSpan.meta[TEST_STATUS], 'pass') + assert.strictEqual(passedTestSpan.meta[TEST_NAME], 'basic pass suite can pass') + assert.strictEqual(passedTestSpan.meta[TEST_SUITE], 'cypress/e2e/basic-pass.js') + assert.strictEqual(passedTestSpan.meta[TEST_FRAMEWORK], 'cypress') + assert.strictEqual(passedTestSpan.meta[TEST_TYPE], 'browser') + assert.ok(passedTestSpan.meta[TEST_SOURCE_FILE] != null) + assert.ok(passedTestSpan.meta[TEST_SOURCE_FILE].includes('cypress/e2e/basic-pass.js')) + assert.ok(passedTestSpan.meta[TEST_FRAMEWORK_VERSION] != null) + assert.ok(passedTestSpan.meta[COMPONENT] != null) + assert.ok(passedTestSpan.metrics[TEST_SOURCE_START] != null) + assert.strictEqual(passedTestSpan.meta[TEST_CODE_OWNERS], JSON.stringify(['@datadog-dd-trace-js'])) + assert.strictEqual(passedTestSpan.meta.customTag, 'customValue') + assert.strictEqual(passedTestSpan.meta.addTagsBeforeEach, 'customBeforeEach') + assert.strictEqual(passedTestSpan.meta.addTagsAfterEach, 'customAfterEach') + + assert.ok(failedTestSpan != null) + assert.strictEqual(failedTestSpan.name, 'cypress.test') + assert.strictEqual(failedTestSpan.resource, 'cypress/e2e/basic-fail.js.basic fail suite can fail') + assert.strictEqual(failedTestSpan.type, 'test') + assert.strictEqual(failedTestSpan.meta[TEST_STATUS], 'fail') + assert.strictEqual(failedTestSpan.meta[TEST_NAME], 'basic fail suite can fail') + assert.strictEqual(failedTestSpan.meta[TEST_SUITE], 'cypress/e2e/basic-fail.js') + assert.strictEqual(failedTestSpan.meta[TEST_FRAMEWORK], 'cypress') + assert.strictEqual(failedTestSpan.meta[TEST_TYPE], 'browser') + assert.ok(failedTestSpan.meta[TEST_SOURCE_FILE] != null) + assert.ok(failedTestSpan.meta[TEST_SOURCE_FILE].includes('cypress/e2e/basic-fail.js')) + assert.ok(failedTestSpan.meta[TEST_FRAMEWORK_VERSION] != null) + assert.ok(failedTestSpan.meta[COMPONENT] != null) + assert.ok(failedTestSpan.meta[ERROR_MESSAGE] != null) + assert.ok(failedTestSpan.meta[ERROR_MESSAGE].includes('expected')) + assert.ok(failedTestSpan.meta[ERROR_TYPE] != null) + assert.ok(failedTestSpan.metrics[TEST_SOURCE_START] != null) + assert.strictEqual(passedTestSpan.meta[TEST_CODE_OWNERS], JSON.stringify(['@datadog-dd-trace-js'])) + assert.strictEqual(failedTestSpan.meta.customTag, 'customValue') + assert.strictEqual(failedTestSpan.meta.addTagsBeforeEach, 'customBeforeEach') + assert.strictEqual(failedTestSpan.meta.addTagsAfterEach, 'customAfterEach') // Tags added after failure should not be present because test failed - assert.notProperty(failedTestSpan.meta, 'addTagsAfterFailure') + assert.ok(!Object.hasOwn(failedTestSpan.meta, 'addTagsAfterFailure')) }, 60000) const { @@ -326,11 +328,8 @@ moduleTypes.forEach(({ once(childProcess, 'exit'), once(childProcess.stdout, 'end') ]) - assert.include( - stdout, - 'WARNING: dd-trace support for Cypress<10.2.0 is deprecated' + - ' and will not be supported in future versions of dd-trace.' - ) + assert.ok(stdout.includes('WARNING: dd-trace support for Cypress<10.2.0 is deprecated' + + ' and will not be supported in future versions of dd-trace.')) }) } @@ -379,8 +378,8 @@ moduleTypes.forEach(({ assert.strictEqual(hasReceivedEvents, false) // TODO: remove try/catch once we find the source of flakiness try { - assert.notInclude(testOutput, 'TypeError') - assert.include(testOutput, '1 of 1 failed') + assert.ok(!testOutput.includes('TypeError')) + assert.ok(testOutput.includes('1 of 1 failed')) } catch (e) { // eslint-disable-next-line no-console console.log('---- Actual test output -----') @@ -412,12 +411,12 @@ moduleTypes.forEach(({ event => event.content.resource === 'cypress/e2e/hook-test-error.cy.js.hook-test-error tests does not run because earlier afterEach fails' ) - assert.equal(passedTest.content.meta[TEST_STATUS], 'pass') - assert.equal(failedTest.content.meta[TEST_STATUS], 'fail') - assert.include(failedTest.content.meta[ERROR_MESSAGE], 'error in after each hook') - assert.equal(skippedTest.content.meta[TEST_STATUS], 'skip') - assert.equal(testHookSuite.content.meta[TEST_STATUS], 'fail') - assert.include(testHookSuite.content.meta[ERROR_MESSAGE], 'error in after each hook') + assert.strictEqual(passedTest.content.meta[TEST_STATUS], 'pass') + assert.strictEqual(failedTest.content.meta[TEST_STATUS], 'fail') + assert.ok(failedTest.content.meta[ERROR_MESSAGE].includes('error in after each hook')) + assert.strictEqual(skippedTest.content.meta[TEST_STATUS], 'skip') + assert.strictEqual(testHookSuite.content.meta[TEST_STATUS], 'fail') + assert.ok(testHookSuite.content.meta[ERROR_MESSAGE].includes('error in after each hook')) // describe level hooks const describeHookSuite = events.find( @@ -432,12 +431,12 @@ moduleTypes.forEach(({ const skippedTestDescribe = events.find( event => event.content.resource === 'cypress/e2e/hook-describe-error.cy.js.before will be skipped' ) - assert.equal(passedTestDescribe.content.meta[TEST_STATUS], 'pass') - assert.equal(failedTestDescribe.content.meta[TEST_STATUS], 'fail') - assert.include(failedTestDescribe.content.meta[ERROR_MESSAGE], 'error in after hook') - assert.equal(skippedTestDescribe.content.meta[TEST_STATUS], 'skip') - assert.equal(describeHookSuite.content.meta[TEST_STATUS], 'fail') - assert.include(describeHookSuite.content.meta[ERROR_MESSAGE], 'error in after hook') + assert.strictEqual(passedTestDescribe.content.meta[TEST_STATUS], 'pass') + assert.strictEqual(failedTestDescribe.content.meta[TEST_STATUS], 'fail') + assert.ok(failedTestDescribe.content.meta[ERROR_MESSAGE].includes('error in after hook')) + assert.strictEqual(skippedTestDescribe.content.meta[TEST_STATUS], 'skip') + assert.strictEqual(describeHookSuite.content.meta[TEST_STATUS], 'fail') + assert.ok(describeHookSuite.content.meta[ERROR_MESSAGE].includes('error in after hook')) }, 25000) const { @@ -470,7 +469,7 @@ moduleTypes.forEach(({ metadataDicts.forEach(metadata => { for (const testLevel of TEST_LEVEL_EVENT_TYPES) { - assert.equal(metadata[testLevel][TEST_SESSION_NAME], 'my-test-session') + assert.strictEqual(metadata[testLevel][TEST_SESSION_NAME], 'my-test-session') } }) const events = payloads.flatMap(({ payload }) => payload.events) @@ -483,23 +482,20 @@ moduleTypes.forEach(({ const { content: testSessionEventContent } = testSessionEvent const { content: testModuleEventContent } = testModuleEvent - assert.exists(testSessionEventContent.test_session_id) - assert.exists(testSessionEventContent.meta[TEST_COMMAND]) - assert.exists(testSessionEventContent.meta[TEST_TOOLCHAIN]) - assert.equal(testSessionEventContent.resource.startsWith('test_session.'), true) - assert.equal(testSessionEventContent.meta[TEST_STATUS], 'fail') - - assert.exists(testModuleEventContent.test_session_id) - assert.exists(testModuleEventContent.test_module_id) - assert.exists(testModuleEventContent.meta[TEST_COMMAND]) - assert.exists(testModuleEventContent.meta[TEST_MODULE]) - assert.equal(testModuleEventContent.resource.startsWith('test_module.'), true) - assert.equal(testModuleEventContent.meta[TEST_STATUS], 'fail') - assert.equal( - testModuleEventContent.test_session_id.toString(10), - testSessionEventContent.test_session_id.toString(10) - ) - assert.exists(testModuleEventContent.meta[TEST_FRAMEWORK_VERSION]) + assert.ok(testSessionEventContent.test_session_id != null) + assert.ok(testSessionEventContent.meta[TEST_COMMAND] != null) + assert.ok(testSessionEventContent.meta[TEST_TOOLCHAIN] != null) + assert.strictEqual(testSessionEventContent.resource.startsWith('test_session.'), true) + assert.strictEqual(testSessionEventContent.meta[TEST_STATUS], 'fail') + + assert.ok(testModuleEventContent.test_session_id != null) + assert.ok(testModuleEventContent.test_module_id != null) + assert.ok(testModuleEventContent.meta[TEST_COMMAND] != null) + assert.ok(testModuleEventContent.meta[TEST_MODULE] != null) + assert.strictEqual(testModuleEventContent.resource.startsWith('test_module.'), true) + assert.strictEqual(testModuleEventContent.meta[TEST_STATUS], 'fail') + assert.strictEqual(testModuleEventContent.test_session_id.toString(10), testSessionEventContent.test_session_id.toString(10)) + assert.ok(testModuleEventContent.meta[TEST_FRAMEWORK_VERSION] != null) assert.includeMembers(testSuiteEvents.map(suite => suite.content.resource), [ 'test_suite.cypress/e2e/other.cy.js', @@ -520,14 +516,14 @@ moduleTypes.forEach(({ test_session_id: testSessionId } }) => { - assert.exists(meta[TEST_COMMAND]) - assert.exists(meta[TEST_MODULE]) - assert.exists(testSuiteId) - assert.equal(testModuleId.toString(10), testModuleEventContent.test_module_id.toString(10)) - assert.equal(testSessionId.toString(10), testSessionEventContent.test_session_id.toString(10)) - assert.isTrue(meta[TEST_SOURCE_FILE].startsWith('cypress/e2e/')) - assert.equal(metrics[TEST_SOURCE_START], 1) - assert.exists(metrics[DD_HOST_CPU_COUNT]) + assert.ok(meta[TEST_COMMAND] != null) + assert.ok(meta[TEST_MODULE] != null) + assert.ok(testSuiteId != null) + assert.strictEqual(testModuleId.toString(10), testModuleEventContent.test_module_id.toString(10)) + assert.strictEqual(testSessionId.toString(10), testSessionEventContent.test_session_id.toString(10)) + assert.strictEqual(meta[TEST_SOURCE_FILE].startsWith('cypress/e2e/'), true) + assert.strictEqual(metrics[TEST_SOURCE_START], 1) + assert.ok(metrics[DD_HOST_CPU_COUNT] != null) }) assert.includeMembers(testEvents.map(test => test.content.resource), [ @@ -551,17 +547,17 @@ moduleTypes.forEach(({ test_session_id: testSessionId } }) => { - assert.exists(meta[TEST_COMMAND]) - assert.exists(meta[TEST_MODULE]) - assert.exists(testSuiteId) - assert.equal(testModuleId.toString(10), testModuleEventContent.test_module_id.toString(10)) - assert.equal(testSessionId.toString(10), testSessionEventContent.test_session_id.toString(10)) - assert.equal(meta[TEST_SOURCE_FILE].startsWith('cypress/e2e/'), true) + assert.ok(meta[TEST_COMMAND] != null) + assert.ok(meta[TEST_MODULE] != null) + assert.ok(testSuiteId != null) + assert.strictEqual(testModuleId.toString(10), testModuleEventContent.test_module_id.toString(10)) + assert.strictEqual(testSessionId.toString(10), testSessionEventContent.test_session_id.toString(10)) + assert.strictEqual(meta[TEST_SOURCE_FILE].startsWith('cypress/e2e/'), true) // Can read DD_TAGS - assert.propertyVal(meta, DD_TEST_IS_USER_PROVIDED_SERVICE, 'false') - assert.propertyVal(meta, 'test.customtag', 'customvalue') - assert.propertyVal(meta, 'test.customtag2', 'customvalue2') - assert.exists(metrics[DD_HOST_CPU_COUNT]) + assert.strictEqual(meta[DD_TEST_IS_USER_PROVIDED_SERVICE], 'false') + assert.strictEqual(meta['test.customtag'], 'customvalue') + assert.strictEqual(meta['test.customtag2'], 'customvalue2') + assert.ok(metrics[DD_HOST_CPU_COUNT] != null) }) }, 25000) @@ -604,10 +600,10 @@ moduleTypes.forEach(({ .flatMap(content => content.coverages) coverages.forEach(coverage => { - assert.property(coverage, 'test_session_id') - assert.property(coverage, 'test_suite_id') - assert.property(coverage, 'span_id') - assert.property(coverage, 'files') + assert.ok(Object.hasOwn(coverage, 'test_session_id')) + assert.ok(Object.hasOwn(coverage, 'test_suite_id')) + assert.ok(Object.hasOwn(coverage, 'span_id')) + assert.ok(Object.hasOwn(coverage, 'files')) }) const fileNames = coverages @@ -672,8 +668,8 @@ moduleTypes.forEach(({ searchCommitsRequestPromise, packfileRequestPromise ]) - assert.propertyVal(searchCommitRequest.headers, 'dd-api-key', '1') - assert.propertyVal(packfileRequest.headers, 'dd-api-key', '1') + assert.strictEqual(searchCommitRequest.headers['dd-api-key'], '1') + assert.strictEqual(packfileRequest.headers['dd-api-key'], '1') }) it('does not report code coverage if disabled by the API', async () => { @@ -716,7 +712,7 @@ moduleTypes.forEach(({ once(childProcess, 'exit'), receiverPromise ]) - assert.isFalse(hasReportedCodeCoverage) + assert.strictEqual(hasReportedCodeCoverage, false) }) it('can skip tests received by the intelligent test runner API and still reports code coverage', async () => { @@ -735,35 +731,35 @@ moduleTypes.forEach(({ const skippedTest = events.find(event => event.content.resource === 'cypress/e2e/other.cy.js.context passes' ).content - assert.propertyVal(skippedTest.meta, TEST_STATUS, 'skip') - assert.propertyVal(skippedTest.meta, TEST_SKIPPED_BY_ITR, 'true') + assert.strictEqual(skippedTest.meta[TEST_STATUS], 'skip') + assert.strictEqual(skippedTest.meta[TEST_SKIPPED_BY_ITR], 'true') assert.includeMembers(eventTypes, ['test', 'test_suite_end', 'test_module_end', 'test_session_end']) const testSession = events.find(event => event.type === 'test_session_end').content - assert.propertyVal(testSession.meta, TEST_ITR_TESTS_SKIPPED, 'true') - assert.propertyVal(testSession.meta, TEST_CODE_COVERAGE_ENABLED, 'true') - assert.propertyVal(testSession.meta, TEST_ITR_SKIPPING_ENABLED, 'true') - assert.propertyVal(testSession.metrics, TEST_ITR_SKIPPING_COUNT, 1) - assert.propertyVal(testSession.meta, TEST_ITR_SKIPPING_TYPE, 'test') + assert.strictEqual(testSession.meta[TEST_ITR_TESTS_SKIPPED], 'true') + assert.strictEqual(testSession.meta[TEST_CODE_COVERAGE_ENABLED], 'true') + assert.strictEqual(testSession.meta[TEST_ITR_SKIPPING_ENABLED], 'true') + assert.strictEqual(testSession.metrics[TEST_ITR_SKIPPING_COUNT], 1) + assert.strictEqual(testSession.meta[TEST_ITR_SKIPPING_TYPE], 'test') const testModule = events.find(event => event.type === 'test_module_end').content - assert.propertyVal(testModule.meta, TEST_ITR_TESTS_SKIPPED, 'true') - assert.propertyVal(testModule.meta, TEST_CODE_COVERAGE_ENABLED, 'true') - assert.propertyVal(testModule.meta, TEST_ITR_SKIPPING_ENABLED, 'true') - assert.propertyVal(testModule.metrics, TEST_ITR_SKIPPING_COUNT, 1) - assert.propertyVal(testModule.meta, TEST_ITR_SKIPPING_TYPE, 'test') + assert.strictEqual(testModule.meta[TEST_ITR_TESTS_SKIPPED], 'true') + assert.strictEqual(testModule.meta[TEST_CODE_COVERAGE_ENABLED], 'true') + assert.strictEqual(testModule.meta[TEST_ITR_SKIPPING_ENABLED], 'true') + assert.strictEqual(testModule.metrics[TEST_ITR_SKIPPING_COUNT], 1) + assert.strictEqual(testModule.meta[TEST_ITR_SKIPPING_TYPE], 'test') }, 25000) const coverageRequestPromise = receiver .payloadReceived(({ url }) => url.endsWith('/api/v2/citestcov'), 25000) .then(coverageRequest => { - assert.propertyVal(coverageRequest.headers, 'dd-api-key', '1') + assert.strictEqual(coverageRequest.headers['dd-api-key'], '1') }) const skippableRequestPromise = receiver .payloadReceived(({ url }) => url.endsWith('/api/v2/ci/tests/skippable'), 25000) .then(skippableRequest => { - assert.propertyVal(skippableRequest.headers, 'dd-api-key', '1') + assert.strictEqual(skippableRequest.headers['dd-api-key'], '1') }) const { @@ -821,8 +817,8 @@ moduleTypes.forEach(({ const notSkippedTest = events.find(event => event.content.resource === 'cypress/e2e/other.cy.js.context passes' ) - assert.exists(notSkippedTest) - assert.equal(notSkippedTest.content.meta[TEST_STATUS], 'pass') + assert.ok(notSkippedTest != null) + assert.strictEqual(notSkippedTest.content.meta[TEST_STATUS], 'pass') }, 25000) const { @@ -851,7 +847,7 @@ moduleTypes.forEach(({ once(childProcess, 'exit'), receiverPromise ]) - assert.isFalse(hasRequestedSkippable) + assert.strictEqual(hasRequestedSkippable, false) }) it('does not skip tests if suite is marked as unskippable', async () => { @@ -883,10 +879,10 @@ moduleTypes.forEach(({ const testSession = events.find(event => event.type === 'test_session_end').content const testModule = events.find(event => event.type === 'test_session_end').content - assert.propertyVal(testSession.meta, TEST_ITR_UNSKIPPABLE, 'true') - assert.propertyVal(testSession.meta, TEST_ITR_FORCED_RUN, 'true') - assert.propertyVal(testModule.meta, TEST_ITR_UNSKIPPABLE, 'true') - assert.propertyVal(testModule.meta, TEST_ITR_FORCED_RUN, 'true') + assert.strictEqual(testSession.meta[TEST_ITR_UNSKIPPABLE], 'true') + assert.strictEqual(testSession.meta[TEST_ITR_FORCED_RUN], 'true') + assert.strictEqual(testModule.meta[TEST_ITR_UNSKIPPABLE], 'true') + assert.strictEqual(testModule.meta[TEST_ITR_FORCED_RUN], 'true') const unskippablePassedTest = events.find(event => event.content.resource === 'cypress/e2e/spec.cy.js.context passes' @@ -894,14 +890,14 @@ moduleTypes.forEach(({ const unskippableFailedTest = events.find(event => event.content.resource === 'cypress/e2e/spec.cy.js.other context fails' ) - assert.propertyVal(unskippablePassedTest.content.meta, TEST_STATUS, 'pass') - assert.propertyVal(unskippablePassedTest.content.meta, TEST_ITR_UNSKIPPABLE, 'true') - assert.propertyVal(unskippablePassedTest.content.meta, TEST_ITR_FORCED_RUN, 'true') + assert.strictEqual(unskippablePassedTest.content.meta[TEST_STATUS], 'pass') + assert.strictEqual(unskippablePassedTest.content.meta[TEST_ITR_UNSKIPPABLE], 'true') + assert.strictEqual(unskippablePassedTest.content.meta[TEST_ITR_FORCED_RUN], 'true') - assert.propertyVal(unskippableFailedTest.content.meta, TEST_STATUS, 'fail') - assert.propertyVal(unskippableFailedTest.content.meta, TEST_ITR_UNSKIPPABLE, 'true') + assert.strictEqual(unskippableFailedTest.content.meta[TEST_STATUS], 'fail') + assert.strictEqual(unskippableFailedTest.content.meta[TEST_ITR_UNSKIPPABLE], 'true') // This was not going to be skipped - assert.notProperty(unskippableFailedTest.content.meta, TEST_ITR_FORCED_RUN) + assert.ok(!Object.hasOwn(unskippableFailedTest.content.meta, TEST_ITR_FORCED_RUN)) }, 25000) const { @@ -955,10 +951,10 @@ moduleTypes.forEach(({ const testSession = events.find(event => event.type === 'test_session_end').content const testModule = events.find(event => event.type === 'test_session_end').content - assert.propertyVal(testSession.meta, TEST_ITR_UNSKIPPABLE, 'true') - assert.notProperty(testSession.meta, TEST_ITR_FORCED_RUN) - assert.propertyVal(testModule.meta, TEST_ITR_UNSKIPPABLE, 'true') - assert.notProperty(testModule.meta, TEST_ITR_FORCED_RUN) + assert.strictEqual(testSession.meta[TEST_ITR_UNSKIPPABLE], 'true') + assert.ok(!Object.hasOwn(testSession.meta, TEST_ITR_FORCED_RUN)) + assert.strictEqual(testModule.meta[TEST_ITR_UNSKIPPABLE], 'true') + assert.ok(!Object.hasOwn(testModule.meta, TEST_ITR_FORCED_RUN)) const unskippablePassedTest = events.find(event => event.content.resource === 'cypress/e2e/spec.cy.js.context passes' @@ -966,15 +962,15 @@ moduleTypes.forEach(({ const unskippableFailedTest = events.find(event => event.content.resource === 'cypress/e2e/spec.cy.js.other context fails' ) - assert.propertyVal(unskippablePassedTest.content.meta, TEST_STATUS, 'pass') - assert.propertyVal(unskippablePassedTest.content.meta, TEST_ITR_UNSKIPPABLE, 'true') + assert.strictEqual(unskippablePassedTest.content.meta[TEST_STATUS], 'pass') + assert.strictEqual(unskippablePassedTest.content.meta[TEST_ITR_UNSKIPPABLE], 'true') // This was not going to be skipped - assert.notProperty(unskippablePassedTest.content.meta, TEST_ITR_FORCED_RUN) + assert.ok(!Object.hasOwn(unskippablePassedTest.content.meta, TEST_ITR_FORCED_RUN)) - assert.propertyVal(unskippableFailedTest.content.meta, TEST_STATUS, 'fail') - assert.propertyVal(unskippableFailedTest.content.meta, TEST_ITR_UNSKIPPABLE, 'true') + assert.strictEqual(unskippableFailedTest.content.meta[TEST_STATUS], 'fail') + assert.strictEqual(unskippableFailedTest.content.meta[TEST_ITR_UNSKIPPABLE], 'true') // This was not going to be skipped - assert.notProperty(unskippableFailedTest.content.meta, TEST_ITR_FORCED_RUN) + assert.ok(!Object.hasOwn(unskippableFailedTest.content.meta, TEST_ITR_FORCED_RUN)) }, 25000) const { @@ -1017,21 +1013,21 @@ moduleTypes.forEach(({ .gatherPayloadsMaxTimeout(({ url }) => url.endsWith('/api/v2/citestcycle'), (payloads) => { const events = payloads.flatMap(({ payload }) => payload.events) const testSession = events.find(event => event.type === 'test_session_end').content - assert.propertyVal(testSession.meta, TEST_ITR_TESTS_SKIPPED, 'false') - assert.propertyVal(testSession.meta, TEST_CODE_COVERAGE_ENABLED, 'true') - assert.propertyVal(testSession.meta, TEST_ITR_SKIPPING_ENABLED, 'true') - assert.propertyVal(testSession.metrics, TEST_ITR_SKIPPING_COUNT, 0) + assert.strictEqual(testSession.meta[TEST_ITR_TESTS_SKIPPED], 'false') + assert.strictEqual(testSession.meta[TEST_CODE_COVERAGE_ENABLED], 'true') + assert.strictEqual(testSession.meta[TEST_ITR_SKIPPING_ENABLED], 'true') + assert.strictEqual(testSession.metrics[TEST_ITR_SKIPPING_COUNT], 0) const testModule = events.find(event => event.type === 'test_module_end').content - assert.propertyVal(testModule.meta, TEST_ITR_TESTS_SKIPPED, 'false') - assert.propertyVal(testModule.meta, TEST_CODE_COVERAGE_ENABLED, 'true') - assert.propertyVal(testModule.meta, TEST_ITR_SKIPPING_ENABLED, 'true') - assert.propertyVal(testModule.metrics, TEST_ITR_SKIPPING_COUNT, 0) + assert.strictEqual(testModule.meta[TEST_ITR_TESTS_SKIPPED], 'false') + assert.strictEqual(testModule.meta[TEST_CODE_COVERAGE_ENABLED], 'true') + assert.strictEqual(testModule.meta[TEST_ITR_SKIPPING_ENABLED], 'true') + assert.strictEqual(testModule.metrics[TEST_ITR_SKIPPING_COUNT], 0) }, 30000) const skippableRequestPromise = receiver .payloadReceived(({ url }) => url.endsWith('/api/v2/ci/tests/skippable'), 30000) .then(skippableRequest => { - assert.propertyVal(skippableRequest.headers, 'dd-api-key', '1') + assert.strictEqual(skippableRequest.headers['dd-api-key'], '1') }) const { @@ -1071,7 +1067,7 @@ moduleTypes.forEach(({ const events = payloads.flatMap(({ payload }) => payload.events) const tests = events.filter(event => event.type === 'test').map(event => event.content) tests.forEach(test => { - assert.equal(test.itr_correlation_id, itrCorrelationId) + assert.strictEqual(test.itr_correlation_id, itrCorrelationId) }) }, 25000) @@ -1174,10 +1170,10 @@ moduleTypes.forEach(({ const testModuleEvent = events.find(event => event.type === 'test_module_end') testEvents.forEach(testEvent => { - assert.exists(testEvent.content.test_suite_id) - assert.exists(testEvent.content.test_module_id) - assert.exists(testEvent.content.test_session_id) - assert.notEqual(testEvent.content.test_suite_id, testModuleEvent.content.test_module_id) + assert.ok(testEvent.content.test_suite_id != null) + assert.ok(testEvent.content.test_module_id != null) + assert.ok(testEvent.content.test_session_id != null) + assert.notStrictEqual(testEvent.content.test_suite_id, testModuleEvent.content.test_module_id) }) }, 25000) @@ -1206,13 +1202,13 @@ moduleTypes.forEach(({ .gatherPayloadsMaxTimeout(({ url }) => url.endsWith('/api/v2/citestcycle'), payloads => { const events = payloads.flatMap(({ payload }) => payload.events) const testSessionEvent = events.find(event => event.type === 'test_session_end') - assert.exists(testSessionEvent) + assert.ok(testSessionEvent != null) const testModuleEvent = events.find(event => event.type === 'test_module_end') - assert.exists(testModuleEvent) + assert.ok(testModuleEvent != null) const testSuiteEvents = events.filter(event => event.type === 'test_suite_end') - assert.equal(testSuiteEvents.length, 4) + assert.strictEqual(testSuiteEvents.length, 4) const testEvents = events.filter(event => event.type === 'test') - assert.equal(testEvents.length, 9) + assert.strictEqual(testEvents.length, 9) }, 30000) const { @@ -1244,13 +1240,13 @@ moduleTypes.forEach(({ .gatherPayloadsMaxTimeout(({ url }) => url.endsWith('/api/v2/citestcycle'), payloads => { const events = payloads.flatMap(({ payload }) => payload.events) const testSessionEvent = events.find(event => event.type === 'test_session_end') - assert.exists(testSessionEvent) + assert.ok(testSessionEvent != null) const testModuleEvent = events.find(event => event.type === 'test_module_end') - assert.exists(testModuleEvent) + assert.ok(testModuleEvent != null) const testSuiteEvents = events.filter(event => event.type === 'test_suite_end') - assert.equal(testSuiteEvents.length, 4) + assert.strictEqual(testSuiteEvents.length, 4) const testEvents = events.filter(event => event.type === 'test') - assert.equal(testEvents.length, 9) + assert.strictEqual(testEvents.length, 9) }, 30000) const { @@ -1302,28 +1298,28 @@ moduleTypes.forEach(({ .gatherPayloadsMaxTimeout(({ url }) => url.endsWith('/api/v2/citestcycle'), payloads => { const events = payloads.flatMap(({ payload }) => payload.events) const tests = events.filter(event => event.type === 'test').map(event => event.content) - assert.equal(tests.length, 5) + assert.strictEqual(tests.length, 5) const newTests = tests.filter(test => test.meta[TEST_IS_NEW] === 'true') - assert.equal(newTests.length, NUM_RETRIES_EFD + 1) + assert.strictEqual(newTests.length, NUM_RETRIES_EFD + 1) const retriedTests = tests.filter(test => test.meta[TEST_IS_RETRY] === 'true') - assert.equal(retriedTests.length, NUM_RETRIES_EFD) + assert.strictEqual(retriedTests.length, NUM_RETRIES_EFD) retriedTests.forEach((retriedTest) => { - assert.equal(retriedTest.meta[TEST_RETRY_REASON], TEST_RETRY_REASON_TYPES.efd) + assert.strictEqual(retriedTest.meta[TEST_RETRY_REASON], TEST_RETRY_REASON_TYPES.efd) }) newTests.forEach(newTest => { - assert.equal(newTest.resource, 'cypress/e2e/spec.cy.js.context passes') + assert.strictEqual(newTest.resource, 'cypress/e2e/spec.cy.js.context passes') }) const knownTest = tests.filter(test => !test.meta[TEST_IS_NEW]) - assert.equal(knownTest.length, 1) - assert.equal(knownTest[0].resource, 'cypress/e2e/spec.cy.js.other context fails') + assert.strictEqual(knownTest.length, 1) + assert.strictEqual(knownTest[0].resource, 'cypress/e2e/spec.cy.js.other context fails') const testSession = events.find(event => event.type === 'test_session_end').content - assert.propertyVal(testSession.meta, TEST_EARLY_FLAKE_ENABLED, 'true') + assert.strictEqual(testSession.meta[TEST_EARLY_FLAKE_ENABLED], 'true') }, 25000) const { @@ -1381,17 +1377,17 @@ moduleTypes.forEach(({ .gatherPayloadsMaxTimeout(({ url }) => url.endsWith('/api/v2/citestcycle'), payloads => { const events = payloads.flatMap(({ payload }) => payload.events) const tests = events.filter(event => event.type === 'test').map(event => event.content) - assert.equal(tests.length, 2) + assert.strictEqual(tests.length, 2) // new tests are detected but not retried const newTests = tests.filter(test => test.meta[TEST_IS_NEW] === 'true') - assert.equal(newTests.length, 1) + assert.strictEqual(newTests.length, 1) const retriedTests = tests.filter(test => test.meta[TEST_IS_RETRY] === 'true') - assert.equal(retriedTests.length, 0) + assert.strictEqual(retriedTests.length, 0) const testSession = events.find(event => event.type === 'test_session_end').content - assert.notProperty(testSession.meta, TEST_EARLY_FLAKE_ENABLED) + assert.ok(!Object.hasOwn(testSession.meta, TEST_EARLY_FLAKE_ENABLED)) }, 25000) const specToRun = 'cypress/e2e/spec.cy.js' @@ -1439,16 +1435,16 @@ moduleTypes.forEach(({ .gatherPayloadsMaxTimeout(({ url }) => url.endsWith('/api/v2/citestcycle'), payloads => { const events = payloads.flatMap(({ payload }) => payload.events) const tests = events.filter(event => event.type === 'test').map(event => event.content) - assert.equal(tests.length, 1) + assert.strictEqual(tests.length, 1) const newTests = tests.filter(test => test.meta[TEST_IS_NEW] === 'true') - assert.equal(newTests.length, 0) + assert.strictEqual(newTests.length, 0) - assert.equal(tests[0].resource, 'cypress/e2e/skipped-test.js.skipped skipped') - assert.propertyVal(tests[0].meta, TEST_STATUS, 'skip') + assert.strictEqual(tests[0].resource, 'cypress/e2e/skipped-test.js.skipped skipped') + assert.strictEqual(tests[0].meta[TEST_STATUS], 'skip') const testSession = events.find(event => event.type === 'test_session_end').content - assert.propertyVal(testSession.meta, TEST_EARLY_FLAKE_ENABLED, 'true') + assert.strictEqual(testSession.meta[TEST_EARLY_FLAKE_ENABLED], 'true') }, 25000) const specToRun = 'cypress/e2e/skipped-test.js' @@ -1497,13 +1493,13 @@ moduleTypes.forEach(({ .gatherPayloadsMaxTimeout(({ url }) => url.endsWith('/api/v2/citestcycle'), payloads => { const events = payloads.flatMap(({ payload }) => payload.events) const testSession = events.find(event => event.type === 'test_session_end').content - assert.notProperty(testSession.meta, TEST_EARLY_FLAKE_ENABLED) + assert.ok(!Object.hasOwn(testSession.meta, TEST_EARLY_FLAKE_ENABLED)) const tests = events.filter(event => event.type === 'test').map(event => event.content) - assert.equal(tests.length, 2) + assert.strictEqual(tests.length, 2) const newTests = tests.filter(test => test.meta[TEST_IS_NEW] === 'true') - assert.equal(newTests.length, 0) + assert.strictEqual(newTests.length, 0) }, 25000) const specToRun = 'cypress/e2e/spec.cy.js' @@ -1556,17 +1552,17 @@ moduleTypes.forEach(({ .gatherPayloadsMaxTimeout(({ url }) => url.endsWith('/api/v2/citestcycle'), payloads => { const events = payloads.flatMap(({ payload }) => payload.events) const tests = events.filter(event => event.type === 'test').map(event => event.content) - assert.equal(tests.length, 2) + assert.strictEqual(tests.length, 2) // new tests are not detected const newTests = tests.filter(test => test.meta[TEST_IS_NEW] === 'true') - assert.equal(newTests.length, 0) + assert.strictEqual(newTests.length, 0) const retriedTests = tests.filter(test => test.meta[TEST_IS_RETRY] === 'true') - assert.equal(retriedTests.length, 0) + assert.strictEqual(retriedTests.length, 0) const testSession = events.find(event => event.type === 'test_session_end').content - assert.notProperty(testSession.meta, TEST_EARLY_FLAKE_ENABLED) + assert.ok(!Object.hasOwn(testSession.meta, TEST_EARLY_FLAKE_ENABLED)) }, 25000) const specToRun = 'cypress/e2e/spec.cy.js' @@ -1618,17 +1614,17 @@ moduleTypes.forEach(({ .gatherPayloadsMaxTimeout(({ url }) => url.endsWith('/api/v2/citestcycle'), payloads => { const events = payloads.flatMap(({ payload }) => payload.events) const tests = events.filter(event => event.type === 'test').map(event => event.content) - assert.equal(tests.length, 2) + assert.strictEqual(tests.length, 2) // new tests are not detected const newTests = tests.filter(test => test.meta[TEST_IS_NEW] === 'true') - assert.equal(newTests.length, 0) + assert.strictEqual(newTests.length, 0) const retriedTests = tests.filter(test => test.meta[TEST_IS_RETRY] === 'true') - assert.equal(retriedTests.length, 0) + assert.strictEqual(retriedTests.length, 0) const testSession = events.find(event => event.type === 'test_session_end').content - assert.notProperty(testSession.meta, TEST_EARLY_FLAKE_ENABLED) + assert.ok(!Object.hasOwn(testSession.meta, TEST_EARLY_FLAKE_ENABLED)) }, 25000) const specToRun = 'cypress/e2e/spec.cy.js' @@ -1841,11 +1837,11 @@ moduleTypes.forEach(({ .gatherPayloadsMaxTimeout(({ url }) => url.endsWith('/api/v2/citestcycle'), payloads => { const events = payloads.flatMap(({ payload }) => payload.events) const testSuites = events.filter(event => event.type === 'test_suite_end').map(event => event.content) - assert.equal(testSuites.length, 1) - assert.equal(testSuites[0].meta[TEST_STATUS], 'fail') + assert.strictEqual(testSuites.length, 1) + assert.strictEqual(testSuites[0].meta[TEST_STATUS], 'fail') const tests = events.filter(event => event.type === 'test').map(event => event.content) - assert.equal(tests.length, 10) + assert.strictEqual(tests.length, 10) assert.includeMembers(tests.map(test => test.resource), [ 'cypress/e2e/flaky-test-retries.js.flaky test retry eventually passes', @@ -1866,22 +1862,22 @@ moduleTypes.forEach(({ const eventuallyPassingTest = tests.filter( test => test.resource === 'cypress/e2e/flaky-test-retries.js.flaky test retry eventually passes' ) - assert.equal(eventuallyPassingTest.length, 3) - assert.equal(eventuallyPassingTest.filter(test => test.meta[TEST_STATUS] === 'fail').length, 2) - assert.equal(eventuallyPassingTest.filter(test => test.meta[TEST_STATUS] === 'pass').length, 1) - assert.equal(eventuallyPassingTest.filter(test => test.meta[TEST_IS_RETRY] === 'true').length, 2) - assert.equal(eventuallyPassingTest.filter(test => + assert.strictEqual(eventuallyPassingTest.length, 3) + assert.strictEqual(eventuallyPassingTest.filter(test => test.meta[TEST_STATUS] === 'fail').length, 2) + assert.strictEqual(eventuallyPassingTest.filter(test => test.meta[TEST_STATUS] === 'pass').length, 1) + assert.strictEqual(eventuallyPassingTest.filter(test => test.meta[TEST_IS_RETRY] === 'true').length, 2) + assert.strictEqual(eventuallyPassingTest.filter(test => test.meta[TEST_RETRY_REASON] === TEST_RETRY_REASON_TYPES.atr ).length, 2) const neverPassingTest = tests.filter( test => test.resource === 'cypress/e2e/flaky-test-retries.js.flaky test retry never passes' ) - assert.equal(neverPassingTest.length, 6) - assert.equal(neverPassingTest.filter(test => test.meta[TEST_STATUS] === 'fail').length, 6) - assert.equal(neverPassingTest.filter(test => test.meta[TEST_STATUS] === 'pass').length, 0) - assert.equal(neverPassingTest.filter(test => test.meta[TEST_IS_RETRY] === 'true').length, 5) - assert.equal(neverPassingTest.filter( + assert.strictEqual(neverPassingTest.length, 6) + assert.strictEqual(neverPassingTest.filter(test => test.meta[TEST_STATUS] === 'fail').length, 6) + assert.strictEqual(neverPassingTest.filter(test => test.meta[TEST_STATUS] === 'pass').length, 0) + assert.strictEqual(neverPassingTest.filter(test => test.meta[TEST_IS_RETRY] === 'true').length, 5) + assert.strictEqual(neverPassingTest.filter( test => test.meta[TEST_RETRY_REASON] === TEST_RETRY_REASON_TYPES.atr ).length, 5) }, 30000) @@ -1931,18 +1927,18 @@ moduleTypes.forEach(({ .gatherPayloadsMaxTimeout(({ url }) => url.endsWith('/api/v2/citestcycle'), payloads => { const events = payloads.flatMap(({ payload }) => payload.events) const testSuites = events.filter(event => event.type === 'test_suite_end').map(event => event.content) - assert.equal(testSuites.length, 1) - assert.equal(testSuites[0].meta[TEST_STATUS], 'fail') + assert.strictEqual(testSuites.length, 1) + assert.strictEqual(testSuites[0].meta[TEST_STATUS], 'fail') const tests = events.filter(event => event.type === 'test').map(event => event.content) - assert.equal(tests.length, 3) + assert.strictEqual(tests.length, 3) assert.includeMembers(tests.map(test => test.resource), [ 'cypress/e2e/flaky-test-retries.js.flaky test retry eventually passes', 'cypress/e2e/flaky-test-retries.js.flaky test retry never passes', 'cypress/e2e/flaky-test-retries.js.flaky test retry always passes' ]) - assert.equal(tests.filter(test => test.meta[TEST_RETRY_REASON] === TEST_RETRY_REASON_TYPES.atr).length, 0) + assert.strictEqual(tests.filter(test => test.meta[TEST_RETRY_REASON] === TEST_RETRY_REASON_TYPES.atr).length, 0) }, 25000) const { @@ -1987,11 +1983,11 @@ moduleTypes.forEach(({ .gatherPayloadsMaxTimeout(({ url }) => url.endsWith('/api/v2/citestcycle'), payloads => { const events = payloads.flatMap(({ payload }) => payload.events) const testSuites = events.filter(event => event.type === 'test_suite_end').map(event => event.content) - assert.equal(testSuites.length, 1) - assert.equal(testSuites[0].meta[TEST_STATUS], 'fail') + assert.strictEqual(testSuites.length, 1) + assert.strictEqual(testSuites[0].meta[TEST_STATUS], 'fail') const tests = events.filter(event => event.type === 'test').map(event => event.content) - assert.equal(tests.length, 5) + assert.strictEqual(tests.length, 5) assert.includeMembers(tests.map(test => test.resource), [ 'cypress/e2e/flaky-test-retries.js.flaky test retry eventually passes', @@ -2001,7 +1997,7 @@ moduleTypes.forEach(({ 'cypress/e2e/flaky-test-retries.js.flaky test retry always passes' ]) - assert.equal(tests.filter(test => test.meta[TEST_RETRY_REASON] === TEST_RETRY_REASON_TYPES.atr).length, 2) + assert.strictEqual(tests.filter(test => test.meta[TEST_RETRY_REASON] === TEST_RETRY_REASON_TYPES.atr).length, 2) }, 25000) const { @@ -2182,9 +2178,9 @@ moduleTypes.forEach(({ const test = events.find(event => event.type === 'test').content const testSuite = events.find(event => event.type === 'test_suite_end').content // The test is in a subproject - assert.notEqual(test.meta[TEST_SOURCE_FILE], test.meta[TEST_SUITE]) - assert.equal(test.meta[TEST_CODE_OWNERS], JSON.stringify(['@datadog-dd-trace-js'])) - assert.equal(testSuite.meta[TEST_CODE_OWNERS], JSON.stringify(['@datadog-dd-trace-js'])) + assert.notStrictEqual(test.meta[TEST_SOURCE_FILE], test.meta[TEST_SUITE]) + assert.strictEqual(test.meta[TEST_CODE_OWNERS], JSON.stringify(['@datadog-dd-trace-js'])) + assert.strictEqual(testSuite.meta[TEST_CODE_OWNERS], JSON.stringify(['@datadog-dd-trace-js'])) }, 25000) childProcess = exec( @@ -2229,17 +2225,17 @@ moduleTypes.forEach(({ .gatherPayloadsMaxTimeout(({ url }) => url.endsWith('/api/v2/citestcycle'), payloads => { const events = payloads.flatMap(({ payload }) => payload.events) const tests = events.filter(event => event.type === 'test').map(event => event.content) - assert.equal(tests.length, 2) + assert.strictEqual(tests.length, 2) // new tests are detected but not retried const newTests = tests.filter(test => test.meta[TEST_IS_NEW] === 'true') - assert.equal(newTests.length, 1) + assert.strictEqual(newTests.length, 1) const retriedTests = tests.filter(test => test.meta[TEST_IS_RETRY] === 'true') - assert.equal(retriedTests.length, 0) + assert.strictEqual(retriedTests.length, 0) const testSession = events.find(event => event.type === 'test_session_end').content - assert.notProperty(testSession.meta, TEST_EARLY_FLAKE_ENABLED) + assert.ok(!Object.hasOwn(testSession.meta, TEST_EARLY_FLAKE_ENABLED)) }, 25000) const specToRun = 'cypress/e2e/spec.cy.js' @@ -2275,11 +2271,11 @@ moduleTypes.forEach(({ const receiverPromise = receiver .gatherPayloadsMaxTimeout(({ url }) => url.endsWith('/api/v2/citestcycle'), payloads => { const events = payloads.flatMap(({ payload }) => payload.events) - assert.equal(events.length, 4) + assert.strictEqual(events.length, 4) const test = events.find(event => event.type === 'test').content - assert.equal(test.resource, 'cypress/e2e/multi-origin.js.tests multiple origins') - assert.equal(test.meta[TEST_STATUS], 'pass') + assert.strictEqual(test.resource, 'cypress/e2e/multi-origin.js.tests multiple origins') + assert.strictEqual(test.meta[TEST_STATUS], 'pass') }, 25000) secondWebAppServer = http.createServer((req, res) => { @@ -2331,7 +2327,7 @@ moduleTypes.forEach(({ const testEvents = events.filter(event => event.type === 'test') testEvents.forEach(({ content: { meta } }) => { - assert.propertyVal(meta, DD_TEST_IS_USER_PROVIDED_SERVICE, 'true') + assert.strictEqual(meta[DD_TEST_IS_USER_PROVIDED_SERVICE], 'true') }) }, 25000) @@ -2393,9 +2389,9 @@ moduleTypes.forEach(({ const testSession = events.find(event => event.type === 'test_session_end').content if (isAttemptToFix) { - assert.propertyVal(testSession.meta, TEST_MANAGEMENT_ENABLED, 'true') + assert.strictEqual(testSession.meta[TEST_MANAGEMENT_ENABLED], 'true') } else { - assert.notProperty(testSession.meta, TEST_MANAGEMENT_ENABLED) + assert.ok(!Object.hasOwn(testSession.meta, TEST_MANAGEMENT_ENABLED)) } const resourceNames = tests.map(span => span.resource) @@ -2411,48 +2407,48 @@ moduleTypes.forEach(({ ) if (isAttemptToFix) { - assert.equal(attemptToFixTests.length, 4) + assert.strictEqual(attemptToFixTests.length, 4) } else { - assert.equal(attemptToFixTests.length, 1) + assert.strictEqual(attemptToFixTests.length, 1) } for (let i = attemptToFixTests.length - 1; i >= 0; i--) { const test = attemptToFixTests[i] if (!isAttemptToFix) { - assert.notProperty(test.meta, TEST_MANAGEMENT_IS_ATTEMPT_TO_FIX) - assert.notProperty(test.meta, TEST_IS_RETRY) - assert.notProperty(test.meta, TEST_RETRY_REASON) + assert.ok(!Object.hasOwn(test.meta, TEST_MANAGEMENT_IS_ATTEMPT_TO_FIX)) + assert.ok(!Object.hasOwn(test.meta, TEST_IS_RETRY)) + assert.ok(!Object.hasOwn(test.meta, TEST_RETRY_REASON)) continue } if (isQuarantined) { - assert.propertyVal(test.meta, TEST_MANAGEMENT_IS_QUARANTINED, 'true') - assert.notPropertyVal(test.meta, TEST_STATUS, 'skip') + assert.strictEqual(test.meta[TEST_MANAGEMENT_IS_QUARANTINED], 'true') + assert.notStrictEqual(test.meta[TEST_STATUS], 'skip') } if (isDisabled) { - assert.propertyVal(test.meta, TEST_MANAGEMENT_IS_DISABLED, 'true') - assert.notPropertyVal(test.meta, TEST_STATUS, 'skip') + assert.strictEqual(test.meta[TEST_MANAGEMENT_IS_DISABLED], 'true') + assert.notStrictEqual(test.meta[TEST_STATUS], 'skip') } const isLastAttempt = i === attemptToFixTests.length - 1 const isFirstAttempt = i === 0 - assert.propertyVal(test.meta, TEST_MANAGEMENT_IS_ATTEMPT_TO_FIX, 'true') + assert.strictEqual(test.meta[TEST_MANAGEMENT_IS_ATTEMPT_TO_FIX], 'true') if (isFirstAttempt) { - assert.notProperty(test.meta, TEST_IS_RETRY) - assert.notProperty(test.meta, TEST_RETRY_REASON) + assert.ok(!Object.hasOwn(test.meta, TEST_IS_RETRY)) + assert.ok(!Object.hasOwn(test.meta, TEST_RETRY_REASON)) } else { - assert.propertyVal(test.meta, TEST_IS_RETRY, 'true') - assert.propertyVal(test.meta, TEST_RETRY_REASON, TEST_RETRY_REASON_TYPES.atf) + assert.strictEqual(test.meta[TEST_IS_RETRY], 'true') + assert.strictEqual(test.meta[TEST_RETRY_REASON], TEST_RETRY_REASON_TYPES.atf) } if (isLastAttempt) { if (shouldFailSometimes) { - assert.notProperty(test.meta, TEST_HAS_FAILED_ALL_RETRIES) - assert.propertyVal(test.meta, TEST_MANAGEMENT_ATTEMPT_TO_FIX_PASSED, 'false') + assert.ok(!Object.hasOwn(test.meta, TEST_HAS_FAILED_ALL_RETRIES)) + assert.strictEqual(test.meta[TEST_MANAGEMENT_ATTEMPT_TO_FIX_PASSED], 'false') } else if (shouldAlwaysPass) { - assert.propertyVal(test.meta, TEST_MANAGEMENT_ATTEMPT_TO_FIX_PASSED, 'true') - assert.notProperty(test.meta, TEST_HAS_FAILED_ALL_RETRIES) + assert.strictEqual(test.meta[TEST_MANAGEMENT_ATTEMPT_TO_FIX_PASSED], 'true') + assert.ok(!Object.hasOwn(test.meta, TEST_HAS_FAILED_ALL_RETRIES)) } else { - assert.propertyVal(test.meta, TEST_HAS_FAILED_ALL_RETRIES, 'true') - assert.propertyVal(test.meta, TEST_MANAGEMENT_ATTEMPT_TO_FIX_PASSED, 'false') + assert.strictEqual(test.meta[TEST_HAS_FAILED_ALL_RETRIES], 'true') + assert.strictEqual(test.meta[TEST_MANAGEMENT_ATTEMPT_TO_FIX_PASSED], 'false') } } } @@ -2507,11 +2503,11 @@ moduleTypes.forEach(({ ]) if (shouldAlwaysPass) { - assert.equal(exitCode, 0) + assert.strictEqual(exitCode, 0) } else { // TODO: we need to figure out how to trick cypress into returning exit code 0 // even if there are failed tests - assert.equal(exitCode, 1) + assert.strictEqual(exitCode, 1) } } @@ -2630,19 +2626,19 @@ moduleTypes.forEach(({ const testSession = events.find(event => event.type === 'test_session_end').content if (isDisabling) { - assert.propertyVal(testSession.meta, TEST_MANAGEMENT_ENABLED, 'true') + assert.strictEqual(testSession.meta[TEST_MANAGEMENT_ENABLED], 'true') } else { - assert.notProperty(testSession.meta, TEST_MANAGEMENT_ENABLED) + assert.ok(!Object.hasOwn(testSession.meta, TEST_MANAGEMENT_ENABLED)) } - assert.equal(failedTest.resource, 'cypress/e2e/disable.js.disable is disabled') + assert.strictEqual(failedTest.resource, 'cypress/e2e/disable.js.disable is disabled') if (isDisabling) { - assert.propertyVal(failedTest.meta, TEST_STATUS, 'skip') - assert.propertyVal(failedTest.meta, TEST_MANAGEMENT_IS_DISABLED, 'true') + assert.strictEqual(failedTest.meta[TEST_STATUS], 'skip') + assert.strictEqual(failedTest.meta[TEST_MANAGEMENT_IS_DISABLED], 'true') } else { - assert.propertyVal(failedTest.meta, TEST_STATUS, 'fail') - assert.notProperty(failedTest.meta, TEST_MANAGEMENT_IS_DISABLED) + assert.strictEqual(failedTest.meta[TEST_STATUS], 'fail') + assert.ok(!Object.hasOwn(failedTest.meta, TEST_MANAGEMENT_IS_DISABLED)) } }, 25000) @@ -2676,9 +2672,9 @@ moduleTypes.forEach(({ ]) if (isDisabling) { - assert.equal(exitCode, 0) + assert.strictEqual(exitCode, 0) } else { - assert.equal(exitCode, 1) + assert.strictEqual(exitCode, 1) } } @@ -2728,20 +2724,20 @@ moduleTypes.forEach(({ const testSession = events.find(event => event.type === 'test_session_end').content if (isQuarantining) { - assert.propertyVal(testSession.meta, TEST_MANAGEMENT_ENABLED, 'true') + assert.strictEqual(testSession.meta[TEST_MANAGEMENT_ENABLED], 'true') } else { - assert.notProperty(testSession.meta, TEST_MANAGEMENT_ENABLED) + assert.ok(!Object.hasOwn(testSession.meta, TEST_MANAGEMENT_ENABLED)) } - assert.equal(failedTest.resource, 'cypress/e2e/quarantine.js.quarantine is quarantined') + assert.strictEqual(failedTest.resource, 'cypress/e2e/quarantine.js.quarantine is quarantined') if (isQuarantining) { // TODO: run instead of skipping, but ignore its result - assert.propertyVal(failedTest.meta, TEST_STATUS, 'skip') - assert.propertyVal(failedTest.meta, TEST_MANAGEMENT_IS_QUARANTINED, 'true') + assert.strictEqual(failedTest.meta[TEST_STATUS], 'skip') + assert.strictEqual(failedTest.meta[TEST_MANAGEMENT_IS_QUARANTINED], 'true') } else { - assert.propertyVal(failedTest.meta, TEST_STATUS, 'fail') - assert.notProperty(failedTest.meta, TEST_MANAGEMENT_IS_QUARANTINED) + assert.strictEqual(failedTest.meta[TEST_STATUS], 'fail') + assert.ok(!Object.hasOwn(failedTest.meta, TEST_MANAGEMENT_IS_QUARANTINED)) } }, 25000) @@ -2775,9 +2771,9 @@ moduleTypes.forEach(({ ]) if (isQuarantining) { - assert.equal(exitCode, 0) + assert.strictEqual(exitCode, 0) } else { - assert.equal(exitCode, 1) + assert.strictEqual(exitCode, 1) } } @@ -2811,10 +2807,10 @@ moduleTypes.forEach(({ .gatherPayloadsMaxTimeout(({ url }) => url.endsWith('/api/v2/citestcycle'), (payloads) => { const events = payloads.flatMap(({ payload }) => payload.events) const testSession = events.find(event => event.type === 'test_session_end').content - assert.notProperty(testSession.meta, TEST_MANAGEMENT_ENABLED) + assert.ok(!Object.hasOwn(testSession.meta, TEST_MANAGEMENT_ENABLED)) const tests = events.filter(event => event.type === 'test').map(event => event.content) // it is not retried - assert.equal(tests.length, 1) + assert.strictEqual(tests.length, 1) }, 25000) const { @@ -3037,18 +3033,18 @@ moduleTypes.forEach(({ .gatherPayloadsMaxTimeout(({ url }) => url.endsWith('/api/v2/citestcycle'), payloads => { const metadataDicts = payloads.flatMap(({ payload }) => payload.metadata) - assert.isNotEmpty(metadataDicts) + assert.ok(metadataDicts.length > 0) metadataDicts.forEach(metadata => { - assert.equal(metadata.test[DD_CAPABILITIES_TEST_IMPACT_ANALYSIS], '1') - assert.equal(metadata.test[DD_CAPABILITIES_EARLY_FLAKE_DETECTION], '1') - assert.equal(metadata.test[DD_CAPABILITIES_AUTO_TEST_RETRIES], '1') - assert.equal(metadata.test[DD_CAPABILITIES_IMPACTED_TESTS], '1') - assert.equal(metadata.test[DD_CAPABILITIES_TEST_MANAGEMENT_QUARANTINE], '1') - assert.equal(metadata.test[DD_CAPABILITIES_TEST_MANAGEMENT_DISABLE], '1') - assert.equal(metadata.test[DD_CAPABILITIES_TEST_MANAGEMENT_ATTEMPT_TO_FIX], '5') - assert.equal(metadata.test[DD_CAPABILITIES_FAILED_TEST_REPLAY], '1') + assert.strictEqual(metadata.test[DD_CAPABILITIES_TEST_IMPACT_ANALYSIS], '1') + assert.strictEqual(metadata.test[DD_CAPABILITIES_EARLY_FLAKE_DETECTION], '1') + assert.strictEqual(metadata.test[DD_CAPABILITIES_AUTO_TEST_RETRIES], '1') + assert.strictEqual(metadata.test[DD_CAPABILITIES_IMPACTED_TESTS], '1') + assert.strictEqual(metadata.test[DD_CAPABILITIES_TEST_MANAGEMENT_QUARANTINE], '1') + assert.strictEqual(metadata.test[DD_CAPABILITIES_TEST_MANAGEMENT_DISABLE], '1') + assert.strictEqual(metadata.test[DD_CAPABILITIES_TEST_MANAGEMENT_ATTEMPT_TO_FIX], '5') + assert.strictEqual(metadata.test[DD_CAPABILITIES_FAILED_TEST_REPLAY], '1') // capabilities logic does not overwrite test session name - assert.equal(metadata.test[TEST_SESSION_NAME], 'my-test-session-name') + assert.strictEqual(metadata.test[TEST_SESSION_NAME], 'my-test-session-name') }) }, 25000) @@ -3133,9 +3129,9 @@ moduleTypes.forEach(({ const testSession = events.find(event => event.type === 'test_session_end').content if (isEfd) { - assert.propertyVal(testSession.meta, TEST_EARLY_FLAKE_ENABLED, 'true') + assert.strictEqual(testSession.meta[TEST_EARLY_FLAKE_ENABLED], 'true') } else { - assert.notProperty(testSession.meta, TEST_EARLY_FLAKE_ENABLED) + assert.ok(!Object.hasOwn(testSession.meta, TEST_EARLY_FLAKE_ENABLED)) } const resourceNames = tests.map(span => span.resource) @@ -3151,21 +3147,21 @@ moduleTypes.forEach(({ test.meta[TEST_NAME] === 'impacted test is impacted test') if (isEfd) { - assert.equal(impactedTests.length, NUM_RETRIES_EFD + 1) // Retries + original test + assert.strictEqual(impactedTests.length, NUM_RETRIES_EFD + 1) // Retries + original test } else { - assert.equal(impactedTests.length, 1) + assert.strictEqual(impactedTests.length, 1) } for (const impactedTest of impactedTests) { if (isModified) { - assert.propertyVal(impactedTest.meta, TEST_IS_MODIFIED, 'true') + assert.strictEqual(impactedTest.meta[TEST_IS_MODIFIED], 'true') } else { - assert.notProperty(impactedTest.meta, TEST_IS_MODIFIED) + assert.ok(!Object.hasOwn(impactedTest.meta, TEST_IS_MODIFIED)) } if (isNew) { - assert.propertyVal(impactedTest.meta, TEST_IS_NEW, 'true') + assert.strictEqual(impactedTest.meta[TEST_IS_NEW], 'true') } else { - assert.notProperty(impactedTest.meta, TEST_IS_NEW) + assert.ok(!Object.hasOwn(impactedTest.meta, TEST_IS_NEW)) } } @@ -3174,7 +3170,7 @@ moduleTypes.forEach(({ test => test.meta[TEST_IS_RETRY] === 'true' && test.meta[TEST_NAME] === 'impacted test is impacted test' ) - assert.equal(retriedTests.length, NUM_RETRIES_EFD) + assert.strictEqual(retriedTests.length, NUM_RETRIES_EFD) let retriedTestNew = 0 let retriedTestsWithReason = 0 retriedTests.forEach(test => { @@ -3185,11 +3181,8 @@ moduleTypes.forEach(({ retriedTestsWithReason++ } }) - assert.equal(retriedTestNew, isNew ? NUM_RETRIES_EFD : 0) - assert.equal( - retriedTestsWithReason, - NUM_RETRIES_EFD - ) + assert.strictEqual(retriedTestNew, isNew ? NUM_RETRIES_EFD : 0) + assert.strictEqual(retriedTestsWithReason, NUM_RETRIES_EFD) } }, 25000) diff --git a/integration-tests/debugger/redact.spec.js b/integration-tests/debugger/redact.spec.js index d6b4b374f20..f4daeb7832a 100644 --- a/integration-tests/debugger/redact.spec.js +++ b/integration-tests/debugger/redact.spec.js @@ -1,6 +1,6 @@ 'use strict' -const { assert } = require('chai') +const assert = require('node:assert/strict') const { setup } = require('./utils') const { once } = require('node:events') diff --git a/integration-tests/debugger/snapshot-global-sample-rate.spec.js b/integration-tests/debugger/snapshot-global-sample-rate.spec.js index 105d95a2de7..f117a21e626 100644 --- a/integration-tests/debugger/snapshot-global-sample-rate.spec.js +++ b/integration-tests/debugger/snapshot-global-sample-rate.spec.js @@ -1,6 +1,6 @@ 'use strict' -const { assert } = require('chai') +const assert = require('node:assert/strict') const { setup } = require('./utils') describe('Dynamic Instrumentation', function () { @@ -61,14 +61,14 @@ describe('Dynamic Instrumentation', function () { const timeSincePrevTimestamp = timestamp - prevTimestamp // Allow for a time variance (time will tell if this is enough). Timeouts can vary. - assert.isAtLeast(duration, 925) - assert.isBelow(duration, 1050) + assert.ok(duration >= 925) + assert.ok(duration < 1050) // A sanity check to make sure we're not saturating the event loop. We expect a lot of snapshots to be // sampled in the beginning of the sample window and then once the threshold is hit, we expect a "quiet" // period until the end of the window. If there's no "quiet" period, then we're saturating the event loop // and this test isn't really testing anything. - assert.isAtLeast(timeSincePrevTimestamp, 250) + assert.ok(timeSincePrevTimestamp >= 250) clearTimeout(state[rcConfig1.config.id].timer) clearTimeout(state[rcConfig2.config.id].timer) diff --git a/integration-tests/debugger/snapshot-pruning.spec.js b/integration-tests/debugger/snapshot-pruning.spec.js index be81e8b79d7..6004e78c27b 100644 --- a/integration-tests/debugger/snapshot-pruning.spec.js +++ b/integration-tests/debugger/snapshot-pruning.spec.js @@ -1,6 +1,6 @@ 'use strict' -const { assert } = require('chai') +const assert = require('node:assert/strict') const { setup } = require('./utils') describe('Dynamic Instrumentation', function () { @@ -13,7 +13,7 @@ describe('Dynamic Instrumentation', function () { it('should prune snapshot if payload is too large', function (done) { t.agent.on('debugger-input', ({ payload: [payload] }) => { assert.isBelow(Buffer.byteLength(JSON.stringify(payload)), 1024 * 1024) // 1MB - assert.notProperty(payload.debugger.snapshot, 'captures') + assert.ok(!Object.hasOwn(payload.debugger.snapshot, 'captures')) assert.strictEqual( payload.debugger.snapshot.captureError, 'Snapshot was too large (max allowed size is 1 MiB). ' + diff --git a/integration-tests/debugger/snapshot.spec.js b/integration-tests/debugger/snapshot.spec.js index a6f1321633b..44d636d96c7 100644 --- a/integration-tests/debugger/snapshot.spec.js +++ b/integration-tests/debugger/snapshot.spec.js @@ -1,6 +1,6 @@ 'use strict' -const { assert } = require('chai') +const assert = require('node:assert/strict') const { setup } = require('./utils') describe('Dynamic Instrumentation', function () { @@ -12,8 +12,8 @@ describe('Dynamic Instrumentation', function () { it('should capture a snapshot', function (done) { t.agent.on('debugger-input', ({ payload: [{ debugger: { snapshot: { captures } } }] }) => { - assert.deepEqual(Object.keys(captures), ['lines']) - assert.deepEqual(Object.keys(captures.lines), [String(t.breakpoint.line)]) + assert.deepStrictEqual(Object.keys(captures), ['lines']) + assert.deepStrictEqual(Object.keys(captures.lines), [String(t.breakpoint.line)]) const { locals } = captures.lines[t.breakpoint.line] const { request, fastify, getUndefined } = locals @@ -22,7 +22,7 @@ describe('Dynamic Instrumentation', function () { delete locals.getUndefined // from block scope - assert.deepEqual(locals, { + assert.deepStrictEqual(locals, { nil: { type: 'null', isNull: true }, undef: { type: 'undefined' }, bool: { type: 'boolean', value: 'true' }, @@ -85,22 +85,22 @@ describe('Dynamic Instrumentation', function () { // from local scope // There's no reason to test the `request` object 100%, instead just check its fingerprint - assert.deepEqual(Object.keys(request), ['type', 'fields']) - assert.equal(request.type, 'Request') - assert.equal(request.fields.id.type, 'string') + assert.deepStrictEqual(Object.keys(request), ['type', 'fields']) + assert.strictEqual(request.type, 'Request') + assert.strictEqual(request.fields.id.type, 'string') assert.match(request.fields.id.value, /^req-\d+$/) - assert.deepEqual(request.fields.params, { + assert.deepStrictEqual(request.fields.params, { type: 'NullObject', fields: { name: { type: 'string', value: 'foo' } } }) - assert.deepEqual(request.fields.query, { type: 'Object', fields: {} }) - assert.deepEqual(request.fields.body, { type: 'undefined' }) + assert.deepStrictEqual(request.fields.query, { type: 'Object', fields: {} }) + assert.deepStrictEqual(request.fields.body, { type: 'undefined' }) // from closure scope // There's no reason to test the `fastify` object 100%, instead just check its fingerprint - assert.equal(fastify.type, 'Object') - assert.typeOf(fastify.fields, 'Object') + assert.strictEqual(fastify.type, 'Object') + assert.strictEqual(typeof fastify.fields, 'Object') - assert.deepEqual(getUndefined, { + assert.deepStrictEqual(getUndefined, { type: 'Function', fields: { length: { type: 'number', value: '0' }, @@ -121,7 +121,7 @@ describe('Dynamic Instrumentation', function () { delete locals.fastify delete locals.getUndefined - assert.deepEqual(locals, { + assert.deepStrictEqual(locals, { nil: { type: 'null', isNull: true }, undef: { type: 'undefined' }, bool: { type: 'boolean', value: 'true' }, @@ -154,7 +154,7 @@ describe('Dynamic Instrumentation', function () { t.agent.on('debugger-input', ({ payload: [{ debugger: { snapshot: { captures } } }] }) => { const { locals } = captures.lines[t.breakpoint.line] - assert.deepEqual(locals.lstr, { + assert.deepStrictEqual(locals.lstr, { type: 'string', value: 'Lorem ipsu', truncated: true, @@ -171,7 +171,7 @@ describe('Dynamic Instrumentation', function () { t.agent.on('debugger-input', ({ payload: [{ debugger: { snapshot: { captures } } }] }) => { const { locals } = captures.lines[t.breakpoint.line] - assert.deepEqual(locals.arr, { + assert.deepStrictEqual(locals.arr, { type: 'Array', elements: [ { type: 'number', value: '1' }, @@ -195,9 +195,9 @@ describe('Dynamic Instrumentation', function () { if ('fields' in prop) { if (prop.notCapturedReason === 'fieldCount') { assert.strictEqual(Object.keys(prop.fields).length, maxFieldCount) - assert.isAbove(prop.size, maxFieldCount) + assert.ok(prop.size > maxFieldCount) } else { - assert.isBelow(Object.keys(prop.fields).length, maxFieldCount) + assert.ok(Object.keys(prop.fields).length < maxFieldCount) } } @@ -219,12 +219,12 @@ describe('Dynamic Instrumentation', function () { assert.strictEqual(locals.request.type, 'Request') assert.strictEqual(Object.keys(locals.request.fields).length, maxFieldCount) assert.strictEqual(locals.request.notCapturedReason, 'fieldCount') - assert.isAbove(locals.request.size, maxFieldCount) + assert.ok(locals.request.size > maxFieldCount) assert.strictEqual(locals.fastify.type, 'Object') assert.strictEqual(Object.keys(locals.fastify.fields).length, maxFieldCount) assert.strictEqual(locals.fastify.notCapturedReason, 'fieldCount') - assert.isAbove(locals.fastify.size, maxFieldCount) + assert.ok(locals.fastify.size > maxFieldCount) for (const value of Object.values(locals)) { assertMaxFieldCount(value) diff --git a/integration-tests/debugger/source-map-support.spec.js b/integration-tests/debugger/source-map-support.spec.js index 92726002534..a6cf9747ddb 100644 --- a/integration-tests/debugger/source-map-support.spec.js +++ b/integration-tests/debugger/source-map-support.spec.js @@ -1,6 +1,6 @@ 'use strict' -const { assert } = require('chai') +const assert = require('node:assert/strict') const { setup } = require('./utils') describe('Dynamic Instrumentation', function () { @@ -15,7 +15,7 @@ describe('Dynamic Instrumentation', function () { it('should support source maps', function (done) { t.agent.on('debugger-input', ({ payload: [{ debugger: { snapshot: { probe: { location } } } }] }) => { - assert.deepEqual(location, { + assert.deepStrictEqual(location, { file: 'target-app/source-map-support/typescript.ts', lines: ['11'] }) @@ -36,7 +36,7 @@ describe('Dynamic Instrumentation', function () { it('should support source maps', function (done) { t.agent.on('debugger-input', ({ payload: [{ debugger: { snapshot: { probe: { location } } } }] }) => { - assert.deepEqual(location, { + assert.deepStrictEqual(location, { file: 'target-app/source-map-support/minify.js', lines: ['9'] }) @@ -60,7 +60,7 @@ describe('Dynamic Instrumentation', function () { it('should support relative source paths in source maps', function (done) { t.agent.on('debugger-input', ({ payload: [{ debugger: { snapshot: { probe: { location } } } }] }) => { - assert.deepEqual(location, { + assert.deepStrictEqual(location, { file: 'target-app/source-map-support/hello/world.ts', lines: ['2'] }) diff --git a/integration-tests/debugger/template.spec.js b/integration-tests/debugger/template.spec.js index 9805a936606..34c5d2fe679 100644 --- a/integration-tests/debugger/template.spec.js +++ b/integration-tests/debugger/template.spec.js @@ -1,6 +1,6 @@ 'use strict' -const { assert } = require('chai') +const assert = require('node:assert/strict') const semver = require('semver') const { setup } = require('./utils') const { NODE_MAJOR } = require('../../version') @@ -202,7 +202,7 @@ describe('Dynamic Instrumentation', function () { const { evaluationErrors } = payload.debugger.snapshot - assert.isArray(evaluationErrors) + assert.ok(Array.isArray(evaluationErrors)) assert.strictEqual(evaluationErrors.length, 2) assert.strictEqual(evaluationErrors[0].expr, 'request.invalid.name') assert.strictEqual(evaluationErrors[0].message, 'TypeError: Cannot convert undefined or null to object') diff --git a/integration-tests/debugger/unreffed.spec.js b/integration-tests/debugger/unreffed.spec.js index 3ce9458f341..b1e0a4aaca0 100644 --- a/integration-tests/debugger/unreffed.spec.js +++ b/integration-tests/debugger/unreffed.spec.js @@ -1,6 +1,6 @@ 'use strict' -const { assert } = require('chai') +const assert = require('node:assert/strict') const { setup } = require('./utils') describe('Dynamic Instrumentation', function () { diff --git a/integration-tests/helpers/fake-agent.js b/integration-tests/helpers/fake-agent.js index 572b9304c1a..e4c982f6bfa 100644 --- a/integration-tests/helpers/fake-agent.js +++ b/integration-tests/helpers/fake-agent.js @@ -1,5 +1,7 @@ 'use strict' +const assert = require('node:assert/strict') + const { createHash } = require('crypto') const { EventEmitter, once } = require('events') const http = require('http') diff --git a/integration-tests/jest/jest.spec.js b/integration-tests/jest/jest.spec.js index ab95ce7aa89..f5830ff5a81 100644 --- a/integration-tests/jest/jest.spec.js +++ b/integration-tests/jest/jest.spec.js @@ -1,11 +1,12 @@ 'use strict' +const assert = require('node:assert/strict') + const { once } = require('node:events') const { fork, exec, execSync } = require('child_process') const path = require('path') const fs = require('fs') - -const { assert } = require('chai') +const { assertObjectContains } = require('../helpers') const { sandboxCwd, @@ -154,19 +155,19 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { ) const areAllTestSpans = testSpans.every(span => span.name === 'jest.test') - assert.isTrue(areAllTestSpans) + assert.strictEqual(areAllTestSpans, true) - assert.include(testOutput, expectedStdout) + assert.ok(testOutput.includes(expectedStdout)) // Can read DD_TAGS testSpans.forEach(testSpan => { - assert.propertyVal(testSpan.meta, 'test.customtag', 'customvalue') - assert.propertyVal(testSpan.meta, 'test.customtag2', 'customvalue2') + assert.strictEqual(testSpan.meta['test.customtag'], 'customvalue') + assert.strictEqual(testSpan.meta['test.customtag2'], 'customvalue2') }) testSpans.forEach(testSpan => { - assert.equal(testSpan.meta[TEST_SOURCE_FILE].startsWith('ci-visibility/test/ci-visibility-test'), true) - assert.exists(testSpan.metrics[TEST_SOURCE_START]) + assert.strictEqual(testSpan.meta[TEST_SOURCE_FILE].startsWith('ci-visibility/test/ci-visibility-test'), true) + assert.ok(testSpan.metrics[TEST_SOURCE_START] != null) }) done() @@ -236,46 +237,46 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { (!parameters || test.meta[TEST_PARAMETERS] === JSON.stringify(parameters)) ) - assert.exists(test, `Expected to find test "${name}" with status "${status}"`) - - assert.propertyVal(test.meta, 'language', 'javascript') - assert.propertyVal(test.meta, 'service', 'plugin-tests') - assert.propertyVal(test.meta, ORIGIN_KEY, CI_APP_ORIGIN) - assert.propertyVal(test.meta, TEST_FRAMEWORK, 'jest') - assert.propertyVal(test.meta, TEST_NAME, name) - assert.propertyVal(test.meta, TEST_STATUS, status) - assert.propertyVal(test.meta, TEST_SUITE, 'ci-visibility/jest-plugin-tests/jest-test.js') - assert.propertyVal(test.meta, TEST_SOURCE_FILE, 'ci-visibility/jest-plugin-tests/jest-test.js') - assert.propertyVal(test.meta, TEST_TYPE, 'test') - assert.propertyVal(test.meta, JEST_TEST_RUNNER, 'jest-circus') - assert.propertyVal(test.meta, LIBRARY_VERSION, ddTraceVersion) - assert.propertyVal(test.meta, COMPONENT, 'jest') - assert.include(test.meta[TEST_CODE_OWNERS], '@datadog-dd-trace-js') - - assert.equal(test.type, 'test') - assert.equal(test.name, 'jest.test') - assert.equal(test.service, 'plugin-tests') - assert.equal(test.resource, `ci-visibility/jest-plugin-tests/jest-test.js.${name}`) - - assert.exists(test.metrics[TEST_SOURCE_START]) - assert.exists(test.meta[TEST_FRAMEWORK_VERSION]) + assert.ok(test != null) + + assert.strictEqual(test.meta['language'], 'javascript') + assert.strictEqual(test.meta['service'], 'plugin-tests') + assert.strictEqual(test.meta[ORIGIN_KEY], CI_APP_ORIGIN) + assert.strictEqual(test.meta[TEST_FRAMEWORK], 'jest') + assert.strictEqual(test.meta[TEST_NAME], name) + assert.strictEqual(test.meta[TEST_STATUS], status) + assert.strictEqual(test.meta[TEST_SUITE], 'ci-visibility/jest-plugin-tests/jest-test.js') + assert.strictEqual(test.meta[TEST_SOURCE_FILE], 'ci-visibility/jest-plugin-tests/jest-test.js') + assert.strictEqual(test.meta[TEST_TYPE], 'test') + assert.strictEqual(test.meta[JEST_TEST_RUNNER], 'jest-circus') + assert.strictEqual(test.meta[LIBRARY_VERSION], ddTraceVersion) + assert.strictEqual(test.meta[COMPONENT], 'jest') + assert.ok(test.meta[TEST_CODE_OWNERS].includes('@datadog-dd-trace-js')) + + assert.strictEqual(test.type, 'test') + assert.strictEqual(test.name, 'jest.test') + assert.strictEqual(test.service, 'plugin-tests') + assert.strictEqual(test.resource, `ci-visibility/jest-plugin-tests/jest-test.js.${name}`) + + assert.ok(test.metrics[TEST_SOURCE_START] != null) + assert.ok(test.meta[TEST_FRAMEWORK_VERSION] != null) if (extraTags) { Object.entries(extraTags).forEach(([key, value]) => { - assert.propertyVal(test.meta, key, value) + assert.strictEqual(test.meta[key], value) }) } if (error) { - assert.include(test.meta[ERROR_MESSAGE], error) + assert.ok(test.meta[ERROR_MESSAGE].includes(error)) } // TODO: why did this work in jsdom before? if (name === 'jest-test-suite can do integration http') { const httpSpan = spans.find(span => span.name === 'http.request') - assert.propertyVal(httpSpan.meta, ORIGIN_KEY, CI_APP_ORIGIN) - assert.include(httpSpan.meta['http.url'], '/info') - assert.equal(httpSpan.parent_id.toString(), test.span_id.toString()) + assert.strictEqual(httpSpan.meta[ORIGIN_KEY], CI_APP_ORIGIN) + assert.ok(httpSpan.meta['http.url'].includes('/info')) + assert.strictEqual(httpSpan.parent_id.toString(), test.span_id.toString()) } }) }, 25000) @@ -314,22 +315,22 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { span.resource === `ci-visibility/jest-plugin-tests/jest-hook-failure.js.${name}` ) - assert.exists(testSpan, `Expected to find test "${name}"`) - assert.propertyVal(testSpan.meta, 'language', 'javascript') - assert.propertyVal(testSpan.meta, ORIGIN_KEY, CI_APP_ORIGIN) - assert.propertyVal(testSpan.meta, TEST_FRAMEWORK, 'jest') - assert.propertyVal(testSpan.meta, TEST_NAME, name) - assert.propertyVal(testSpan.meta, TEST_STATUS, 'fail') - assert.propertyVal(testSpan.meta, TEST_SUITE, 'ci-visibility/jest-plugin-tests/jest-hook-failure.js') - assert.propertyVal(testSpan.meta, TEST_SOURCE_FILE, 'ci-visibility/jest-plugin-tests/jest-hook-failure.js') - assert.propertyVal(testSpan.meta, TEST_TYPE, 'test') - assert.propertyVal(testSpan.meta, JEST_TEST_RUNNER, 'jest-circus') - assert.propertyVal(testSpan.meta, COMPONENT, 'jest') - assert.equal(testSpan.meta[ERROR_MESSAGE], error) - assert.equal(testSpan.type, 'test') - assert.equal(testSpan.name, 'jest.test') - assert.equal(testSpan.resource, `ci-visibility/jest-plugin-tests/jest-hook-failure.js.${name}`) - assert.exists(testSpan.meta[TEST_FRAMEWORK_VERSION]) + assert.ok(testSpan != null) + assert.strictEqual(testSpan.meta['language'], 'javascript') + assert.strictEqual(testSpan.meta[ORIGIN_KEY], CI_APP_ORIGIN) + assert.strictEqual(testSpan.meta[TEST_FRAMEWORK], 'jest') + assert.strictEqual(testSpan.meta[TEST_NAME], name) + assert.strictEqual(testSpan.meta[TEST_STATUS], 'fail') + assert.strictEqual(testSpan.meta[TEST_SUITE], 'ci-visibility/jest-plugin-tests/jest-hook-failure.js') + assert.strictEqual(testSpan.meta[TEST_SOURCE_FILE], 'ci-visibility/jest-plugin-tests/jest-hook-failure.js') + assert.strictEqual(testSpan.meta[TEST_TYPE], 'test') + assert.strictEqual(testSpan.meta[JEST_TEST_RUNNER], 'jest-circus') + assert.strictEqual(testSpan.meta[COMPONENT], 'jest') + assert.strictEqual(testSpan.meta[ERROR_MESSAGE], error) + assert.strictEqual(testSpan.type, 'test') + assert.strictEqual(testSpan.name, 'jest.test') + assert.strictEqual(testSpan.resource, `ci-visibility/jest-plugin-tests/jest-hook-failure.js.${name}`) + assert.ok(testSpan.meta[TEST_FRAMEWORK_VERSION] != null) }) }, 25000) @@ -367,19 +368,19 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { span.resource === `ci-visibility/jest-plugin-tests/jest-focus.js.${name}` ) - assert.exists(testSpan, `Expected to find test "${name}"`) - assert.propertyVal(testSpan.meta, 'language', 'javascript') - assert.propertyVal(testSpan.meta, ORIGIN_KEY, CI_APP_ORIGIN) - assert.propertyVal(testSpan.meta, TEST_FRAMEWORK, 'jest') - assert.propertyVal(testSpan.meta, TEST_NAME, name) - assert.propertyVal(testSpan.meta, TEST_STATUS, status) - assert.propertyVal(testSpan.meta, TEST_SUITE, 'ci-visibility/jest-plugin-tests/jest-focus.js') - assert.propertyVal(testSpan.meta, TEST_SOURCE_FILE, 'ci-visibility/jest-plugin-tests/jest-focus.js') - assert.propertyVal(testSpan.meta, COMPONENT, 'jest') - assert.equal(testSpan.type, 'test') - assert.equal(testSpan.name, 'jest.test') - assert.equal(testSpan.resource, `ci-visibility/jest-plugin-tests/jest-focus.js.${name}`) - assert.exists(testSpan.meta[TEST_FRAMEWORK_VERSION]) + assert.ok(testSpan != null) + assert.strictEqual(testSpan.meta['language'], 'javascript') + assert.strictEqual(testSpan.meta[ORIGIN_KEY], CI_APP_ORIGIN) + assert.strictEqual(testSpan.meta[TEST_FRAMEWORK], 'jest') + assert.strictEqual(testSpan.meta[TEST_NAME], name) + assert.strictEqual(testSpan.meta[TEST_STATUS], status) + assert.strictEqual(testSpan.meta[TEST_SUITE], 'ci-visibility/jest-plugin-tests/jest-focus.js') + assert.strictEqual(testSpan.meta[TEST_SOURCE_FILE], 'ci-visibility/jest-plugin-tests/jest-focus.js') + assert.strictEqual(testSpan.meta[COMPONENT], 'jest') + assert.strictEqual(testSpan.type, 'test') + assert.strictEqual(testSpan.name, 'jest.test') + assert.strictEqual(testSpan.resource, `ci-visibility/jest-plugin-tests/jest-focus.js.${name}`) + assert.ok(testSpan.meta[TEST_FRAMEWORK_VERSION] != null) }) }, 25000) @@ -408,10 +409,10 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { const testSpan = payloads .flatMap(({ payload }) => payload.flatMap(trace => trace)) .find(span => span.type === 'test') - assert.exists(testSpan, 'Expected to find test span') - assert.propertyVal(testSpan.meta, TEST_NAME, 'jest-inject-globals will be run') - assert.propertyVal(testSpan.meta, TEST_STATUS, 'pass') - assert.propertyVal(testSpan.meta, TEST_SUITE, 'ci-visibility/jest-plugin-tests/jest-inject-globals.js') + assert.ok(testSpan != null) + assert.strictEqual(testSpan.meta[TEST_NAME], 'jest-inject-globals will be run') + assert.strictEqual(testSpan.meta[TEST_STATUS], 'pass') + assert.strictEqual(testSpan.meta[TEST_SUITE], 'ci-visibility/jest-plugin-tests/jest-inject-globals.js') }) childProcess = exec( @@ -450,7 +451,7 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { metadataDicts.forEach(metadata => { for (const testLevel of TEST_LEVEL_EVENT_TYPES) { - assert.equal(metadata[testLevel][TEST_SESSION_NAME], 'my-test-session') + assert.strictEqual(metadata[testLevel][TEST_SESSION_NAME], 'my-test-session') } }) @@ -468,26 +469,26 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { 'ci-visibility/test/ci-visibility-test-2.js.ci visibility 2 can report tests 2' ] ) - assert.equal(suites.length, 2) - assert.exists(sessionEventContent) - assert.exists(moduleEventContent) + assert.strictEqual(suites.length, 2) + assert.ok(sessionEventContent != null) + assert.ok(moduleEventContent != null) - assert.include(testOutput, expectedStdout) + assert.ok(testOutput.includes(expectedStdout)) tests.forEach(testEvent => { - assert.equal(testEvent.meta[TEST_SOURCE_FILE].startsWith('ci-visibility/test/ci-visibility-test'), true) - assert.exists(testEvent.metrics[TEST_SOURCE_START]) - assert.equal(testEvent.meta[DD_TEST_IS_USER_PROVIDED_SERVICE], 'false') + assert.strictEqual(testEvent.meta[TEST_SOURCE_FILE].startsWith('ci-visibility/test/ci-visibility-test'), true) + assert.ok(testEvent.metrics[TEST_SOURCE_START] != null) + assert.strictEqual(testEvent.meta[DD_TEST_IS_USER_PROVIDED_SERVICE], 'false') // Can read DD_TAGS - assert.propertyVal(testEvent.meta, 'test.customtag', 'customvalue') - assert.propertyVal(testEvent.meta, 'test.customtag2', 'customvalue2') - assert.exists(testEvent.metrics[DD_HOST_CPU_COUNT]) + assert.strictEqual(testEvent.meta['test.customtag'], 'customvalue') + assert.strictEqual(testEvent.meta['test.customtag2'], 'customvalue2') + assert.ok(testEvent.metrics[DD_HOST_CPU_COUNT] != null) }) suites.forEach(testSuite => { - assert.isTrue(testSuite.meta[TEST_SOURCE_FILE].startsWith('ci-visibility/test/ci-visibility-test')) - assert.equal(testSuite.metrics[TEST_SOURCE_START], 1) - assert.exists(testSuite.metrics[DD_HOST_CPU_COUNT]) + assert.strictEqual(testSuite.meta[TEST_SOURCE_FILE].startsWith('ci-visibility/test/ci-visibility-test'), true) + assert.strictEqual(testSuite.metrics[TEST_SOURCE_START], 1) + assert.ok(testSuite.metrics[DD_HOST_CPU_COUNT] != null) }) done() @@ -527,38 +528,38 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { const testSuiteEvent = events.find(event => event.type === 'test_suite_end').content const testEvent = events.find(event => event.type === 'test').content - assert.exists(testSessionEvent) - assert.equal(testSessionEvent.meta[TEST_STATUS], 'pass') - assert.exists(testSessionEvent[TEST_SESSION_ID]) - assert.exists(testSessionEvent.meta[TEST_COMMAND]) - assert.notExists(testSessionEvent[TEST_SUITE_ID]) - assert.notExists(testSessionEvent[TEST_MODULE_ID]) - - assert.exists(testModuleEvent) - assert.equal(testModuleEvent.meta[TEST_STATUS], 'pass') - assert.exists(testModuleEvent[TEST_SESSION_ID]) - assert.exists(testModuleEvent[TEST_MODULE_ID]) - assert.exists(testModuleEvent.meta[TEST_COMMAND]) - assert.notExists(testModuleEvent[TEST_SUITE_ID]) - - assert.exists(testSuiteEvent) - assert.equal(testSuiteEvent.meta[TEST_STATUS], 'pass') - assert.equal(testSuiteEvent.meta[TEST_SUITE], 'ci-visibility/jest-plugin-tests/jest-test-suite.js') - assert.exists(testSuiteEvent.meta[TEST_COMMAND]) - assert.exists(testSuiteEvent.meta[TEST_MODULE]) - assert.exists(testSuiteEvent[TEST_SUITE_ID]) - assert.exists(testSuiteEvent[TEST_SESSION_ID]) - assert.exists(testSuiteEvent[TEST_MODULE_ID]) - - assert.exists(testEvent) - assert.equal(testEvent.meta[TEST_STATUS], 'pass') - assert.equal(testEvent.meta[TEST_NAME], 'jest-test-suite-visibility works') - assert.equal(testEvent.meta[TEST_SUITE], 'ci-visibility/jest-plugin-tests/jest-test-suite.js') - assert.exists(testEvent.meta[TEST_COMMAND]) - assert.exists(testEvent.meta[TEST_MODULE]) - assert.exists(testEvent[TEST_SUITE_ID]) - assert.exists(testEvent[TEST_SESSION_ID]) - assert.exists(testEvent[TEST_MODULE_ID]) + assert.ok(testSessionEvent != null) + assert.strictEqual(testSessionEvent.meta[TEST_STATUS], 'pass') + assert.ok(testSessionEvent[TEST_SESSION_ID] != null) + assert.ok(testSessionEvent.meta[TEST_COMMAND] != null) + assert.ok(testSessionEvent[TEST_SUITE_ID] == null) + assert.ok(testSessionEvent[TEST_MODULE_ID] == null) + + assert.ok(testModuleEvent != null) + assert.strictEqual(testModuleEvent.meta[TEST_STATUS], 'pass') + assert.ok(testModuleEvent[TEST_SESSION_ID] != null) + assert.ok(testModuleEvent[TEST_MODULE_ID] != null) + assert.ok(testModuleEvent.meta[TEST_COMMAND] != null) + assert.ok(testModuleEvent[TEST_SUITE_ID] == null) + + assert.ok(testSuiteEvent != null) + assert.strictEqual(testSuiteEvent.meta[TEST_STATUS], 'pass') + assert.strictEqual(testSuiteEvent.meta[TEST_SUITE], 'ci-visibility/jest-plugin-tests/jest-test-suite.js') + assert.ok(testSuiteEvent.meta[TEST_COMMAND] != null) + assert.ok(testSuiteEvent.meta[TEST_MODULE] != null) + assert.ok(testSuiteEvent[TEST_SUITE_ID] != null) + assert.ok(testSuiteEvent[TEST_SESSION_ID] != null) + assert.ok(testSuiteEvent[TEST_MODULE_ID] != null) + + assert.ok(testEvent != null) + assert.strictEqual(testEvent.meta[TEST_STATUS], 'pass') + assert.strictEqual(testEvent.meta[TEST_NAME], 'jest-test-suite-visibility works') + assert.strictEqual(testEvent.meta[TEST_SUITE], 'ci-visibility/jest-plugin-tests/jest-test-suite.js') + assert.ok(testEvent.meta[TEST_COMMAND] != null) + assert.ok(testEvent.meta[TEST_MODULE] != null) + assert.ok(testEvent[TEST_SUITE_ID] != null) + assert.ok(testEvent[TEST_SESSION_ID] != null) + assert.ok(testEvent[TEST_MODULE_ID] != null) }) childProcess = exec( @@ -606,7 +607,7 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { testOutput += chunk.toString() }) childProcess.on('message', () => { - assert.include(testOutput, expectedStdout) + assert.ok(testOutput.includes(expectedStdout)) done() }) }) @@ -630,9 +631,9 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { testOutput += chunk.toString() }) childProcess.on('message', () => { - assert.notInclude(testOutput, 'TypeError') - assert.notInclude(testOutput, 'Uncaught error outside test suite') - assert.include(testOutput, expectedStdout) + assert.ok(!testOutput.includes('TypeError')) + assert.ok(!testOutput.includes('Uncaught error outside test suite')) + assert.ok(testOutput.includes(expectedStdout)) done() }) }) @@ -646,9 +647,9 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { const test = events.find(event => event.type === 'test').content const testSuite = events.find(event => event.type === 'test_suite_end').content // The test is in a subproject - assert.notEqual(test.meta[TEST_SOURCE_FILE], test.meta[TEST_SUITE]) - assert.equal(test.meta[TEST_CODE_OWNERS], JSON.stringify(['@datadog-dd-trace-js'])) - assert.equal(testSuite.meta[TEST_CODE_OWNERS], JSON.stringify(['@datadog-dd-trace-js'])) + assert.notStrictEqual(test.meta[TEST_SOURCE_FILE], test.meta[TEST_SUITE]) + assert.strictEqual(test.meta[TEST_CODE_OWNERS], JSON.stringify(['@datadog-dd-trace-js'])) + assert.strictEqual(testSuite.meta[TEST_CODE_OWNERS], JSON.stringify(['@datadog-dd-trace-js'])) }) childProcess = exec( @@ -677,7 +678,7 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { onlyLatestIt('works when sharding', (done) => { receiver.payloadReceived(({ url }) => url === '/api/v2/citestcycle').then(events => { const testSuiteEvents = events.payload.events.filter(event => event.type === 'test_suite_end') - assert.equal(testSuiteEvents.length, 3) + assert.strictEqual(testSuiteEvents.length, 3) const testSuites = testSuiteEvents.map(span => span.content.meta[TEST_SUITE]) assert.includeMembers(testSuites, @@ -689,7 +690,7 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { ) const testSession = events.payload.events.find(event => event.type === 'test_session_end').content - assert.propertyVal(testSession.meta, TEST_ITR_TESTS_SKIPPED, 'false') + assert.strictEqual(testSession.meta[TEST_ITR_TESTS_SKIPPED], 'false') // We run the second shard receiver.setSuitesToSkip([ @@ -723,11 +724,11 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { const testSuiteEvents = secondShardEvents.payload.events.filter(event => event.type === 'test_suite_end') // The suites for this shard are to be skipped - assert.equal(testSuiteEvents.length, 2) + assert.strictEqual(testSuiteEvents.length, 2) testSuiteEvents.forEach(testSuite => { - assert.propertyVal(testSuite.content.meta, TEST_STATUS, 'skip') - assert.propertyVal(testSuite.content.meta, TEST_SKIPPED_BY_ITR, 'true') + assert.strictEqual(testSuite.content.meta[TEST_STATUS], 'skip') + assert.strictEqual(testSuite.content.meta[TEST_SKIPPED_BY_ITR], 'true') }) const testSession = secondShardEvents @@ -735,9 +736,9 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { .events .find(event => event.type === 'test_session_end').content - assert.propertyVal(testSession.meta, TEST_ITR_TESTS_SKIPPED, 'true') - assert.propertyVal(testSession.meta, TEST_ITR_SKIPPING_TYPE, 'suite') - assert.propertyVal(testSession.metrics, TEST_ITR_SKIPPING_COUNT, 2) + assert.strictEqual(testSession.meta[TEST_ITR_TESTS_SKIPPED], 'true') + assert.strictEqual(testSession.meta[TEST_ITR_SKIPPING_TYPE], 'suite') + assert.strictEqual(testSession.metrics[TEST_ITR_SKIPPING_COUNT], 2) done() }) @@ -771,8 +772,8 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { testOutput += chunk.toString() }) childProcess.on('message', () => { - assert.notInclude(testOutput, 'TypeError') - assert.include(testOutput, expectedStdout) + assert.ok(!testOutput.includes('TypeError')) + assert.ok(testOutput.includes(expectedStdout)) done() }) }) @@ -795,7 +796,7 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { testOutput += chunk.toString() }) childProcess.on('message', () => { - assert.notInclude(testOutput, 'TypeError') + assert.ok(!testOutput.includes('TypeError')) done() }) }) @@ -815,10 +816,10 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { receiver.gatherPayloads(({ url }) => url === '/v0.4/traces', 5000).then(tracesRequests => { const testSpans = tracesRequests.flatMap(trace => trace.payload).flatMap(request => request) - assert.equal(testSpans.length, 2) + assert.strictEqual(testSpans.length, 2) const spanTypes = testSpans.map(span => span.type) assert.includeMembers(spanTypes, ['test']) - assert.notInclude(spanTypes, ['test_session_end', 'test_suite_end', 'test_module_end']) + assert.ok(!spanTypes.includes(['test_session_end', 'test_suite_end', 'test_module_end'])) receiver.setInfoResponse({ endpoints: ['/evp_proxy/v2'] }) done() }).catch(done) @@ -841,7 +842,7 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { // it propagates test session name to the test and test suite events in parallel mode metadataDicts.forEach(metadata => { for (const testLevel of TEST_LEVEL_EVENT_TYPES) { - assert.equal(metadata[testLevel][TEST_SESSION_NAME], 'my-test-session') + assert.strictEqual(metadata[testLevel][TEST_SESSION_NAME], 'my-test-session') } }) @@ -890,19 +891,17 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { const tests = events.filter(event => event.type === 'test').map(event => event.content) const retriedTests = tests.filter(test => test.meta[TEST_RETRY_REASON] === TEST_RETRY_REASON_TYPES.atr) - assert.equal(retriedTests.length, 2) + assert.strictEqual(retriedTests.length, 2) const retriedTest = retriedTests.find(test => test.meta[TEST_SUITE].includes('test-hit-breakpoint.js')) - assert.propertyVal(retriedTest.meta, DI_ERROR_DEBUG_INFO_CAPTURED, 'true') + assert.strictEqual(retriedTest.meta[DI_ERROR_DEBUG_INFO_CAPTURED], 'true') - assert.isTrue( - retriedTest.meta[`${DI_DEBUG_ERROR_PREFIX}.0.${DI_DEBUG_ERROR_FILE_SUFFIX}`] - .endsWith('ci-visibility/dynamic-instrumentation/dependency.js') - ) - assert.equal(retriedTest.metrics[`${DI_DEBUG_ERROR_PREFIX}.0.${DI_DEBUG_ERROR_LINE_SUFFIX}`], 6) + assert.strictEqual(retriedTest.meta[`${DI_DEBUG_ERROR_PREFIX}.0.${DI_DEBUG_ERROR_FILE_SUFFIX}`] + .endsWith('ci-visibility/dynamic-instrumentation/dependency.js'), true) + assert.strictEqual(retriedTest.metrics[`${DI_DEBUG_ERROR_PREFIX}.0.${DI_DEBUG_ERROR_LINE_SUFFIX}`], 6) const snapshotIdKey = `${DI_DEBUG_ERROR_PREFIX}.0.${DI_DEBUG_ERROR_SNAPSHOT_ID_SUFFIX}` - assert.exists(retriedTest.meta[snapshotIdKey]) + assert.ok(retriedTest.meta[snapshotIdKey] != null) snapshotIdByTest = retriedTest.meta[snapshotIdKey] spanIdByTest = retriedTest.span_id.toString() @@ -910,17 +909,17 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { const notRetriedTest = tests.find(test => test.meta[TEST_NAME].includes('is not retried')) - assert.notProperty(notRetriedTest.meta, DI_ERROR_DEBUG_INFO_CAPTURED) + assert.ok(!Object.hasOwn(notRetriedTest.meta, DI_ERROR_DEBUG_INFO_CAPTURED)) }) const logsPromise = receiver .gatherPayloadsMaxTimeout(({ url }) => url.endsWith('/api/v2/logs'), (payloads) => { const [{ logMessage: [diLog] }] = payloads - assert.deepInclude(diLog, { + assertObjectContains(diLog, { ddsource: 'dd_debugger', level: 'error' }) - assert.equal(diLog.debugger.snapshot.language, 'javascript') + assert.strictEqual(diLog.debugger.snapshot.language, 'javascript') spanIdByLog = diLog.dd.span_id traceIdByLog = diLog.dd.trace_id snapshotIdByLog = diLog.debugger.snapshot.id @@ -941,9 +940,9 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { childProcess.on('exit', () => { Promise.all([eventsPromise, logsPromise]).then(() => { - assert.equal(snapshotIdByTest, snapshotIdByLog) - assert.equal(spanIdByTest, spanIdByLog) - assert.equal(traceIdByTest, traceIdByLog) + assert.strictEqual(snapshotIdByTest, snapshotIdByLog) + assert.strictEqual(spanIdByTest, spanIdByLog) + assert.strictEqual(traceIdByTest, traceIdByLog) done() }).catch(done) }) @@ -979,7 +978,7 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { .gatherPayloadsMaxTimeout(({ url }) => url.endsWith('/api/v2/citestcycle'), (payloads) => { const events = payloads.flatMap(({ payload }) => payload.events) const suites = events.filter(event => event.type === 'test_suite_end') - assert.equal(suites.length, 2) + assert.strictEqual(suites.length, 2) const resourceNames = suites.map(suite => suite.content.resource) @@ -988,8 +987,8 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { 'test_suite.ci-visibility/test-parsing-error/parsing-error.js' ]) suites.forEach(suite => { - assert.equal(suite.content.meta[TEST_STATUS], 'fail') - assert.include(suite.content.meta[ERROR_MESSAGE], 'chao') + assert.strictEqual(suite.content.meta[TEST_STATUS], 'fail') + assert.ok(suite.content.meta[ERROR_MESSAGE].includes('chao')) }) }) childProcess = fork(testFile, { @@ -1013,22 +1012,22 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { .gatherPayloadsMaxTimeout(({ url }) => url.endsWith('/api/v2/citestcycle'), (payloads) => { const events = payloads.flatMap(({ payload }) => payload.events) const suites = events.filter(event => event.type === 'test_suite_end') - assert.equal(suites.length, 3) + assert.strictEqual(suites.length, 3) const failedTestSuites = suites.filter( suite => suite.content.meta[TEST_SUITE] === 'ci-visibility/jest-bad-import/jest-bad-import-test.js' ) - assert.equal(failedTestSuites.length, 1) + assert.strictEqual(failedTestSuites.length, 1) const [failedTestSuite] = failedTestSuites - assert.equal(failedTestSuite.content.meta[TEST_STATUS], 'fail') - assert.include(failedTestSuite.content.meta[ERROR_MESSAGE], 'a file outside of the scope of the test code') - assert.equal(failedTestSuite.content.meta[ERROR_TYPE], 'Error') + assert.strictEqual(failedTestSuite.content.meta[TEST_STATUS], 'fail') + assert.ok(failedTestSuite.content.meta[ERROR_MESSAGE].includes('a file outside of the scope of the test code')) + assert.strictEqual(failedTestSuite.content.meta[ERROR_TYPE], 'Error') const passedTestSuites = suites.filter( suite => suite.content.meta[TEST_STATUS] === 'pass' ) - assert.equal(passedTestSuites.length, 2) + assert.strictEqual(passedTestSuites.length, 2) }) childProcess = exec(runTestsCommand, { @@ -1054,33 +1053,27 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { const events = payloads.flatMap(({ payload }) => payload.events) const suites = events.filter(event => event.type === 'test_suite_end') // this is not retried by the jest worker, so it's just 3 suites - assert.equal(suites.length, 3) + assert.strictEqual(suites.length, 3) const badImportTestSuites = suites.filter( suite => suite.content.meta[TEST_SUITE] === 'ci-visibility/jest-bad-import-torn-down/jest-bad-import-test.js' ) - assert.equal(badImportTestSuites.length, 1) + assert.strictEqual(badImportTestSuites.length, 1) const [badImportTestSuite] = badImportTestSuites // jest still reports the test suite as passing - assert.equal(badImportTestSuite.content.meta[TEST_STATUS], 'pass') - assert.include( - badImportTestSuite.content.meta[ERROR_MESSAGE], - 'a file after the Jest environment has been torn down' - ) - assert.include( - badImportTestSuite.content.meta[ERROR_MESSAGE], - 'From ci-visibility/jest-bad-import-torn-down/jest-bad-import-test.js' - ) + assert.strictEqual(badImportTestSuite.content.meta[TEST_STATUS], 'pass') + assert.ok(badImportTestSuite.content.meta[ERROR_MESSAGE].includes('a file after the Jest environment has been torn down')) + assert.ok(badImportTestSuite.content.meta[ERROR_MESSAGE].includes('From ci-visibility/jest-bad-import-torn-down/jest-bad-import-test.js')) // This is the error message that jest should show. We check that we don't mess it up. - assert.include(badImportTestSuite.content.meta[ERROR_MESSAGE], 'off-timing-import') - assert.include(badImportTestSuite.content.meta[ERROR_MESSAGE], 'afterAll') - assert.include(badImportTestSuite.content.meta[ERROR_MESSAGE], 'nextTick') + assert.ok(badImportTestSuite.content.meta[ERROR_MESSAGE].includes('off-timing-import')) + assert.ok(badImportTestSuite.content.meta[ERROR_MESSAGE].includes('afterAll')) + assert.ok(badImportTestSuite.content.meta[ERROR_MESSAGE].includes('nextTick')) const passedTestSuites = suites.filter( suite => suite.content.meta[TEST_STATUS] === 'pass' ) - assert.equal(passedTestSuites.length, 3) + assert.strictEqual(passedTestSuites.length, 3) }) childProcess = exec(runTestsCommand, { @@ -1109,7 +1102,7 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { receiver.assertPayloadReceived(({ payload }) => { const testSession = payload.events.find(event => event.type === 'test_session_end').content - assert.notProperty(testSession.metrics, TEST_CODE_COVERAGE_LINES_PCT) + assert.ok(!Object.hasOwn(testSession.metrics, TEST_CODE_COVERAGE_LINES_PCT)) }, ({ url }) => url === '/api/v2/citestcycle').then(() => done()).catch(done) childProcess = exec( @@ -1131,7 +1124,7 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { receiver.assertPayloadReceived(({ payload }) => { const testSession = payload.events.find(event => event.type === 'test_session_end').content - assert.exists(testSession.metrics[TEST_CODE_COVERAGE_LINES_PCT]) + assert.ok(testSession.metrics[TEST_CODE_COVERAGE_LINES_PCT] != null) }, ({ url }) => url === '/api/v2/citestcycle').then(() => done()).catch(done) childProcess = exec( @@ -1147,7 +1140,7 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { it('works with --forceExit and logs a warning', (done) => { const eventsPromise = receiver .gatherPayloadsMaxTimeout(({ url }) => url.endsWith('/api/v2/citestcycle'), (payloads) => { - assert.include(testOutput, "Jest's '--forceExit' flag has been passed") + assert.ok(testOutput.includes("Jest's '--forceExit' flag has been passed")) const events = payloads.flatMap(({ payload }) => payload.events) const testSession = events.find(event => event.type === 'test_session_end') @@ -1155,10 +1148,10 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { const testSuites = events.filter(event => event.type === 'test_suite_end') const tests = events.filter(event => event.type === 'test') - assert.exists(testSession) - assert.exists(testModule) - assert.equal(testSuites.length, 2) - assert.equal(tests.length, 2) + assert.ok(testSession != null) + assert.ok(testModule != null) + assert.strictEqual(testSuites.length, 2) + assert.strictEqual(tests.length, 2) }) // Needs to run with the CLI if we want --forceExit to work childProcess = exec( @@ -1205,16 +1198,10 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { const EXPECTED_FORCE_EXIT_LOG_MESSAGE = "Jest's '--forceExit' flag has been passed" const EXPECTED_TIMEOUT_LOG_MESSAGE = 'Timeout waiting for the tracer to flush' childProcess.on('exit', () => { - assert.include( - testOutput, - EXPECTED_FORCE_EXIT_LOG_MESSAGE, - `"${EXPECTED_FORCE_EXIT_LOG_MESSAGE}" log message is not in test output: ${testOutput}` - ) - assert.include( - testOutput, - EXPECTED_TIMEOUT_LOG_MESSAGE, - `"${EXPECTED_TIMEOUT_LOG_MESSAGE}" log message is not in the test output: ${testOutput}` - ) + assert.ok(testOutput.includes(EXPECTED_FORCE_EXIT_LOG_MESSAGE, + `"${EXPECTED_FORCE_EXIT_LOG_MESSAGE}" log message is not in test output: ${testOutput}`)) + assert.ok(testOutput.includes(EXPECTED_TIMEOUT_LOG_MESSAGE, + `"${EXPECTED_TIMEOUT_LOG_MESSAGE}" log message is not in the test output: ${testOutput}`)) done() }) childProcess.stdout.on('data', (chunk) => { @@ -1230,21 +1217,21 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { .gatherPayloadsMaxTimeout(({ url }) => url.endsWith('/api/v2/citestcycle'), (payloads) => { const events = payloads.flatMap(({ payload }) => payload.events) const tests = events.filter(event => event.type === 'test').map(event => event.content) - assert.equal(tests.length, 4) // two per display name + assert.strictEqual(tests.length, 4) // two per display name const nodeTests = tests.filter(test => test.meta[JEST_DISPLAY_NAME] === 'node') - assert.equal(nodeTests.length, 2) + assert.strictEqual(nodeTests.length, 2) const standardTests = tests.filter(test => test.meta[JEST_DISPLAY_NAME] === 'standard') - assert.equal(standardTests.length, 2) + assert.strictEqual(standardTests.length, 2) const suites = events.filter(event => event.type === 'test_suite_end').map(event => event.content) - assert.equal(suites.length, 4) + assert.strictEqual(suites.length, 4) const nodeSuites = suites.filter(suite => suite.meta[JEST_DISPLAY_NAME] === 'node') - assert.equal(nodeSuites.length, 2) + assert.strictEqual(nodeSuites.length, 2) const standardSuites = suites.filter(suite => suite.meta[JEST_DISPLAY_NAME] === 'standard') - assert.equal(standardSuites.length, 2) + assert.strictEqual(standardSuites.length, 2) }) childProcess = exec( 'node ./node_modules/jest/bin/jest --config config-jest-multiproject.js', @@ -1266,9 +1253,9 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { .gatherPayloadsMaxTimeout(({ url }) => url.endsWith('/api/v2/citestcycle'), (payloads) => { const events = payloads.flatMap(({ payload }) => payload.events) const testSession = events.find(event => event.type === 'test_session_end').content - assert.propertyVal(testSession.meta, TEST_STATUS, 'fail') + assert.strictEqual(testSession.meta[TEST_STATUS], 'fail') const errorMessage = 'Failed test suites: 1. Failed tests: 1' - assert.include(testSession.meta[ERROR_MESSAGE], errorMessage) + assert.ok(testSession.meta[ERROR_MESSAGE].includes(errorMessage)) }) childProcess = exec( @@ -1309,11 +1296,10 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { testOutput += chunk.toString() }) childProcess.on('message', () => { - assert.include(testOutput, expectedStdout) - assert.include(testOutput, 'DD_CIVISIBILITY_AGENTLESS_ENABLED is set, ' + + assert.ok(testOutput.includes(expectedStdout)) + assert.ok(testOutput.includes('DD_CIVISIBILITY_AGENTLESS_ENABLED is set, ' + 'but neither DD_API_KEY nor DATADOG_API_KEY are set in your environment, ' + - 'so dd-trace will not be initialized.' - ) + 'so dd-trace will not be initialized.')) done() }) }) @@ -1330,15 +1316,15 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { packfileRequestPromise, eventsRequestPromise ]).then(([searchCommitRequest, packfileRequest, eventsRequest]) => { - assert.propertyVal(searchCommitRequest.headers, 'dd-api-key', '1') - assert.propertyVal(packfileRequest.headers, 'dd-api-key', '1') + assert.strictEqual(searchCommitRequest.headers['dd-api-key'], '1') + assert.strictEqual(packfileRequest.headers['dd-api-key'], '1') const eventTypes = eventsRequest.payload.events.map(event => event.type) assert.includeMembers(eventTypes, ['test', 'test_suite_end', 'test_module_end', 'test_session_end']) const numSuites = eventTypes.reduce( (acc, type) => type === 'test_suite_end' ? acc + 1 : acc, 0 ) - assert.equal(numSuites, 2) + assert.strictEqual(numSuites, 2) done() }).catch(done) @@ -1404,35 +1390,35 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { codeCovRequestPromise, eventsRequestPromise ]).then(([libraryConfigRequest, codeCovRequest, eventsRequest]) => { - assert.propertyVal(libraryConfigRequest.headers, 'dd-api-key', '1') + assert.strictEqual(libraryConfigRequest.headers['dd-api-key'], '1') const [coveragePayload] = codeCovRequest.payload - assert.propertyVal(codeCovRequest.headers, 'dd-api-key', '1') + assert.strictEqual(codeCovRequest.headers['dd-api-key'], '1') - assert.propertyVal(coveragePayload, 'name', 'coverage1') - assert.propertyVal(coveragePayload, 'filename', 'coverage1.msgpack') - assert.propertyVal(coveragePayload, 'type', 'application/msgpack') - assert.include(coveragePayload.content, { + assert.strictEqual(coveragePayload['name'], 'coverage1') + assert.strictEqual(coveragePayload['filename'], 'coverage1.msgpack') + assert.strictEqual(coveragePayload['type'], 'application/msgpack') + assert.ok(coveragePayload.content.includes({ version: 2 - }) + })) const allCoverageFiles = codeCovRequest.payload .flatMap(coverage => coverage.content.coverages) .flatMap(file => file.files) .map(file => file.filename) assert.includeMembers(allCoverageFiles, expectedCoverageFiles) - assert.exists(coveragePayload.content.coverages[0].test_session_id) - assert.exists(coveragePayload.content.coverages[0].test_suite_id) + assert.ok(coveragePayload.content.coverages[0].test_session_id != null) + assert.ok(coveragePayload.content.coverages[0].test_suite_id != null) const testSession = eventsRequest.payload.events.find(event => event.type === 'test_session_end').content - assert.exists(testSession.metrics[TEST_CODE_COVERAGE_LINES_PCT]) + assert.ok(testSession.metrics[TEST_CODE_COVERAGE_LINES_PCT] != null) const eventTypes = eventsRequest.payload.events.map(event => event.type) assert.includeMembers(eventTypes, ['test', 'test_suite_end', 'test_module_end', 'test_session_end']) const numSuites = eventTypes.reduce( (acc, type) => type === 'test_suite_end' ? acc + 1 : acc, 0 ) - assert.equal(numSuites, 2) + assert.strictEqual(numSuites, 2) }) childProcess = exec( @@ -1465,18 +1451,18 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { }, ({ url }) => url === '/api/v2/citestcov').catch(() => {}) receiver.assertPayloadReceived(({ headers, payload }) => { - assert.propertyVal(headers, 'dd-api-key', '1') + assert.strictEqual(headers['dd-api-key'], '1') const eventTypes = payload.events.map(event => event.type) assert.includeMembers(eventTypes, ['test', 'test_session_end', 'test_module_end', 'test_suite_end']) const testSession = payload.events.find(event => event.type === 'test_session_end').content - assert.propertyVal(testSession.meta, TEST_ITR_TESTS_SKIPPED, 'false') - assert.propertyVal(testSession.meta, TEST_CODE_COVERAGE_ENABLED, 'false') - assert.propertyVal(testSession.meta, TEST_ITR_SKIPPING_ENABLED, 'false') - assert.exists(testSession.metrics[TEST_CODE_COVERAGE_LINES_PCT]) + assert.strictEqual(testSession.meta[TEST_ITR_TESTS_SKIPPED], 'false') + assert.strictEqual(testSession.meta[TEST_CODE_COVERAGE_ENABLED], 'false') + assert.strictEqual(testSession.meta[TEST_ITR_SKIPPING_ENABLED], 'false') + assert.ok(testSession.metrics[TEST_CODE_COVERAGE_LINES_PCT] != null) const testModule = payload.events.find(event => event.type === 'test_module_end').content - assert.propertyVal(testModule.meta, TEST_ITR_TESTS_SKIPPED, 'false') - assert.propertyVal(testModule.meta, TEST_CODE_COVERAGE_ENABLED, 'false') - assert.propertyVal(testModule.meta, TEST_ITR_SKIPPING_ENABLED, 'false') + assert.strictEqual(testModule.meta[TEST_ITR_TESTS_SKIPPED], 'false') + assert.strictEqual(testModule.meta[TEST_CODE_COVERAGE_ENABLED], 'false') + assert.strictEqual(testModule.meta[TEST_ITR_SKIPPING_ENABLED], 'false') }, ({ url }) => url === '/api/v2/citestcycle').then(() => done()).catch(done) childProcess = exec( @@ -1509,38 +1495,38 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { coverageRequestPromise, eventsRequestPromise ]).then(([skippableRequest, coverageRequest, eventsRequest]) => { - assert.propertyVal(skippableRequest.headers, 'dd-api-key', '1') + assert.strictEqual(skippableRequest.headers['dd-api-key'], '1') const [coveragePayload] = coverageRequest.payload - assert.propertyVal(coverageRequest.headers, 'dd-api-key', '1') - assert.propertyVal(coveragePayload, 'name', 'coverage1') - assert.propertyVal(coveragePayload, 'filename', 'coverage1.msgpack') - assert.propertyVal(coveragePayload, 'type', 'application/msgpack') + assert.strictEqual(coverageRequest.headers['dd-api-key'], '1') + assert.strictEqual(coveragePayload['name'], 'coverage1') + assert.strictEqual(coveragePayload['filename'], 'coverage1.msgpack') + assert.strictEqual(coveragePayload['type'], 'application/msgpack') - assert.propertyVal(eventsRequest.headers, 'dd-api-key', '1') + assert.strictEqual(eventsRequest.headers['dd-api-key'], '1') const eventTypes = eventsRequest.payload.events.map(event => event.type) const skippedSuite = eventsRequest.payload.events.find(event => event.content.resource === 'test_suite.ci-visibility/test/ci-visibility-test.js' ).content - assert.propertyVal(skippedSuite.meta, TEST_STATUS, 'skip') - assert.propertyVal(skippedSuite.meta, TEST_SKIPPED_BY_ITR, 'true') + assert.strictEqual(skippedSuite.meta[TEST_STATUS], 'skip') + assert.strictEqual(skippedSuite.meta[TEST_SKIPPED_BY_ITR], 'true') assert.includeMembers(eventTypes, ['test', 'test_suite_end', 'test_module_end', 'test_session_end']) const numSuites = eventTypes.reduce( (acc, type) => type === 'test_suite_end' ? acc + 1 : acc, 0 ) - assert.equal(numSuites, 2) + assert.strictEqual(numSuites, 2) const testSession = eventsRequest.payload.events.find(event => event.type === 'test_session_end').content - assert.propertyVal(testSession.meta, TEST_ITR_TESTS_SKIPPED, 'true') - assert.propertyVal(testSession.meta, TEST_CODE_COVERAGE_ENABLED, 'true') - assert.propertyVal(testSession.meta, TEST_ITR_SKIPPING_ENABLED, 'true') - assert.propertyVal(testSession.meta, TEST_ITR_SKIPPING_TYPE, 'suite') - assert.propertyVal(testSession.metrics, TEST_ITR_SKIPPING_COUNT, 1) + assert.strictEqual(testSession.meta[TEST_ITR_TESTS_SKIPPED], 'true') + assert.strictEqual(testSession.meta[TEST_CODE_COVERAGE_ENABLED], 'true') + assert.strictEqual(testSession.meta[TEST_ITR_SKIPPING_ENABLED], 'true') + assert.strictEqual(testSession.meta[TEST_ITR_SKIPPING_TYPE], 'suite') + assert.strictEqual(testSession.metrics[TEST_ITR_SKIPPING_COUNT], 1) const testModule = eventsRequest.payload.events.find(event => event.type === 'test_module_end').content - assert.propertyVal(testModule.meta, TEST_ITR_TESTS_SKIPPED, 'true') - assert.propertyVal(testModule.meta, TEST_CODE_COVERAGE_ENABLED, 'true') - assert.propertyVal(testModule.meta, TEST_ITR_SKIPPING_ENABLED, 'true') - assert.propertyVal(testModule.meta, TEST_ITR_SKIPPING_TYPE, 'suite') - assert.propertyVal(testModule.metrics, TEST_ITR_SKIPPING_COUNT, 1) + assert.strictEqual(testModule.meta[TEST_ITR_TESTS_SKIPPED], 'true') + assert.strictEqual(testModule.meta[TEST_CODE_COVERAGE_ENABLED], 'true') + assert.strictEqual(testModule.meta[TEST_ITR_SKIPPING_ENABLED], 'true') + assert.strictEqual(testModule.meta[TEST_ITR_SKIPPING_TYPE], 'suite') + assert.strictEqual(testModule.metrics[TEST_ITR_SKIPPING_COUNT], 1) done() }).catch(done) @@ -1576,7 +1562,7 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { .gatherPayloadsMaxTimeout(({ url }) => url.endsWith('/api/v2/citestcycle'), (payloads) => { const events = payloads.flatMap(({ payload }) => payload.events) const testSession = events.find(event => event.type === 'test_session_end').content - assert.propertyVal(testSession.meta, TEST_STATUS, 'skip') + assert.strictEqual(testSession.meta[TEST_STATUS], 'skip') }) childProcess = exec( runTestsCommand, @@ -1609,22 +1595,22 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { }, ({ url }) => url === '/api/v2/ci/tests/skippable').catch(() => {}) receiver.assertPayloadReceived(({ headers, payload }) => { - assert.propertyVal(headers, 'dd-api-key', '1') + assert.strictEqual(headers['dd-api-key'], '1') const eventTypes = payload.events.map(event => event.type) // because they are not skipped assert.includeMembers(eventTypes, ['test', 'test_suite_end', 'test_module_end', 'test_session_end']) const numSuites = eventTypes.reduce( (acc, type) => type === 'test_suite_end' ? acc + 1 : acc, 0 ) - assert.equal(numSuites, 2) + assert.strictEqual(numSuites, 2) const testSession = payload.events.find(event => event.type === 'test_session_end').content - assert.propertyVal(testSession.meta, TEST_ITR_TESTS_SKIPPED, 'false') - assert.propertyVal(testSession.meta, TEST_CODE_COVERAGE_ENABLED, 'true') - assert.propertyVal(testSession.meta, TEST_ITR_SKIPPING_ENABLED, 'true') + assert.strictEqual(testSession.meta[TEST_ITR_TESTS_SKIPPED], 'false') + assert.strictEqual(testSession.meta[TEST_CODE_COVERAGE_ENABLED], 'true') + assert.strictEqual(testSession.meta[TEST_ITR_SKIPPING_ENABLED], 'true') const testModule = payload.events.find(event => event.type === 'test_module_end').content - assert.propertyVal(testModule.meta, TEST_ITR_TESTS_SKIPPED, 'false') - assert.propertyVal(testModule.meta, TEST_CODE_COVERAGE_ENABLED, 'true') - assert.propertyVal(testModule.meta, TEST_ITR_SKIPPING_ENABLED, 'true') + assert.strictEqual(testModule.meta[TEST_ITR_TESTS_SKIPPED], 'false') + assert.strictEqual(testModule.meta[TEST_CODE_COVERAGE_ENABLED], 'true') + assert.strictEqual(testModule.meta[TEST_ITR_SKIPPING_ENABLED], 'true') }, ({ url }) => url === '/api/v2/citestcycle').then(() => done()).catch(done) childProcess = exec( @@ -1657,14 +1643,14 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { }, ({ url }) => url === '/api/v2/ci/tests/skippable').catch(() => {}) receiver.assertPayloadReceived(({ headers, payload }) => { - assert.propertyVal(headers, 'dd-api-key', '1') + assert.strictEqual(headers['dd-api-key'], '1') const eventTypes = payload.events.map(event => event.type) // because they are not skipped assert.includeMembers(eventTypes, ['test', 'test_suite_end', 'test_module_end', 'test_session_end']) const numSuites = eventTypes.reduce( (acc, type) => type === 'test_suite_end' ? acc + 1 : acc, 0 ) - assert.equal(numSuites, 2) + assert.strictEqual(numSuites, 2) }, ({ url }) => url === '/api/v2/citestcycle').then(() => done()).catch(done) childProcess = exec( @@ -1698,14 +1684,14 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { const events = payloads.flatMap(({ payload }) => payload.events) const suites = events.filter(event => event.type === 'test_suite_end') - assert.equal(suites.length, 3) + assert.strictEqual(suites.length, 3) const testSession = events.find(event => event.type === 'test_session_end').content const testModule = events.find(event => event.type === 'test_module_end').content - assert.propertyVal(testSession.meta, TEST_ITR_FORCED_RUN, 'true') - assert.propertyVal(testSession.meta, TEST_ITR_UNSKIPPABLE, 'true') - assert.propertyVal(testModule.meta, TEST_ITR_FORCED_RUN, 'true') - assert.propertyVal(testModule.meta, TEST_ITR_UNSKIPPABLE, 'true') + assert.strictEqual(testSession.meta[TEST_ITR_FORCED_RUN], 'true') + assert.strictEqual(testSession.meta[TEST_ITR_UNSKIPPABLE], 'true') + assert.strictEqual(testModule.meta[TEST_ITR_FORCED_RUN], 'true') + assert.strictEqual(testModule.meta[TEST_ITR_UNSKIPPABLE], 'true') const passedSuite = suites.find( event => event.content.resource === 'test_suite.ci-visibility/unskippable-test/test-to-run.js' @@ -1717,17 +1703,17 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { event => event.content.resource === 'test_suite.ci-visibility/unskippable-test/test-unskippable.js' ) // It does not mark as unskippable if there is no docblock - assert.propertyVal(passedSuite.content.meta, TEST_STATUS, 'pass') - assert.notProperty(passedSuite.content.meta, TEST_ITR_UNSKIPPABLE) - assert.notProperty(passedSuite.content.meta, TEST_ITR_FORCED_RUN) + assert.strictEqual(passedSuite.content.meta[TEST_STATUS], 'pass') + assert.ok(!Object.hasOwn(passedSuite.content.meta, TEST_ITR_UNSKIPPABLE)) + assert.ok(!Object.hasOwn(passedSuite.content.meta, TEST_ITR_FORCED_RUN)) - assert.propertyVal(skippedSuite.content.meta, TEST_STATUS, 'skip') - assert.notProperty(skippedSuite.content.meta, TEST_ITR_UNSKIPPABLE) - assert.notProperty(skippedSuite.content.meta, TEST_ITR_FORCED_RUN) + assert.strictEqual(skippedSuite.content.meta[TEST_STATUS], 'skip') + assert.ok(!Object.hasOwn(skippedSuite.content.meta, TEST_ITR_UNSKIPPABLE)) + assert.ok(!Object.hasOwn(skippedSuite.content.meta, TEST_ITR_FORCED_RUN)) - assert.propertyVal(forcedToRunSuite.content.meta, TEST_STATUS, 'pass') - assert.propertyVal(forcedToRunSuite.content.meta, TEST_ITR_UNSKIPPABLE, 'true') - assert.propertyVal(forcedToRunSuite.content.meta, TEST_ITR_FORCED_RUN, 'true') + assert.strictEqual(forcedToRunSuite.content.meta[TEST_STATUS], 'pass') + assert.strictEqual(forcedToRunSuite.content.meta[TEST_ITR_UNSKIPPABLE], 'true') + assert.strictEqual(forcedToRunSuite.content.meta[TEST_ITR_FORCED_RUN], 'true') }, 25000) childProcess = exec( @@ -1764,14 +1750,14 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { const events = payloads.flatMap(({ payload }) => payload.events) const suites = events.filter(event => event.type === 'test_suite_end') - assert.equal(suites.length, 3) + assert.strictEqual(suites.length, 3) const testSession = events.find(event => event.type === 'test_session_end').content const testModule = events.find(event => event.type === 'test_module_end').content - assert.notProperty(testSession.meta, TEST_ITR_FORCED_RUN) - assert.propertyVal(testSession.meta, TEST_ITR_UNSKIPPABLE, 'true') - assert.notProperty(testModule.meta, TEST_ITR_FORCED_RUN) - assert.propertyVal(testModule.meta, TEST_ITR_UNSKIPPABLE, 'true') + assert.ok(!Object.hasOwn(testSession.meta, TEST_ITR_FORCED_RUN)) + assert.strictEqual(testSession.meta[TEST_ITR_UNSKIPPABLE], 'true') + assert.ok(!Object.hasOwn(testModule.meta, TEST_ITR_FORCED_RUN)) + assert.strictEqual(testModule.meta[TEST_ITR_UNSKIPPABLE], 'true') const passedSuite = suites.find( event => event.content.resource === 'test_suite.ci-visibility/unskippable-test/test-to-run.js' @@ -1784,16 +1770,16 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { ).content // It does not mark as unskippable if there is no docblock - assert.propertyVal(passedSuite.content.meta, TEST_STATUS, 'pass') - assert.notProperty(passedSuite.content.meta, TEST_ITR_UNSKIPPABLE) - assert.notProperty(passedSuite.content.meta, TEST_ITR_FORCED_RUN) + assert.strictEqual(passedSuite.content.meta[TEST_STATUS], 'pass') + assert.ok(!Object.hasOwn(passedSuite.content.meta, TEST_ITR_UNSKIPPABLE)) + assert.ok(!Object.hasOwn(passedSuite.content.meta, TEST_ITR_FORCED_RUN)) - assert.propertyVal(skippedSuite.meta, TEST_STATUS, 'skip') + assert.strictEqual(skippedSuite.meta[TEST_STATUS], 'skip') - assert.propertyVal(nonSkippedSuite.meta, TEST_STATUS, 'pass') - assert.propertyVal(nonSkippedSuite.meta, TEST_ITR_UNSKIPPABLE, 'true') + assert.strictEqual(nonSkippedSuite.meta[TEST_STATUS], 'pass') + assert.strictEqual(nonSkippedSuite.meta[TEST_ITR_UNSKIPPABLE], 'true') // it was not forced to run because it wasn't going to be skipped - assert.notProperty(nonSkippedSuite.meta, TEST_ITR_FORCED_RUN) + assert.ok(!Object.hasOwn(nonSkippedSuite.meta, TEST_ITR_FORCED_RUN)) }, 25000) childProcess = exec( @@ -1826,13 +1812,13 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { .gatherPayloadsMaxTimeout(({ url }) => url.endsWith('/api/v2/citestcycle'), (payloads) => { const events = payloads.flatMap(({ payload }) => payload.events) const testSession = events.find(event => event.type === 'test_session_end').content - assert.propertyVal(testSession.meta, TEST_ITR_TESTS_SKIPPED, 'false') - assert.propertyVal(testSession.meta, TEST_CODE_COVERAGE_ENABLED, 'true') - assert.propertyVal(testSession.meta, TEST_ITR_SKIPPING_ENABLED, 'true') + assert.strictEqual(testSession.meta[TEST_ITR_TESTS_SKIPPED], 'false') + assert.strictEqual(testSession.meta[TEST_CODE_COVERAGE_ENABLED], 'true') + assert.strictEqual(testSession.meta[TEST_ITR_SKIPPING_ENABLED], 'true') const testModule = events.find(event => event.type === 'test_module_end').content - assert.propertyVal(testModule.meta, TEST_ITR_TESTS_SKIPPED, 'false') - assert.propertyVal(testModule.meta, TEST_CODE_COVERAGE_ENABLED, 'true') - assert.propertyVal(testModule.meta, TEST_ITR_SKIPPING_ENABLED, 'true') + assert.strictEqual(testModule.meta[TEST_ITR_TESTS_SKIPPED], 'false') + assert.strictEqual(testModule.meta[TEST_CODE_COVERAGE_ENABLED], 'true') + assert.strictEqual(testModule.meta[TEST_ITR_SKIPPING_ENABLED], 'true') }, 25000) childProcess = exec( @@ -1858,7 +1844,7 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { const events = payloads.flatMap(({ payload }) => payload.events) const testSuites = events.filter(event => event.type === 'test_suite_end').map(event => event.content) testSuites.forEach(testSuite => { - assert.equal(testSuite.itr_correlation_id, itrCorrelationId) + assert.strictEqual(testSuite.itr_correlation_id, itrCorrelationId) }) }, 25000) childProcess = exec( @@ -1900,11 +1886,11 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { const skippedSuites = testSuites.filter( suite => suite.resource === 'test_suite.ci-visibility/test/ci-visibility-test.js' ) - assert.equal(skippedSuites.length, 2) + assert.strictEqual(skippedSuites.length, 2) skippedSuites.forEach(skippedSuite => { - assert.equal(skippedSuite.meta[TEST_STATUS], 'skip') - assert.equal(skippedSuite.meta[TEST_SKIPPED_BY_ITR], 'true') + assert.strictEqual(skippedSuite.meta[TEST_STATUS], 'skip') + assert.strictEqual(skippedSuite.meta[TEST_SKIPPED_BY_ITR], 'true') }) }) @@ -1947,7 +1933,7 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { // The reason is that skipping jest's `addUntestedFiles`, we would not see unexecuted lines. // In this cause, these would be from the `unused-dependency.js` file. // It is 50% now because we only cover 1 out of 2 files (`used-dependency.js`). - assert.propertyVal(testSession.metrics, TEST_CODE_COVERAGE_LINES_PCT, 50) + assert.strictEqual(testSession.metrics[TEST_CODE_COVERAGE_LINES_PCT], 50) }) childProcess = exec( @@ -2070,7 +2056,7 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { const events = payloads.flatMap(({ payload }) => payload.events) const testSession = events.find(event => event.type === 'test_session_end').content - assert.propertyVal(testSession.meta, TEST_EARLY_FLAKE_ENABLED, 'true') + assert.strictEqual(testSession.meta[TEST_EARLY_FLAKE_ENABLED], 'true') const tests = events.filter(event => event.type === 'test').map(event => event.content) @@ -2079,29 +2065,26 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { test.meta[TEST_SUITE] === 'ci-visibility/test/ci-visibility-test.js' ) oldTests.forEach(test => { - assert.notProperty(test.meta, TEST_IS_NEW) + assert.ok(!Object.hasOwn(test.meta, TEST_IS_NEW)) }) - assert.equal(oldTests.length, 1) + assert.strictEqual(oldTests.length, 1) const newTests = tests.filter(test => test.meta[TEST_SUITE] === 'ci-visibility/test/ci-visibility-test-2.js' ) newTests.forEach(test => { - assert.propertyVal(test.meta, TEST_IS_NEW, 'true') + assert.strictEqual(test.meta[TEST_IS_NEW], 'true') }) const retriedTests = newTests.filter(test => test.meta[TEST_IS_RETRY] === 'true') // all but one has been retried - assert.equal( - newTests.length - 1, - retriedTests.length - ) - assert.equal(retriedTests.length, NUM_RETRIES_EFD) + assert.strictEqual(newTests.length - 1, retriedTests.length) + assert.strictEqual(retriedTests.length, NUM_RETRIES_EFD) retriedTests.forEach(test => { - assert.propertyVal(test.meta, TEST_RETRY_REASON, TEST_RETRY_REASON_TYPES.efd) + assert.strictEqual(test.meta[TEST_RETRY_REASON], TEST_RETRY_REASON_TYPES.efd) }) // Test name does not change newTests.forEach(test => { - assert.equal(test.meta[TEST_NAME], 'ci visibility 2 can report tests 2') + assert.strictEqual(test.meta[TEST_NAME], 'ci visibility 2 can report tests 2') }) }) @@ -2147,13 +2130,13 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { const tests = events.filter(event => event.type === 'test').map(event => event.content) const testSession = events.find(event => event.type === 'test_session_end').content - assert.propertyVal(testSession.meta, TEST_EARLY_FLAKE_ENABLED, 'true') + assert.strictEqual(testSession.meta[TEST_EARLY_FLAKE_ENABLED], 'true') const newTests = tests.filter(test => test.meta[TEST_SUITE] === `ci-visibility/test-early-flake-detection/${parameterizedTestFile}` ) newTests.forEach(test => { - assert.propertyVal(test.meta, TEST_IS_NEW, 'true') + assert.strictEqual(test.meta[TEST_IS_NEW], 'true') }) // Each parameter is repeated independently const testsForFirstParameter = tests.filter(test => test.resource === @@ -2164,18 +2147,12 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { `ci-visibility/test-early-flake-detection/${parameterizedTestFile}.parameterized test parameter 2` ) - assert.equal(testsForFirstParameter.length, testsForSecondParameter.length) + assert.strictEqual(testsForFirstParameter.length, testsForSecondParameter.length) // all but one have been retried - assert.equal( - testsForFirstParameter.length - 1, - testsForFirstParameter.filter(test => test.meta[TEST_IS_RETRY] === 'true').length - ) + assert.strictEqual(testsForFirstParameter.length - 1, testsForFirstParameter.filter(test => test.meta[TEST_IS_RETRY] === 'true').length) - assert.equal( - testsForSecondParameter.length - 1, - testsForSecondParameter.filter(test => test.meta[TEST_IS_RETRY] === 'true').length - ) + assert.strictEqual(testsForSecondParameter.length - 1, testsForSecondParameter.filter(test => test.meta[TEST_IS_RETRY] === 'true').length) }) childProcess = exec( @@ -2216,18 +2193,18 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { .gatherPayloadsMaxTimeout(({ url }) => url.endsWith('/api/v2/citestcycle'), (payloads) => { const events = payloads.flatMap(({ payload }) => payload.events) const testSession = events.find(event => event.type === 'test_session_end').content - assert.notProperty(testSession.meta, TEST_EARLY_FLAKE_ENABLED) + assert.ok(!Object.hasOwn(testSession.meta, TEST_EARLY_FLAKE_ENABLED)) const tests = events.filter(event => event.type === 'test').map(event => event.content) const newTests = tests.filter(test => test.meta[TEST_IS_NEW] === 'true' ) // new tests are detected but not retried - assert.equal(newTests.length, 1) + assert.strictEqual(newTests.length, 1) const retriedTests = tests.filter(test => test.meta[TEST_IS_RETRY] === 'true' ) - assert.equal(retriedTests.length, 0) + assert.strictEqual(retriedTests.length, 0) }) childProcess = exec( @@ -2271,26 +2248,23 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { const events = payloads.flatMap(({ payload }) => payload.events) const testSession = events.find(event => event.type === 'test_session_end').content - assert.propertyVal(testSession.meta, TEST_EARLY_FLAKE_ENABLED, 'true') + assert.strictEqual(testSession.meta[TEST_EARLY_FLAKE_ENABLED], 'true') const tests = events.filter(event => event.type === 'test').map(event => event.content) const retriedTests = tests.filter(test => test.meta[TEST_IS_RETRY] === 'true') // all but one has been retried - assert.equal( - tests.length - 1, - retriedTests.length - ) - assert.equal(retriedTests.length, NUM_RETRIES_EFD) + assert.strictEqual(tests.length - 1, retriedTests.length) + assert.strictEqual(retriedTests.length, NUM_RETRIES_EFD) // Out of NUM_RETRIES_EFD + 1 total runs, half will be passing and half will be failing, // based on the global counter in the test file const passingTests = tests.filter(test => test.meta[TEST_STATUS] === 'pass') const failingTests = tests.filter(test => test.meta[TEST_STATUS] === 'fail') - assert.equal(passingTests.length, (NUM_RETRIES_EFD + 1) / 2) - assert.equal(failingTests.length, (NUM_RETRIES_EFD + 1) / 2) + assert.strictEqual(passingTests.length, (NUM_RETRIES_EFD + 1) / 2) + assert.strictEqual(failingTests.length, (NUM_RETRIES_EFD + 1) / 2) // Test name does not change retriedTests.forEach(test => { - assert.equal(test.meta[TEST_NAME], 'fail occasionally fails') + assert.strictEqual(test.meta[TEST_NAME], 'fail occasionally fails') }) }) @@ -2335,21 +2309,21 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { const events = payloads.flatMap(({ payload }) => payload.events) const testSession = events.find(event => event.type === 'test_session_end').content - assert.propertyVal(testSession.meta, TEST_EARLY_FLAKE_ENABLED, 'true') + assert.strictEqual(testSession.meta[TEST_EARLY_FLAKE_ENABLED], 'true') const tests = events.filter(event => event.type === 'test').map(event => event.content) const newSkippedTests = tests.filter( test => test.meta[TEST_NAME] === 'ci visibility skip will not be retried' ) - assert.equal(newSkippedTests.length, 1) - assert.notProperty(newSkippedTests[0].meta, TEST_IS_RETRY) + assert.strictEqual(newSkippedTests.length, 1) + assert.ok(!Object.hasOwn(newSkippedTests[0].meta, TEST_IS_RETRY)) const newTodoTests = tests.filter( test => test.meta[TEST_NAME] === 'ci visibility todo will not be retried' ) - assert.equal(newTodoTests.length, 1) - assert.notProperty(newTodoTests[0].meta, TEST_IS_RETRY) + assert.strictEqual(newTodoTests.length, 1) + assert.ok(!Object.hasOwn(newTodoTests[0].meta, TEST_IS_RETRY)) }) childProcess = exec( @@ -2398,7 +2372,7 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { const events = payloads.flatMap(({ payload }) => payload.events) const tests = events.filter(event => event.type === 'test').map(event => event.content) - assert.equal(tests.length, 2) + assert.strictEqual(tests.length, 2) const resourceNames = tests.map(test => test.resource) @@ -2413,7 +2387,7 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { test => test.meta[TEST_IS_NEW] === 'true' ) // no new tests - assert.equal(newTests.length, 0) + assert.strictEqual(newTests.length, 0) }) childProcess = exec( @@ -2455,15 +2429,15 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { const events = payloads.flatMap(({ payload }) => payload.events) const testSession = events.find(event => event.type === 'test_session_end').content - assert.notProperty(testSession.meta, TEST_EARLY_FLAKE_ENABLED) + assert.ok(!Object.hasOwn(testSession.meta, TEST_EARLY_FLAKE_ENABLED)) const tests = events.filter(event => event.type === 'test').map(event => event.content) - assert.equal(tests.length, 2) + assert.strictEqual(tests.length, 2) const newTests = tests.filter( test => test.meta[TEST_IS_NEW] === 'true' ) - assert.equal(newTests.length, 0) + assert.strictEqual(newTests.length, 0) }) childProcess = exec( @@ -2505,26 +2479,23 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { const events = payloads.flatMap(({ payload }) => payload.events) const testSession = events.find(event => event.type === 'test_session_end').content - assert.propertyVal(testSession.meta, TEST_EARLY_FLAKE_ENABLED, 'true') + assert.strictEqual(testSession.meta[TEST_EARLY_FLAKE_ENABLED], 'true') const tests = events.filter(event => event.type === 'test').map(event => event.content) const retriedTests = tests.filter(test => test.meta[TEST_IS_RETRY] === 'true') // all but one has been retried - assert.equal( - tests.length - 1, - retriedTests.length - ) - assert.equal(retriedTests.length, NUM_RETRIES_EFD) + assert.strictEqual(tests.length - 1, retriedTests.length) + assert.strictEqual(retriedTests.length, NUM_RETRIES_EFD) // Out of NUM_RETRIES_EFD + 1 total runs, half will be passing and half will be failing, // based on the global counter in the test file const passingTests = tests.filter(test => test.meta[TEST_STATUS] === 'pass') const failingTests = tests.filter(test => test.meta[TEST_STATUS] === 'fail') - assert.equal(passingTests.length, (NUM_RETRIES_EFD + 1) / 2) - assert.equal(failingTests.length, (NUM_RETRIES_EFD + 1) / 2) + assert.strictEqual(passingTests.length, (NUM_RETRIES_EFD + 1) / 2) + assert.strictEqual(failingTests.length, (NUM_RETRIES_EFD + 1) / 2) // Test name does not change retriedTests.forEach(test => { - assert.equal(test.meta[TEST_NAME], 'fail occasionally fails') + assert.strictEqual(test.meta[TEST_NAME], 'fail occasionally fails') }) }) @@ -2548,8 +2519,8 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { }) childProcess.on('exit', (exitCode) => { - assert.include(testOutput, '2 failed, 2 passed') - assert.equal(exitCode, 0) + assert.ok(testOutput.includes('2 failed, 2 passed')) + assert.strictEqual(exitCode, 0) eventsPromise.then(() => { done() }).catch(done) @@ -2586,26 +2557,26 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { const events = payloads.flatMap(({ payload }) => payload.events) const testSession = events.find(event => event.type === 'test_session_end').content - assert.propertyVal(testSession.meta, TEST_EARLY_FLAKE_ENABLED, 'true') + assert.strictEqual(testSession.meta[TEST_EARLY_FLAKE_ENABLED], 'true') const tests = events.filter(event => event.type === 'test').map(event => event.content) // 6 tests, 4 of which are new: 4*(1 test + 3 retries) + 2*(1 test) = 18 - assert.equal(tests.length, 18) + assert.strictEqual(tests.length, 18) const retriedTests = tests.filter(test => test.meta[TEST_IS_RETRY] === 'true') // 4*(3 retries) - assert.equal(retriedTests.length, 12) + assert.strictEqual(retriedTests.length, 12) const newTests = tests.filter(test => test.meta[TEST_IS_NEW] === 'true') // 4*(1 test + 3 retries) - assert.equal(newTests.length, 16) + assert.strictEqual(newTests.length, 16) const flakyTests = tests.filter(test => test.meta[TEST_NAME] === 'test is flaky') - assert.equal(flakyTests.length, 4) + assert.strictEqual(flakyTests.length, 4) const failedFlakyTests = flakyTests.filter(test => test.meta[TEST_STATUS] === 'fail') - assert.equal(failedFlakyTests.length, 2) + assert.strictEqual(failedFlakyTests.length, 2) const passedFlakyTests = flakyTests.filter(test => test.meta[TEST_STATUS] === 'pass') - assert.equal(passedFlakyTests.length, 2) + assert.strictEqual(passedFlakyTests.length, 2) }) childProcess = exec(runTestsCommand, { @@ -2622,7 +2593,7 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { once(childProcess, 'exit'), eventsPromise ]) - assert.equal(exitCode, 0) + assert.strictEqual(exitCode, 0) }) // resetting snapshot state logic only works in latest versions @@ -2650,22 +2621,22 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { const events = payloads.flatMap(({ payload }) => payload.events) const testSession = events.find(event => event.type === 'test_session_end').content - assert.propertyVal(testSession.meta, TEST_EARLY_FLAKE_ENABLED, 'true') + assert.strictEqual(testSession.meta[TEST_EARLY_FLAKE_ENABLED], 'true') const tests = events.filter(event => event.type === 'test').map(event => event.content) // 1 new test - assert.equal(tests.length, 4) + assert.strictEqual(tests.length, 4) const retriedTests = tests.filter(test => test.meta[TEST_IS_RETRY] === 'true') - assert.equal(retriedTests.length, 3) + assert.strictEqual(retriedTests.length, 3) const newTests = tests.filter(test => test.meta[TEST_IS_NEW] === 'true') - assert.equal(newTests.length, 4) + assert.strictEqual(newTests.length, 4) const failedFlakyTests = tests.filter(test => test.meta[TEST_STATUS] === 'fail') - assert.equal(failedFlakyTests.length, 2) + assert.strictEqual(failedFlakyTests.length, 2) const passedFlakyTests = tests.filter(test => test.meta[TEST_STATUS] === 'pass') - assert.equal(passedFlakyTests.length, 2) + assert.strictEqual(passedFlakyTests.length, 2) }) childProcess = exec(runTestsCommand, { @@ -2682,7 +2653,7 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { once(childProcess, 'exit'), eventsPromise ]) - assert.equal(exitCode, 0) + assert.strictEqual(exitCode, 0) }) it('bails out of EFD if the percentage of new tests is too high', (done) => { @@ -2707,16 +2678,16 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { const events = payloads.flatMap(({ payload }) => payload.events) const testSession = events.find(event => event.type === 'test_session_end').content - assert.propertyVal(testSession.meta, TEST_EARLY_FLAKE_ABORT_REASON, 'faulty') + assert.strictEqual(testSession.meta[TEST_EARLY_FLAKE_ABORT_REASON], 'faulty') const tests = events.filter(event => event.type === 'test').map(event => event.content) - assert.equal(tests.length, 2) + assert.strictEqual(tests.length, 2) const newTests = tests.filter( test => test.meta[TEST_IS_NEW] === 'true' ) // no new tests - assert.equal(newTests.length, 0) + assert.strictEqual(newTests.length, 0) }) childProcess = exec(runTestsCommand, { @@ -2763,26 +2734,23 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { test.meta[TEST_SUITE] === 'ci-visibility/test/ci-visibility-test.js' ) oldTests.forEach(test => { - assert.notProperty(test.meta, TEST_IS_NEW) + assert.ok(!Object.hasOwn(test.meta, TEST_IS_NEW)) }) - assert.equal(oldTests.length, 1) + assert.strictEqual(oldTests.length, 1) const newTests = tests.filter(test => test.meta[TEST_SUITE] === 'ci-visibility/test/ci-visibility-test-2.js' ) newTests.forEach(test => { - assert.propertyVal(test.meta, TEST_IS_NEW, 'true') + assert.strictEqual(test.meta[TEST_IS_NEW], 'true') }) const retriedTests = newTests.filter(test => test.meta[TEST_IS_RETRY] === 'true') // all but one has been retried - assert.equal( - newTests.length - 1, - retriedTests.length - ) - assert.equal(retriedTests.length, NUM_RETRIES_EFD) + assert.strictEqual(newTests.length - 1, retriedTests.length) + assert.strictEqual(retriedTests.length, NUM_RETRIES_EFD) // Test name does not change newTests.forEach(test => { - assert.equal(test.meta[TEST_NAME], 'ci visibility 2 can report tests 2') + assert.strictEqual(test.meta[TEST_NAME], 'ci visibility 2 can report tests 2') }) }) @@ -2838,26 +2806,23 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { test.meta[TEST_SUITE] === 'ci-visibility/test/ci-visibility-test.js' ) oldTests.forEach(test => { - assert.notProperty(test.meta, TEST_IS_NEW) + assert.ok(!Object.hasOwn(test.meta, TEST_IS_NEW)) }) - assert.equal(oldTests.length, 1) + assert.strictEqual(oldTests.length, 1) const newTests = tests.filter(test => test.meta[TEST_SUITE] === 'ci-visibility/test/ci-visibility-test-2.js' ) newTests.forEach(test => { - assert.propertyVal(test.meta, TEST_IS_NEW, 'true') + assert.strictEqual(test.meta[TEST_IS_NEW], 'true') }) const retriedTests = newTests.filter(test => test.meta[TEST_IS_RETRY] === 'true') // all but one has been retried - assert.equal( - newTests.length - 1, - retriedTests.length - ) - assert.equal(retriedTests.length, NUM_RETRIES_EFD) + assert.strictEqual(newTests.length - 1, retriedTests.length) + assert.strictEqual(retriedTests.length, NUM_RETRIES_EFD) // Test name does not change newTests.forEach(test => { - assert.equal(test.meta[TEST_NAME], 'ci visibility 2 can report tests 2') + assert.strictEqual(test.meta[TEST_NAME], 'ci visibility 2 can report tests 2') }) }) @@ -2904,7 +2869,7 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { const events = payloads.flatMap(({ payload }) => payload.events) const testSession = events.find(event => event.type === 'test_session_end').content - assert.notProperty(testSession.meta, TEST_EARLY_FLAKE_ENABLED) + assert.ok(!Object.hasOwn(testSession.meta, TEST_EARLY_FLAKE_ENABLED)) const tests = events.filter(event => event.type === 'test').map(event => event.content) @@ -2912,17 +2877,17 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { test.meta[TEST_SUITE] === 'ci-visibility/test/ci-visibility-test.js' ) oldTests.forEach(test => { - assert.notProperty(test.meta, TEST_IS_NEW) + assert.ok(!Object.hasOwn(test.meta, TEST_IS_NEW)) }) - assert.equal(oldTests.length, 1) + assert.strictEqual(oldTests.length, 1) const newTests = tests.filter(test => test.meta[TEST_SUITE] === 'ci-visibility/test/ci-visibility-test-2.js' ) newTests.forEach(test => { - assert.notProperty(test.meta, TEST_IS_NEW) + assert.ok(!Object.hasOwn(test.meta, TEST_IS_NEW)) }) const retriedTests = newTests.filter(test => test.meta[TEST_IS_RETRY] === 'true') - assert.equal(retriedTests.length, 0) + assert.strictEqual(retriedTests.length, 0) }) childProcess = exec( @@ -2959,7 +2924,7 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { const events = payloads.flatMap(({ payload }) => payload.events) const testSession = events.find(event => event.type === 'test_session_end').content - assert.propertyVal(testSession.meta, TEST_EARLY_FLAKE_ENABLED, 'true') + assert.strictEqual(testSession.meta[TEST_EARLY_FLAKE_ENABLED], 'true') const tests = events.filter(event => event.type === 'test').map(event => event.content) @@ -2967,9 +2932,9 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { test.meta[TEST_SUITE] === 'ci-visibility/jest/failing-test.js' ) newTests.forEach(test => { - assert.notProperty(test.meta, TEST_IS_NEW) + assert.ok(!Object.hasOwn(test.meta, TEST_IS_NEW)) }) - assert.equal(newTests.length, 2) + assert.strictEqual(newTests.length, 2) const passingTests = tests.filter(test => test.meta[TEST_NAME] === 'failing can report failed tests' @@ -2978,14 +2943,14 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { test.meta[TEST_NAME] === 'failing can report failing tests as failures' ) passingTests.forEach(test => { - assert.equal(test.meta[TEST_STATUS], 'pass') + assert.strictEqual(test.meta[TEST_STATUS], 'pass') }) failingTests.forEach(test => { - assert.equal(test.meta[TEST_STATUS], 'fail') + assert.strictEqual(test.meta[TEST_STATUS], 'fail') }) const retriedTests = newTests.filter(test => test.meta[TEST_IS_RETRY] === 'true') - assert.equal(retriedTests.length, 0) + assert.strictEqual(retriedTests.length, 0) }) childProcess = exec( @@ -3031,7 +2996,7 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { const events = payloads.flatMap(({ payload }) => payload.events) const testSession = events.find(event => event.type === 'test_session_end').content - assert.propertyVal(testSession.meta, TEST_EARLY_FLAKE_ENABLED, 'true') + assert.strictEqual(testSession.meta[TEST_EARLY_FLAKE_ENABLED], 'true') const tests = events.filter(event => event.type === 'test').map(event => event.content) @@ -3040,26 +3005,23 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { test.meta[TEST_SUITE] !== 'ci-visibility/test/efd-parallel/ci-visibility-test-4.js' ) oldTests.forEach(test => { - assert.notProperty(test.meta, TEST_IS_NEW) + assert.ok(!Object.hasOwn(test.meta, TEST_IS_NEW)) }) - assert.equal(oldTests.length, 3) + assert.strictEqual(oldTests.length, 3) const newTests = tests.filter(test => test.meta[TEST_SUITE] === 'ci-visibility/test/efd-parallel/ci-visibility-test-4.js' ) newTests.forEach(test => { - assert.propertyVal(test.meta, TEST_IS_NEW, 'true') + assert.strictEqual(test.meta[TEST_IS_NEW], 'true') }) const retriedTests = newTests.filter(test => test.meta[TEST_IS_RETRY] === 'true') // all but one has been retried - assert.equal( - newTests.length - 1, - retriedTests.length - ) - assert.equal(retriedTests.length, NUM_RETRIES_EFD) + assert.strictEqual(newTests.length - 1, retriedTests.length) + assert.strictEqual(retriedTests.length, NUM_RETRIES_EFD) retriedTests.forEach(test => { - assert.propertyVal(test.meta, TEST_RETRY_REASON, TEST_RETRY_REASON_TYPES.efd) + assert.strictEqual(test.meta[TEST_RETRY_REASON], TEST_RETRY_REASON_TYPES.efd) }) }) @@ -3106,16 +3068,16 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { const events = payloads.flatMap(({ payload }) => payload.events) const testSession = events.find(event => event.type === 'test_session_end').content - assert.notProperty(testSession.meta, TEST_EARLY_FLAKE_ENABLED) - assert.propertyVal(testSession.meta, TEST_EARLY_FLAKE_ABORT_REASON, 'faulty') + assert.ok(!Object.hasOwn(testSession.meta, TEST_EARLY_FLAKE_ENABLED)) + assert.strictEqual(testSession.meta[TEST_EARLY_FLAKE_ABORT_REASON], 'faulty') const tests = events.filter(event => event.type === 'test').map(event => event.content) - assert.equal(tests.length, 4) + assert.strictEqual(tests.length, 4) const newTests = tests.filter( test => test.meta[TEST_IS_NEW] === 'true' ) - assert.equal(newTests.length, 0) + assert.strictEqual(newTests.length, 0) }) childProcess = exec( @@ -3170,27 +3132,27 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { const events = payloads.flatMap(({ payload }) => payload.events) const testSession = events.find(event => event.type === 'test_session_end').content - assert.propertyVal(testSession.meta, TEST_EARLY_FLAKE_ENABLED, 'true') + assert.strictEqual(testSession.meta[TEST_EARLY_FLAKE_ENABLED], 'true') // 12 tests (6 per file): 8 new, 4 known const tests = events.filter(event => event.type === 'test').map(event => event.content) // 8*(1 test + 3 retries) + 4*(1 test) = 36 - assert.equal(tests.length, 36) + assert.strictEqual(tests.length, 36) const retriedTests = tests.filter(test => test.meta[TEST_IS_RETRY] === 'true') // 8*(3 retries) - assert.equal(retriedTests.length, 24) + assert.strictEqual(retriedTests.length, 24) const newTests = tests.filter(test => test.meta[TEST_IS_NEW] === 'true') // 8*(1 test + 3 retries) - assert.equal(newTests.length, 32) + assert.strictEqual(newTests.length, 32) const flakyTests = tests.filter(test => test.meta[TEST_NAME].includes('is flaky')) - assert.equal(flakyTests.length, 8) + assert.strictEqual(flakyTests.length, 8) const failedFlakyTests = flakyTests.filter(test => test.meta[TEST_STATUS] === 'fail') - assert.equal(failedFlakyTests.length, 4) + assert.strictEqual(failedFlakyTests.length, 4) const passedFlakyTests = flakyTests.filter(test => test.meta[TEST_STATUS] === 'pass') - assert.equal(passedFlakyTests.length, 4) + assert.strictEqual(passedFlakyTests.length, 4) }) childProcess = exec(runTestsCommand, { @@ -3230,7 +3192,7 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { const tests = events.filter(event => event.type === 'test').map(event => event.content) - assert.equal(tests.length, 10) + assert.strictEqual(tests.length, 10) assert.includeMembers(tests.map(test => test.resource), [ // does not retry 'ci-visibility/jest-flaky/flaky-passes.js.test-flaky-test-retries will not retry passed tests', @@ -3251,11 +3213,11 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { test => test.resource === 'ci-visibility/jest-flaky/flaky-passes.js.test-flaky-test-retries can retry flaky tests' ) - assert.equal(eventuallyPassingTest.length, 3) - assert.equal(eventuallyPassingTest.filter(test => test.meta[TEST_STATUS] === 'fail').length, 2) - assert.equal(eventuallyPassingTest.filter(test => test.meta[TEST_STATUS] === 'pass').length, 1) - assert.equal(eventuallyPassingTest.filter(test => test.meta[TEST_IS_RETRY] === 'true').length, 2) - assert.equal(eventuallyPassingTest.filter(test => + assert.strictEqual(eventuallyPassingTest.length, 3) + assert.strictEqual(eventuallyPassingTest.filter(test => test.meta[TEST_STATUS] === 'fail').length, 2) + assert.strictEqual(eventuallyPassingTest.filter(test => test.meta[TEST_STATUS] === 'pass').length, 1) + assert.strictEqual(eventuallyPassingTest.filter(test => test.meta[TEST_IS_RETRY] === 'true').length, 2) + assert.strictEqual(eventuallyPassingTest.filter(test => test.meta[TEST_RETRY_REASON] === TEST_RETRY_REASON_TYPES.atr ).length, 2) @@ -3263,11 +3225,11 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { test => test.resource === 'ci-visibility/jest-flaky/flaky-fails.js.test-flaky-test-retries can retry failed tests' ) - assert.equal(neverPassingTest.length, 6) - assert.equal(neverPassingTest.filter(test => test.meta[TEST_STATUS] === 'fail').length, 6) - assert.equal(neverPassingTest.filter(test => test.meta[TEST_STATUS] === 'pass').length, 0) - assert.equal(neverPassingTest.filter(test => test.meta[TEST_IS_RETRY] === 'true').length, 5) - assert.equal(neverPassingTest.filter( + assert.strictEqual(neverPassingTest.length, 6) + assert.strictEqual(neverPassingTest.filter(test => test.meta[TEST_STATUS] === 'fail').length, 6) + assert.strictEqual(neverPassingTest.filter(test => test.meta[TEST_STATUS] === 'pass').length, 0) + assert.strictEqual(neverPassingTest.filter(test => test.meta[TEST_IS_RETRY] === 'true').length, 5) + assert.strictEqual(neverPassingTest.filter( test => test.meta[TEST_RETRY_REASON] === TEST_RETRY_REASON_TYPES.atr ).length, 5) @@ -3276,12 +3238,12 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { const passingSuite = testSuites.find( suite => suite.resource === 'test_suite.ci-visibility/jest-flaky/flaky-passes.js' ) - assert.equal(passingSuite.meta[TEST_STATUS], 'pass') + assert.strictEqual(passingSuite.meta[TEST_STATUS], 'pass') const failedSuite = testSuites.find( suite => suite.resource === 'test_suite.ci-visibility/jest-flaky/flaky-fails.js' ) - assert.equal(failedSuite.meta[TEST_STATUS], 'fail') + assert.strictEqual(failedSuite.meta[TEST_STATUS], 'fail') }) childProcess = exec( @@ -3320,7 +3282,7 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { const tests = events.filter(event => event.type === 'test').map(event => event.content) - assert.equal(tests.length, 3) + assert.strictEqual(tests.length, 3) assert.includeMembers(tests.map(test => test.resource), [ // does not retry anything 'ci-visibility/jest-flaky/flaky-passes.js.test-flaky-test-retries will not retry passed tests', @@ -3330,7 +3292,7 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { const retriedTests = tests.filter(test => test.meta[TEST_RETRY_REASON] === TEST_RETRY_REASON_TYPES.atr) - assert.equal(retriedTests.length, 0) + assert.strictEqual(retriedTests.length, 0) }) childProcess = exec( @@ -3369,10 +3331,10 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { const events = payloads.flatMap(({ payload }) => payload.events) const tests = events.filter(event => event.type === 'test').map(event => event.content) - assert.equal(tests.filter(test => test.meta[TEST_IS_RETRY] === 'true').length, 2) - assert.equal(tests.filter(test => test.meta[TEST_RETRY_REASON] === TEST_RETRY_REASON_TYPES.atr).length, 2) + assert.strictEqual(tests.filter(test => test.meta[TEST_IS_RETRY] === 'true').length, 2) + assert.strictEqual(tests.filter(test => test.meta[TEST_RETRY_REASON] === TEST_RETRY_REASON_TYPES.atr).length, 2) - assert.equal(tests.length, 5) + assert.strictEqual(tests.length, 5) // only one retry assert.includeMembers(tests.map(test => test.resource), [ 'ci-visibility/jest-flaky/flaky-passes.js.test-flaky-test-retries will not retry passed tests', @@ -3415,13 +3377,13 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { const tests = events.filter(event => event.type === 'test').map(event => event.content) const retriedTests = tests.filter(test => test.meta[TEST_RETRY_REASON] === TEST_RETRY_REASON_TYPES.atr) - assert.equal(retriedTests.length, 1) + assert.strictEqual(retriedTests.length, 1) const [retriedTest] = retriedTests const hasDebugTags = Object.keys(retriedTest.meta) .some(property => property.startsWith(DI_DEBUG_ERROR_PREFIX) || property === DI_ERROR_DEBUG_INFO_CAPTURED) - assert.isFalse(hasDebugTags) + assert.strictEqual(hasDebugTags, false) }) const logsPromise = receiver @@ -3446,7 +3408,7 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { childProcess.on('exit', (code) => { Promise.all([eventsPromise, logsPromise]).then(() => { - assert.equal(code, 0) + assert.strictEqual(code, 0) done() }).catch(done) }) @@ -3464,13 +3426,13 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { const tests = events.filter(event => event.type === 'test').map(event => event.content) const retriedTests = tests.filter(test => test.meta[TEST_RETRY_REASON] === TEST_RETRY_REASON_TYPES.atr) - assert.equal(retriedTests.length, 1) + assert.strictEqual(retriedTests.length, 1) const [retriedTest] = retriedTests const hasDebugTags = Object.keys(retriedTest.meta) .some(property => property.startsWith(DI_DEBUG_ERROR_PREFIX) || property === DI_ERROR_DEBUG_INFO_CAPTURED) - assert.isFalse(hasDebugTags) + assert.strictEqual(hasDebugTags, false) }) const logsPromise = receiver .gatherPayloadsMaxTimeout(({ url }) => url.endsWith('/api/v2/logs'), (payloads) => { @@ -3493,7 +3455,7 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { childProcess.on('exit', (code) => { Promise.all([eventsPromise, logsPromise]).then(() => { - assert.equal(code, 0) + assert.strictEqual(code, 0) done() }).catch(done) }) @@ -3513,19 +3475,17 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { const tests = events.filter(event => event.type === 'test').map(event => event.content) const retriedTests = tests.filter(test => test.meta[TEST_RETRY_REASON] === TEST_RETRY_REASON_TYPES.atr) - assert.equal(retriedTests.length, 1) + assert.strictEqual(retriedTests.length, 1) const [retriedTest] = retriedTests - assert.propertyVal(retriedTest.meta, DI_ERROR_DEBUG_INFO_CAPTURED, 'true') + assert.strictEqual(retriedTest.meta[DI_ERROR_DEBUG_INFO_CAPTURED], 'true') - assert.isTrue( - retriedTest.meta[`${DI_DEBUG_ERROR_PREFIX}.0.${DI_DEBUG_ERROR_FILE_SUFFIX}`] - .endsWith('ci-visibility/dynamic-instrumentation/dependency.js') - ) - assert.equal(retriedTest.metrics[`${DI_DEBUG_ERROR_PREFIX}.0.${DI_DEBUG_ERROR_LINE_SUFFIX}`], 6) + assert.strictEqual(retriedTest.meta[`${DI_DEBUG_ERROR_PREFIX}.0.${DI_DEBUG_ERROR_FILE_SUFFIX}`] + .endsWith('ci-visibility/dynamic-instrumentation/dependency.js'), true) + assert.strictEqual(retriedTest.metrics[`${DI_DEBUG_ERROR_PREFIX}.0.${DI_DEBUG_ERROR_LINE_SUFFIX}`], 6) const snapshotIdKey = `${DI_DEBUG_ERROR_PREFIX}.0.${DI_DEBUG_ERROR_SNAPSHOT_ID_SUFFIX}` - assert.exists(retriedTest.meta[snapshotIdKey]) + assert.ok(retriedTest.meta[snapshotIdKey] != null) snapshotIdByTest = retriedTest.meta[snapshotIdKey] spanIdByTest = retriedTest.span_id.toString() @@ -3533,17 +3493,17 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { const notRetriedTest = tests.find(test => test.meta[TEST_NAME].includes('is not retried')) - assert.notProperty(notRetriedTest.meta, DI_ERROR_DEBUG_INFO_CAPTURED) + assert.ok(!Object.hasOwn(notRetriedTest.meta, DI_ERROR_DEBUG_INFO_CAPTURED)) }) const logsPromise = receiver .gatherPayloadsMaxTimeout(({ url }) => url.endsWith('/api/v2/logs'), (payloads) => { const [{ logMessage: [diLog] }] = payloads - assert.deepInclude(diLog, { + assertObjectContains(diLog, { ddsource: 'dd_debugger', level: 'error' }) - assert.equal(diLog.debugger.snapshot.language, 'javascript') + assert.strictEqual(diLog.debugger.snapshot.language, 'javascript') assert.deepInclude(diLog.debugger.snapshot.captures.lines['6'].locals, { a: { type: 'number', @@ -3577,9 +3537,9 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { childProcess.on('exit', () => { Promise.all([eventsPromise, logsPromise]).then(() => { - assert.equal(snapshotIdByTest, snapshotIdByLog) - assert.equal(spanIdByTest, spanIdByLog) - assert.equal(traceIdByTest, traceIdByLog) + assert.strictEqual(snapshotIdByTest, snapshotIdByLog) + assert.strictEqual(spanIdByTest, spanIdByLog) + assert.strictEqual(traceIdByTest, traceIdByLog) done() }).catch(done) }) @@ -3599,19 +3559,17 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { const tests = events.filter(event => event.type === 'test').map(event => event.content) const retriedTests = tests.filter(test => test.meta[TEST_RETRY_REASON] === TEST_RETRY_REASON_TYPES.atr) - assert.equal(retriedTests.length, 1) + assert.strictEqual(retriedTests.length, 1) const [retriedTest] = retriedTests - assert.propertyVal(retriedTest.meta, DI_ERROR_DEBUG_INFO_CAPTURED, 'true') + assert.strictEqual(retriedTest.meta[DI_ERROR_DEBUG_INFO_CAPTURED], 'true') - assert.isTrue( - retriedTest.meta[`${DI_DEBUG_ERROR_PREFIX}.0.${DI_DEBUG_ERROR_FILE_SUFFIX}`] - .endsWith('ci-visibility/dynamic-instrumentation/dependency.js') - ) - assert.equal(retriedTest.metrics[`${DI_DEBUG_ERROR_PREFIX}.0.${DI_DEBUG_ERROR_LINE_SUFFIX}`], 6) + assert.strictEqual(retriedTest.meta[`${DI_DEBUG_ERROR_PREFIX}.0.${DI_DEBUG_ERROR_FILE_SUFFIX}`] + .endsWith('ci-visibility/dynamic-instrumentation/dependency.js'), true) + assert.strictEqual(retriedTest.metrics[`${DI_DEBUG_ERROR_PREFIX}.0.${DI_DEBUG_ERROR_LINE_SUFFIX}`], 6) const snapshotIdKey = `${DI_DEBUG_ERROR_PREFIX}.0.${DI_DEBUG_ERROR_SNAPSHOT_ID_SUFFIX}` - assert.exists(retriedTest.meta[snapshotIdKey]) + assert.ok(retriedTest.meta[snapshotIdKey] != null) snapshotIdByTest = retriedTest.meta[snapshotIdKey] spanIdByTest = retriedTest.span_id.toString() @@ -3619,19 +3577,19 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { const notRetriedTest = tests.find(test => test.meta[TEST_NAME].includes('is not retried')) - assert.notProperty(notRetriedTest.meta, DI_ERROR_DEBUG_INFO_CAPTURED) + assert.ok(!Object.hasOwn(notRetriedTest.meta, DI_ERROR_DEBUG_INFO_CAPTURED)) }) const logsPromise = receiver .gatherPayloadsMaxTimeout(({ url }) => url.endsWith('/api/v2/logs'), (payloads) => { const [{ logMessage: [diLog] }] = payloads - assert.deepInclude(diLog, { + assertObjectContains(diLog, { ddsource: 'dd_debugger', level: 'error' }) - assert.include(diLog.ddtags, 'git.repository_url:') - assert.include(diLog.ddtags, 'git.commit.sha:') - assert.equal(diLog.debugger.snapshot.language, 'javascript') + assert.ok(diLog.ddtags.includes('git.repository_url:')) + assert.ok(diLog.ddtags.includes('git.commit.sha:')) + assert.strictEqual(diLog.debugger.snapshot.language, 'javascript') assert.deepInclude(diLog.debugger.snapshot.captures.lines['6'].locals, { a: { type: 'number', @@ -3666,9 +3624,9 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { childProcess.on('exit', () => { Promise.all([eventsPromise, logsPromise]).then(() => { - assert.equal(snapshotIdByTest, snapshotIdByLog) - assert.equal(spanIdByTest, spanIdByLog) - assert.equal(traceIdByTest, traceIdByLog) + assert.strictEqual(snapshotIdByTest, snapshotIdByLog) + assert.strictEqual(spanIdByTest, spanIdByLog) + assert.strictEqual(traceIdByTest, traceIdByLog) done() }).catch(done) }) @@ -3686,13 +3644,13 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { const tests = events.filter(event => event.type === 'test').map(event => event.content) const retriedTests = tests.filter(test => test.meta[TEST_RETRY_REASON] === TEST_RETRY_REASON_TYPES.atr) - assert.equal(retriedTests.length, 1) + assert.strictEqual(retriedTests.length, 1) const [retriedTest] = retriedTests const hasDebugTags = Object.keys(retriedTest.meta) .some(property => property.startsWith(DI_DEBUG_ERROR_PREFIX) || property === DI_ERROR_DEBUG_INFO_CAPTURED) - assert.isFalse(hasDebugTags) + assert.strictEqual(hasDebugTags, false) }) const logsPromise = receiver .gatherPayloadsMaxTimeout(({ url }) => url.endsWith('/api/v2/logs'), (payloads) => { @@ -3715,7 +3673,7 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { childProcess.on('exit', (code) => { Promise.all([eventsPromise, logsPromise]).then(() => { - assert.equal(code, 0) + assert.strictEqual(code, 0) done() }).catch(done) }) @@ -3734,10 +3692,10 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { const tests = events.filter(event => event.type === 'test').map(event => event.content) const retriedTests = tests.filter(test => test.meta[TEST_RETRY_REASON] === TEST_RETRY_REASON_TYPES.atr) - assert.equal(retriedTests.length, 1) + assert.strictEqual(retriedTests.length, 1) const [retriedTest] = retriedTests // Duration is in nanoseconds, so 200 * 1e6 is 200ms - assert.equal(retriedTest.duration < 200 * 1e6, true) + assert.strictEqual(retriedTest.duration < 200 * 1e6, true) }) childProcess = exec(runTestsCommand, @@ -3778,7 +3736,7 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { const tests = events.filter(event => event.type === 'test').map(event => event.content) - assert.equal(tests.length, 1) + assert.strictEqual(tests.length, 1) }) childProcess = exec(runTestsCommand, @@ -3794,7 +3752,7 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { childProcess.on('exit', (code) => { eventsPromise.then(() => { - assert.equal(code, 0) + assert.strictEqual(code, 0) done() }).catch(done) }) @@ -3822,7 +3780,7 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { const events = payloads.flatMap(({ payload }) => payload.events) const testSession = events.find(event => event.type === 'test_session_end').content - assert.notProperty(testSession.meta, TEST_EARLY_FLAKE_ENABLED) + assert.ok(!Object.hasOwn(testSession.meta, TEST_EARLY_FLAKE_ENABLED)) const tests = events.filter(event => event.type === 'test').map(event => event.content) @@ -3831,19 +3789,19 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { test.meta[TEST_SUITE] === 'ci-visibility/test/ci-visibility-test.js' ) oldTests.forEach(test => { - assert.notProperty(test.meta, TEST_IS_NEW) + assert.ok(!Object.hasOwn(test.meta, TEST_IS_NEW)) }) - assert.equal(oldTests.length, 1) + assert.strictEqual(oldTests.length, 1) const newTests = tests.filter(test => test.meta[TEST_SUITE] === 'ci-visibility/test/ci-visibility-test-2.js' ) newTests.forEach(test => { - assert.propertyVal(test.meta, TEST_IS_NEW, 'true') + assert.strictEqual(test.meta[TEST_IS_NEW], 'true') }) const retriedTests = newTests.filter(test => test.meta[TEST_IS_RETRY] === 'true') // no test has been retried - assert.equal(retriedTests.length, 0) + assert.strictEqual(retriedTests.length, 0) }) childProcess = exec( @@ -3869,7 +3827,7 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { const events = payloads.flatMap(({ payload }) => payload.events) const tests = events.filter(event => event.type === 'test').map(event => event.content) tests.forEach(test => { - assert.equal(test.meta[DD_TEST_IS_USER_PROVIDED_SERVICE], 'true') + assert.strictEqual(test.meta[DD_TEST_IS_USER_PROVIDED_SERVICE], 'true') }) }) @@ -3928,9 +3886,9 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { const testSession = events.find(event => event.type === 'test_session_end').content if (isAttemptToFix) { - assert.propertyVal(testSession.meta, TEST_MANAGEMENT_ENABLED, 'true') + assert.strictEqual(testSession.meta[TEST_MANAGEMENT_ENABLED], 'true') } else { - assert.notProperty(testSession.meta, TEST_MANAGEMENT_ENABLED) + assert.ok(!Object.hasOwn(testSession.meta, TEST_MANAGEMENT_ENABLED)) } const resourceNames = tests.map(span => span.resource) @@ -3957,41 +3915,41 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { for (let i = 0; i < retriedTests.length; i++) { const test = retriedTests[i] if (!isAttemptToFix) { - assert.notProperty(test.meta, TEST_MANAGEMENT_IS_ATTEMPT_TO_FIX) - assert.notProperty(test.meta, TEST_IS_RETRY) - assert.notProperty(test.meta, TEST_RETRY_REASON) + assert.ok(!Object.hasOwn(test.meta, TEST_MANAGEMENT_IS_ATTEMPT_TO_FIX)) + assert.ok(!Object.hasOwn(test.meta, TEST_IS_RETRY)) + assert.ok(!Object.hasOwn(test.meta, TEST_RETRY_REASON)) continue } if (isQuarantined) { - assert.propertyVal(test.meta, TEST_MANAGEMENT_IS_QUARANTINED, 'true') + assert.strictEqual(test.meta[TEST_MANAGEMENT_IS_QUARANTINED], 'true') } if (isDisabled) { - assert.propertyVal(test.meta, TEST_MANAGEMENT_IS_DISABLED, 'true') + assert.strictEqual(test.meta[TEST_MANAGEMENT_IS_DISABLED], 'true') } const isFirstAttempt = i === 0 const isLastAttempt = i === retriedTests.length - 1 - assert.propertyVal(test.meta, TEST_MANAGEMENT_IS_ATTEMPT_TO_FIX, 'true') + assert.strictEqual(test.meta[TEST_MANAGEMENT_IS_ATTEMPT_TO_FIX], 'true') if (isFirstAttempt) { - assert.notProperty(test.meta, TEST_IS_RETRY) - assert.notProperty(test.meta, TEST_RETRY_REASON) + assert.ok(!Object.hasOwn(test.meta, TEST_IS_RETRY)) + assert.ok(!Object.hasOwn(test.meta, TEST_RETRY_REASON)) } else { - assert.propertyVal(test.meta, TEST_IS_RETRY, 'true') - assert.propertyVal(test.meta, TEST_RETRY_REASON, TEST_RETRY_REASON_TYPES.atf) + assert.strictEqual(test.meta[TEST_IS_RETRY], 'true') + assert.strictEqual(test.meta[TEST_RETRY_REASON], TEST_RETRY_REASON_TYPES.atf) } if (isLastAttempt) { if (shouldAlwaysPass) { - assert.propertyVal(test.meta, TEST_MANAGEMENT_ATTEMPT_TO_FIX_PASSED, 'true') + assert.strictEqual(test.meta[TEST_MANAGEMENT_ATTEMPT_TO_FIX_PASSED], 'true') } else if (shouldFailSometimes) { - assert.notProperty(test.meta, TEST_HAS_FAILED_ALL_RETRIES) - assert.propertyVal(test.meta, TEST_MANAGEMENT_ATTEMPT_TO_FIX_PASSED, 'false') + assert.ok(!Object.hasOwn(test.meta, TEST_HAS_FAILED_ALL_RETRIES)) + assert.strictEqual(test.meta[TEST_MANAGEMENT_ATTEMPT_TO_FIX_PASSED], 'false') } else { - assert.propertyVal(test.meta, TEST_HAS_FAILED_ALL_RETRIES, 'true') - assert.propertyVal(test.meta, TEST_MANAGEMENT_ATTEMPT_TO_FIX_PASSED, 'false') + assert.strictEqual(test.meta[TEST_HAS_FAILED_ALL_RETRIES], 'true') + assert.strictEqual(test.meta[TEST_MANAGEMENT_ATTEMPT_TO_FIX_PASSED], 'false') } } } @@ -4042,12 +4000,12 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { childProcess.on('exit', exitCode => { testAssertionsPromise.then(() => { - assert.include(stdout, 'I am running when attempt to fix') + assert.ok(stdout.includes('I am running when attempt to fix')) if (isQuarantined || shouldAlwaysPass || isDisabled) { // even though a test fails, the exit code is 0 because the test is quarantined - assert.equal(exitCode, 0) + assert.strictEqual(exitCode, 0) } else { - assert.equal(exitCode, 1) + assert.strictEqual(exitCode, 1) } done() }).catch(done) @@ -4152,23 +4110,23 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { const tests = events.filter(event => event.type === 'test').map(event => event.content) const testSession = events.find(event => event.type === 'test_session_end').content - assert.propertyVal(testSession.meta, TEST_MANAGEMENT_ENABLED, 'true') + assert.strictEqual(testSession.meta[TEST_MANAGEMENT_ENABLED], 'true') - assert.equal(tests.length, 4) + assert.strictEqual(tests.length, 4) const retriedTests = tests.filter( test => test.meta[TEST_IS_RETRY] === 'true' ) - assert.equal(retriedTests.length, 3) + assert.strictEqual(retriedTests.length, 3) const failedTests = tests.filter( test => test.meta[TEST_STATUS] === 'fail' ) - assert.equal(failedTests.length, 2) + assert.strictEqual(failedTests.length, 2) const passedTests = tests.filter( test => test.meta[TEST_STATUS] === 'pass' ) - assert.equal(passedTests.length, 2) + assert.strictEqual(passedTests.length, 2) }) childProcess = exec( @@ -4213,14 +4171,14 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { const tests = events.filter(event => event.type === 'test').map(event => event.content) const testSession = events.find(event => event.type === 'test_session_end').content - assert.propertyVal(testSession.meta, TEST_MANAGEMENT_ENABLED, 'true') + assert.strictEqual(testSession.meta[TEST_MANAGEMENT_ENABLED], 'true') - assert.equal(tests.length, 4) + assert.strictEqual(tests.length, 4) const passedTests = tests.filter( test => test.meta[TEST_STATUS] === 'pass' ) - assert.equal(passedTests.length, 4) + assert.strictEqual(passedTests.length, 4) }) childProcess = exec( @@ -4240,7 +4198,7 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { once(childProcess, 'exit'), eventsPromise ]) - assert.equal(exitCode, 0) + assert.strictEqual(exitCode, 0) }) onlyLatestIt('works with image snapshot tests', async () => { @@ -4267,23 +4225,23 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { const tests = events.filter(event => event.type === 'test').map(event => event.content) const testSession = events.find(event => event.type === 'test_session_end').content - assert.propertyVal(testSession.meta, TEST_MANAGEMENT_ENABLED, 'true') + assert.strictEqual(testSession.meta[TEST_MANAGEMENT_ENABLED], 'true') - assert.equal(tests.length, 4) + assert.strictEqual(tests.length, 4) const retriedTests = tests.filter( test => test.meta[TEST_IS_RETRY] === 'true' ) - assert.equal(retriedTests.length, 3) + assert.strictEqual(retriedTests.length, 3) const failedTests = tests.filter( test => test.meta[TEST_STATUS] === 'fail' ) - assert.equal(failedTests.length, 2) + assert.strictEqual(failedTests.length, 2) const passedTests = tests.filter( test => test.meta[TEST_STATUS] === 'pass' ) - assert.equal(passedTests.length, 2) + assert.strictEqual(passedTests.length, 2) }) childProcess = exec( @@ -4356,23 +4314,23 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { const tests = events.filter(event => event.type === 'test').map(event => event.content) const testSession = events.find(event => event.type === 'test_session_end').content - assert.propertyVal(testSession.meta, TEST_MANAGEMENT_ENABLED, 'true') + assert.strictEqual(testSession.meta[TEST_MANAGEMENT_ENABLED], 'true') - assert.equal(tests.length, 8) + assert.strictEqual(tests.length, 8) const retriedTests = tests.filter( test => test.meta[TEST_IS_RETRY] === 'true' ) - assert.equal(retriedTests.length, 6) + assert.strictEqual(retriedTests.length, 6) const failedTests = tests.filter( test => test.meta[TEST_STATUS] === 'fail' ) - assert.equal(failedTests.length, 4) + assert.strictEqual(failedTests.length, 4) const passedTests = tests.filter( test => test.meta[TEST_STATUS] === 'pass' ) - assert.equal(passedTests.length, 4) + assert.strictEqual(passedTests.length, 4) }) childProcess = exec( @@ -4423,9 +4381,9 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { const testSession = events.find(event => event.type === 'test_session_end').content if (isDisabling) { - assert.propertyVal(testSession.meta, TEST_MANAGEMENT_ENABLED, 'true') + assert.strictEqual(testSession.meta[TEST_MANAGEMENT_ENABLED], 'true') } else { - assert.notProperty(testSession.meta, TEST_MANAGEMENT_ENABLED) + assert.ok(!Object.hasOwn(testSession.meta, TEST_MANAGEMENT_ENABLED)) } const resourceNames = tests.map(span => span.resource) @@ -4450,11 +4408,11 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { ) if (isDisabling) { - assert.equal(skippedTest.meta[TEST_STATUS], 'skip') - assert.propertyVal(skippedTest.meta, TEST_MANAGEMENT_IS_DISABLED, 'true') + assert.strictEqual(skippedTest.meta[TEST_STATUS], 'skip') + assert.strictEqual(skippedTest.meta[TEST_MANAGEMENT_IS_DISABLED], 'true') } else { - assert.equal(skippedTest.meta[TEST_STATUS], 'fail') - assert.notProperty(skippedTest.meta, TEST_MANAGEMENT_IS_DISABLED) + assert.strictEqual(skippedTest.meta[TEST_STATUS], 'fail') + assert.ok(!Object.hasOwn(skippedTest.meta, TEST_MANAGEMENT_IS_DISABLED)) } }) @@ -4484,12 +4442,12 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { childProcess.on('exit', exitCode => { testAssertionsPromise.then(() => { if (isDisabling) { - assert.notInclude(stdout, 'I am running') + assert.ok(!stdout.includes('I am running')) // even though a test fails, the exit code is 0 because the test is disabled - assert.equal(exitCode, 0) + assert.strictEqual(exitCode, 0) } else { - assert.include(stdout, 'I am running') - assert.equal(exitCode, 1) + assert.ok(stdout.includes('I am running')) + assert.strictEqual(exitCode, 1) } done() }).catch(done) @@ -4557,9 +4515,9 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { const testSession = events.find(event => event.type === 'test_session_end').content if (isQuarantining) { - assert.propertyVal(testSession.meta, TEST_MANAGEMENT_ENABLED, 'true') + assert.strictEqual(testSession.meta[TEST_MANAGEMENT_ENABLED], 'true') } else { - assert.notProperty(testSession.meta, TEST_MANAGEMENT_ENABLED) + assert.ok(!Object.hasOwn(testSession.meta, TEST_MANAGEMENT_ENABLED)) } const resourceNames = tests.map(span => span.resource) @@ -4584,12 +4542,12 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { const failedTest = tests.find( test => test.meta[TEST_NAME] === 'quarantine tests can quarantine a test' ) - assert.equal(failedTest.meta[TEST_STATUS], 'fail') + assert.strictEqual(failedTest.meta[TEST_STATUS], 'fail') if (isQuarantining) { - assert.propertyVal(failedTest.meta, TEST_MANAGEMENT_IS_QUARANTINED, 'true') + assert.strictEqual(failedTest.meta[TEST_MANAGEMENT_IS_QUARANTINED], 'true') } else { - assert.notProperty(failedTest.meta, TEST_MANAGEMENT_IS_QUARANTINED) + assert.ok(!Object.hasOwn(failedTest.meta, TEST_MANAGEMENT_IS_QUARANTINED)) } }) @@ -4619,12 +4577,12 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { childProcess.on('exit', exitCode => { testAssertionsPromise.then(() => { // it runs regardless of quarantine status - assert.include(stdout, 'I am running when quarantined') + assert.ok(stdout.includes('I am running when quarantined')) if (isQuarantining) { // even though a test fails, the exit code is 0 because the test is quarantined - assert.equal(exitCode, 0) + assert.strictEqual(exitCode, 0) } else { - assert.equal(exitCode, 1) + assert.strictEqual(exitCode, 1) } done() }).catch(done) @@ -4677,10 +4635,10 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { .gatherPayloadsMaxTimeout(({ url }) => url.endsWith('/api/v2/citestcycle'), (payloads) => { const events = payloads.flatMap(({ payload }) => payload.events) const testSession = events.find(event => event.type === 'test_session_end').content - assert.notProperty(testSession.meta, TEST_MANAGEMENT_ENABLED) + assert.ok(!Object.hasOwn(testSession.meta, TEST_MANAGEMENT_ENABLED)) const tests = events.filter(event => event.type === 'test').map(event => event.content) // it is not retried - assert.equal(tests.length, 1) + assert.strictEqual(tests.length, 1) }) childProcess = exec(runTestsCommand, { @@ -4706,7 +4664,7 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { once(childProcess.stderr, 'end'), eventsPromise ]) - assert.include(testOutput, 'Test management tests could not be fetched') + assert.ok(testOutput.includes('Test management tests could not be fetched')) }) }) @@ -4716,18 +4674,18 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { .gatherPayloadsMaxTimeout(({ url }) => url.endsWith('/api/v2/citestcycle'), payloads => { const metadataDicts = payloads.flatMap(({ payload }) => payload.metadata) - assert.isNotEmpty(metadataDicts) + assert.ok(metadataDicts.length > 0) metadataDicts.forEach(metadata => { - assert.equal(metadata.test[DD_CAPABILITIES_TEST_IMPACT_ANALYSIS], '1') - assert.equal(metadata.test[DD_CAPABILITIES_EARLY_FLAKE_DETECTION], '1') - assert.equal(metadata.test[DD_CAPABILITIES_AUTO_TEST_RETRIES], '1') - assert.equal(metadata.test[DD_CAPABILITIES_IMPACTED_TESTS], '1') - assert.equal(metadata.test[DD_CAPABILITIES_TEST_MANAGEMENT_QUARANTINE], '1') - assert.equal(metadata.test[DD_CAPABILITIES_TEST_MANAGEMENT_DISABLE], '1') - assert.equal(metadata.test[DD_CAPABILITIES_TEST_MANAGEMENT_ATTEMPT_TO_FIX], '5') - assert.equal(metadata.test[DD_CAPABILITIES_FAILED_TEST_REPLAY], '1') + assert.strictEqual(metadata.test[DD_CAPABILITIES_TEST_IMPACT_ANALYSIS], '1') + assert.strictEqual(metadata.test[DD_CAPABILITIES_EARLY_FLAKE_DETECTION], '1') + assert.strictEqual(metadata.test[DD_CAPABILITIES_AUTO_TEST_RETRIES], '1') + assert.strictEqual(metadata.test[DD_CAPABILITIES_IMPACTED_TESTS], '1') + assert.strictEqual(metadata.test[DD_CAPABILITIES_TEST_MANAGEMENT_QUARANTINE], '1') + assert.strictEqual(metadata.test[DD_CAPABILITIES_TEST_MANAGEMENT_DISABLE], '1') + assert.strictEqual(metadata.test[DD_CAPABILITIES_TEST_MANAGEMENT_ATTEMPT_TO_FIX], '5') + assert.strictEqual(metadata.test[DD_CAPABILITIES_FAILED_TEST_REPLAY], '1') // capabilities logic does not overwrite test session name - assert.equal(metadata.test[TEST_SESSION_NAME], 'my-test-session-name') + assert.strictEqual(metadata.test[TEST_SESSION_NAME], 'my-test-session-name') }) }) @@ -4758,10 +4716,10 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { const events = payloads.flatMap(({ payload }) => payload.events) const test = events.find(event => event.type === 'test').content - assert.isNotEmpty(test.meta) - assert.equal(test.meta['custom_tag.beforeEach'], 'true') - assert.equal(test.meta['custom_tag.it'], 'true') - assert.equal(test.meta['custom_tag.afterEach'], 'true') + assert.ok(test.meta.length > 0) + assert.strictEqual(test.meta['custom_tag.beforeEach'], 'true') + assert.strictEqual(test.meta['custom_tag.it'], 'true') + assert.strictEqual(test.meta['custom_tag.afterEach'], 'true') }) childProcess = exec( @@ -4810,10 +4768,10 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { describe('impacted tests', () => { it('can pass normally', () => { - expect(1 + 2).to.equal(4) + assert.strictEqual(1 + 2, 4) }) it('can fail', () => { - expect(1 + 2).to.equal(4) + assert.strictEqual(1 + 2, 4) }) })` ) @@ -4834,9 +4792,9 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { const testSession = events.find(event => event.type === 'test_session_end').content if (isEfd) { - assert.propertyVal(testSession.meta, TEST_EARLY_FLAKE_ENABLED, 'true') + assert.strictEqual(testSession.meta[TEST_EARLY_FLAKE_ENABLED], 'true') } else { - assert.notProperty(testSession.meta, TEST_EARLY_FLAKE_ENABLED) + assert.ok(!Object.hasOwn(testSession.meta, TEST_EARLY_FLAKE_ENABLED)) } const resourceNames = tests.map(span => span.resource) @@ -4863,21 +4821,21 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { test.meta[TEST_NAME] === 'impacted tests can pass normally') if (isEfd) { - assert.equal(impactedTests.length, NUM_RETRIES + 1) // Retries + original test + assert.strictEqual(impactedTests.length, NUM_RETRIES + 1) // Retries + original test } else { - assert.equal(impactedTests.length, 1) + assert.strictEqual(impactedTests.length, 1) } for (const impactedTest of impactedTests) { if (isModified) { - assert.propertyVal(impactedTest.meta, TEST_IS_MODIFIED, 'true') + assert.strictEqual(impactedTest.meta[TEST_IS_MODIFIED], 'true') } else { - assert.notProperty(impactedTest.meta, TEST_IS_MODIFIED) + assert.ok(!Object.hasOwn(impactedTest.meta, TEST_IS_MODIFIED)) } if (isNew) { - assert.propertyVal(impactedTest.meta, TEST_IS_NEW, 'true') + assert.strictEqual(impactedTest.meta[TEST_IS_NEW], 'true') } else { - assert.notProperty(impactedTest.meta, TEST_IS_NEW) + assert.ok(!Object.hasOwn(impactedTest.meta, TEST_IS_NEW)) } } @@ -4886,7 +4844,7 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { test.meta[TEST_IS_RETRY] === 'true' && test.meta[TEST_NAME] !== 'impacted tests can pass normally' ) - assert.equal(retriedTests.length, NUM_RETRIES) + assert.strictEqual(retriedTests.length, NUM_RETRIES) let retriedTestNew = 0 let retriedTestsWithReason = 0 retriedTests.forEach(test => { @@ -4897,8 +4855,8 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { retriedTestsWithReason++ } }) - assert.equal(retriedTestNew, isNew ? NUM_RETRIES : 0) - assert.equal(retriedTestsWithReason, NUM_RETRIES) + assert.strictEqual(retriedTestNew, isNew ? NUM_RETRIES : 0) + assert.strictEqual(retriedTestsWithReason, NUM_RETRIES) } }) @@ -4994,7 +4952,7 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { ) const [code] = await once(childProcess, 'exit') - assert.equal(code, 0, `Jest should pass but failed with code ${code}`) + assert.strictEqual(code, 0, `Jest should pass but failed with code ${code}`) }) }) @@ -5004,8 +4962,8 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { .gatherPayloadsMaxTimeout(({ url }) => url.endsWith('/api/v2/citestcycle'), payloads => { const events = payloads.flatMap(({ payload }) => payload.events) const tests = events.filter(event => event.type === 'test').map(event => event.content) - assert.equal(tests.length, 1) - assert.equal(tests[0].meta[TEST_NAME], 'fast check will not include seed') + assert.strictEqual(tests.length, 1) + assert.strictEqual(tests[0].meta[TEST_NAME], 'fast check will not include seed') }) childProcess = exec( @@ -5030,8 +4988,8 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { .gatherPayloadsMaxTimeout(({ url }) => url.endsWith('/api/v2/citestcycle'), payloads => { const events = payloads.flatMap(({ payload }) => payload.events) const tests = events.filter(event => event.type === 'test').map(event => event.content) - assert.equal(tests.length, 1) - assert.equal(tests[0].meta[TEST_NAME], 'fast check with seed should include seed (with seed=12)') + assert.strictEqual(tests.length, 1) + assert.strictEqual(tests[0].meta[TEST_NAME], 'fast check with seed should include seed (with seed=12)') }) childProcess = exec( @@ -5084,13 +5042,13 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { const events = payloads.flatMap(({ payload }) => payload.events) const tests = events.filter(event => event.type === 'test').map(event => event.content) const testSuites = events.filter(event => event.type === 'test_suite_end').map(event => event.content) - assert.equal(tests.length, 6) - assert.equal(testSuites.length, 6) - assert.equal(testSuites.every(suite => suite.meta[TEST_STATUS] === 'pass'), true) - assert.equal(tests.every(test => test.meta[TEST_STATUS] === 'pass'), true) + assert.strictEqual(tests.length, 6) + assert.strictEqual(testSuites.length, 6) + assert.strictEqual(testSuites.every(suite => suite.meta[TEST_STATUS] === 'pass'), true) + assert.strictEqual(tests.every(test => test.meta[TEST_STATUS] === 'pass'), true) }) ]) - assert.notInclude(testOutput, 'Cannot find module') - assert.include(testOutput, '6 passed') + assert.ok(!testOutput.includes('Cannot find module')) + assert.ok(testOutput.includes('6 passed')) }) }) diff --git a/integration-tests/mocha/mocha.spec.js b/integration-tests/mocha/mocha.spec.js index a2521303c51..4b3b28e6300 100644 --- a/integration-tests/mocha/mocha.spec.js +++ b/integration-tests/mocha/mocha.spec.js @@ -1,11 +1,11 @@ 'use strict' -const { once } = require('node:events') const { fork, exec, execSync } = require('child_process') -const path = require('path') const fs = require('fs') - -const { assert } = require('chai') +const assert = require('node:assert/strict') +const { once } = require('node:events') +const path = require('path') +const { assertObjectContains } = require('../helpers') const { sandboxCwd, @@ -134,22 +134,22 @@ describe(`mocha@${MOCHA_VERSION}`, function () { ) const areAllTestSpans = testSpans.every(span => span.name === 'mocha.test') - assert.isTrue(areAllTestSpans) + assert.strictEqual(areAllTestSpans, true) - assert.include(testOutput, expectedStdout) + assert.ok(testOutput.includes(expectedStdout)) if (extraStdout) { - assert.include(testOutput, extraStdout) + assert.ok(testOutput.includes(extraStdout)) } // Can read DD_TAGS testSpans.forEach(testSpan => { - assert.propertyVal(testSpan.meta, 'test.customtag', 'customvalue') - assert.propertyVal(testSpan.meta, 'test.customtag2', 'customvalue2') + assert.strictEqual(testSpan.meta['test.customtag'], 'customvalue') + assert.strictEqual(testSpan.meta['test.customtag2'], 'customvalue2') }) testSpans.forEach(testSpan => { - assert.equal(testSpan.meta[TEST_SOURCE_FILE].startsWith('ci-visibility/test/ci-visibility-test'), true) - assert.exists(testSpan.metrics[TEST_SOURCE_START]) + assert.strictEqual(testSpan.meta[TEST_SOURCE_FILE].startsWith('ci-visibility/test/ci-visibility-test'), true) + assert.ok(testSpan.metrics[TEST_SOURCE_START] != null) }) done() @@ -193,7 +193,7 @@ describe(`mocha@${MOCHA_VERSION}`, function () { metadataDicts.forEach(metadata => { for (const testLevel of TEST_LEVEL_EVENT_TYPES) { - assert.equal(metadata[testLevel][TEST_SESSION_NAME], 'my-test-session') + assert.strictEqual(metadata[testLevel][TEST_SESSION_NAME], 'my-test-session') } }) @@ -211,24 +211,24 @@ describe(`mocha@${MOCHA_VERSION}`, function () { 'ci-visibility/test/ci-visibility-test-2.js.ci visibility 2 can report tests 2' ] ) - assert.equal(suites.length, 2) - assert.exists(sessionEventContent) - assert.exists(moduleEventContent) + assert.strictEqual(suites.length, 2) + assert.ok(sessionEventContent != null) + assert.ok(moduleEventContent != null) tests.forEach(testEvent => { - assert.equal(testEvent.meta[TEST_SOURCE_FILE].startsWith('ci-visibility/test/ci-visibility-test'), true) - assert.exists(testEvent.metrics[TEST_SOURCE_START]) - assert.equal(testEvent.meta[DD_TEST_IS_USER_PROVIDED_SERVICE], 'false') + assert.strictEqual(testEvent.meta[TEST_SOURCE_FILE].startsWith('ci-visibility/test/ci-visibility-test'), true) + assert.ok(testEvent.metrics[TEST_SOURCE_START] != null) + assert.strictEqual(testEvent.meta[DD_TEST_IS_USER_PROVIDED_SERVICE], 'false') // Can read DD_TAGS - assert.propertyVal(testEvent.meta, 'test.customtag', 'customvalue') - assert.propertyVal(testEvent.meta, 'test.customtag2', 'customvalue2') - assert.exists(testEvent.metrics[DD_HOST_CPU_COUNT]) + assert.strictEqual(testEvent.meta['test.customtag'], 'customvalue') + assert.strictEqual(testEvent.meta['test.customtag2'], 'customvalue2') + assert.ok(testEvent.metrics[DD_HOST_CPU_COUNT] != null) }) suites.forEach(testSuite => { - assert.isTrue(testSuite.meta[TEST_SOURCE_FILE].startsWith('ci-visibility/test/ci-visibility-test')) - assert.equal(testSuite.metrics[TEST_SOURCE_START], 1) - assert.exists(testSuite.metrics[DD_HOST_CPU_COUNT]) + assert.strictEqual(testSuite.meta[TEST_SOURCE_FILE].startsWith('ci-visibility/test/ci-visibility-test'), true) + assert.strictEqual(testSuite.metrics[TEST_SOURCE_START], 1) + assert.ok(testSuite.metrics[DD_HOST_CPU_COUNT] != null) }) }) @@ -256,8 +256,8 @@ describe(`mocha@${MOCHA_VERSION}`, function () { once(childProcess.stderr, 'end'), once(childProcess, 'exit') ]) - assert.include(testOutput, expectedStdout) - assert.include(testOutput, extraStdout) + assert.ok(testOutput.includes(expectedStdout)) + assert.ok(testOutput.includes(extraStdout)) }) it('passing tests', async () => { @@ -272,17 +272,17 @@ describe(`mocha@${MOCHA_VERSION}`, function () { const events = payloads.flatMap(({ payload }) => payload.events) const tests = events.filter(event => event.type === 'test').map(event => event.content) - assert.equal(tests.length, 4) + assert.strictEqual(tests.length, 4) assert.includeMembers(tests.map(test => test.meta[TEST_NAME]), testNames) tests.forEach(test => { - assert.equal(test.parent_id.toString(), '0') - assert.equal(test.meta[TEST_STATUS], 'pass') - assert.equal(test.meta[ORIGIN_KEY], CI_APP_ORIGIN) - assert.exists(test.meta[TEST_FRAMEWORK_VERSION]) - assert.equal(test.meta[TEST_CODE_OWNERS], JSON.stringify(['@datadog-dd-trace-js'])) - assert.equal(test.meta[LIBRARY_VERSION], ddTraceVersion) - assert.equal(test.meta[COMPONENT], 'mocha') + assert.strictEqual(test.parent_id.toString(), '0') + assert.strictEqual(test.meta[TEST_STATUS], 'pass') + assert.strictEqual(test.meta[ORIGIN_KEY], CI_APP_ORIGIN) + assert.ok(test.meta[TEST_FRAMEWORK_VERSION] != null) + assert.strictEqual(test.meta[TEST_CODE_OWNERS], JSON.stringify(['@datadog-dd-trace-js'])) + assert.strictEqual(test.meta[LIBRARY_VERSION], ddTraceVersion) + assert.strictEqual(test.meta[COMPONENT], 'mocha') }) }) @@ -306,24 +306,24 @@ describe(`mocha@${MOCHA_VERSION}`, function () { .gatherPayloadsMaxTimeout(({ url }) => url.endsWith('/api/v2/citestcycle'), (payloads) => { const events = payloads.flatMap(({ payload }) => payload.events) const tests = events.filter(event => event.type === 'test').map(event => event.content) - assert.equal(tests.length, 1) + assert.strictEqual(tests.length, 1) const [test] = tests - assert.propertyVal(test.meta, COMPONENT, 'mocha') - assert.propertyVal(test.meta, 'language', 'javascript') - assert.propertyVal(test.meta, TEST_NAME, 'mocha-test-fail can fail') - assert.propertyVal(test.meta, TEST_STATUS, 'fail') - assert.propertyVal(test.meta, TEST_TYPE, 'test') - assert.propertyVal(test.meta, TEST_FRAMEWORK, 'mocha') - assert.propertyVal(test.meta, TEST_SUITE, 'ci-visibility/mocha-plugin-tests/failing.js') - assert.propertyVal(test.meta, TEST_SOURCE_FILE, 'ci-visibility/mocha-plugin-tests/failing.js') - assert.propertyVal(test.meta, ERROR_TYPE, 'AssertionError') - assert.propertyVal(test.meta, ERROR_MESSAGE, 'expected true to equal false') - assert.exists(test.metrics[TEST_SOURCE_START]) - assert.exists(test.meta[ERROR_STACK]) - assert.equal(test.parent_id.toString(), '0') - assert.equal(test.type, 'test') - assert.equal(test.name, 'mocha.test') - assert.equal(test.resource, 'ci-visibility/mocha-plugin-tests/failing.js.mocha-test-fail can fail') + assert.strictEqual(test.meta[COMPONENT], 'mocha') + assert.strictEqual(test.meta['language'], 'javascript') + assert.strictEqual(test.meta[TEST_NAME], 'mocha-test-fail can fail') + assert.strictEqual(test.meta[TEST_STATUS], 'fail') + assert.strictEqual(test.meta[TEST_TYPE], 'test') + assert.strictEqual(test.meta[TEST_FRAMEWORK], 'mocha') + assert.strictEqual(test.meta[TEST_SUITE], 'ci-visibility/mocha-plugin-tests/failing.js') + assert.strictEqual(test.meta[TEST_SOURCE_FILE], 'ci-visibility/mocha-plugin-tests/failing.js') + assert.strictEqual(test.meta[ERROR_TYPE], 'AssertionError') + assert.strictEqual(test.meta[ERROR_MESSAGE], 'expected true to equal false') + assert.ok(test.metrics[TEST_SOURCE_START] != null) + assert.ok(test.meta[ERROR_STACK] != null) + assert.strictEqual(test.parent_id.toString(), '0') + assert.strictEqual(test.type, 'test') + assert.strictEqual(test.name, 'mocha.test') + assert.strictEqual(test.resource, 'ci-visibility/mocha-plugin-tests/failing.js.mocha-test-fail can fail') }) childProcess = exec( @@ -352,18 +352,18 @@ describe(`mocha@${MOCHA_VERSION}`, function () { .gatherPayloadsMaxTimeout(({ url }) => url.endsWith('/api/v2/citestcycle'), (payloads) => { const events = payloads.flatMap(({ payload }) => payload.events) const tests = events.filter(event => event.type === 'test').map(event => event.content) - assert.equal(tests.length, 4) + assert.strictEqual(tests.length, 4) assert.includeMembers(tests.map(test => test.meta[TEST_NAME]), testNames) tests.forEach(test => { - assert.equal(test.parent_id.toString(), '0') - assert.equal(test.meta[TEST_STATUS], 'skip') - assert.equal(test.meta[ORIGIN_KEY], CI_APP_ORIGIN) - assert.equal(test.meta[COMPONENT], 'mocha') - assert.equal(test.meta[TEST_TYPE], 'test') - assert.equal(test.meta[TEST_FRAMEWORK], 'mocha') - assert.equal(test.meta[TEST_SUITE], 'ci-visibility/mocha-plugin-tests/skipping.js') - assert.equal(test.meta[TEST_SOURCE_FILE], 'ci-visibility/mocha-plugin-tests/skipping.js') + assert.strictEqual(test.parent_id.toString(), '0') + assert.strictEqual(test.meta[TEST_STATUS], 'skip') + assert.strictEqual(test.meta[ORIGIN_KEY], CI_APP_ORIGIN) + assert.strictEqual(test.meta[COMPONENT], 'mocha') + assert.strictEqual(test.meta[TEST_TYPE], 'test') + assert.strictEqual(test.meta[TEST_FRAMEWORK], 'mocha') + assert.strictEqual(test.meta[TEST_SUITE], 'ci-visibility/mocha-plugin-tests/skipping.js') + assert.strictEqual(test.meta[TEST_SOURCE_FILE], 'ci-visibility/mocha-plugin-tests/skipping.js') }) }) @@ -387,15 +387,15 @@ describe(`mocha@${MOCHA_VERSION}`, function () { .gatherPayloadsMaxTimeout(({ url }) => url.endsWith('/api/v2/citestcycle'), (payloads) => { const events = payloads.flatMap(({ payload }) => payload.events) const tests = events.filter(event => event.type === 'test').map(event => event.content) - assert.equal(tests.length, 1) + assert.strictEqual(tests.length, 1) const [test] = tests - assert.propertyVal(test.meta, COMPONENT, 'mocha') - assert.propertyVal(test.meta, TEST_NAME, 'mocha-test-done-pass can do passed tests with done') - assert.propertyVal(test.meta, TEST_STATUS, 'pass') - assert.propertyVal(test.meta, TEST_TYPE, 'test') - assert.propertyVal(test.meta, TEST_FRAMEWORK, 'mocha') - assert.propertyVal(test.meta, TEST_SUITE, 'ci-visibility/mocha-plugin-tests/done-pass.js') - assert.propertyVal(test.meta, TEST_SOURCE_FILE, 'ci-visibility/mocha-plugin-tests/done-pass.js') + assert.strictEqual(test.meta[COMPONENT], 'mocha') + assert.strictEqual(test.meta[TEST_NAME], 'mocha-test-done-pass can do passed tests with done') + assert.strictEqual(test.meta[TEST_STATUS], 'pass') + assert.strictEqual(test.meta[TEST_TYPE], 'test') + assert.strictEqual(test.meta[TEST_FRAMEWORK], 'mocha') + assert.strictEqual(test.meta[TEST_SUITE], 'ci-visibility/mocha-plugin-tests/done-pass.js') + assert.strictEqual(test.meta[TEST_SOURCE_FILE], 'ci-visibility/mocha-plugin-tests/done-pass.js') }) childProcess = exec( @@ -418,18 +418,18 @@ describe(`mocha@${MOCHA_VERSION}`, function () { .gatherPayloadsMaxTimeout(({ url }) => url.endsWith('/api/v2/citestcycle'), (payloads) => { const events = payloads.flatMap(({ payload }) => payload.events) const tests = events.filter(event => event.type === 'test').map(event => event.content) - assert.equal(tests.length, 1) + assert.strictEqual(tests.length, 1) const [test] = tests - assert.propertyVal(test.meta, COMPONENT, 'mocha') - assert.propertyVal(test.meta, TEST_NAME, 'mocha-test-done-fail can do failed tests with done') - assert.propertyVal(test.meta, TEST_STATUS, 'fail') - assert.propertyVal(test.meta, TEST_TYPE, 'test') - assert.propertyVal(test.meta, TEST_FRAMEWORK, 'mocha') - assert.propertyVal(test.meta, TEST_SUITE, 'ci-visibility/mocha-plugin-tests/done-fail.js') - assert.propertyVal(test.meta, TEST_SOURCE_FILE, 'ci-visibility/mocha-plugin-tests/done-fail.js') - assert.propertyVal(test.meta, ERROR_TYPE, 'AssertionError') - assert.propertyVal(test.meta, ERROR_MESSAGE, 'expected true to equal false') - assert.exists(test.meta[ERROR_STACK]) + assert.strictEqual(test.meta[COMPONENT], 'mocha') + assert.strictEqual(test.meta[TEST_NAME], 'mocha-test-done-fail can do failed tests with done') + assert.strictEqual(test.meta[TEST_STATUS], 'fail') + assert.strictEqual(test.meta[TEST_TYPE], 'test') + assert.strictEqual(test.meta[TEST_FRAMEWORK], 'mocha') + assert.strictEqual(test.meta[TEST_SUITE], 'ci-visibility/mocha-plugin-tests/done-fail.js') + assert.strictEqual(test.meta[TEST_SOURCE_FILE], 'ci-visibility/mocha-plugin-tests/done-fail.js') + assert.strictEqual(test.meta[ERROR_TYPE], 'AssertionError') + assert.strictEqual(test.meta[ERROR_MESSAGE], 'expected true to equal false') + assert.ok(test.meta[ERROR_STACK] != null) }) childProcess = exec( @@ -452,15 +452,15 @@ describe(`mocha@${MOCHA_VERSION}`, function () { .gatherPayloadsMaxTimeout(({ url }) => url.endsWith('/api/v2/citestcycle'), (payloads) => { const events = payloads.flatMap(({ payload }) => payload.events) const tests = events.filter(event => event.type === 'test').map(event => event.content) - assert.equal(tests.length, 1) + assert.strictEqual(tests.length, 1) const [test] = tests - assert.propertyVal(test.meta, COMPONENT, 'mocha') - assert.propertyVal(test.meta, TEST_NAME, 'mocha-test-promise-pass can do passed promise tests') - assert.propertyVal(test.meta, TEST_STATUS, 'pass') - assert.propertyVal(test.meta, TEST_TYPE, 'test') - assert.propertyVal(test.meta, TEST_FRAMEWORK, 'mocha') - assert.propertyVal(test.meta, TEST_SUITE, 'ci-visibility/mocha-plugin-tests/promise-pass.js') - assert.propertyVal(test.meta, TEST_SOURCE_FILE, 'ci-visibility/mocha-plugin-tests/promise-pass.js') + assert.strictEqual(test.meta[COMPONENT], 'mocha') + assert.strictEqual(test.meta[TEST_NAME], 'mocha-test-promise-pass can do passed promise tests') + assert.strictEqual(test.meta[TEST_STATUS], 'pass') + assert.strictEqual(test.meta[TEST_TYPE], 'test') + assert.strictEqual(test.meta[TEST_FRAMEWORK], 'mocha') + assert.strictEqual(test.meta[TEST_SUITE], 'ci-visibility/mocha-plugin-tests/promise-pass.js') + assert.strictEqual(test.meta[TEST_SOURCE_FILE], 'ci-visibility/mocha-plugin-tests/promise-pass.js') }) childProcess = exec( @@ -483,18 +483,18 @@ describe(`mocha@${MOCHA_VERSION}`, function () { .gatherPayloadsMaxTimeout(({ url }) => url.endsWith('/api/v2/citestcycle'), (payloads) => { const events = payloads.flatMap(({ payload }) => payload.events) const tests = events.filter(event => event.type === 'test').map(event => event.content) - assert.equal(tests.length, 1) + assert.strictEqual(tests.length, 1) const [test] = tests - assert.propertyVal(test.meta, COMPONENT, 'mocha') - assert.propertyVal(test.meta, TEST_NAME, 'mocha-test-promise-fail can do failed promise tests') - assert.propertyVal(test.meta, TEST_STATUS, 'fail') - assert.propertyVal(test.meta, TEST_TYPE, 'test') - assert.propertyVal(test.meta, TEST_FRAMEWORK, 'mocha') - assert.propertyVal(test.meta, TEST_SUITE, 'ci-visibility/mocha-plugin-tests/promise-fail.js') - assert.propertyVal(test.meta, TEST_SOURCE_FILE, 'ci-visibility/mocha-plugin-tests/promise-fail.js') - assert.propertyVal(test.meta, ERROR_TYPE, 'AssertionError') - assert.propertyVal(test.meta, ERROR_MESSAGE, 'expected true to equal false') - assert.exists(test.meta[ERROR_STACK]) + assert.strictEqual(test.meta[COMPONENT], 'mocha') + assert.strictEqual(test.meta[TEST_NAME], 'mocha-test-promise-fail can do failed promise tests') + assert.strictEqual(test.meta[TEST_STATUS], 'fail') + assert.strictEqual(test.meta[TEST_TYPE], 'test') + assert.strictEqual(test.meta[TEST_FRAMEWORK], 'mocha') + assert.strictEqual(test.meta[TEST_SUITE], 'ci-visibility/mocha-plugin-tests/promise-fail.js') + assert.strictEqual(test.meta[TEST_SOURCE_FILE], 'ci-visibility/mocha-plugin-tests/promise-fail.js') + assert.strictEqual(test.meta[ERROR_TYPE], 'AssertionError') + assert.strictEqual(test.meta[ERROR_MESSAGE], 'expected true to equal false') + assert.ok(test.meta[ERROR_STACK] != null) }) childProcess = exec( @@ -517,15 +517,15 @@ describe(`mocha@${MOCHA_VERSION}`, function () { .gatherPayloadsMaxTimeout(({ url }) => url.endsWith('/api/v2/citestcycle'), (payloads) => { const events = payloads.flatMap(({ payload }) => payload.events) const tests = events.filter(event => event.type === 'test').map(event => event.content) - assert.equal(tests.length, 1) + assert.strictEqual(tests.length, 1) const [test] = tests - assert.propertyVal(test.meta, COMPONENT, 'mocha') - assert.propertyVal(test.meta, TEST_NAME, 'mocha-test-async-pass can do passed async tests') - assert.propertyVal(test.meta, TEST_STATUS, 'pass') - assert.propertyVal(test.meta, TEST_TYPE, 'test') - assert.propertyVal(test.meta, TEST_FRAMEWORK, 'mocha') - assert.propertyVal(test.meta, TEST_SUITE, 'ci-visibility/mocha-plugin-tests/async-pass.js') - assert.propertyVal(test.meta, TEST_SOURCE_FILE, 'ci-visibility/mocha-plugin-tests/async-pass.js') + assert.strictEqual(test.meta[COMPONENT], 'mocha') + assert.strictEqual(test.meta[TEST_NAME], 'mocha-test-async-pass can do passed async tests') + assert.strictEqual(test.meta[TEST_STATUS], 'pass') + assert.strictEqual(test.meta[TEST_TYPE], 'test') + assert.strictEqual(test.meta[TEST_FRAMEWORK], 'mocha') + assert.strictEqual(test.meta[TEST_SUITE], 'ci-visibility/mocha-plugin-tests/async-pass.js') + assert.strictEqual(test.meta[TEST_SOURCE_FILE], 'ci-visibility/mocha-plugin-tests/async-pass.js') }) childProcess = exec( @@ -548,18 +548,18 @@ describe(`mocha@${MOCHA_VERSION}`, function () { .gatherPayloadsMaxTimeout(({ url }) => url.endsWith('/api/v2/citestcycle'), (payloads) => { const events = payloads.flatMap(({ payload }) => payload.events) const tests = events.filter(event => event.type === 'test').map(event => event.content) - assert.equal(tests.length, 1) + assert.strictEqual(tests.length, 1) const [test] = tests - assert.propertyVal(test.meta, COMPONENT, 'mocha') - assert.propertyVal(test.meta, TEST_NAME, 'mocha-test-async-fail can do failed async tests') - assert.propertyVal(test.meta, TEST_STATUS, 'fail') - assert.propertyVal(test.meta, TEST_TYPE, 'test') - assert.propertyVal(test.meta, TEST_FRAMEWORK, 'mocha') - assert.propertyVal(test.meta, TEST_SUITE, 'ci-visibility/mocha-plugin-tests/async-fail.js') - assert.propertyVal(test.meta, TEST_SOURCE_FILE, 'ci-visibility/mocha-plugin-tests/async-fail.js') - assert.propertyVal(test.meta, ERROR_TYPE, 'AssertionError') - assert.propertyVal(test.meta, ERROR_MESSAGE, 'expected true to equal false') - assert.exists(test.meta[ERROR_STACK]) + assert.strictEqual(test.meta[COMPONENT], 'mocha') + assert.strictEqual(test.meta[TEST_NAME], 'mocha-test-async-fail can do failed async tests') + assert.strictEqual(test.meta[TEST_STATUS], 'fail') + assert.strictEqual(test.meta[TEST_TYPE], 'test') + assert.strictEqual(test.meta[TEST_FRAMEWORK], 'mocha') + assert.strictEqual(test.meta[TEST_SUITE], 'ci-visibility/mocha-plugin-tests/async-fail.js') + assert.strictEqual(test.meta[TEST_SOURCE_FILE], 'ci-visibility/mocha-plugin-tests/async-fail.js') + assert.strictEqual(test.meta[ERROR_TYPE], 'AssertionError') + assert.strictEqual(test.meta[ERROR_MESSAGE], 'expected true to equal false') + assert.ok(test.meta[ERROR_STACK] != null) }) childProcess = exec( @@ -582,18 +582,18 @@ describe(`mocha@${MOCHA_VERSION}`, function () { .gatherPayloadsMaxTimeout(({ url }) => url.endsWith('/api/v2/citestcycle'), (payloads) => { const events = payloads.flatMap(({ payload }) => payload.events) const tests = events.filter(event => event.type === 'test').map(event => event.content) - assert.equal(tests.length, 1) + assert.strictEqual(tests.length, 1) const [test] = tests - assert.propertyVal(test.meta, COMPONENT, 'mocha') - assert.propertyVal(test.meta, TEST_NAME, 'mocha-test-timeout-fail times out') - assert.propertyVal(test.meta, TEST_STATUS, 'fail') - assert.propertyVal(test.meta, TEST_TYPE, 'test') - assert.propertyVal(test.meta, TEST_FRAMEWORK, 'mocha') - assert.propertyVal(test.meta, TEST_SUITE, 'ci-visibility/mocha-plugin-tests/timeout-fail.js') - assert.propertyVal(test.meta, TEST_SOURCE_FILE, 'ci-visibility/mocha-plugin-tests/timeout-fail.js') - assert.propertyVal(test.meta, ERROR_TYPE, 'Error') - assert.include(test.meta[ERROR_MESSAGE], 'Timeout') - assert.exists(test.meta[ERROR_STACK]) + assert.strictEqual(test.meta[COMPONENT], 'mocha') + assert.strictEqual(test.meta[TEST_NAME], 'mocha-test-timeout-fail times out') + assert.strictEqual(test.meta[TEST_STATUS], 'fail') + assert.strictEqual(test.meta[TEST_TYPE], 'test') + assert.strictEqual(test.meta[TEST_FRAMEWORK], 'mocha') + assert.strictEqual(test.meta[TEST_SUITE], 'ci-visibility/mocha-plugin-tests/timeout-fail.js') + assert.strictEqual(test.meta[TEST_SOURCE_FILE], 'ci-visibility/mocha-plugin-tests/timeout-fail.js') + assert.strictEqual(test.meta[ERROR_TYPE], 'Error') + assert.ok(test.meta[ERROR_MESSAGE].includes('Timeout')) + assert.ok(test.meta[ERROR_STACK] != null) }) childProcess = exec( @@ -616,15 +616,15 @@ describe(`mocha@${MOCHA_VERSION}`, function () { .gatherPayloadsMaxTimeout(({ url }) => url.endsWith('/api/v2/citestcycle'), (payloads) => { const events = payloads.flatMap(({ payload }) => payload.events) const tests = events.filter(event => event.type === 'test').map(event => event.content) - assert.equal(tests.length, 1) + assert.strictEqual(tests.length, 1) const [test] = tests - assert.propertyVal(test.meta, COMPONENT, 'mocha') - assert.propertyVal(test.meta, TEST_NAME, 'mocha-test-timeout-pass does not timeout') - assert.propertyVal(test.meta, TEST_STATUS, 'pass') - assert.propertyVal(test.meta, TEST_TYPE, 'test') - assert.propertyVal(test.meta, TEST_FRAMEWORK, 'mocha') - assert.propertyVal(test.meta, TEST_SUITE, 'ci-visibility/mocha-plugin-tests/timeout-pass.js') - assert.propertyVal(test.meta, TEST_SOURCE_FILE, 'ci-visibility/mocha-plugin-tests/timeout-pass.js') + assert.strictEqual(test.meta[COMPONENT], 'mocha') + assert.strictEqual(test.meta[TEST_NAME], 'mocha-test-timeout-pass does not timeout') + assert.strictEqual(test.meta[TEST_STATUS], 'pass') + assert.strictEqual(test.meta[TEST_TYPE], 'test') + assert.strictEqual(test.meta[TEST_FRAMEWORK], 'mocha') + assert.strictEqual(test.meta[TEST_SUITE], 'ci-visibility/mocha-plugin-tests/timeout-pass.js') + assert.strictEqual(test.meta[TEST_SOURCE_FILE], 'ci-visibility/mocha-plugin-tests/timeout-pass.js') }) childProcess = exec( @@ -647,20 +647,20 @@ describe(`mocha@${MOCHA_VERSION}`, function () { .gatherPayloadsMaxTimeout(({ url }) => url.endsWith('/api/v2/citestcycle'), (payloads) => { const events = payloads.flatMap(({ payload }) => payload.events) const tests = events.filter(event => event.type === 'test').map(event => event.content) - assert.equal(tests.length, 1) + assert.strictEqual(tests.length, 1) const [test] = tests - assert.propertyVal(test.meta, COMPONENT, 'mocha') - assert.propertyVal(test.meta, TEST_NAME, 'mocha-parameterized can do parameterized') - assert.propertyVal(test.meta, TEST_STATUS, 'pass') - assert.propertyVal(test.meta, TEST_TYPE, 'test') - assert.propertyVal(test.meta, TEST_FRAMEWORK, 'mocha') - assert.propertyVal(test.meta, TEST_SUITE, 'ci-visibility/mocha-plugin-tests/parameterized.js') - assert.propertyVal(test.meta, TEST_SOURCE_FILE, 'ci-visibility/mocha-plugin-tests/parameterized.js') - assert.propertyVal(test.meta, TEST_PARAMETERS, JSON.stringify({ arguments: [1, 2, 3], metadata: {} })) - assert.exists(test.metrics[TEST_SOURCE_START]) - assert.equal(test.parent_id.toString(), '0') - assert.equal(test.type, 'test') - assert.equal(test.name, 'mocha.test') + assert.strictEqual(test.meta[COMPONENT], 'mocha') + assert.strictEqual(test.meta[TEST_NAME], 'mocha-parameterized can do parameterized') + assert.strictEqual(test.meta[TEST_STATUS], 'pass') + assert.strictEqual(test.meta[TEST_TYPE], 'test') + assert.strictEqual(test.meta[TEST_FRAMEWORK], 'mocha') + assert.strictEqual(test.meta[TEST_SUITE], 'ci-visibility/mocha-plugin-tests/parameterized.js') + assert.strictEqual(test.meta[TEST_SOURCE_FILE], 'ci-visibility/mocha-plugin-tests/parameterized.js') + assert.strictEqual(test.meta[TEST_PARAMETERS], JSON.stringify({ arguments: [1, 2, 3], metadata: {} })) + assert.ok(test.metrics[TEST_SOURCE_START] != null) + assert.strictEqual(test.parent_id.toString(), '0') + assert.strictEqual(test.type, 'test') + assert.strictEqual(test.name, 'mocha.test') }) childProcess = exec( @@ -685,33 +685,30 @@ describe(`mocha@${MOCHA_VERSION}`, function () { const tests = events.filter(event => event.type === 'test').map(event => event.content) const spans = events.filter(event => event.type === 'span').map(event => event.content) - assert.equal(tests.length, 1) + assert.strictEqual(tests.length, 1) const [testSpan] = tests const httpSpan = spans.find(span => span.name === 'http.request') - assert.exists(httpSpan, 'HTTP span should exist') + assert.ok(httpSpan != null) // Test span assertions - assert.propertyVal(testSpan.meta, COMPONENT, 'mocha') - assert.propertyVal(testSpan.meta, TEST_NAME, 'mocha-test-integration-http can do integration http') - assert.propertyVal(testSpan.meta, TEST_STATUS, 'pass') - assert.propertyVal(testSpan.meta, TEST_FRAMEWORK, 'mocha') - assert.propertyVal(testSpan.meta, TEST_SUITE, 'ci-visibility/mocha-plugin-tests/integration.js') - assert.propertyVal(testSpan.meta, TEST_SOURCE_FILE, 'ci-visibility/mocha-plugin-tests/integration.js') - assert.propertyVal(testSpan.meta, ORIGIN_KEY, CI_APP_ORIGIN) - assert.exists(testSpan.metrics[TEST_SOURCE_START]) - assert.equal(testSpan.parent_id.toString(), '0') + assert.strictEqual(testSpan.meta[COMPONENT], 'mocha') + assert.strictEqual(testSpan.meta[TEST_NAME], 'mocha-test-integration-http can do integration http') + assert.strictEqual(testSpan.meta[TEST_STATUS], 'pass') + assert.strictEqual(testSpan.meta[TEST_FRAMEWORK], 'mocha') + assert.strictEqual(testSpan.meta[TEST_SUITE], 'ci-visibility/mocha-plugin-tests/integration.js') + assert.strictEqual(testSpan.meta[TEST_SOURCE_FILE], 'ci-visibility/mocha-plugin-tests/integration.js') + assert.strictEqual(testSpan.meta[ORIGIN_KEY], CI_APP_ORIGIN) + assert.ok(testSpan.metrics[TEST_SOURCE_START] != null) + assert.strictEqual(testSpan.parent_id.toString(), '0') // HTTP span assertions - assert.propertyVal(httpSpan.meta, ORIGIN_KEY, CI_APP_ORIGIN) + assert.strictEqual(httpSpan.meta[ORIGIN_KEY], CI_APP_ORIGIN) const endpointUrl = envVars.DD_CIVISIBILITY_AGENTLESS_URL || `http://127.0.0.1:${envVars.DD_TRACE_AGENT_PORT}` - assert.propertyVal(httpSpan.meta, 'http.url', `${endpointUrl}/info`) - assert.equal( - httpSpan.parent_id.toString(), - testSpan.span_id.toString(), - 'HTTP span should be child of test span' - ) + assert.strictEqual(httpSpan.meta['http.url'], `${endpointUrl}/info`) + assert.strictEqual(httpSpan.parent_id.toString(), testSpan.span_id.toString(), + 'HTTP span should be child of test span') }) childProcess = exec( @@ -734,17 +731,14 @@ describe(`mocha@${MOCHA_VERSION}`, function () { .gatherPayloadsMaxTimeout(({ url }) => url.endsWith('/api/v2/citestcycle'), (payloads) => { const events = payloads.flatMap(({ payload }) => payload.events) const tests = events.filter(event => event.type === 'test').map(event => event.content) - assert.equal(tests.length, 1) + assert.strictEqual(tests.length, 1) const [test] = tests - assert.propertyVal(test.meta, COMPONENT, 'mocha') - assert.propertyVal(test.meta, TEST_STATUS, 'fail') - assert.propertyVal(test.meta, ERROR_TYPE, 'TypeError') - assert.include( - test.meta[ERROR_MESSAGE], - 'mocha-fail-hook-sync "before each" hook for "will not run but be reported as failed":' - ) - assert.include(test.meta[ERROR_MESSAGE], 'Cannot set ') - assert.exists(test.meta[ERROR_STACK]) + assert.strictEqual(test.meta[COMPONENT], 'mocha') + assert.strictEqual(test.meta[TEST_STATUS], 'fail') + assert.strictEqual(test.meta[ERROR_TYPE], 'TypeError') + assert.ok(test.meta[ERROR_MESSAGE].includes('mocha-fail-hook-sync "before each" hook for "will not run but be reported as failed":')) + assert.ok(test.meta[ERROR_MESSAGE].includes('Cannot set ')) + assert.ok(test.meta[ERROR_STACK] != null) }) childProcess = exec( @@ -771,12 +765,12 @@ describe(`mocha@${MOCHA_VERSION}`, function () { .gatherPayloadsMaxTimeout(({ url }) => url.endsWith('/api/v2/citestcycle'), (payloads) => { const events = payloads.flatMap(({ payload }) => payload.events) const tests = events.filter(event => event.type === 'test').map(event => event.content) - assert.equal(tests.length, 2) + assert.strictEqual(tests.length, 2) assert.includeMembers(tests.map(test => test.meta[TEST_NAME]), testNames) tests.forEach(test => { - assert.equal(test.meta[TEST_STATUS], 'pass') - assert.equal(test.meta[COMPONENT], 'mocha') + assert.strictEqual(test.meta[TEST_STATUS], 'pass') + assert.strictEqual(test.meta[COMPONENT], 'mocha') }) }) @@ -827,17 +821,17 @@ describe(`mocha@${MOCHA_VERSION}`, function () { .gatherPayloadsMaxTimeout(({ url }) => url.endsWith('/api/v2/citestcycle'), (payloads) => { const events = payloads.flatMap(({ payload }) => payload.events) const tests = events.filter(event => event.type === 'test').map(event => event.content) - assert.equal(tests.length, 5) + assert.strictEqual(tests.length, 5) testNames.forEach(({ name, status, errorMsg }) => { const test = tests.find(t => t.meta[TEST_NAME] === name) - assert.exists(test, `Test ${name} should exist`) - assert.equal(test.meta[TEST_STATUS], status) - assert.equal(test.meta[COMPONENT], 'mocha') + assert.ok(test != null) + assert.strictEqual(test.meta[TEST_STATUS], status) + assert.strictEqual(test.meta[COMPONENT], 'mocha') if (errorMsg) { - assert.equal(test.meta[ERROR_MESSAGE].startsWith(errorMsg), true) - assert.equal(test.meta[ERROR_TYPE], 'Error') - assert.exists(test.meta[ERROR_STACK]) + assert.strictEqual(test.meta[ERROR_MESSAGE].startsWith(errorMsg), true) + assert.strictEqual(test.meta[ERROR_TYPE], 'Error') + assert.ok(test.meta[ERROR_STACK] != null) } }) }) @@ -862,14 +856,14 @@ describe(`mocha@${MOCHA_VERSION}`, function () { .gatherPayloadsMaxTimeout(({ url }) => url.endsWith('/api/v2/citestcycle'), (payloads) => { const events = payloads.flatMap(({ payload }) => payload.events) const tests = events.filter(event => event.type === 'test').map(event => event.content) - assert.equal(tests.length, 1) + assert.strictEqual(tests.length, 1) const [test] = tests - assert.propertyVal(test.meta, COMPONENT, 'mocha') - assert.propertyVal(test.meta, TEST_NAME, 'mocha-test-done-fail can do badly setup failed tests with done') - assert.propertyVal(test.meta, TEST_STATUS, 'fail') - assert.propertyVal(test.meta, ERROR_TYPE, 'AssertionError') - assert.propertyVal(test.meta, ERROR_MESSAGE, 'expected true to equal false') - assert.exists(test.meta[ERROR_STACK]) + assert.strictEqual(test.meta[COMPONENT], 'mocha') + assert.strictEqual(test.meta[TEST_NAME], 'mocha-test-done-fail can do badly setup failed tests with done') + assert.strictEqual(test.meta[TEST_STATUS], 'fail') + assert.strictEqual(test.meta[ERROR_TYPE], 'AssertionError') + assert.strictEqual(test.meta[ERROR_MESSAGE], 'expected true to equal false') + assert.ok(test.meta[ERROR_STACK] != null) }) childProcess = exec( @@ -897,18 +891,18 @@ describe(`mocha@${MOCHA_VERSION}`, function () { const events = payloads.flatMap(({ payload }) => payload.events) const tests = events.filter(event => event.type === 'test').map(event => event.content) if (isLatestMocha) { - assert.equal(tests.length, 8) + assert.strictEqual(tests.length, 8) } else { - assert.equal(tests.length, 2) + assert.strictEqual(tests.length, 2) } const eventuallyPassingTests = tests.filter(t => t.meta[TEST_NAME] === 'mocha-test-retries will be retried and pass' ) if (isLatestMocha) { - assert.equal(eventuallyPassingTests.length, 3) + assert.strictEqual(eventuallyPassingTests.length, 3) } else { - assert.equal(eventuallyPassingTests.length, 1) + assert.strictEqual(eventuallyPassingTests.length, 1) } const failedTests = tests.filter(t => @@ -916,9 +910,9 @@ describe(`mocha@${MOCHA_VERSION}`, function () { t.meta[TEST_STATUS] === 'fail' ) if (isLatestMocha) { - assert.equal(failedTests.length, 5) + assert.strictEqual(failedTests.length, 5) } else { - assert.equal(failedTests.length, 1) + assert.strictEqual(failedTests.length, 1) } }) @@ -946,13 +940,13 @@ describe(`mocha@${MOCHA_VERSION}`, function () { .gatherPayloadsMaxTimeout(({ url }) => url.endsWith('/api/v2/citestcycle'), (payloads) => { const events = payloads.flatMap(({ payload }) => payload.events) const tests = events.filter(event => event.type === 'test').map(event => event.content) - assert.equal(tests.length, 2) + assert.strictEqual(tests.length, 2) testNames.forEach(({ name, status }) => { const test = tests.find(t => t.meta[TEST_NAME] === name) - assert.exists(test, `Test ${name} should exist`) - assert.equal(test.meta[TEST_STATUS], status) - assert.equal(test.meta[COMPONENT], 'mocha') + assert.ok(test != null) + assert.strictEqual(test.meta[TEST_STATUS], status) + assert.strictEqual(test.meta[COMPONENT], 'mocha') }) }) @@ -984,11 +978,11 @@ describe(`mocha@${MOCHA_VERSION}`, function () { if (reportingOption === 'evp proxy') { const headers = payloads.map(({ headers }) => headers) headers.forEach(header => { - assert.equal(header['x-datadog-evp-subdomain'], 'citestcycle-intake') + assert.strictEqual(header['x-datadog-evp-subdomain'], 'citestcycle-intake') }) const urls = payloads.map(({ url }) => url) urls.forEach(url => { - assert.equal(url, '/evp_proxy/v4/api/v2/citestcycle') + assert.strictEqual(url, '/evp_proxy/v4/api/v2/citestcycle') }) } @@ -998,12 +992,12 @@ describe(`mocha@${MOCHA_VERSION}`, function () { const testModuleEvent = events.find(event => event.type === 'test_module_end')?.content const testSuiteEvents = events.filter(event => event.type === 'test_suite_end').map(e => e.content) - assert.exists(testSessionEvent, 'test_session_end event should exist') - assert.exists(testModuleEvent, 'test_module_end event should exist') - assert.equal(testSuiteEvents.length, 4, 'Should have 4 test suite events') + assert.ok(testSessionEvent != null) + assert.ok(testModuleEvent != null) + assert.strictEqual(testSuiteEvents.length, 4, 'Should have 4 test suite events') - assert.equal(testSessionEvent.meta[TEST_STATUS], 'fail') - assert.equal(testModuleEvent.meta[TEST_STATUS], 'fail') + assert.strictEqual(testSessionEvent.meta[TEST_STATUS], 'fail') + assert.strictEqual(testModuleEvent.meta[TEST_STATUS], 'fail') // Check that all suites have the same session ID assert.isTrue( @@ -1022,10 +1016,8 @@ describe(`mocha@${MOCHA_VERSION}`, function () { ) // Check that all suites have a test_suite_id - assert.isTrue( - testSuiteEvents.every(suite => suite.test_suite_id !== undefined), - 'All suites should have a test_suite_id' - ) + assert.strictEqual(testSuiteEvents.every(suite => suite.test_suite_id !== undefined), + 'All suites should have a test_suite_id', true) // Check that all suites match expected suite names assert.isTrue( @@ -1036,12 +1028,10 @@ describe(`mocha@${MOCHA_VERSION}`, function () { const failedSuites = testSuiteEvents.filter(suite => suite.meta[TEST_STATUS] === 'fail') const passedSuites = testSuiteEvents.filter(suite => suite.meta[TEST_STATUS] === 'pass') - assert.equal(passedSuites.length, 1, 'Should have 1 passing suite') - assert.equal(failedSuites.length, 3, 'Should have 3 failing suites') - assert.isTrue( - failedSuites.every(suite => suite.meta[ERROR_MESSAGE] !== undefined), - 'All failed suites should have an error message' - ) + assert.strictEqual(passedSuites.length, 1, 'Should have 1 passing suite') + assert.strictEqual(failedSuites.length, 3, 'Should have 3 failing suites') + assert.strictEqual(failedSuites.every(suite => suite.meta[ERROR_MESSAGE] !== undefined), + 'All failed suites should have an error message', true) }) childProcess = exec( @@ -1087,7 +1077,7 @@ describe(`mocha@${MOCHA_VERSION}`, function () { testOutput += chunk.toString() }) childProcess.on('message', () => { - assert.include(testOutput, expectedStdout) + assert.ok(testOutput.includes(expectedStdout)) done() }) }) @@ -1101,10 +1091,10 @@ describe(`mocha@${MOCHA_VERSION}`, function () { const events = payloads.flatMap(({ payload }) => payload.events) const test = events.find(event => event.type === 'test').content - assert.isNotEmpty(test.meta) - assert.equal(test.meta['custom_tag.beforeEach'], 'true') - assert.equal(test.meta['custom_tag.it'], 'true') - assert.equal(test.meta['custom_tag.afterEach'], 'true') + assert.ok(test.meta.length > 0) + assert.strictEqual(test.meta['custom_tag.beforeEach'], 'true') + assert.strictEqual(test.meta['custom_tag.it'], 'true') + assert.strictEqual(test.meta['custom_tag.afterEach'], 'true') }) childProcess = exec( @@ -1146,9 +1136,9 @@ describe(`mocha@${MOCHA_VERSION}`, function () { testOutput += chunk.toString() }) childProcess.on('message', () => { - assert.notInclude(testOutput, 'TypeError') - assert.notInclude(testOutput, 'Uncaught error outside test suite') - assert.include(testOutput, expectedStdout) + assert.ok(!testOutput.includes('TypeError')) + assert.ok(!testOutput.includes('Uncaught error outside test suite')) + assert.ok(testOutput.includes(expectedStdout)) done() }) }) @@ -1162,9 +1152,9 @@ describe(`mocha@${MOCHA_VERSION}`, function () { const test = events.find(event => event.type === 'test').content const testSuite = events.find(event => event.type === 'test_suite_end').content // The test is in a subproject - assert.notEqual(test.meta[TEST_SOURCE_FILE], test.meta[TEST_SUITE]) - assert.equal(test.meta[TEST_CODE_OWNERS], JSON.stringify(['@datadog-dd-trace-js'])) - assert.equal(testSuite.meta[TEST_CODE_OWNERS], JSON.stringify(['@datadog-dd-trace-js'])) + assert.notStrictEqual(test.meta[TEST_SOURCE_FILE], test.meta[TEST_SUITE]) + assert.strictEqual(test.meta[TEST_CODE_OWNERS], JSON.stringify(['@datadog-dd-trace-js'])) + assert.strictEqual(testSuite.meta[TEST_CODE_OWNERS], JSON.stringify(['@datadog-dd-trace-js'])) }) childProcess = exec( @@ -1213,8 +1203,8 @@ describe(`mocha@${MOCHA_VERSION}`, function () { testOutput += chunk.toString() }) childProcess.on('exit', () => { - assert.include(testOutput, 'Invalid URL') - assert.include(testOutput, '1 passing') // we only run one file here + assert.ok(testOutput.includes('Invalid URL')) + assert.ok(testOutput.includes('1 passing')) // we only run one file here done() }) }) @@ -1226,7 +1216,7 @@ describe(`mocha@${MOCHA_VERSION}`, function () { metadataDicts.forEach(metadata => { for (const testLevel of TEST_LEVEL_EVENT_TYPES) { - assert.equal(metadata[testLevel][TEST_SESSION_NAME], 'my-test-session') + assert.strictEqual(metadata[testLevel][TEST_SESSION_NAME], 'my-test-session') } }) @@ -1236,22 +1226,19 @@ describe(`mocha@${MOCHA_VERSION}`, function () { const suites = events.filter(event => event.type === 'test_suite_end').map(event => event.content) const tests = events.filter(event => event.type === 'test').map(event => event.content) - assert.equal(sessionEventContent.meta[MOCHA_IS_PARALLEL], 'true') - assert.equal( - sessionEventContent.test_session_id.toString(10), - moduleEventContent.test_session_id.toString(10) - ) + assert.strictEqual(sessionEventContent.meta[MOCHA_IS_PARALLEL], 'true') + assert.strictEqual(sessionEventContent.test_session_id.toString(10), moduleEventContent.test_session_id.toString(10)) suites.forEach(({ meta, test_suite_id: testSuiteId, test_module_id: testModuleId, test_session_id: testSessionId }) => { - assert.exists(meta[TEST_COMMAND]) - assert.exists(meta[TEST_MODULE]) - assert.exists(testSuiteId) - assert.equal(testModuleId.toString(10), moduleEventContent.test_module_id.toString(10)) - assert.equal(testSessionId.toString(10), moduleEventContent.test_session_id.toString(10)) + assert.ok(meta[TEST_COMMAND] != null) + assert.ok(meta[TEST_MODULE] != null) + assert.ok(testSuiteId != null) + assert.strictEqual(testModuleId.toString(10), moduleEventContent.test_module_id.toString(10)) + assert.strictEqual(testSessionId.toString(10), moduleEventContent.test_session_id.toString(10)) }) tests.forEach(({ @@ -1261,13 +1248,13 @@ describe(`mocha@${MOCHA_VERSION}`, function () { test_module_id: testModuleId, test_session_id: testSessionId }) => { - assert.exists(meta[TEST_COMMAND]) - assert.exists(meta[TEST_MODULE]) - assert.exists(testSuiteId) - assert.equal(testModuleId.toString(10), moduleEventContent.test_module_id.toString(10)) - assert.equal(testSessionId.toString(10), moduleEventContent.test_session_id.toString(10)) - assert.propertyVal(meta, MOCHA_IS_PARALLEL, 'true') - assert.exists(metrics[TEST_SOURCE_START]) + assert.ok(meta[TEST_COMMAND] != null) + assert.ok(meta[TEST_MODULE] != null) + assert.ok(testSuiteId != null) + assert.strictEqual(testModuleId.toString(10), moduleEventContent.test_module_id.toString(10)) + assert.strictEqual(testSessionId.toString(10), moduleEventContent.test_session_id.toString(10)) + assert.strictEqual(meta[MOCHA_IS_PARALLEL], 'true') + assert.ok(metrics[TEST_SOURCE_START] != null) }) }) @@ -1290,7 +1277,7 @@ describe(`mocha@${MOCHA_VERSION}`, function () { }) childProcess.on('message', () => { eventsPromise.then(() => { - assert.notInclude(testOutput, 'TypeError') + assert.ok(!testOutput.includes('TypeError')) done() }).catch(done) }) @@ -1304,9 +1291,9 @@ describe(`mocha@${MOCHA_VERSION}`, function () { const suites = events.filter(event => event.type === 'test_suite_end').map(event => event.content) const tests = events.filter(event => event.type === 'test').map(event => event.content) - assert.equal(sessionEventContent.meta[MOCHA_IS_PARALLEL], 'true') - assert.equal(suites.length, 2) - assert.equal(tests.length, 2) + assert.strictEqual(sessionEventContent.meta[MOCHA_IS_PARALLEL], 'true') + assert.strictEqual(suites.length, 2) + assert.strictEqual(tests.length, 2) }) childProcess = exec( @@ -1323,7 +1310,7 @@ describe(`mocha@${MOCHA_VERSION}`, function () { }) childProcess.on('exit', () => { eventsPromise.then(() => { - assert.notInclude(testOutput, 'TypeError') + assert.ok(!testOutput.includes('TypeError')) done() }).catch(done) }) @@ -1342,8 +1329,8 @@ describe(`mocha@${MOCHA_VERSION}`, function () { testOutput += chunk.toString() }) childProcess.on('exit', (code) => { - assert.include(testOutput, 'result 7') - assert.equal(code, 0) + assert.ok(testOutput.includes('result 7')) + assert.strictEqual(code, 0) done() }) }) @@ -1353,9 +1340,9 @@ describe(`mocha@${MOCHA_VERSION}`, function () { .gatherPayloadsMaxTimeout(({ url }) => url.endsWith('/api/v2/citestcycle'), (payloads) => { const events = payloads.flatMap(({ payload }) => payload.events) const testSession = events.find(event => event.type === 'test_session_end').content - assert.propertyVal(testSession.meta, TEST_STATUS, 'fail') + assert.strictEqual(testSession.meta[TEST_STATUS], 'fail') const errorMessage = 'Failed tests: 1' - assert.include(testSession.meta[ERROR_MESSAGE], errorMessage) + assert.ok(testSession.meta[ERROR_MESSAGE].includes(errorMessage)) }) childProcess = exec( @@ -1398,11 +1385,10 @@ describe(`mocha@${MOCHA_VERSION}`, function () { testOutput += chunk.toString() }) childProcess.on('message', () => { - assert.include(testOutput, expectedStdout) - assert.include(testOutput, 'DD_CIVISIBILITY_AGENTLESS_ENABLED is set, ' + + assert.ok(testOutput.includes(expectedStdout)) + assert.ok(testOutput.includes('DD_CIVISIBILITY_AGENTLESS_ENABLED is set, ' + 'but neither DD_API_KEY nor DATADOG_API_KEY are set in your environment, ' + - 'so dd-trace will not be initialized.' - ) + 'so dd-trace will not be initialized.')) done() }) }) @@ -1419,15 +1405,15 @@ describe(`mocha@${MOCHA_VERSION}`, function () { packfileRequestPromise, eventsRequestPromise ]).then(([searchCommitRequest, packfileRequest, eventsRequest]) => { - assert.propertyVal(searchCommitRequest.headers, 'dd-api-key', '1') - assert.propertyVal(packfileRequest.headers, 'dd-api-key', '1') + assert.strictEqual(searchCommitRequest.headers['dd-api-key'], '1') + assert.strictEqual(packfileRequest.headers['dd-api-key'], '1') const eventTypes = eventsRequest.payload.events.map(event => event.type) assert.includeMembers(eventTypes, ['test', 'test_suite_end', 'test_module_end', 'test_session_end']) const numSuites = eventTypes.reduce( (acc, type) => type === 'test_suite_end' ? acc + 1 : acc, 0 ) - assert.equal(numSuites, 2) + assert.strictEqual(numSuites, 2) done() }).catch(done) @@ -1494,17 +1480,17 @@ describe(`mocha@${MOCHA_VERSION}`, function () { codeCovRequestPromise, eventsRequestPromise ]).then(([libraryConfigRequest, codeCovRequest, eventsRequest]) => { - assert.propertyVal(libraryConfigRequest.headers, 'dd-api-key', '1') + assert.strictEqual(libraryConfigRequest.headers['dd-api-key'], '1') const [coveragePayload] = codeCovRequest.payload - assert.propertyVal(codeCovRequest.headers, 'dd-api-key', '1') + assert.strictEqual(codeCovRequest.headers['dd-api-key'], '1') - assert.propertyVal(coveragePayload, 'name', 'coverage1') - assert.propertyVal(coveragePayload, 'filename', 'coverage1.msgpack') - assert.propertyVal(coveragePayload, 'type', 'application/msgpack') - assert.include(coveragePayload.content, { + assert.strictEqual(coveragePayload['name'], 'coverage1') + assert.strictEqual(coveragePayload['filename'], 'coverage1.msgpack') + assert.strictEqual(coveragePayload['type'], 'application/msgpack') + assert.ok(coveragePayload.content.includes({ version: 2 - }) + })) const allCoverageFiles = codeCovRequest.payload .flatMap(coverage => coverage.content.coverages) .flatMap(file => file.files) @@ -1517,18 +1503,18 @@ describe(`mocha@${MOCHA_VERSION}`, function () { 'ci-visibility/test/ci-visibility-test-2.js' ] ) - assert.exists(coveragePayload.content.coverages[0].test_session_id) - assert.exists(coveragePayload.content.coverages[0].test_suite_id) + assert.ok(coveragePayload.content.coverages[0].test_session_id != null) + assert.ok(coveragePayload.content.coverages[0].test_suite_id != null) const testSession = eventsRequest.payload.events.find(event => event.type === 'test_session_end').content - assert.exists(testSession.metrics[TEST_CODE_COVERAGE_LINES_PCT]) + assert.ok(testSession.metrics[TEST_CODE_COVERAGE_LINES_PCT] != null) const eventTypes = eventsRequest.payload.events.map(event => event.type) assert.includeMembers(eventTypes, ['test', 'test_suite_end', 'test_module_end', 'test_session_end']) const numSuites = eventTypes.reduce( (acc, type) => type === 'test_suite_end' ? acc + 1 : acc, 0 ) - assert.equal(numSuites, 2) + assert.strictEqual(numSuites, 2) }).catch(done) childProcess = exec( @@ -1544,7 +1530,7 @@ describe(`mocha@${MOCHA_VERSION}`, function () { }) childProcess.on('exit', () => { // coverage report - assert.include(testOutput, 'Lines ') + assert.ok(testOutput.includes('Lines ')) done() }) }) @@ -1562,18 +1548,18 @@ describe(`mocha@${MOCHA_VERSION}`, function () { }, ({ url }) => url === '/api/v2/citestcov').catch(() => {}) receiver.assertPayloadReceived(({ headers, payload }) => { - assert.propertyVal(headers, 'dd-api-key', '1') + assert.strictEqual(headers['dd-api-key'], '1') const eventTypes = payload.events.map(event => event.type) assert.includeMembers(eventTypes, ['test', 'test_session_end', 'test_module_end', 'test_suite_end']) const testSession = payload.events.find(event => event.type === 'test_session_end').content - assert.propertyVal(testSession.meta, TEST_ITR_TESTS_SKIPPED, 'false') - assert.propertyVal(testSession.meta, TEST_CODE_COVERAGE_ENABLED, 'false') - assert.propertyVal(testSession.meta, TEST_ITR_SKIPPING_ENABLED, 'false') - assert.exists(testSession.metrics[TEST_CODE_COVERAGE_LINES_PCT]) + assert.strictEqual(testSession.meta[TEST_ITR_TESTS_SKIPPED], 'false') + assert.strictEqual(testSession.meta[TEST_CODE_COVERAGE_ENABLED], 'false') + assert.strictEqual(testSession.meta[TEST_ITR_SKIPPING_ENABLED], 'false') + assert.ok(testSession.metrics[TEST_CODE_COVERAGE_LINES_PCT] != null) const testModule = payload.events.find(event => event.type === 'test_module_end').content - assert.propertyVal(testModule.meta, TEST_ITR_TESTS_SKIPPED, 'false') - assert.propertyVal(testModule.meta, TEST_CODE_COVERAGE_ENABLED, 'false') - assert.propertyVal(testModule.meta, TEST_ITR_SKIPPING_ENABLED, 'false') + assert.strictEqual(testModule.meta[TEST_ITR_TESTS_SKIPPED], 'false') + assert.strictEqual(testModule.meta[TEST_CODE_COVERAGE_ENABLED], 'false') + assert.strictEqual(testModule.meta[TEST_ITR_SKIPPING_ENABLED], 'false') }, ({ url }) => url === '/api/v2/citestcycle').then(() => done()).catch(done) childProcess = exec( @@ -1603,38 +1589,38 @@ describe(`mocha@${MOCHA_VERSION}`, function () { coverageRequestPromise, eventsRequestPromise ]).then(([skippableRequest, coverageRequest, eventsRequest]) => { - assert.propertyVal(skippableRequest.headers, 'dd-api-key', '1') + assert.strictEqual(skippableRequest.headers['dd-api-key'], '1') const [coveragePayload] = coverageRequest.payload - assert.propertyVal(coverageRequest.headers, 'dd-api-key', '1') - assert.propertyVal(coveragePayload, 'name', 'coverage1') - assert.propertyVal(coveragePayload, 'filename', 'coverage1.msgpack') - assert.propertyVal(coveragePayload, 'type', 'application/msgpack') + assert.strictEqual(coverageRequest.headers['dd-api-key'], '1') + assert.strictEqual(coveragePayload['name'], 'coverage1') + assert.strictEqual(coveragePayload['filename'], 'coverage1.msgpack') + assert.strictEqual(coveragePayload['type'], 'application/msgpack') - assert.propertyVal(eventsRequest.headers, 'dd-api-key', '1') + assert.strictEqual(eventsRequest.headers['dd-api-key'], '1') const eventTypes = eventsRequest.payload.events.map(event => event.type) const skippedSuite = eventsRequest.payload.events.find(event => event.content.resource === 'test_suite.ci-visibility/test/ci-visibility-test.js' ).content - assert.propertyVal(skippedSuite.meta, TEST_STATUS, 'skip') - assert.propertyVal(skippedSuite.meta, TEST_SKIPPED_BY_ITR, 'true') + assert.strictEqual(skippedSuite.meta[TEST_STATUS], 'skip') + assert.strictEqual(skippedSuite.meta[TEST_SKIPPED_BY_ITR], 'true') assert.includeMembers(eventTypes, ['test', 'test_suite_end', 'test_module_end', 'test_session_end']) const numSuites = eventTypes.reduce( (acc, type) => type === 'test_suite_end' ? acc + 1 : acc, 0 ) - assert.equal(numSuites, 2) + assert.strictEqual(numSuites, 2) const testSession = eventsRequest.payload.events.find(event => event.type === 'test_session_end').content - assert.propertyVal(testSession.meta, TEST_ITR_TESTS_SKIPPED, 'true') - assert.propertyVal(testSession.meta, TEST_CODE_COVERAGE_ENABLED, 'true') - assert.propertyVal(testSession.meta, TEST_ITR_SKIPPING_ENABLED, 'true') - assert.propertyVal(testSession.meta, TEST_ITR_SKIPPING_TYPE, 'suite') - assert.propertyVal(testSession.metrics, TEST_ITR_SKIPPING_COUNT, 1) + assert.strictEqual(testSession.meta[TEST_ITR_TESTS_SKIPPED], 'true') + assert.strictEqual(testSession.meta[TEST_CODE_COVERAGE_ENABLED], 'true') + assert.strictEqual(testSession.meta[TEST_ITR_SKIPPING_ENABLED], 'true') + assert.strictEqual(testSession.meta[TEST_ITR_SKIPPING_TYPE], 'suite') + assert.strictEqual(testSession.metrics[TEST_ITR_SKIPPING_COUNT], 1) const testModule = eventsRequest.payload.events.find(event => event.type === 'test_module_end').content - assert.propertyVal(testModule.meta, TEST_ITR_TESTS_SKIPPED, 'true') - assert.propertyVal(testModule.meta, TEST_CODE_COVERAGE_ENABLED, 'true') - assert.propertyVal(testModule.meta, TEST_ITR_SKIPPING_ENABLED, 'true') - assert.propertyVal(testModule.meta, TEST_ITR_SKIPPING_TYPE, 'suite') - assert.propertyVal(testModule.metrics, TEST_ITR_SKIPPING_COUNT, 1) + assert.strictEqual(testModule.meta[TEST_ITR_TESTS_SKIPPED], 'true') + assert.strictEqual(testModule.meta[TEST_CODE_COVERAGE_ENABLED], 'true') + assert.strictEqual(testModule.meta[TEST_ITR_SKIPPING_ENABLED], 'true') + assert.strictEqual(testModule.meta[TEST_ITR_SKIPPING_TYPE], 'suite') + assert.strictEqual(testModule.metrics[TEST_ITR_SKIPPING_COUNT], 1) done() }).catch(done) @@ -1670,7 +1656,7 @@ describe(`mocha@${MOCHA_VERSION}`, function () { .gatherPayloadsMaxTimeout(({ url }) => url.endsWith('/api/v2/citestcycle'), (payloads) => { const events = payloads.flatMap(({ payload }) => payload.events) const testSession = events.find(event => event.type === 'test_session_end').content - assert.propertyVal(testSession.meta, TEST_STATUS, 'skip') + assert.strictEqual(testSession.meta[TEST_STATUS], 'skip') }) childProcess = exec( runTestsWithCoverageCommand, @@ -1703,22 +1689,22 @@ describe(`mocha@${MOCHA_VERSION}`, function () { }, ({ url }) => url === '/api/v2/ci/tests/skippable').catch(() => {}) receiver.assertPayloadReceived(({ headers, payload }) => { - assert.propertyVal(headers, 'dd-api-key', '1') + assert.strictEqual(headers['dd-api-key'], '1') const eventTypes = payload.events.map(event => event.type) // because they are not skipped assert.includeMembers(eventTypes, ['test', 'test_suite_end', 'test_module_end', 'test_session_end']) const numSuites = eventTypes.reduce( (acc, type) => type === 'test_suite_end' ? acc + 1 : acc, 0 ) - assert.equal(numSuites, 2) + assert.strictEqual(numSuites, 2) const testSession = payload.events.find(event => event.type === 'test_session_end').content - assert.propertyVal(testSession.meta, TEST_ITR_TESTS_SKIPPED, 'false') - assert.propertyVal(testSession.meta, TEST_CODE_COVERAGE_ENABLED, 'true') - assert.propertyVal(testSession.meta, TEST_ITR_SKIPPING_ENABLED, 'true') + assert.strictEqual(testSession.meta[TEST_ITR_TESTS_SKIPPED], 'false') + assert.strictEqual(testSession.meta[TEST_CODE_COVERAGE_ENABLED], 'true') + assert.strictEqual(testSession.meta[TEST_ITR_SKIPPING_ENABLED], 'true') const testModule = payload.events.find(event => event.type === 'test_module_end').content - assert.propertyVal(testModule.meta, TEST_ITR_TESTS_SKIPPED, 'false') - assert.propertyVal(testModule.meta, TEST_CODE_COVERAGE_ENABLED, 'true') - assert.propertyVal(testModule.meta, TEST_ITR_SKIPPING_ENABLED, 'true') + assert.strictEqual(testModule.meta[TEST_ITR_TESTS_SKIPPED], 'false') + assert.strictEqual(testModule.meta[TEST_CODE_COVERAGE_ENABLED], 'true') + assert.strictEqual(testModule.meta[TEST_ITR_SKIPPING_ENABLED], 'true') }, ({ url }) => url === '/api/v2/citestcycle').then(() => done()).catch(done) childProcess = exec( @@ -1751,14 +1737,14 @@ describe(`mocha@${MOCHA_VERSION}`, function () { }, ({ url }) => url === '/api/v2/ci/tests/skippable').catch(() => {}) receiver.assertPayloadReceived(({ headers, payload }) => { - assert.propertyVal(headers, 'dd-api-key', '1') + assert.strictEqual(headers['dd-api-key'], '1') const eventTypes = payload.events.map(event => event.type) // because they are not skipped assert.includeMembers(eventTypes, ['test', 'test_suite_end', 'test_module_end', 'test_session_end']) const numSuites = eventTypes.reduce( (acc, type) => type === 'test_suite_end' ? acc + 1 : acc, 0 ) - assert.equal(numSuites, 2) + assert.strictEqual(numSuites, 2) }, ({ url }) => url === '/api/v2/citestcycle').then(() => done()).catch(done) childProcess = exec( @@ -1792,14 +1778,14 @@ describe(`mocha@${MOCHA_VERSION}`, function () { const events = payloads.flatMap(({ payload }) => payload.events) const suites = events.filter(event => event.type === 'test_suite_end') - assert.equal(suites.length, 3) + assert.strictEqual(suites.length, 3) const testSession = events.find(event => event.type === 'test_session_end').content const testModule = events.find(event => event.type === 'test_module_end').content - assert.propertyVal(testSession.meta, TEST_ITR_FORCED_RUN, 'true') - assert.propertyVal(testSession.meta, TEST_ITR_UNSKIPPABLE, 'true') - assert.propertyVal(testModule.meta, TEST_ITR_FORCED_RUN, 'true') - assert.propertyVal(testModule.meta, TEST_ITR_UNSKIPPABLE, 'true') + assert.strictEqual(testSession.meta[TEST_ITR_FORCED_RUN], 'true') + assert.strictEqual(testSession.meta[TEST_ITR_UNSKIPPABLE], 'true') + assert.strictEqual(testModule.meta[TEST_ITR_FORCED_RUN], 'true') + assert.strictEqual(testModule.meta[TEST_ITR_UNSKIPPABLE], 'true') const passedSuite = suites.find( event => event.content.resource === 'test_suite.ci-visibility/unskippable-test/test-to-run.js' @@ -1811,17 +1797,17 @@ describe(`mocha@${MOCHA_VERSION}`, function () { event => event.content.resource === 'test_suite.ci-visibility/unskippable-test/test-unskippable.js' ) // It does not mark as unskippable if there is no docblock - assert.propertyVal(passedSuite.content.meta, TEST_STATUS, 'pass') - assert.notProperty(passedSuite.content.meta, TEST_ITR_UNSKIPPABLE) - assert.notProperty(passedSuite.content.meta, TEST_ITR_FORCED_RUN) + assert.strictEqual(passedSuite.content.meta[TEST_STATUS], 'pass') + assert.ok(!Object.hasOwn(passedSuite.content.meta, TEST_ITR_UNSKIPPABLE)) + assert.ok(!Object.hasOwn(passedSuite.content.meta, TEST_ITR_FORCED_RUN)) - assert.propertyVal(skippedSuite.content.meta, TEST_STATUS, 'skip') - assert.notProperty(skippedSuite.content.meta, TEST_ITR_UNSKIPPABLE) - assert.notProperty(skippedSuite.content.meta, TEST_ITR_FORCED_RUN) + assert.strictEqual(skippedSuite.content.meta[TEST_STATUS], 'skip') + assert.ok(!Object.hasOwn(skippedSuite.content.meta, TEST_ITR_UNSKIPPABLE)) + assert.ok(!Object.hasOwn(skippedSuite.content.meta, TEST_ITR_FORCED_RUN)) - assert.propertyVal(forcedToRunSuite.content.meta, TEST_STATUS, 'pass') - assert.propertyVal(forcedToRunSuite.content.meta, TEST_ITR_UNSKIPPABLE, 'true') - assert.propertyVal(forcedToRunSuite.content.meta, TEST_ITR_FORCED_RUN, 'true') + assert.strictEqual(forcedToRunSuite.content.meta[TEST_STATUS], 'pass') + assert.strictEqual(forcedToRunSuite.content.meta[TEST_ITR_UNSKIPPABLE], 'true') + assert.strictEqual(forcedToRunSuite.content.meta[TEST_ITR_FORCED_RUN], 'true') }, 25000) childProcess = exec( @@ -1862,14 +1848,14 @@ describe(`mocha@${MOCHA_VERSION}`, function () { const events = payloads.flatMap(({ payload }) => payload.events) const suites = events.filter(event => event.type === 'test_suite_end') - assert.equal(suites.length, 3) + assert.strictEqual(suites.length, 3) const testSession = events.find(event => event.type === 'test_session_end').content const testModule = events.find(event => event.type === 'test_module_end').content - assert.notProperty(testSession.meta, TEST_ITR_FORCED_RUN) - assert.propertyVal(testSession.meta, TEST_ITR_UNSKIPPABLE, 'true') - assert.notProperty(testModule.meta, TEST_ITR_FORCED_RUN) - assert.propertyVal(testModule.meta, TEST_ITR_UNSKIPPABLE, 'true') + assert.ok(!Object.hasOwn(testSession.meta, TEST_ITR_FORCED_RUN)) + assert.strictEqual(testSession.meta[TEST_ITR_UNSKIPPABLE], 'true') + assert.ok(!Object.hasOwn(testModule.meta, TEST_ITR_FORCED_RUN)) + assert.strictEqual(testModule.meta[TEST_ITR_UNSKIPPABLE], 'true') const passedSuite = suites.find( event => event.content.resource === 'test_suite.ci-visibility/unskippable-test/test-to-run.js' @@ -1882,16 +1868,16 @@ describe(`mocha@${MOCHA_VERSION}`, function () { ).content // It does not mark as unskippable if there is no docblock - assert.propertyVal(passedSuite.content.meta, TEST_STATUS, 'pass') - assert.notProperty(passedSuite.content.meta, TEST_ITR_UNSKIPPABLE) - assert.notProperty(passedSuite.content.meta, TEST_ITR_FORCED_RUN) + assert.strictEqual(passedSuite.content.meta[TEST_STATUS], 'pass') + assert.ok(!Object.hasOwn(passedSuite.content.meta, TEST_ITR_UNSKIPPABLE)) + assert.ok(!Object.hasOwn(passedSuite.content.meta, TEST_ITR_FORCED_RUN)) - assert.propertyVal(skippedSuite.meta, TEST_STATUS, 'skip') + assert.strictEqual(skippedSuite.meta[TEST_STATUS], 'skip') - assert.propertyVal(nonSkippedSuite.meta, TEST_STATUS, 'pass') - assert.propertyVal(nonSkippedSuite.meta, TEST_ITR_UNSKIPPABLE, 'true') + assert.strictEqual(nonSkippedSuite.meta[TEST_STATUS], 'pass') + assert.strictEqual(nonSkippedSuite.meta[TEST_ITR_UNSKIPPABLE], 'true') // it was not forced to run because it wasn't going to be skipped - assert.notProperty(nonSkippedSuite.meta, TEST_ITR_FORCED_RUN) + assert.ok(!Object.hasOwn(nonSkippedSuite.meta, TEST_ITR_FORCED_RUN)) }, 25000) childProcess = exec( @@ -1928,13 +1914,13 @@ describe(`mocha@${MOCHA_VERSION}`, function () { .gatherPayloadsMaxTimeout(({ url }) => url.endsWith('/api/v2/citestcycle'), (payloads) => { const events = payloads.flatMap(({ payload }) => payload.events) const testSession = events.find(event => event.type === 'test_session_end').content - assert.propertyVal(testSession.meta, TEST_ITR_TESTS_SKIPPED, 'false') - assert.propertyVal(testSession.meta, TEST_CODE_COVERAGE_ENABLED, 'true') - assert.propertyVal(testSession.meta, TEST_ITR_SKIPPING_ENABLED, 'true') + assert.strictEqual(testSession.meta[TEST_ITR_TESTS_SKIPPED], 'false') + assert.strictEqual(testSession.meta[TEST_CODE_COVERAGE_ENABLED], 'true') + assert.strictEqual(testSession.meta[TEST_ITR_SKIPPING_ENABLED], 'true') const testModule = events.find(event => event.type === 'test_module_end').content - assert.propertyVal(testModule.meta, TEST_ITR_TESTS_SKIPPED, 'false') - assert.propertyVal(testModule.meta, TEST_CODE_COVERAGE_ENABLED, 'true') - assert.propertyVal(testModule.meta, TEST_ITR_SKIPPING_ENABLED, 'true') + assert.strictEqual(testModule.meta[TEST_ITR_TESTS_SKIPPED], 'false') + assert.strictEqual(testModule.meta[TEST_CODE_COVERAGE_ENABLED], 'true') + assert.strictEqual(testModule.meta[TEST_ITR_SKIPPING_ENABLED], 'true') }, 25000) childProcess = exec( @@ -1960,7 +1946,7 @@ describe(`mocha@${MOCHA_VERSION}`, function () { const events = payloads.flatMap(({ payload }) => payload.events) const testSuites = events.filter(event => event.type === 'test_suite_end').map(event => event.content) testSuites.forEach(testSuite => { - assert.equal(testSuite.itr_correlation_id, itrCorrelationId) + assert.strictEqual(testSuite.itr_correlation_id, itrCorrelationId) }) }, 25000) childProcess = exec( @@ -2042,7 +2028,7 @@ describe(`mocha@${MOCHA_VERSION}`, function () { const events = payloads.flatMap(({ payload }) => payload.events) const testSession = events.find(event => event.type === 'test_session_end').content - assert.propertyVal(testSession.meta, TEST_EARLY_FLAKE_ENABLED, 'true') + assert.strictEqual(testSession.meta[TEST_EARLY_FLAKE_ENABLED], 'true') const tests = events.filter(event => event.type === 'test').map(event => event.content) @@ -2051,29 +2037,26 @@ describe(`mocha@${MOCHA_VERSION}`, function () { test.meta[TEST_SUITE] === 'ci-visibility/test/ci-visibility-test.js' ) oldTests.forEach(test => { - assert.notProperty(test.meta, TEST_IS_NEW) + assert.ok(!Object.hasOwn(test.meta, TEST_IS_NEW)) }) - assert.equal(oldTests.length, 1) + assert.strictEqual(oldTests.length, 1) const newTests = tests.filter(test => test.meta[TEST_SUITE] === 'ci-visibility/test/ci-visibility-test-2.js' ) newTests.forEach(test => { - assert.propertyVal(test.meta, TEST_IS_NEW, 'true') + assert.strictEqual(test.meta[TEST_IS_NEW], 'true') }) const retriedTests = newTests.filter(test => test.meta[TEST_IS_RETRY] === 'true') // all but one has been retried - assert.equal( - newTests.length - 1, - retriedTests.length - ) - assert.equal(retriedTests.length, NUM_RETRIES_EFD) + assert.strictEqual(newTests.length - 1, retriedTests.length) + assert.strictEqual(retriedTests.length, NUM_RETRIES_EFD) retriedTests.forEach(test => { - assert.propertyVal(test.meta, TEST_RETRY_REASON, TEST_RETRY_REASON_TYPES.efd) + assert.strictEqual(test.meta[TEST_RETRY_REASON], TEST_RETRY_REASON_TYPES.efd) }) // Test name does not change newTests.forEach(test => { - assert.equal(test.meta[TEST_NAME], 'ci visibility 2 can report tests 2') + assert.strictEqual(test.meta[TEST_NAME], 'ci visibility 2 can report tests 2') }) }) @@ -2123,13 +2106,13 @@ describe(`mocha@${MOCHA_VERSION}`, function () { const tests = events.filter(event => event.type === 'test').map(event => event.content) const testSession = events.find(event => event.type === 'test_session_end').content - assert.propertyVal(testSession.meta, TEST_EARLY_FLAKE_ENABLED, 'true') + assert.strictEqual(testSession.meta[TEST_EARLY_FLAKE_ENABLED], 'true') const newTests = tests.filter(test => test.meta[TEST_SUITE] === 'ci-visibility/test-early-flake-detection/mocha-parameterized.js' ) newTests.forEach(test => { - assert.propertyVal(test.meta, TEST_IS_NEW, 'true') + assert.strictEqual(test.meta[TEST_IS_NEW], 'true') }) // Each parameter is repeated independently const testsForFirstParameter = tests.filter(test => test.resource === @@ -2140,18 +2123,12 @@ describe(`mocha@${MOCHA_VERSION}`, function () { 'ci-visibility/test-early-flake-detection/mocha-parameterized.js.parameterized test parameter 2' ) - assert.equal(testsForFirstParameter.length, testsForSecondParameter.length) + assert.strictEqual(testsForFirstParameter.length, testsForSecondParameter.length) // all but one have been retried - assert.equal( - testsForFirstParameter.length - 1, - testsForFirstParameter.filter(test => test.meta[TEST_IS_RETRY] === 'true').length - ) + assert.strictEqual(testsForFirstParameter.length - 1, testsForFirstParameter.filter(test => test.meta[TEST_IS_RETRY] === 'true').length) - assert.equal( - testsForSecondParameter.length - 1, - testsForSecondParameter.filter(test => test.meta[TEST_IS_RETRY] === 'true').length - ) + assert.strictEqual(testsForSecondParameter.length - 1, testsForSecondParameter.filter(test => test.meta[TEST_IS_RETRY] === 'true').length) }) childProcess = exec( @@ -2197,18 +2174,18 @@ describe(`mocha@${MOCHA_VERSION}`, function () { .gatherPayloadsMaxTimeout(({ url }) => url.endsWith('/api/v2/citestcycle'), (payloads) => { const events = payloads.flatMap(({ payload }) => payload.events) const testSession = events.find(event => event.type === 'test_session_end').content - assert.notProperty(testSession.meta, TEST_EARLY_FLAKE_ENABLED) + assert.ok(!Object.hasOwn(testSession.meta, TEST_EARLY_FLAKE_ENABLED)) const tests = events.filter(event => event.type === 'test').map(event => event.content) const newTests = tests.filter(test => test.meta[TEST_IS_NEW] === 'true' ) // new tests are detected but not retried - assert.equal(newTests.length, 1) + assert.strictEqual(newTests.length, 1) const retriedTests = tests.filter(test => test.meta[TEST_IS_RETRY] === 'true' ) - assert.equal(retriedTests.length, 0) + assert.strictEqual(retriedTests.length, 0) }) childProcess = exec( @@ -2257,26 +2234,23 @@ describe(`mocha@${MOCHA_VERSION}`, function () { const events = payloads.flatMap(({ payload }) => payload.events) const testSession = events.find(event => event.type === 'test_session_end').content - assert.propertyVal(testSession.meta, TEST_EARLY_FLAKE_ENABLED, 'true') + assert.strictEqual(testSession.meta[TEST_EARLY_FLAKE_ENABLED], 'true') const tests = events.filter(event => event.type === 'test').map(event => event.content) const retriedTests = tests.filter(test => test.meta[TEST_IS_RETRY] === 'true') // all but one has been retried - assert.equal( - tests.length - 1, - retriedTests.length - ) - assert.equal(retriedTests.length, NUM_RETRIES_EFD) + assert.strictEqual(tests.length - 1, retriedTests.length) + assert.strictEqual(retriedTests.length, NUM_RETRIES_EFD) // Out of NUM_RETRIES_EFD + 1 total runs, half will be passing and half will be failing, // based on the global counter in the test file const passingTests = tests.filter(test => test.meta[TEST_STATUS] === 'pass') const failingTests = tests.filter(test => test.meta[TEST_STATUS] === 'fail') - assert.equal(passingTests.length, (NUM_RETRIES_EFD + 1) / 2) - assert.equal(failingTests.length, (NUM_RETRIES_EFD + 1) / 2) + assert.strictEqual(passingTests.length, (NUM_RETRIES_EFD + 1) / 2) + assert.strictEqual(failingTests.length, (NUM_RETRIES_EFD + 1) / 2) // Test name does not change retriedTests.forEach(test => { - assert.equal(test.meta[TEST_NAME], 'fail occasionally fails') + assert.strictEqual(test.meta[TEST_NAME], 'fail occasionally fails') }) }) @@ -2297,7 +2271,7 @@ describe(`mocha@${MOCHA_VERSION}`, function () { childProcess.on('exit', (exitCode) => { // TODO: check exit code: if a new, retried test fails, the exit code should remain 0 eventsPromise.then(() => { - assert.equal(exitCode, 0) + assert.strictEqual(exitCode, 0) done() }).catch(done) }) @@ -2326,15 +2300,15 @@ describe(`mocha@${MOCHA_VERSION}`, function () { const events = payloads.flatMap(({ payload }) => payload.events) const testSession = events.find(event => event.type === 'test_session_end').content - assert.propertyVal(testSession.meta, TEST_EARLY_FLAKE_ENABLED, 'true') + assert.strictEqual(testSession.meta[TEST_EARLY_FLAKE_ENABLED], 'true') const tests = events.filter(event => event.type === 'test').map(event => event.content) const newSkippedTests = tests.filter( test => test.meta[TEST_NAME] === 'ci visibility skip will not be retried' ) - assert.equal(newSkippedTests.length, 1) - assert.notProperty(newSkippedTests[0].meta, TEST_IS_RETRY) + assert.strictEqual(newSkippedTests.length, 1) + assert.ok(!Object.hasOwn(newSkippedTests[0].meta, TEST_IS_RETRY)) }) childProcess = exec( @@ -2384,7 +2358,7 @@ describe(`mocha@${MOCHA_VERSION}`, function () { const events = payloads.flatMap(({ payload }) => payload.events) const tests = events.filter(event => event.type === 'test').map(event => event.content) - assert.equal(tests.length, 2) + assert.strictEqual(tests.length, 2) const resourceNames = tests.map(test => test.resource) @@ -2399,7 +2373,7 @@ describe(`mocha@${MOCHA_VERSION}`, function () { test => test.meta[TEST_IS_NEW] === 'true' ) // no new tests - assert.equal(newTests.length, 0) + assert.strictEqual(newTests.length, 0) }) childProcess = exec( @@ -2442,15 +2416,15 @@ describe(`mocha@${MOCHA_VERSION}`, function () { const events = payloads.flatMap(({ payload }) => payload.events) const testSession = events.find(event => event.type === 'test_session_end').content - assert.notProperty(testSession.meta, TEST_EARLY_FLAKE_ENABLED) + assert.ok(!Object.hasOwn(testSession.meta, TEST_EARLY_FLAKE_ENABLED)) const tests = events.filter(event => event.type === 'test').map(event => event.content) - assert.equal(tests.length, 2) + assert.strictEqual(tests.length, 2) const newTests = tests.filter( test => test.meta[TEST_IS_NEW] === 'true' ) - assert.equal(newTests.length, 0) + assert.strictEqual(newTests.length, 0) }) childProcess = exec( @@ -2496,26 +2470,23 @@ describe(`mocha@${MOCHA_VERSION}`, function () { const events = payloads.flatMap(({ payload }) => payload.events) const testSession = events.find(event => event.type === 'test_session_end').content - assert.propertyVal(testSession.meta, TEST_EARLY_FLAKE_ENABLED, 'true') + assert.strictEqual(testSession.meta[TEST_EARLY_FLAKE_ENABLED], 'true') const tests = events.filter(event => event.type === 'test').map(event => event.content) const retriedTests = tests.filter(test => test.meta[TEST_IS_RETRY] === 'true') // all but one has been retried - assert.equal( - tests.length - 1, - retriedTests.length - ) - assert.equal(retriedTests.length, NUM_RETRIES_EFD) + assert.strictEqual(tests.length - 1, retriedTests.length) + assert.strictEqual(retriedTests.length, NUM_RETRIES_EFD) // Out of NUM_RETRIES_EFD + 1 total runs, half will be passing and half will be failing, // based on the global counter in the test file const passingTests = tests.filter(test => test.meta[TEST_STATUS] === 'pass') const failingTests = tests.filter(test => test.meta[TEST_STATUS] === 'fail') - assert.equal(passingTests.length, (NUM_RETRIES_EFD + 1) / 2) - assert.equal(failingTests.length, (NUM_RETRIES_EFD + 1) / 2) + assert.strictEqual(passingTests.length, (NUM_RETRIES_EFD + 1) / 2) + assert.strictEqual(failingTests.length, (NUM_RETRIES_EFD + 1) / 2) // Test name does not change retriedTests.forEach(test => { - assert.equal(test.meta[TEST_NAME], 'fail occasionally fails') + assert.strictEqual(test.meta[TEST_NAME], 'fail occasionally fails') }) }) @@ -2539,9 +2510,9 @@ describe(`mocha@${MOCHA_VERSION}`, function () { }) childProcess.on('exit', (exitCode) => { - assert.include(testOutput, '2 passing') - assert.include(testOutput, '2 failing') - assert.equal(exitCode, 0) + assert.ok(testOutput.includes('2 passing')) + assert.ok(testOutput.includes('2 failing')) + assert.strictEqual(exitCode, 0) eventsPromise.then(() => { done() }).catch(done) @@ -2573,16 +2544,16 @@ describe(`mocha@${MOCHA_VERSION}`, function () { const events = payloads.flatMap(({ payload }) => payload.events) const testSession = events.find(event => event.type === 'test_session_end').content - assert.notProperty(testSession.meta, TEST_EARLY_FLAKE_ENABLED) - assert.propertyVal(testSession.meta, TEST_EARLY_FLAKE_ABORT_REASON, 'faulty') + assert.ok(!Object.hasOwn(testSession.meta, TEST_EARLY_FLAKE_ENABLED)) + assert.strictEqual(testSession.meta[TEST_EARLY_FLAKE_ABORT_REASON], 'faulty') const tests = events.filter(event => event.type === 'test').map(event => event.content) const newTests = tests.filter(test => test.meta[TEST_IS_NEW] === 'true') - assert.equal(newTests.length, 0) + assert.strictEqual(newTests.length, 0) const retriedTests = newTests.filter(test => test.meta[TEST_IS_RETRY] === 'true') - assert.equal(retriedTests.length, 0) + assert.strictEqual(retriedTests.length, 0) }) childProcess = exec( @@ -2634,28 +2605,25 @@ describe(`mocha@${MOCHA_VERSION}`, function () { const events = payloads.flatMap(({ payload }) => payload.events) const testSession = events.find(event => event.type === 'test_session_end').content - assert.propertyVal(testSession.meta, TEST_EARLY_FLAKE_ENABLED, 'true') - assert.propertyVal(testSession.meta, MOCHA_IS_PARALLEL, 'true') + assert.strictEqual(testSession.meta[TEST_EARLY_FLAKE_ENABLED], 'true') + assert.strictEqual(testSession.meta[MOCHA_IS_PARALLEL], 'true') const tests = events.filter(event => event.type === 'test').map(event => event.content) const retriedTests = tests.filter(test => test.meta[TEST_IS_RETRY] === 'true') // all but one has been retried - assert.equal( - tests.length - 1, - retriedTests.length - ) - assert.equal(retriedTests.length, NUM_RETRIES_EFD) + assert.strictEqual(tests.length - 1, retriedTests.length) + assert.strictEqual(retriedTests.length, NUM_RETRIES_EFD) // Out of NUM_RETRIES_EFD + 1 (5) total runs, 3 will be passing and 2 will be failing, // based on the global counter in the test file const passingTests = tests.filter(test => test.meta[TEST_STATUS] === 'pass') const failingTests = tests.filter(test => test.meta[TEST_STATUS] === 'fail') - assert.equal(passingTests.length, 3) - assert.equal(failingTests.length, 2) + assert.strictEqual(passingTests.length, 3) + assert.strictEqual(failingTests.length, 2) // Test name does not change retriedTests.forEach(test => { - assert.equal(test.meta[TEST_NAME], 'fail occasionally fails') - assert.equal(test.meta[TEST_RETRY_REASON], TEST_RETRY_REASON_TYPES.efd) + assert.strictEqual(test.meta[TEST_NAME], 'fail occasionally fails') + assert.strictEqual(test.meta[TEST_RETRY_REASON], TEST_RETRY_REASON_TYPES.efd) }) }) @@ -2669,7 +2637,7 @@ describe(`mocha@${MOCHA_VERSION}`, function () { childProcess.on('exit', (exitCode) => { eventsPromise.then(() => { - assert.equal(exitCode, 0) + assert.strictEqual(exitCode, 0) done() }).catch(done) }) @@ -2698,27 +2666,24 @@ describe(`mocha@${MOCHA_VERSION}`, function () { const events = payloads.flatMap(({ payload }) => payload.events) const testSession = events.find(event => event.type === 'test_session_end').content - assert.propertyVal(testSession.meta, TEST_EARLY_FLAKE_ENABLED, 'true') - assert.propertyVal(testSession.meta, MOCHA_IS_PARALLEL, 'true') + assert.strictEqual(testSession.meta[TEST_EARLY_FLAKE_ENABLED], 'true') + assert.strictEqual(testSession.meta[MOCHA_IS_PARALLEL], 'true') const tests = events.filter(event => event.type === 'test').map(event => event.content) const retriedTests = tests.filter(test => test.meta[TEST_IS_RETRY] === 'true') // all but one has been retried - assert.equal( - tests.length - 1, - retriedTests.length - ) - assert.equal(retriedTests.length, NUM_RETRIES_EFD) + assert.strictEqual(tests.length - 1, retriedTests.length) + assert.strictEqual(retriedTests.length, NUM_RETRIES_EFD) // Out of NUM_RETRIES_EFD + 1 total runs, half will be passing and half will be failing, // based on the global counter in the test file const passingTests = tests.filter(test => test.meta[TEST_STATUS] === 'pass') const failingTests = tests.filter(test => test.meta[TEST_STATUS] === 'fail') - assert.equal(passingTests.length, (NUM_RETRIES_EFD + 1) / 2) - assert.equal(failingTests.length, (NUM_RETRIES_EFD + 1) / 2) + assert.strictEqual(passingTests.length, (NUM_RETRIES_EFD + 1) / 2) + assert.strictEqual(failingTests.length, (NUM_RETRIES_EFD + 1) / 2) // Test name does not change retriedTests.forEach(test => { - assert.equal(test.meta[TEST_NAME], 'fail occasionally fails') + assert.strictEqual(test.meta[TEST_NAME], 'fail occasionally fails') }) }) @@ -2738,7 +2703,7 @@ describe(`mocha@${MOCHA_VERSION}`, function () { ) childProcess.on('exit', (exitCode) => { eventsPromise.then(() => { - assert.equal(exitCode, 0) + assert.strictEqual(exitCode, 0) done() }).catch(done) }) @@ -2769,16 +2734,16 @@ describe(`mocha@${MOCHA_VERSION}`, function () { const events = payloads.flatMap(({ payload }) => payload.events) const testSession = events.find(event => event.type === 'test_session_end').content - assert.notProperty(testSession.meta, TEST_EARLY_FLAKE_ENABLED) - assert.propertyVal(testSession.meta, TEST_EARLY_FLAKE_ABORT_REASON, 'faulty') + assert.ok(!Object.hasOwn(testSession.meta, TEST_EARLY_FLAKE_ENABLED)) + assert.strictEqual(testSession.meta[TEST_EARLY_FLAKE_ABORT_REASON], 'faulty') const tests = events.filter(event => event.type === 'test').map(event => event.content) const newTests = tests.filter(test => test.meta[TEST_IS_NEW] === 'true') - assert.equal(newTests.length, 0) + assert.strictEqual(newTests.length, 0) const retriedTests = newTests.filter(test => test.meta[TEST_IS_RETRY] === 'true') - assert.equal(retriedTests.length, 0) + assert.strictEqual(retriedTests.length, 0) }) childProcess = exec( @@ -2829,15 +2794,15 @@ describe(`mocha@${MOCHA_VERSION}`, function () { const events = payloads.flatMap(({ payload }) => payload.events) const testSession = events.find(event => event.type === 'test_session_end').content - assert.notProperty(testSession.meta, TEST_EARLY_FLAKE_ENABLED) + assert.ok(!Object.hasOwn(testSession.meta, TEST_EARLY_FLAKE_ENABLED)) const tests = events.filter(event => event.type === 'test').map(event => event.content) const newTests = tests.filter(test => test.meta[TEST_IS_NEW] === 'true') - assert.equal(newTests.length, 0) + assert.strictEqual(newTests.length, 0) const retriedTests = newTests.filter(test => test.meta[TEST_IS_RETRY] === 'true') - assert.equal(retriedTests.length, 0) + assert.strictEqual(retriedTests.length, 0) }) childProcess = exec( @@ -2885,7 +2850,7 @@ describe(`mocha@${MOCHA_VERSION}`, function () { const events = payloads.flatMap(({ payload }) => payload.events) const testSession = events.find(event => event.type === 'test_session_end').content - assert.notProperty(testSession.meta, TEST_EARLY_FLAKE_ENABLED) + assert.ok(!Object.hasOwn(testSession.meta, TEST_EARLY_FLAKE_ENABLED)) const tests = events.filter(event => event.type === 'test').map(event => event.content) @@ -2893,17 +2858,17 @@ describe(`mocha@${MOCHA_VERSION}`, function () { test.meta[TEST_SUITE] === 'ci-visibility/test/ci-visibility-test.js' ) oldTests.forEach(test => { - assert.notProperty(test.meta, TEST_IS_NEW) + assert.ok(!Object.hasOwn(test.meta, TEST_IS_NEW)) }) - assert.equal(oldTests.length, 1) + assert.strictEqual(oldTests.length, 1) const newTests = tests.filter(test => test.meta[TEST_SUITE] === 'ci-visibility/test/ci-visibility-test-2.js' ) newTests.forEach(test => { - assert.notProperty(test.meta, TEST_IS_NEW) + assert.ok(!Object.hasOwn(test.meta, TEST_IS_NEW)) }) const retriedTests = newTests.filter(test => test.meta[TEST_IS_RETRY] === 'true') - assert.equal(retriedTests.length, 0) + assert.strictEqual(retriedTests.length, 0) }) childProcess = exec( @@ -2961,24 +2926,24 @@ describe(`mocha@${MOCHA_VERSION}`, function () { const events = payloads.flatMap(({ payload }) => payload.events) const tests = events.filter(event => event.type === 'test').map(event => event.content) - assert.equal(tests.length, 3) // two failed retries and then the pass + assert.strictEqual(tests.length, 3) // two failed retries and then the pass const failedAttempts = tests.filter(test => test.meta[TEST_STATUS] === 'fail') - assert.equal(failedAttempts.length, 2) + assert.strictEqual(failedAttempts.length, 2) failedAttempts.forEach((failedTest, index) => { - assert.include(failedTest.meta[ERROR_MESSAGE], `expected ${index + 1} to equal 3`) + assert.ok(failedTest.meta[ERROR_MESSAGE].includes(`expected ${index + 1} to equal 3`)) }) // The first attempt is not marked as a retry const retriedFailure = failedAttempts.filter( test => test.meta[TEST_RETRY_REASON] === TEST_RETRY_REASON_TYPES.atr ) - assert.equal(retriedFailure.length, 1) + assert.strictEqual(retriedFailure.length, 1) const passedAttempt = tests.find(test => test.meta[TEST_STATUS] === 'pass') - assert.equal(passedAttempt.meta[TEST_IS_RETRY], 'true') - assert.equal(passedAttempt.meta[TEST_RETRY_REASON], TEST_RETRY_REASON_TYPES.atr) + assert.strictEqual(passedAttempt.meta[TEST_IS_RETRY], 'true') + assert.strictEqual(passedAttempt.meta[TEST_RETRY_REASON], TEST_RETRY_REASON_TYPES.atr) }) childProcess.on('exit', () => { @@ -3004,10 +2969,10 @@ describe(`mocha@${MOCHA_VERSION}`, function () { const events = payloads.flatMap(({ payload }) => payload.events) const tests = events.filter(event => event.type === 'test').map(event => event.content) - assert.equal(tests.length, 1) + assert.strictEqual(tests.length, 1) const retries = tests.filter(test => test.meta[TEST_RETRY_REASON] === TEST_RETRY_REASON_TYPES.atr) - assert.equal(retries.length, 0) + assert.strictEqual(retries.length, 0) }) childProcess = exec( @@ -3048,15 +3013,15 @@ describe(`mocha@${MOCHA_VERSION}`, function () { const events = payloads.flatMap(({ payload }) => payload.events) const tests = events.filter(event => event.type === 'test').map(event => event.content) - assert.equal(tests.length, 2) // one retry + assert.strictEqual(tests.length, 2) // one retry const failedAttempts = tests.filter(test => test.meta[TEST_STATUS] === 'fail') - assert.equal(failedAttempts.length, 2) + assert.strictEqual(failedAttempts.length, 2) const retriedFailure = failedAttempts.filter( test => test.meta[TEST_RETRY_REASON] === TEST_RETRY_REASON_TYPES.atr ) - assert.equal(retriedFailure.length, 1) + assert.strictEqual(retriedFailure.length, 1) }) childProcess = exec( @@ -3115,11 +3080,8 @@ describe(`mocha@${MOCHA_VERSION}`, function () { linePctMatch = testOutput.match(linePctMatchRegex) linesPctFromNyc = linePctMatch ? Number(linePctMatch[1]) : null - assert.equal( - linesPctFromNyc, - codeCoverageWithUntestedFiles, - 'nyc --all output does not match the reported coverage' - ) + assert.strictEqual(linesPctFromNyc, codeCoverageWithUntestedFiles, + 'nyc --all output does not match the reported coverage') // reset test output for next test session testOutput = '' @@ -3152,14 +3114,11 @@ describe(`mocha@${MOCHA_VERSION}`, function () { linePctMatch = testOutput.match(linePctMatchRegex) linesPctFromNyc = linePctMatch ? Number(linePctMatch[1]) : null - assert.equal( - linesPctFromNyc, - codeCoverageWithoutUntestedFiles, - 'nyc output does not match the reported coverage (no --all flag)' - ) + assert.strictEqual(linesPctFromNyc, codeCoverageWithoutUntestedFiles, + 'nyc output does not match the reported coverage (no --all flag)') eventsPromise.then(() => { - assert.isAbove(codeCoverageWithoutUntestedFiles, codeCoverageWithUntestedFiles) + assert.ok(codeCoverageWithoutUntestedFiles > codeCoverageWithUntestedFiles) done() }).catch(done) }) @@ -3184,13 +3143,13 @@ describe(`mocha@${MOCHA_VERSION}`, function () { test => test.meta[TEST_RETRY_REASON] === TEST_RETRY_REASON_TYPES.atr ) - assert.equal(retriedTests.length, 1) + assert.strictEqual(retriedTests.length, 1) const [retriedTest] = retriedTests const hasDebugTags = Object.keys(retriedTest.meta) .some(property => property.startsWith(DI_DEBUG_ERROR_PREFIX) || property === DI_ERROR_DEBUG_INFO_CAPTURED) - assert.isFalse(hasDebugTags) + assert.strictEqual(hasDebugTags, false) }) const logsPromise = receiver @@ -3218,7 +3177,7 @@ describe(`mocha@${MOCHA_VERSION}`, function () { childProcess.on('exit', (code) => { Promise.all([eventsPromise, logsPromise]).then(() => { - assert.equal(code, 0) + assert.strictEqual(code, 0) done() }).catch(done) }) @@ -3239,13 +3198,13 @@ describe(`mocha@${MOCHA_VERSION}`, function () { test => test.meta[TEST_RETRY_REASON] === TEST_RETRY_REASON_TYPES.atr ) - assert.equal(retriedTests.length, 1) + assert.strictEqual(retriedTests.length, 1) const [retriedTest] = retriedTests const hasDebugTags = Object.keys(retriedTest.meta) .some(property => property.startsWith(DI_DEBUG_ERROR_PREFIX) || property === DI_ERROR_DEBUG_INFO_CAPTURED) - assert.isFalse(hasDebugTags) + assert.strictEqual(hasDebugTags, false) }) const logsPromise = receiver @@ -3272,7 +3231,7 @@ describe(`mocha@${MOCHA_VERSION}`, function () { childProcess.on('exit', (code) => { Promise.all([eventsPromise, logsPromise]).then(() => { - assert.equal(code, 0) + assert.strictEqual(code, 0) done() }).catch(done) }) @@ -3296,19 +3255,17 @@ describe(`mocha@${MOCHA_VERSION}`, function () { test => test.meta[TEST_RETRY_REASON] === TEST_RETRY_REASON_TYPES.atr ) - assert.equal(retriedTests.length, 1) + assert.strictEqual(retriedTests.length, 1) const [retriedTest] = retriedTests - assert.propertyVal(retriedTest.meta, DI_ERROR_DEBUG_INFO_CAPTURED, 'true') - assert.isTrue( - retriedTest.meta[`${DI_DEBUG_ERROR_PREFIX}.0.${DI_DEBUG_ERROR_FILE_SUFFIX}`] - .endsWith('ci-visibility/dynamic-instrumentation/dependency.js') - ) - assert.equal(retriedTest.metrics[`${DI_DEBUG_ERROR_PREFIX}.0.${DI_DEBUG_ERROR_LINE_SUFFIX}`], 6) + assert.strictEqual(retriedTest.meta[DI_ERROR_DEBUG_INFO_CAPTURED], 'true') + assert.strictEqual(retriedTest.meta[`${DI_DEBUG_ERROR_PREFIX}.0.${DI_DEBUG_ERROR_FILE_SUFFIX}`] + .endsWith('ci-visibility/dynamic-instrumentation/dependency.js'), true) + assert.strictEqual(retriedTest.metrics[`${DI_DEBUG_ERROR_PREFIX}.0.${DI_DEBUG_ERROR_LINE_SUFFIX}`], 6) const snapshotIdKey = `${DI_DEBUG_ERROR_PREFIX}.0.${DI_DEBUG_ERROR_SNAPSHOT_ID_SUFFIX}` - assert.exists(retriedTest.meta[snapshotIdKey]) + assert.ok(retriedTest.meta[snapshotIdKey] != null) snapshotIdByTest = retriedTest.meta[snapshotIdKey] spanIdByTest = retriedTest.span_id.toString() @@ -3316,17 +3273,17 @@ describe(`mocha@${MOCHA_VERSION}`, function () { const notRetriedTest = tests.find(test => test.meta[TEST_NAME].includes('is not retried')) - assert.notProperty(notRetriedTest.meta, DI_ERROR_DEBUG_INFO_CAPTURED) + assert.ok(!Object.hasOwn(notRetriedTest.meta, DI_ERROR_DEBUG_INFO_CAPTURED)) }) const logsPromise = receiver .gatherPayloadsMaxTimeout(({ url }) => url.endsWith('/api/v2/logs'), (payloads) => { const [{ logMessage: [diLog] }] = payloads - assert.deepInclude(diLog, { + assertObjectContains(diLog, { ddsource: 'dd_debugger', level: 'error' }) - assert.equal(diLog.debugger.snapshot.language, 'javascript') + assert.strictEqual(diLog.debugger.snapshot.language, 'javascript') assert.deepInclude(diLog.debugger.snapshot.captures.lines['6'].locals, { a: { type: 'number', @@ -3363,9 +3320,9 @@ describe(`mocha@${MOCHA_VERSION}`, function () { childProcess.on('exit', () => { Promise.all([eventsPromise, logsPromise]).then(() => { - assert.equal(snapshotIdByTest, snapshotIdByLog) - assert.equal(spanIdByTest, spanIdByLog) - assert.equal(traceIdByTest, traceIdByLog) + assert.strictEqual(snapshotIdByTest, snapshotIdByLog) + assert.strictEqual(spanIdByTest, spanIdByLog) + assert.strictEqual(traceIdByTest, traceIdByLog) done() }).catch(done) }) @@ -3386,13 +3343,13 @@ describe(`mocha@${MOCHA_VERSION}`, function () { test => test.meta[TEST_RETRY_REASON] === TEST_RETRY_REASON_TYPES.atr ) - assert.equal(retriedTests.length, 1) + assert.strictEqual(retriedTests.length, 1) const [retriedTest] = retriedTests const hasDebugTags = Object.keys(retriedTest.meta) .some(property => property.startsWith(DI_DEBUG_ERROR_PREFIX) || property === DI_ERROR_DEBUG_INFO_CAPTURED) - assert.isFalse(hasDebugTags) + assert.strictEqual(hasDebugTags, false) }) const logsPromise = receiver .gatherPayloadsMaxTimeout(({ url }) => url.endsWith('/api/v2/logs'), (payloads) => { @@ -3445,7 +3402,7 @@ describe(`mocha@${MOCHA_VERSION}`, function () { const events = payloads.flatMap(({ payload }) => payload.events) const testSession = events.find(event => event.type === 'test_session_end').content - assert.notProperty(testSession.meta, TEST_EARLY_FLAKE_ENABLED) + assert.ok(!Object.hasOwn(testSession.meta, TEST_EARLY_FLAKE_ENABLED)) const tests = events.filter(event => event.type === 'test').map(event => event.content) @@ -3454,19 +3411,19 @@ describe(`mocha@${MOCHA_VERSION}`, function () { test.meta[TEST_SUITE] === 'ci-visibility/test/ci-visibility-test.js' ) oldTests.forEach(test => { - assert.notProperty(test.meta, TEST_IS_NEW) + assert.ok(!Object.hasOwn(test.meta, TEST_IS_NEW)) }) - assert.equal(oldTests.length, 1) + assert.strictEqual(oldTests.length, 1) const newTests = tests.filter(test => test.meta[TEST_SUITE] === 'ci-visibility/test/ci-visibility-test-2.js' ) newTests.forEach(test => { - assert.propertyVal(test.meta, TEST_IS_NEW, 'true') + assert.strictEqual(test.meta[TEST_IS_NEW], 'true') }) const retriedTests = newTests.filter(test => test.meta[TEST_RETRY_REASON] === TEST_RETRY_REASON_TYPES.atr) // no test has been retried - assert.equal(retriedTests.length, 0) + assert.strictEqual(retriedTests.length, 0) }) childProcess = exec( @@ -3499,7 +3456,7 @@ describe(`mocha@${MOCHA_VERSION}`, function () { const tests = events.filter(event => event.type === 'test').map(event => event.content) tests.forEach(test => { - assert.equal(test.meta[DD_TEST_IS_USER_PROVIDED_SERVICE], 'true') + assert.strictEqual(test.meta[DD_TEST_IS_USER_PROVIDED_SERVICE], 'true') }) }) @@ -3560,9 +3517,9 @@ describe(`mocha@${MOCHA_VERSION}`, function () { const testSession = events.find(event => event.type === 'test_session_end').content if (isAttemptToFix) { - assert.propertyVal(testSession.meta, TEST_MANAGEMENT_ENABLED, 'true') + assert.strictEqual(testSession.meta[TEST_MANAGEMENT_ENABLED], 'true') } else { - assert.notProperty(testSession.meta, TEST_MANAGEMENT_ENABLED) + assert.ok(!Object.hasOwn(testSession.meta, TEST_MANAGEMENT_ENABLED)) } const resourceNames = tests.map(span => span.resource) @@ -3582,39 +3539,39 @@ describe(`mocha@${MOCHA_VERSION}`, function () { const isFirstAttempt = i === 0 const isLastAttempt = i === retriedTests.length - 1 if (!isAttemptToFix) { - assert.notProperty(test.meta, TEST_MANAGEMENT_IS_ATTEMPT_TO_FIX) - assert.notProperty(test.meta, TEST_IS_RETRY) - assert.notProperty(test.meta, TEST_RETRY_REASON) + assert.ok(!Object.hasOwn(test.meta, TEST_MANAGEMENT_IS_ATTEMPT_TO_FIX)) + assert.ok(!Object.hasOwn(test.meta, TEST_IS_RETRY)) + assert.ok(!Object.hasOwn(test.meta, TEST_RETRY_REASON)) continue } - assert.propertyVal(test.meta, TEST_MANAGEMENT_IS_ATTEMPT_TO_FIX, 'true') + assert.strictEqual(test.meta[TEST_MANAGEMENT_IS_ATTEMPT_TO_FIX], 'true') if (isFirstAttempt) { - assert.notProperty(test.meta, TEST_IS_RETRY) - assert.notProperty(test.meta, TEST_RETRY_REASON) + assert.ok(!Object.hasOwn(test.meta, TEST_IS_RETRY)) + assert.ok(!Object.hasOwn(test.meta, TEST_RETRY_REASON)) } else { - assert.propertyVal(test.meta, TEST_IS_RETRY, 'true') - assert.propertyVal(test.meta, TEST_RETRY_REASON, TEST_RETRY_REASON_TYPES.atf) + assert.strictEqual(test.meta[TEST_IS_RETRY], 'true') + assert.strictEqual(test.meta[TEST_RETRY_REASON], TEST_RETRY_REASON_TYPES.atf) } if (isQuarantined) { - assert.propertyVal(test.meta, TEST_MANAGEMENT_IS_QUARANTINED, 'true') + assert.strictEqual(test.meta[TEST_MANAGEMENT_IS_QUARANTINED], 'true') } if (isDisabled) { - assert.propertyVal(test.meta, TEST_MANAGEMENT_IS_DISABLED, 'true') + assert.strictEqual(test.meta[TEST_MANAGEMENT_IS_DISABLED], 'true') } if (isLastAttempt) { if (shouldAlwaysPass) { - assert.propertyVal(test.meta, TEST_MANAGEMENT_ATTEMPT_TO_FIX_PASSED, 'true') - assert.notProperty(test.meta, TEST_HAS_FAILED_ALL_RETRIES) + assert.strictEqual(test.meta[TEST_MANAGEMENT_ATTEMPT_TO_FIX_PASSED], 'true') + assert.ok(!Object.hasOwn(test.meta, TEST_HAS_FAILED_ALL_RETRIES)) } else if (shouldFailSometimes) { - assert.notProperty(test.meta, TEST_HAS_FAILED_ALL_RETRIES) - assert.propertyVal(test.meta, TEST_MANAGEMENT_ATTEMPT_TO_FIX_PASSED, 'false') + assert.ok(!Object.hasOwn(test.meta, TEST_HAS_FAILED_ALL_RETRIES)) + assert.strictEqual(test.meta[TEST_MANAGEMENT_ATTEMPT_TO_FIX_PASSED], 'false') } else { - assert.propertyVal(test.meta, TEST_HAS_FAILED_ALL_RETRIES, 'true') - assert.propertyVal(test.meta, TEST_MANAGEMENT_ATTEMPT_TO_FIX_PASSED, 'false') + assert.strictEqual(test.meta[TEST_HAS_FAILED_ALL_RETRIES], 'true') + assert.strictEqual(test.meta[TEST_MANAGEMENT_ATTEMPT_TO_FIX_PASSED], 'false') } } } @@ -3661,12 +3618,12 @@ describe(`mocha@${MOCHA_VERSION}`, function () { childProcess.on('exit', exitCode => { testAssertionsPromise.then(() => { - assert.include(stdout, 'I am running when attempt to fix') + assert.ok(stdout.includes('I am running when attempt to fix')) if (shouldAlwaysPass || isQuarantined || isDisabled) { // even though a test fails, the exit code is 0 because the test is quarantined or disabled - assert.equal(exitCode, 0) + assert.strictEqual(exitCode, 0) } else { - assert.equal(exitCode, 1) + assert.strictEqual(exitCode, 1) } done() }).catch(done) @@ -3775,9 +3732,9 @@ describe(`mocha@${MOCHA_VERSION}`, function () { const testSession = events.find(event => event.type === 'test_session_end').content if (isDisabling) { - assert.propertyVal(testSession.meta, TEST_MANAGEMENT_ENABLED, 'true') + assert.strictEqual(testSession.meta[TEST_MANAGEMENT_ENABLED], 'true') } else { - assert.notProperty(testSession.meta, TEST_MANAGEMENT_ENABLED) + assert.ok(!Object.hasOwn(testSession.meta, TEST_MANAGEMENT_ENABLED)) } const resourceNames = tests.map(span => span.resource) @@ -3793,11 +3750,11 @@ describe(`mocha@${MOCHA_VERSION}`, function () { ) if (isDisabling) { - assert.equal(skippedTests.meta[TEST_STATUS], 'skip') - assert.propertyVal(skippedTests.meta, TEST_MANAGEMENT_IS_DISABLED, 'true') + assert.strictEqual(skippedTests.meta[TEST_STATUS], 'skip') + assert.strictEqual(skippedTests.meta[TEST_MANAGEMENT_IS_DISABLED], 'true') } else { - assert.equal(skippedTests.meta[TEST_STATUS], 'fail') - assert.notProperty(skippedTests.meta, TEST_MANAGEMENT_IS_DISABLED) + assert.strictEqual(skippedTests.meta[TEST_STATUS], 'fail') + assert.ok(!Object.hasOwn(skippedTests.meta, TEST_MANAGEMENT_IS_DISABLED)) } }) @@ -3828,11 +3785,11 @@ describe(`mocha@${MOCHA_VERSION}`, function () { childProcess.on('exit', (exitCode) => { testAssertionsPromise.then(() => { if (isDisabling) { - assert.notInclude(stdout, 'I am running') - assert.equal(exitCode, 0) + assert.ok(!stdout.includes('I am running')) + assert.strictEqual(exitCode, 0) } else { - assert.include(stdout, 'I am running') - assert.equal(exitCode, 1) + assert.ok(stdout.includes('I am running')) + assert.strictEqual(exitCode, 1) } done() }).catch(done) @@ -3899,9 +3856,9 @@ describe(`mocha@${MOCHA_VERSION}`, function () { const testSession = events.find(event => event.type === 'test_session_end').content if (isQuarantining) { - assert.propertyVal(testSession.meta, TEST_MANAGEMENT_ENABLED, 'true') + assert.strictEqual(testSession.meta[TEST_MANAGEMENT_ENABLED], 'true') } else { - assert.notProperty(testSession.meta, TEST_MANAGEMENT_ENABLED) + assert.ok(!Object.hasOwn(testSession.meta, TEST_MANAGEMENT_ENABLED)) } const resourceNames = tests.map(span => span.resource) @@ -3917,12 +3874,12 @@ describe(`mocha@${MOCHA_VERSION}`, function () { test => test.meta[TEST_NAME] === 'quarantine tests can quarantine a test' ) // The test fails but the exit code is 0 if it's quarantined - assert.equal(failedTest.meta[TEST_STATUS], 'fail') + assert.strictEqual(failedTest.meta[TEST_STATUS], 'fail') if (isQuarantining) { - assert.propertyVal(failedTest.meta, TEST_MANAGEMENT_IS_QUARANTINED, 'true') + assert.strictEqual(failedTest.meta[TEST_MANAGEMENT_IS_QUARANTINED], 'true') } else { - assert.notProperty(failedTest.meta, TEST_MANAGEMENT_IS_QUARANTINED) + assert.ok(!Object.hasOwn(failedTest.meta, TEST_MANAGEMENT_IS_QUARANTINED)) } }) @@ -3953,11 +3910,11 @@ describe(`mocha@${MOCHA_VERSION}`, function () { childProcess.on('exit', (exitCode) => { testAssertionsPromise.then(() => { // it runs regardless of the quarantine status - assert.include(stdout, 'I am running when quarantined') + assert.ok(stdout.includes('I am running when quarantined')) if (isQuarantining) { - assert.equal(exitCode, 0) + assert.strictEqual(exitCode, 0) } else { - assert.equal(exitCode, 1) + assert.strictEqual(exitCode, 1) } done() }).catch(done) @@ -4009,10 +3966,10 @@ describe(`mocha@${MOCHA_VERSION}`, function () { .gatherPayloadsMaxTimeout(({ url }) => url.endsWith('/api/v2/citestcycle'), (payloads) => { const events = payloads.flatMap(({ payload }) => payload.events) const testSession = events.find(event => event.type === 'test_session_end').content - assert.notProperty(testSession.meta, TEST_MANAGEMENT_ENABLED) + assert.ok(!Object.hasOwn(testSession.meta, TEST_MANAGEMENT_ENABLED)) const tests = events.filter(event => event.type === 'test').map(event => event.content) // it is not retried - assert.equal(tests.length, 1) + assert.strictEqual(tests.length, 1) }) childProcess = exec( @@ -4043,7 +4000,7 @@ describe(`mocha@${MOCHA_VERSION}`, function () { once(childProcess.stderr, 'end'), eventsPromise ]) - assert.include(testOutput, 'Test management tests could not be fetched') + assert.ok(testOutput.includes('Test management tests could not be fetched')) }) }) @@ -4052,22 +4009,22 @@ describe(`mocha@${MOCHA_VERSION}`, function () { receiver.gatherPayloadsMaxTimeout(({ url }) => url.endsWith('citestcycle'), (payloads) => { const metadataDicts = payloads.flatMap(({ payload }) => payload.metadata) - assert.isNotEmpty(metadataDicts) + assert.ok(metadataDicts.length > 0) metadataDicts.forEach(metadata => { if (isParallel) { - assert.equal(metadata.test[DD_CAPABILITIES_TEST_IMPACT_ANALYSIS], undefined) - assert.equal(metadata.test[DD_CAPABILITIES_TEST_MANAGEMENT_ATTEMPT_TO_FIX], undefined) + assert.strictEqual(metadata.test[DD_CAPABILITIES_TEST_IMPACT_ANALYSIS], undefined) + assert.strictEqual(metadata.test[DD_CAPABILITIES_TEST_MANAGEMENT_ATTEMPT_TO_FIX], undefined) } else { - assert.equal(metadata.test[DD_CAPABILITIES_TEST_IMPACT_ANALYSIS], '1') - assert.equal(metadata.test[DD_CAPABILITIES_TEST_MANAGEMENT_ATTEMPT_TO_FIX], '5') + assert.strictEqual(metadata.test[DD_CAPABILITIES_TEST_IMPACT_ANALYSIS], '1') + assert.strictEqual(metadata.test[DD_CAPABILITIES_TEST_MANAGEMENT_ATTEMPT_TO_FIX], '5') } - assert.equal(metadata.test[DD_CAPABILITIES_EARLY_FLAKE_DETECTION], '1') - assert.equal(metadata.test[DD_CAPABILITIES_AUTO_TEST_RETRIES], '1') - assert.equal(metadata.test[DD_CAPABILITIES_TEST_MANAGEMENT_QUARANTINE], '1') - assert.equal(metadata.test[DD_CAPABILITIES_TEST_MANAGEMENT_DISABLE], '1') - assert.equal(metadata.test[DD_CAPABILITIES_FAILED_TEST_REPLAY], '1') + assert.strictEqual(metadata.test[DD_CAPABILITIES_EARLY_FLAKE_DETECTION], '1') + assert.strictEqual(metadata.test[DD_CAPABILITIES_AUTO_TEST_RETRIES], '1') + assert.strictEqual(metadata.test[DD_CAPABILITIES_TEST_MANAGEMENT_QUARANTINE], '1') + assert.strictEqual(metadata.test[DD_CAPABILITIES_TEST_MANAGEMENT_DISABLE], '1') + assert.strictEqual(metadata.test[DD_CAPABILITIES_FAILED_TEST_REPLAY], '1') // capabilities logic does not overwrite test session name - assert.equal(metadata.test[TEST_SESSION_NAME], 'my-test-session-name') + assert.strictEqual(metadata.test[TEST_SESSION_NAME], 'my-test-session-name') }) }) @@ -4109,7 +4066,7 @@ describe(`mocha@${MOCHA_VERSION}`, function () { const events = payloads.flatMap(({ payload }) => payload.events) const tests = events.filter(event => event.type === 'test').map(event => event.content) - assert.equal(tests.length, 2) + assert.strictEqual(tests.length, 2) assert.includeMembers(tests.map(test => test.meta[TEST_STATUS]), [ 'pass', @@ -4146,11 +4103,11 @@ describe(`mocha@${MOCHA_VERSION}`, function () { eventsPromise ]) - assert.include(stdout, 'beforeEach') - assert.include(stdout, 'beforeEach in context') - assert.include(stdout, 'test') - assert.include(stdout, 'afterEach') - assert.include(stdout, 'afterEach in context') + assert.ok(stdout.includes('beforeEach')) + assert.ok(stdout.includes('beforeEach in context')) + assert.ok(stdout.includes('test')) + assert.ok(stdout.includes('afterEach')) + assert.ok(stdout.includes('afterEach in context')) }) onlyLatestIt('works when tests are retried', async () => { @@ -4159,7 +4116,7 @@ describe(`mocha@${MOCHA_VERSION}`, function () { const events = payloads.flatMap(({ payload }) => payload.events) const tests = events.filter(event => event.type === 'test').map(event => event.content) - assert.equal(tests.length, 3) + assert.strictEqual(tests.length, 3) assert.includeMembers(tests.map(test => test.meta[TEST_STATUS]), [ 'fail', @@ -4173,18 +4130,18 @@ describe(`mocha@${MOCHA_VERSION}`, function () { ]) const retriedTests = tests.filter(test => test.meta[TEST_IS_RETRY] === 'true') - assert.equal(retriedTests.length, 1) - assert.equal(retriedTests[0].meta[TEST_STATUS], 'pass') + assert.strictEqual(retriedTests.length, 1) + assert.strictEqual(retriedTests[0].meta[TEST_STATUS], 'pass') const notNestedTests = tests.filter(test => test.resource === 'ci-visibility/test-nested-hooks/test-nested-hooks.js.describe is not nested' ) - assert.equal(notNestedTests.length, 2) + assert.strictEqual(notNestedTests.length, 2) const failedAttempts = notNestedTests.filter(test => test.meta[TEST_STATUS] === 'fail') - assert.equal(failedAttempts.length, 1) + assert.strictEqual(failedAttempts.length, 1) const passedAttempts = notNestedTests.filter(test => test.meta[TEST_STATUS] === 'pass') - assert.equal(passedAttempts.length, 1) + assert.strictEqual(passedAttempts.length, 1) }) childProcess = exec( @@ -4212,11 +4169,11 @@ describe(`mocha@${MOCHA_VERSION}`, function () { eventsPromise ]) - assert.include(stdout, 'beforeEach') - assert.include(stdout, 'beforeEach in context') - assert.include(stdout, 'test') - assert.include(stdout, 'afterEach') - assert.include(stdout, 'afterEach in context') + assert.ok(stdout.includes('beforeEach')) + assert.ok(stdout.includes('beforeEach in context')) + assert.ok(stdout.includes('test')) + assert.ok(stdout.includes('afterEach')) + assert.ok(stdout.includes('afterEach in context')) }) }) @@ -4239,11 +4196,11 @@ describe(`mocha@${MOCHA_VERSION}`, function () { `const { expect } = require('chai') describe('impacted tests', () => { it('can pass normally', () => { - expect(2 + 2).to.equal(3) + assert.strictEqual(2 + 2, 3) }) it('can fail', () => { - expect(1 + 2).to.equal(4) + assert.strictEqual(1 + 2, 4) }) })` ) @@ -4266,9 +4223,9 @@ describe(`mocha@${MOCHA_VERSION}`, function () { const testSession = events.find(event => event.type === 'test_session_end').content if (isEfd) { - assert.propertyVal(testSession.meta, TEST_EARLY_FLAKE_ENABLED, 'true') + assert.strictEqual(testSession.meta[TEST_EARLY_FLAKE_ENABLED], 'true') } else { - assert.notProperty(testSession.meta, TEST_EARLY_FLAKE_ENABLED) + assert.ok(!Object.hasOwn(testSession.meta, TEST_EARLY_FLAKE_ENABLED)) } const resourceNames = tests.map(span => span.resource) @@ -4295,21 +4252,21 @@ describe(`mocha@${MOCHA_VERSION}`, function () { test.meta[TEST_NAME] === 'impacted tests can pass normally') if (isEfd) { - assert.equal(impactedTests.length, NUM_RETRIES + 1) // Retries + original test + assert.strictEqual(impactedTests.length, NUM_RETRIES + 1) // Retries + original test } else { - assert.equal(impactedTests.length, 1) + assert.strictEqual(impactedTests.length, 1) } for (const impactedTest of impactedTests) { if (isModified) { - assert.propertyVal(impactedTest.meta, TEST_IS_MODIFIED, 'true') + assert.strictEqual(impactedTest.meta[TEST_IS_MODIFIED], 'true') } else { - assert.notProperty(impactedTest.meta, TEST_IS_MODIFIED) + assert.ok(!Object.hasOwn(impactedTest.meta, TEST_IS_MODIFIED)) } if (isNew) { - assert.propertyVal(impactedTest.meta, TEST_IS_NEW, 'true') + assert.strictEqual(impactedTest.meta[TEST_IS_NEW], 'true') } else { - assert.notProperty(impactedTest.meta, TEST_IS_NEW) + assert.ok(!Object.hasOwn(impactedTest.meta, TEST_IS_NEW)) } } @@ -4321,7 +4278,7 @@ describe(`mocha@${MOCHA_VERSION}`, function () { test => test.meta[TEST_IS_RETRY] === 'true' && test.meta[TEST_NAME] === 'impacted tests can pass normally' ) - assert.equal(retriedTests.length, NUM_RETRIES) + assert.strictEqual(retriedTests.length, NUM_RETRIES) let retriedTestNew = 0 let retriedTestsWithReason = 0 retriedTests.forEach(test => { @@ -4332,8 +4289,8 @@ describe(`mocha@${MOCHA_VERSION}`, function () { retriedTestsWithReason++ } }) - assert.equal(retriedTestNew, isNew ? NUM_RETRIES : 0) - assert.equal(retriedTestsWithReason, NUM_RETRIES) + assert.strictEqual(retriedTestNew, isNew ? NUM_RETRIES : 0) + assert.strictEqual(retriedTestsWithReason, NUM_RETRIES) } }) @@ -4435,19 +4392,19 @@ describe(`mocha@${MOCHA_VERSION}`, function () { const events = payloads.flatMap(({ payload }) => payload.events) const tests = events.filter(event => event.type === 'test').map(event => event.content) if (MOCHA_VERSION === 'latest') { - assert.equal(tests.length, 3) + assert.strictEqual(tests.length, 3) const failedTests = tests.filter(test => test.meta[TEST_STATUS] === 'fail') - assert.equal(failedTests.length, 2) + assert.strictEqual(failedTests.length, 2) const passedTests = tests.filter(test => test.meta[TEST_STATUS] === 'pass') - assert.equal(passedTests.length, 1) + assert.strictEqual(passedTests.length, 1) const [passedTest] = passedTests - assert.equal(passedTest.meta[TEST_IS_RETRY], 'true') + assert.strictEqual(passedTest.meta[TEST_IS_RETRY], 'true') } else { // there's no `retry` handled so it's just reported as a single passed test event // because the test ends up passing after retries - assert.equal(tests.length, 1) + assert.strictEqual(tests.length, 1) const passedTests = tests.filter(test => test.meta[TEST_STATUS] === 'pass') - assert.equal(passedTests.length, 1) + assert.strictEqual(passedTests.length, 1) } }) diff --git a/integration-tests/openfeature/openfeature-exposure-events.spec.js b/integration-tests/openfeature/openfeature-exposure-events.spec.js index 2dd06260870..dc445ea1627 100644 --- a/integration-tests/openfeature/openfeature-exposure-events.spec.js +++ b/integration-tests/openfeature/openfeature-exposure-events.spec.js @@ -1,28 +1,29 @@ 'use strict' +const assert = require('node:assert/strict') + const { sandboxCwd, useSandbox, FakeAgent, spawnProc } = require('../helpers') const path = require('path') -const { assert } = require('chai') const { UNACKNOWLEDGED, ACKNOWLEDGED } = require('../../packages/dd-trace/src/remote_config/apply_states') const ufcPayloads = require('./fixtures/ufc-payloads') const RC_PRODUCT = 'FFE_FLAGS' // Helper function to check exposure event structure function validateExposureEvent (event, expectedFlag, expectedUser, expectedAttributes = {}) { - assert.property(event, 'timestamp') - assert.property(event, 'flag') - assert.property(event, 'variant') - assert.property(event, 'subject') + assert.ok(Object.hasOwn(event, 'timestamp')) + assert.ok(Object.hasOwn(event, 'flag')) + assert.ok(Object.hasOwn(event, 'variant')) + assert.ok(Object.hasOwn(event, 'subject')) - assert.equal(event.flag.key, expectedFlag) - assert.equal(event.subject.id, expectedUser) + assert.strictEqual(event.flag.key, expectedFlag) + assert.strictEqual(event.subject.id, expectedUser) if (Object.keys(expectedAttributes).length > 0) { - assert.deepEqual(event.subject.attributes, expectedAttributes) + assert.deepStrictEqual(event.subject.attributes, expectedAttributes) } - assert.isNumber(event.timestamp) - assert.isTrue(Date.now() - event.timestamp < 10000) // Within last 10 seconds + assert.strictEqual(typeof event.timestamp, 'number') + assert.strictEqual(Date.now() - event.timestamp < 10000, true) // Within last 10 seconds } describe('OpenFeature Remote Config and Exposure Events Integration', () => { @@ -73,21 +74,21 @@ describe('OpenFeature Remote Config and Exposure Events Integration', () => { // Listen for exposure events agent.on('exposures', ({ payload, headers }) => { - assert.property(payload, 'context') - assert.property(payload, 'exposures') - assert.equal(payload.context.service, 'ffe-test-service') - assert.equal(payload.context.version, '1.2.3') - assert.equal(payload.context.env, 'test') + assert.ok(Object.hasOwn(payload, 'context')) + assert.ok(Object.hasOwn(payload, 'exposures')) + assert.strictEqual(payload.context.service, 'ffe-test-service') + assert.strictEqual(payload.context.version, '1.2.3') + assert.strictEqual(payload.context.env, 'test') exposureEvents.push(...payload.exposures) if (exposureEvents.length === 2) { try { - assert.equal(headers['content-type'], 'application/json') - assert.equal(headers['x-datadog-evp-subdomain'], 'event-platform-intake') + assert.strictEqual(headers['content-type'], 'application/json') + assert.strictEqual(headers['x-datadog-evp-subdomain'], 'event-platform-intake') // Verify we got exposure events from flag evaluations - assert.equal(exposureEvents.length, 2) + assert.strictEqual(exposureEvents.length, 2) const booleanEvent = exposureEvents.find(e => e.flag.key === 'test-boolean-flag') const stringEvent = exposureEvents.find(e => e.flag.key === 'test-string-flag') @@ -119,9 +120,9 @@ describe('OpenFeature Remote Config and Exposure Events Integration', () => { setTimeout(async () => { try { const response = await fetch(`${proc.url}/evaluate-flags`) - assert.equal(response.status, 200) + assert.strictEqual(response.status, 200) const data = await response.json() - assert.equal(data.evaluationsCompleted, 2) + assert.strictEqual(data.evaluationsCompleted, 2) // Trigger manual flush to send exposure events await fetch(`${proc.url}/flush`) @@ -157,30 +158,30 @@ describe('OpenFeature Remote Config and Exposure Events Integration', () => { const exposureEvents = [] agent.on('exposures', ({ payload }) => { - assert.property(payload, 'context') - assert.property(payload, 'exposures') - assert.equal(payload.context.service, 'ffe-test-service') - assert.equal(payload.context.version, '1.2.3') - assert.equal(payload.context.env, 'test') + assert.ok(Object.hasOwn(payload, 'context')) + assert.ok(Object.hasOwn(payload, 'exposures')) + assert.strictEqual(payload.context.service, 'ffe-test-service') + assert.strictEqual(payload.context.version, '1.2.3') + assert.strictEqual(payload.context.env, 'test') exposureEvents.push(...payload.exposures) if (exposureEvents.length >= 6) { try { - assert.equal(exposureEvents.length, 6) + assert.strictEqual(exposureEvents.length, 6) const booleanEvents = exposureEvents.filter(e => e.flag.key === 'test-boolean-flag') const stringEvents = exposureEvents.filter(e => e.flag.key === 'test-string-flag') - assert.equal(booleanEvents.length, 3) - assert.equal(stringEvents.length, 3) + assert.strictEqual(booleanEvents.length, 3) + assert.strictEqual(stringEvents.length, 3) // Verify different users const userIds = [...new Set(exposureEvents.map(e => e.subject.id))] - assert.equal(userIds.length, 3) - assert.include(userIds, 'user-1') - assert.include(userIds, 'user-2') - assert.include(userIds, 'user-3') + assert.strictEqual(userIds.length, 3) + assert.ok(userIds.includes('user-1')) + assert.ok(userIds.includes('user-2')) + assert.ok(userIds.includes('user-3')) done() } catch (error) { @@ -198,9 +199,9 @@ describe('OpenFeature Remote Config and Exposure Events Integration', () => { setTimeout(async () => { try { const response = await fetch(`${proc.url}/evaluate-multiple-flags`) - assert.equal(response.status, 200) + assert.strictEqual(response.status, 200) const data = await response.json() - assert.equal(data.evaluationsCompleted, 6) + assert.strictEqual(data.evaluationsCompleted, 6) // No manual flush - let automatic flush handle it (default 1s interval) } catch (error) { @@ -297,12 +298,12 @@ describe('OpenFeature Remote Config and Exposure Events Integration', () => { it('should handle disabled flagging provider gracefully', async () => { const response = await fetch(`${proc.url}/evaluate-flags`) - assert.equal(response.status, 200) + assert.strictEqual(response.status, 200) const data = await response.json() // When provider is disabled, it uses noop provider which returns default values - assert.equal(data.results.boolean, false) - assert.equal(data.results.string, 'default') - assert.equal(data.evaluationsCompleted, 2) + assert.strictEqual(data.results.boolean, false) + assert.strictEqual(data.results.string, 'default') + assert.strictEqual(data.evaluationsCompleted, 2) }) }) }) diff --git a/integration-tests/opentelemetry-logs.spec.js b/integration-tests/opentelemetry-logs.spec.js index c925155f653..0fd1dce5d8e 100644 --- a/integration-tests/opentelemetry-logs.spec.js +++ b/integration-tests/opentelemetry-logs.spec.js @@ -1,6 +1,6 @@ 'use strict' -const { assert } = require('chai') +const assert = require('node:assert/strict') const { useSandbox } = require('./helpers') const http = require('http') diff --git a/integration-tests/opentelemetry.spec.js b/integration-tests/opentelemetry.spec.js index f0817652ff2..eea739a24d5 100644 --- a/integration-tests/opentelemetry.spec.js +++ b/integration-tests/opentelemetry.spec.js @@ -1,9 +1,10 @@ 'use strict' +const assert = require('node:assert/strict') + const { FakeAgent, sandboxCwd, useSandbox } = require('./helpers') const { fork } = require('child_process') const { join } = require('path') -const { assert } = require('chai') const axios = require('axios') async function check (agent, proc, timeout, onMessage = () => { }, isMetrics) { @@ -386,13 +387,13 @@ describe('opentelemetry', () => { assert.strictEqual(trace.length, 3) // Should have expected span names and ordering - assert.isTrue(eachEqual(trace, ['web.request', 'otel-sub', 'dd-sub'], span => span.name)) + assert.strictEqual(eachEqual(trace, ['web.request', 'otel-sub', 'dd-sub'], span => span.name), true) // Should have matching trace ids assert.isTrue(allEqual(trace, span => span.trace_id.toString())) // Should have matching service names - assert.isTrue(allEqual(trace, span => span.service)) + assert.strictEqual(allEqual(trace, span => span.service), true) // Should have expected span parentage const [webSpan, otelSpan, ddSpan] = trace diff --git a/integration-tests/pino.spec.js b/integration-tests/pino.spec.js index 89f5b035dce..4282e0818ed 100644 --- a/integration-tests/pino.spec.js +++ b/integration-tests/pino.spec.js @@ -1,8 +1,9 @@ 'use strict' +const assert = require('node:assert/strict') + const { FakeAgent, spawnProc, sandboxCwd, useSandbox, curl, assertObjectContains } = require('./helpers') const path = require('path') -const { assert } = require('chai') const { once } = require('events') describe('pino test', () => { diff --git a/integration-tests/remote_config.spec.js b/integration-tests/remote_config.spec.js index cd519586800..50d478e8dd2 100644 --- a/integration-tests/remote_config.spec.js +++ b/integration-tests/remote_config.spec.js @@ -1,10 +1,10 @@ 'use strict' +const assert = require('node:assert/strict') + const { sandboxCwd, useSandbox, FakeAgent, spawnProc } = require('./helpers') const path = require('path') const Axios = require('axios') -const { assert } = require('chai') - describe('Remote config client id', () => { let axios, cwd, appFile @@ -42,7 +42,7 @@ describe('Remote config client id', () => { await axios.get('/') return agent.assertMessageReceived(({ payload }) => { - assert.exists(payload[0][0].meta['_dd.rc.client_id']) + assert.ok(payload[0][0].meta['_dd.rc.client_id'] != null) }) }) }) @@ -71,7 +71,7 @@ describe('Remote config client id', () => { await axios.get('/') return agent.assertMessageReceived(({ payload }) => { - assert.notExists(payload[0][0].meta['_dd.rc.client_id']) + assert.ok(payload[0][0].meta['_dd.rc.client_id'] == null) }) }) }) diff --git a/integration-tests/selenium/selenium.spec.js b/integration-tests/selenium/selenium.spec.js index 67d93b6ff92..66b68d67aef 100644 --- a/integration-tests/selenium/selenium.spec.js +++ b/integration-tests/selenium/selenium.spec.js @@ -1,9 +1,8 @@ 'use strict' -const { exec } = require('child_process') - -const { assert } = require('chai') +const assert = require('node:assert/strict') +const { exec } = require('child_process') const { sandboxCwd, useSandbox, @@ -84,14 +83,14 @@ versionRange.forEach(version => { .gatherPayloadsMaxTimeout(({ url }) => url.endsWith('/api/v2/citestcycle'), (payloads) => { const events = payloads.flatMap(({ payload }) => payload.events) const seleniumTest = events.find(event => event.type === 'test').content - assert.include(seleniumTest.meta, { + assert.ok(seleniumTest.meta.includes({ [TEST_BROWSER_DRIVER]: 'selenium', [TEST_BROWSER_NAME]: 'chrome', [TEST_TYPE]: 'browser', [TEST_IS_RUM_ACTIVE]: 'true' - }) - assert.property(seleniumTest.meta, TEST_BROWSER_VERSION) - assert.property(seleniumTest.meta, TEST_BROWSER_DRIVER_VERSION) + })) + assert.ok(Object.hasOwn(seleniumTest.meta, TEST_BROWSER_VERSION)) + assert.ok(Object.hasOwn(seleniumTest.meta, TEST_BROWSER_DRIVER_VERSION)) }) childProcess = exec( @@ -132,8 +131,8 @@ versionRange.forEach(version => { ) childProcess.on('exit', (code) => { - assert.equal(code, 0) - assert.notInclude(testOutput, 'InvalidArgumentError') + assert.strictEqual(code, 0) + assert.ok(!testOutput.includes('InvalidArgumentError')) done() }) diff --git a/integration-tests/startup.spec.js b/integration-tests/startup.spec.js index f4e63416e48..8fa8c98febd 100644 --- a/integration-tests/startup.spec.js +++ b/integration-tests/startup.spec.js @@ -1,5 +1,7 @@ 'use strict' +const assert = require('node:assert/strict') + const { FakeAgent, spawnProc, @@ -8,7 +10,6 @@ const { curlAndAssertMessage } = require('./helpers') const path = require('path') -const { assert } = require('chai') const semver = require('semver') const { inspect } = require('util') const fs = require('fs') @@ -64,12 +65,12 @@ execArgvs.forEach(({ execArgv, skip }) => { } }) return curlAndAssertMessage(agent, proc, ({ headers, payload }) => { - assert.propertyVal(headers, 'host', `127.0.0.1:${agent.port}`) - assert.isArray(payload) + assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.ok(Array.isArray(payload)) assert.strictEqual(payload.length, 1) - assert.isArray(payload[0]) + assert.ok(Array.isArray(payload[0])) assert.strictEqual(payload[0].length, 1) - assert.propertyVal(payload[0][0], 'name', 'web.request') + assert.strictEqual(payload[0][0]['name'], 'web.request') }) }) @@ -115,12 +116,12 @@ execArgvs.forEach(({ execArgv, skip }) => { } }) return curlAndAssertMessage(agent, proc, ({ headers, payload }) => { - assert.propertyVal(headers, 'host', `localhost:${agent.port}`) - assert.isArray(payload) + assert.strictEqual(headers['host'], `localhost:${agent.port}`) + assert.ok(Array.isArray(payload)) assert.strictEqual(payload.length, 1) - assert.isArray(payload[0]) + assert.ok(Array.isArray(payload[0])) assert.strictEqual(payload[0].length, 1) - assert.propertyVal(payload[0][0], 'name', 'web.request') + assert.strictEqual(payload[0][0]['name'], 'web.request') }) }) }) @@ -144,12 +145,12 @@ execArgvs.forEach(({ execArgv, skip }) => { } }) return curlAndAssertMessage(agent, proc, ({ headers, payload }) => { - assert.propertyVal(headers, 'host', `127.0.0.1:${agent.port}`) - assert.isArray(payload) + assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.ok(Array.isArray(payload)) assert.strictEqual(payload.length, 1) - assert.isArray(payload[0]) + assert.ok(Array.isArray(payload[0])) assert.strictEqual(payload[0].length, 1) - assert.propertyVal(payload[0][0], 'name', 'web.request') + assert.strictEqual(payload[0][0]['name'], 'web.request') }) }) @@ -162,12 +163,12 @@ execArgvs.forEach(({ execArgv, skip }) => { } }) return curlAndAssertMessage(agent, proc, ({ headers, payload }) => { - assert.propertyVal(headers, 'host', `localhost:${agent.port}`) - assert.isArray(payload) + assert.strictEqual(headers['host'], `localhost:${agent.port}`) + assert.ok(Array.isArray(payload)) assert.strictEqual(payload.length, 1) - assert.isArray(payload[0]) + assert.ok(Array.isArray(payload[0])) assert.strictEqual(payload[0].length, 1) - assert.propertyVal(payload[0][0], 'name', 'web.request') + assert.strictEqual(payload[0][0]['name'], 'web.request') }) }) }) @@ -190,12 +191,12 @@ execArgvs.forEach(({ execArgv, skip }) => { execArgv }) return curlAndAssertMessage(agent, proc, ({ headers, payload }) => { - assert.propertyVal(headers, 'host', '127.0.0.1:8126') - assert.isArray(payload) + assert.strictEqual(headers['host'], '127.0.0.1:8126') + assert.ok(Array.isArray(payload)) assert.strictEqual(payload.length, 1) - assert.isArray(payload[0]) + assert.ok(Array.isArray(payload[0])) assert.strictEqual(payload[0].length, 1) - assert.propertyVal(payload[0][0], 'name', 'web.request') + assert.strictEqual(payload[0][0]['name'], 'web.request') }) }) @@ -208,12 +209,12 @@ execArgvs.forEach(({ execArgv, skip }) => { } }) return curlAndAssertMessage(agent, proc, ({ headers, payload }) => { - assert.propertyVal(headers, 'host', '127.0.0.1:8126') - assert.isArray(payload) + assert.strictEqual(headers['host'], '127.0.0.1:8126') + assert.ok(Array.isArray(payload)) assert.strictEqual(payload.length, 1) - assert.isArray(payload[0]) + assert.ok(Array.isArray(payload[0])) assert.strictEqual(payload[0].length, 1) - assert.propertyVal(payload[0][0], 'name', 'web.request') + assert.strictEqual(payload[0][0]['name'], 'web.request') }) }) }) diff --git a/integration-tests/vitest/vitest.spec.js b/integration-tests/vitest/vitest.spec.js index e177be6d217..efb338f80a3 100644 --- a/integration-tests/vitest/vitest.spec.js +++ b/integration-tests/vitest/vitest.spec.js @@ -1,11 +1,12 @@ 'use strict' +const assert = require('node:assert/strict') + const { once } = require('node:events') const { exec, execSync } = require('child_process') const path = require('path') const fs = require('fs') - -const { assert } = require('chai') +const { assertObjectContains } = require('../helpers') const { sandboxCwd, @@ -115,7 +116,7 @@ versions.forEach((version) => { metadataDicts.forEach(metadata => { for (const testLevel of TEST_LEVEL_EVENT_TYPES) { - assert.equal(metadata[testLevel][TEST_SESSION_NAME], 'my-test-session') + assert.strictEqual(metadata[testLevel][TEST_SESSION_NAME], 'my-test-session') } }) @@ -124,39 +125,39 @@ versions.forEach((version) => { const testSessionEvent = events.find(event => event.type === 'test_session_end') if (poolConfig === 'threads') { - assert.equal(testSessionEvent.content.meta[VITEST_POOL], 'worker_threads') + assert.strictEqual(testSessionEvent.content.meta[VITEST_POOL], 'worker_threads') } else { - assert.equal(testSessionEvent.content.meta[VITEST_POOL], 'child_process') + assert.strictEqual(testSessionEvent.content.meta[VITEST_POOL], 'child_process') } const testModuleEvent = events.find(event => event.type === 'test_module_end') const testSuiteEvents = events.filter(event => event.type === 'test_suite_end') const testEvents = events.filter(event => event.type === 'test') - assert.include(testSessionEvent.content.resource, 'test_session.vitest run') - assert.equal(testSessionEvent.content.meta[TEST_STATUS], 'fail') - assert.include(testModuleEvent.content.resource, 'test_module.vitest run') - assert.equal(testModuleEvent.content.meta[TEST_STATUS], 'fail') - assert.equal(testSessionEvent.content.meta[TEST_TYPE], 'test') - assert.equal(testModuleEvent.content.meta[TEST_TYPE], 'test') + assert.ok(testSessionEvent.content.resource.includes('test_session.vitest run')) + assert.strictEqual(testSessionEvent.content.meta[TEST_STATUS], 'fail') + assert.ok(testModuleEvent.content.resource.includes('test_module.vitest run')) + assert.strictEqual(testModuleEvent.content.meta[TEST_STATUS], 'fail') + assert.strictEqual(testSessionEvent.content.meta[TEST_TYPE], 'test') + assert.strictEqual(testModuleEvent.content.meta[TEST_TYPE], 'test') const passedSuite = testSuiteEvents.find( suite => suite.content.resource === 'test_suite.ci-visibility/vitest-tests/test-visibility-passed-suite.mjs' ) - assert.equal(passedSuite.content.meta[TEST_STATUS], 'pass') + assert.strictEqual(passedSuite.content.meta[TEST_STATUS], 'pass') const failedSuite = testSuiteEvents.find( suite => suite.content.resource === 'test_suite.ci-visibility/vitest-tests/test-visibility-failed-suite.mjs' ) - assert.equal(failedSuite.content.meta[TEST_STATUS], 'fail') + assert.strictEqual(failedSuite.content.meta[TEST_STATUS], 'fail') const failedSuiteHooks = testSuiteEvents.find( suite => suite.content.resource === 'test_suite.ci-visibility/vitest-tests/test-visibility-failed-hooks.mjs' ) - assert.equal(failedSuiteHooks.content.meta[TEST_STATUS], 'fail') + assert.strictEqual(failedSuiteHooks.content.meta[TEST_STATUS], 'fail') assert.includeMembers(testEvents.map(test => test.content.resource), [ @@ -212,24 +213,22 @@ versions.forEach((version) => { testEvents.forEach(test => { // `threads` config will report directly. TODO: update this once we're testing vitest@>=4 if (poolConfig === 'forks') { - assert.equal(test.content.meta[TEST_IS_TEST_FRAMEWORK_WORKER], 'true') + assert.strictEqual(test.content.meta[TEST_IS_TEST_FRAMEWORK_WORKER], 'true') } - assert.equal(test.content.meta[TEST_COMMAND], 'vitest run') - assert.exists(test.content.metrics[DD_HOST_CPU_COUNT]) - assert.equal(test.content.meta[DD_TEST_IS_USER_PROVIDED_SERVICE], 'false') + assert.strictEqual(test.content.meta[TEST_COMMAND], 'vitest run') + assert.ok(test.content.metrics[DD_HOST_CPU_COUNT] != null) + assert.strictEqual(test.content.meta[DD_TEST_IS_USER_PROVIDED_SERVICE], 'false') }) testSuiteEvents.forEach(testSuite => { // `threads` config will report directly. TODO: update this once we're testing vitest@>=4 if (poolConfig === 'forks') { - assert.equal(testSuite.content.meta[TEST_IS_TEST_FRAMEWORK_WORKER], 'true') + assert.strictEqual(testSuite.content.meta[TEST_IS_TEST_FRAMEWORK_WORKER], 'true') } - assert.equal(testSuite.content.meta[TEST_COMMAND], 'vitest run') - assert.isTrue( - testSuite.content.meta[TEST_SOURCE_FILE].startsWith('ci-visibility/vitest-tests/test-visibility') - ) - assert.equal(testSuite.content.metrics[TEST_SOURCE_START], 1) - assert.exists(testSuite.content.metrics[DD_HOST_CPU_COUNT]) + assert.strictEqual(testSuite.content.meta[TEST_COMMAND], 'vitest run') + assert.strictEqual(testSuite.content.meta[TEST_SOURCE_FILE].startsWith('ci-visibility/vitest-tests/test-visibility'), true) + assert.strictEqual(testSuite.content.metrics[TEST_SOURCE_START], 1) + assert.ok(testSuite.content.metrics[DD_HOST_CPU_COUNT] != null) }) }) ]) @@ -252,7 +251,7 @@ versions.forEach((version) => { const events = payloads.flatMap(({ payload }) => payload.events) const testEvents = events.filter(event => event.type === 'test') - assert.equal(testEvents.length, 11) + assert.strictEqual(testEvents.length, 11) assert.includeMembers(testEvents.map(test => test.content.resource), [ 'ci-visibility/vitest-tests/flaky-test-retries.mjs.flaky test retries can retry tests that eventually pass', 'ci-visibility/vitest-tests/flaky-test-retries.mjs.flaky test retries can retry tests that eventually pass', @@ -273,11 +272,11 @@ versions.forEach((version) => { test => test.content.resource === 'ci-visibility/vitest-tests/flaky-test-retries.mjs.flaky test retries can retry tests that eventually pass' ) - assert.equal(eventuallyPassingTest.length, 4) - assert.equal(eventuallyPassingTest.filter(test => test.content.meta[TEST_STATUS] === 'fail').length, 3) - assert.equal(eventuallyPassingTest.filter(test => test.content.meta[TEST_STATUS] === 'pass').length, 1) - assert.equal(eventuallyPassingTest.filter(test => test.content.meta[TEST_IS_RETRY] === 'true').length, 3) - assert.equal(eventuallyPassingTest.filter(test => + assert.strictEqual(eventuallyPassingTest.length, 4) + assert.strictEqual(eventuallyPassingTest.filter(test => test.content.meta[TEST_STATUS] === 'fail').length, 3) + assert.strictEqual(eventuallyPassingTest.filter(test => test.content.meta[TEST_STATUS] === 'pass').length, 1) + assert.strictEqual(eventuallyPassingTest.filter(test => test.content.meta[TEST_IS_RETRY] === 'true').length, 3) + assert.strictEqual(eventuallyPassingTest.filter(test => test.content.meta[TEST_RETRY_REASON] === TEST_RETRY_REASON_TYPES.atr ).length, 3) @@ -285,11 +284,11 @@ versions.forEach((version) => { test => test.content.resource === 'ci-visibility/vitest-tests/flaky-test-retries.mjs.flaky test retries can retry tests that never pass' ) - assert.equal(neverPassingTest.length, 6) - assert.equal(neverPassingTest.filter(test => test.content.meta[TEST_STATUS] === 'fail').length, 6) - assert.equal(neverPassingTest.filter(test => test.content.meta[TEST_STATUS] === 'pass').length, 0) - assert.equal(neverPassingTest.filter(test => test.content.meta[TEST_IS_RETRY] === 'true').length, 5) - assert.equal(neverPassingTest.filter(test => + assert.strictEqual(neverPassingTest.length, 6) + assert.strictEqual(neverPassingTest.filter(test => test.content.meta[TEST_STATUS] === 'fail').length, 6) + assert.strictEqual(neverPassingTest.filter(test => test.content.meta[TEST_STATUS] === 'pass').length, 0) + assert.strictEqual(neverPassingTest.filter(test => test.content.meta[TEST_IS_RETRY] === 'true').length, 5) + assert.strictEqual(neverPassingTest.filter(test => test.content.meta[TEST_RETRY_REASON] === TEST_RETRY_REASON_TYPES.atr ).length, 5) }).then(() => done()).catch(done) @@ -323,13 +322,13 @@ versions.forEach((version) => { const events = payloads.flatMap(({ payload }) => payload.events) const testEvents = events.filter(event => event.type === 'test') - assert.equal(testEvents.length, 3) + assert.strictEqual(testEvents.length, 3) assert.includeMembers(testEvents.map(test => test.content.resource), [ 'ci-visibility/vitest-tests/flaky-test-retries.mjs.flaky test retries can retry tests that eventually pass', 'ci-visibility/vitest-tests/flaky-test-retries.mjs.flaky test retries can retry tests that never pass', 'ci-visibility/vitest-tests/flaky-test-retries.mjs.flaky test retries does not retry if unnecessary' ]) - assert.equal(testEvents.filter( + assert.strictEqual(testEvents.filter( test => test.content.meta[TEST_RETRY_REASON] === TEST_RETRY_REASON_TYPES.atr ).length, 0) }).then(() => done()).catch(done) @@ -364,7 +363,7 @@ versions.forEach((version) => { const events = payloads.flatMap(({ payload }) => payload.events) const testEvents = events.filter(event => event.type === 'test') - assert.equal(testEvents.length, 5) + assert.strictEqual(testEvents.length, 5) assert.includeMembers(testEvents.map(test => test.content.resource), [ 'ci-visibility/vitest-tests/flaky-test-retries.mjs.flaky test retries can retry tests that eventually pass', 'ci-visibility/vitest-tests/flaky-test-retries.mjs.flaky test retries can retry tests that eventually pass', @@ -372,7 +371,7 @@ versions.forEach((version) => { 'ci-visibility/vitest-tests/flaky-test-retries.mjs.flaky test retries can retry tests that never pass', 'ci-visibility/vitest-tests/flaky-test-retries.mjs.flaky test retries does not retry if unnecessary' ]) - assert.equal(testEvents.filter( + assert.strictEqual(testEvents.filter( test => test.content.meta[TEST_RETRY_REASON] === TEST_RETRY_REASON_TYPES.atr ).length, 2) }).then(() => done()).catch(done) @@ -400,8 +399,8 @@ versions.forEach((version) => { const test = events.find(event => event.type === 'test').content const testSuite = events.find(event => event.type === 'test_suite_end').content - assert.equal(test.meta[TEST_CODE_OWNERS], JSON.stringify(['@datadog-dd-trace-js'])) - assert.equal(testSuite.meta[TEST_CODE_OWNERS], JSON.stringify(['@datadog-dd-trace-js'])) + assert.strictEqual(test.meta[TEST_CODE_OWNERS], JSON.stringify(['@datadog-dd-trace-js'])) + assert.strictEqual(testSuite.meta[TEST_CODE_OWNERS], JSON.stringify(['@datadog-dd-trace-js'])) }, 25000) childProcess = exec( @@ -563,7 +562,7 @@ versions.forEach((version) => { const tests = events.filter(event => event.type === 'test').map(test => test.content) - assert.equal(tests.length, 14) + assert.strictEqual(tests.length, 14) assert.includeMembers(tests.map(test => test.meta[TEST_NAME]), [ 'early flake detection can retry tests that eventually pass', @@ -583,22 +582,22 @@ versions.forEach((version) => { ]) const newTests = tests.filter(test => test.meta[TEST_IS_NEW] === 'true') // 4 executions of the 3 new tests + 1 new skipped test (not retried) - assert.equal(newTests.length, 13) + assert.strictEqual(newTests.length, 13) const retriedTests = tests.filter(test => test.meta[TEST_IS_RETRY] === 'true') - assert.equal(retriedTests.length, 9) // 3 retries of the 3 new tests + assert.strictEqual(retriedTests.length, 9) // 3 retries of the 3 new tests retriedTests.forEach(test => { - assert.equal(test.meta[TEST_RETRY_REASON], TEST_RETRY_REASON_TYPES.efd) + assert.strictEqual(test.meta[TEST_RETRY_REASON], TEST_RETRY_REASON_TYPES.efd) }) // exit code should be 0 and test session should be reported as passed, // even though there are some failing executions const failedTests = tests.filter(test => test.meta[TEST_STATUS] === 'fail') - assert.equal(failedTests.length, 3) + assert.strictEqual(failedTests.length, 3) const testSessionEvent = events.find(event => event.type === 'test_session_end').content - assert.propertyVal(testSessionEvent.meta, TEST_STATUS, 'pass') - assert.propertyVal(testSessionEvent.meta, TEST_EARLY_FLAKE_ENABLED, 'true') + assert.strictEqual(testSessionEvent.meta[TEST_STATUS], 'pass') + assert.strictEqual(testSessionEvent.meta[TEST_EARLY_FLAKE_ENABLED], 'true') }) childProcess = exec( @@ -617,7 +616,7 @@ versions.forEach((version) => { childProcess.on('exit', (exitCode) => { eventsPromise.then(() => { - assert.equal(exitCode, 0) + assert.strictEqual(exitCode, 0) done() }).catch(done) }) @@ -651,7 +650,7 @@ versions.forEach((version) => { const tests = events.filter(event => event.type === 'test').map(test => test.content) - assert.equal(tests.length, 10) + assert.strictEqual(tests.length, 10) assert.includeMembers(tests.map(test => test.meta[TEST_NAME]), [ 'early flake detection can retry tests that eventually pass', @@ -667,18 +666,18 @@ versions.forEach((version) => { ]) const newTests = tests.filter(test => test.meta[TEST_IS_NEW] === 'true') // 4 executions of the 2 new tests + 1 new skipped test (not retried) - assert.equal(newTests.length, 9) + assert.strictEqual(newTests.length, 9) const retriedTests = tests.filter(test => test.meta[TEST_IS_RETRY] === 'true') - assert.equal(retriedTests.length, 6) // 3 retries of the 2 new tests + assert.strictEqual(retriedTests.length, 6) // 3 retries of the 2 new tests // the multiple attempts did not result in a single pass, // so the test session should be reported as failed const failedTests = tests.filter(test => test.meta[TEST_STATUS] === 'fail') - assert.equal(failedTests.length, 6) + assert.strictEqual(failedTests.length, 6) const testSessionEvent = events.find(event => event.type === 'test_session_end').content - assert.propertyVal(testSessionEvent.meta, TEST_STATUS, 'fail') - assert.propertyVal(testSessionEvent.meta, TEST_EARLY_FLAKE_ENABLED, 'true') + assert.strictEqual(testSessionEvent.meta[TEST_STATUS], 'fail') + assert.strictEqual(testSessionEvent.meta[TEST_EARLY_FLAKE_ENABLED], 'true') }) childProcess = exec( @@ -697,7 +696,7 @@ versions.forEach((version) => { childProcess.on('exit', (exitCode) => { eventsPromise.then(() => { - assert.equal(exitCode, 1) + assert.strictEqual(exitCode, 1) done() }).catch(done) }) @@ -724,16 +723,16 @@ versions.forEach((version) => { const events = payloads.flatMap(({ payload }) => payload.events) const testSession = events.find(event => event.type === 'test_session_end').content - assert.propertyVal(testSession.meta, TEST_EARLY_FLAKE_ABORT_REASON, 'faulty') + assert.strictEqual(testSession.meta[TEST_EARLY_FLAKE_ABORT_REASON], 'faulty') const tests = events.filter(event => event.type === 'test').map(event => event.content) - assert.equal(tests.length, 4) + assert.strictEqual(tests.length, 4) const newTests = tests.filter( test => test.meta[TEST_IS_NEW] === 'true' ) // no new tests - assert.equal(newTests.length, 0) + assert.strictEqual(newTests.length, 0) }) childProcess = exec( @@ -751,7 +750,7 @@ versions.forEach((version) => { childProcess.on('exit', (exitCode) => { eventsPromise.then(() => { - assert.equal(exitCode, 1) + assert.strictEqual(exitCode, 1) done() }).catch(done) }) @@ -785,7 +784,7 @@ versions.forEach((version) => { const tests = events.filter(event => event.type === 'test').map(test => test.content) - assert.equal(tests.length, 4) + assert.strictEqual(tests.length, 4) assert.includeMembers(tests.map(test => test.meta[TEST_NAME]), [ 'early flake detection can retry tests that eventually pass', @@ -796,15 +795,15 @@ versions.forEach((version) => { // new tests are detected but not retried const newTests = tests.filter(test => test.meta[TEST_IS_NEW] === 'true') - assert.equal(newTests.length, 3) + assert.strictEqual(newTests.length, 3) const retriedTests = tests.filter(test => test.meta[TEST_IS_RETRY] === 'true') - assert.equal(retriedTests.length, 0) + assert.strictEqual(retriedTests.length, 0) const failedTests = tests.filter(test => test.meta[TEST_STATUS] === 'fail') - assert.equal(failedTests.length, 1) + assert.strictEqual(failedTests.length, 1) const testSessionEvent = events.find(event => event.type === 'test_session_end').content - assert.equal(testSessionEvent.meta[TEST_STATUS], 'fail') + assert.strictEqual(testSessionEvent.meta[TEST_STATUS], 'fail') }) childProcess = exec( @@ -823,7 +822,7 @@ versions.forEach((version) => { childProcess.on('exit', (exitCode) => { eventsPromise.then(() => { - assert.equal(exitCode, 1) + assert.strictEqual(exitCode, 1) done() }).catch(done) }) @@ -849,7 +848,7 @@ versions.forEach((version) => { const tests = events.filter(event => event.type === 'test').map(test => test.content) - assert.equal(tests.length, 4) + assert.strictEqual(tests.length, 4) assert.includeMembers(tests.map(test => test.meta[TEST_NAME]), [ 'early flake detection can retry tests that eventually pass', @@ -858,15 +857,15 @@ versions.forEach((version) => { 'early flake detection does not retry if the test is skipped' ]) const newTests = tests.filter(test => test.meta[TEST_IS_NEW] === 'true') - assert.equal(newTests.length, 0) + assert.strictEqual(newTests.length, 0) const retriedTests = tests.filter(test => test.meta[TEST_IS_RETRY] === 'true') - assert.equal(retriedTests.length, 0) + assert.strictEqual(retriedTests.length, 0) const failedTests = tests.filter(test => test.meta[TEST_STATUS] === 'fail') - assert.equal(failedTests.length, 1) + assert.strictEqual(failedTests.length, 1) const testSessionEvent = events.find(event => event.type === 'test_session_end').content - assert.equal(testSessionEvent.meta[TEST_STATUS], 'fail') + assert.strictEqual(testSessionEvent.meta[TEST_STATUS], 'fail') }) childProcess = exec( @@ -884,7 +883,7 @@ versions.forEach((version) => { childProcess.on('exit', (exitCode) => { eventsPromise.then(() => { - assert.equal(exitCode, 1) + assert.strictEqual(exitCode, 1) done() }).catch(done) }) @@ -916,11 +915,11 @@ versions.forEach((version) => { const tests = events.filter(event => event.type === 'test').map(test => test.content) // no retries - assert.equal(tests.length, 1) + assert.strictEqual(tests.length, 1) - assert.propertyVal(tests[0].meta, TEST_SUITE, 'ci-visibility/subproject/vitest-test.mjs') + assert.strictEqual(tests[0].meta[TEST_SUITE], 'ci-visibility/subproject/vitest-test.mjs') // it's not considered new - assert.notProperty(tests[0].meta, TEST_IS_NEW) + assert.ok(!Object.hasOwn(tests[0].meta, TEST_IS_NEW)) }) childProcess = exec( @@ -938,7 +937,7 @@ versions.forEach((version) => { childProcess.on('exit', (exitCode) => { eventsPromise.then(() => { - assert.equal(exitCode, 0) + assert.strictEqual(exitCode, 0) done() }).catch(done) }) @@ -970,7 +969,7 @@ versions.forEach((version) => { const tests = events.filter(event => event.type === 'test').map(test => test.content) - assert.equal(tests.length, 8) + assert.strictEqual(tests.length, 8) assert.includeMembers(tests.map(test => test.meta[TEST_NAME]), [ 'early flake detection can retry tests that eventually pass', @@ -984,19 +983,19 @@ versions.forEach((version) => { ]) const newTests = tests.filter(test => test.meta[TEST_IS_NEW] === 'true') // all but one are considered new - assert.equal(newTests.length, 7) + assert.strictEqual(newTests.length, 7) const retriedTests = tests.filter(test => test.meta[TEST_IS_RETRY] === 'true') - assert.equal(retriedTests.length, 4) // 2 repetitions on 2 tests + assert.strictEqual(retriedTests.length, 4) // 2 repetitions on 2 tests // vitest reports the test as failed if any of the repetitions fail, so we'll follow that // TODO: we might want to improve this const failedTests = tests.filter(test => test.meta[TEST_STATUS] === 'fail') - assert.equal(failedTests.length, 3) + assert.strictEqual(failedTests.length, 3) const testSessionEvent = events.find(event => event.type === 'test_session_end').content - assert.propertyVal(testSessionEvent.meta, TEST_STATUS, 'fail') - assert.notProperty(testSessionEvent.meta, TEST_EARLY_FLAKE_ENABLED) + assert.strictEqual(testSessionEvent.meta[TEST_STATUS], 'fail') + assert.ok(!Object.hasOwn(testSessionEvent.meta, TEST_EARLY_FLAKE_ENABLED)) }) childProcess = exec( @@ -1015,7 +1014,7 @@ versions.forEach((version) => { childProcess.on('exit', (exitCode) => { eventsPromise.then(() => { - assert.equal(exitCode, 1) + assert.strictEqual(exitCode, 1) done() }).catch(done) }) @@ -1049,7 +1048,7 @@ versions.forEach((version) => { const tests = events.filter(event => event.type === 'test').map(test => test.content) - assert.equal(tests.length, 4) + assert.strictEqual(tests.length, 4) assert.includeMembers(tests.map(test => test.meta[TEST_NAME]), [ 'early flake detection can retry tests that eventually pass', @@ -1060,15 +1059,15 @@ versions.forEach((version) => { // new tests are not detected and not retried const newTests = tests.filter(test => test.meta[TEST_IS_NEW] === 'true') - assert.equal(newTests.length, 0) + assert.strictEqual(newTests.length, 0) const retriedTests = tests.filter(test => test.meta[TEST_IS_RETRY] === 'true') - assert.equal(retriedTests.length, 0) + assert.strictEqual(retriedTests.length, 0) const failedTests = tests.filter(test => test.meta[TEST_STATUS] === 'fail') - assert.equal(failedTests.length, 1) + assert.strictEqual(failedTests.length, 1) const testSessionEvent = events.find(event => event.type === 'test_session_end').content - assert.equal(testSessionEvent.meta[TEST_STATUS], 'fail') + assert.strictEqual(testSessionEvent.meta[TEST_STATUS], 'fail') }) childProcess = exec( @@ -1086,7 +1085,7 @@ versions.forEach((version) => { childProcess.on('exit', (exitCode) => { eventsPromise.then(() => { - assert.equal(exitCode, 1) + assert.strictEqual(exitCode, 1) done() }).catch(done) }) @@ -1109,16 +1108,16 @@ versions.forEach((version) => { const events = payloads.flatMap(({ payload }) => payload.events) const testSession = events.find(event => event.type === 'test_session_end').content - assert.propertyVal(testSession.meta, TEST_EARLY_FLAKE_ABORT_REASON, 'faulty') + assert.strictEqual(testSession.meta[TEST_EARLY_FLAKE_ABORT_REASON], 'faulty') const tests = events.filter(event => event.type === 'test').map(event => event.content) - assert.equal(tests.length, 4) + assert.strictEqual(tests.length, 4) const newTests = tests.filter( test => test.meta[TEST_IS_NEW] === 'true' ) // no new tests - assert.equal(newTests.length, 0) + assert.strictEqual(newTests.length, 0) }) childProcess = exec( @@ -1156,7 +1155,7 @@ versions.forEach((version) => { const tests = events.filter(event => event.type === 'test').map(event => event.content) const retriedTests = tests.filter(test => test.meta[TEST_IS_RETRY] === 'true') - assert.equal(retriedTests.length, 1) + assert.strictEqual(retriedTests.length, 1) const [retriedTest] = retriedTests const hasDebugTags = Object.keys(retriedTest.meta) @@ -1164,7 +1163,7 @@ versions.forEach((version) => { property.startsWith(DI_DEBUG_ERROR_PREFIX) || property === DI_ERROR_DEBUG_INFO_CAPTURED ) - assert.isFalse(hasDebugTags) + assert.strictEqual(hasDebugTags, false) }) const logsPromise = receiver @@ -1208,14 +1207,14 @@ versions.forEach((version) => { const tests = events.filter(event => event.type === 'test').map(event => event.content) const retriedTests = tests.filter(test => test.meta[TEST_IS_RETRY] === 'true') - assert.equal(retriedTests.length, 1) + assert.strictEqual(retriedTests.length, 1) const [retriedTest] = retriedTests const hasDebugTags = Object.keys(retriedTest.meta) .some(property => property.startsWith(DI_DEBUG_ERROR_PREFIX) || property === DI_ERROR_DEBUG_INFO_CAPTURED ) - assert.isFalse(hasDebugTags) + assert.strictEqual(hasDebugTags, false) }) const logsPromise = receiver @@ -1261,19 +1260,17 @@ versions.forEach((version) => { const tests = events.filter(event => event.type === 'test').map(event => event.content) const retriedTests = tests.filter(test => test.meta[TEST_IS_RETRY] === 'true') - assert.equal(retriedTests.length, 1) + assert.strictEqual(retriedTests.length, 1) const [retriedTest] = retriedTests - assert.propertyVal(retriedTest.meta, DI_ERROR_DEBUG_INFO_CAPTURED, 'true') + assert.strictEqual(retriedTest.meta[DI_ERROR_DEBUG_INFO_CAPTURED], 'true') - assert.isTrue( - retriedTest.meta[`${DI_DEBUG_ERROR_PREFIX}.0.${DI_DEBUG_ERROR_FILE_SUFFIX}`] - .endsWith('ci-visibility/vitest-tests/bad-sum.mjs') - ) - assert.equal(retriedTest.metrics[`${DI_DEBUG_ERROR_PREFIX}.0.${DI_DEBUG_ERROR_LINE_SUFFIX}`], 4) + assert.strictEqual(retriedTest.meta[`${DI_DEBUG_ERROR_PREFIX}.0.${DI_DEBUG_ERROR_FILE_SUFFIX}`] + .endsWith('ci-visibility/vitest-tests/bad-sum.mjs'), true) + assert.strictEqual(retriedTest.metrics[`${DI_DEBUG_ERROR_PREFIX}.0.${DI_DEBUG_ERROR_LINE_SUFFIX}`], 4) const snapshotIdKey = `${DI_DEBUG_ERROR_PREFIX}.0.${DI_DEBUG_ERROR_SNAPSHOT_ID_SUFFIX}` - assert.exists(retriedTest.meta[snapshotIdKey]) + assert.ok(retriedTest.meta[snapshotIdKey] != null) snapshotIdByTest = retriedTest.meta[snapshotIdKey] spanIdByTest = retriedTest.span_id.toString() @@ -1281,19 +1278,19 @@ versions.forEach((version) => { const notRetriedTest = tests.find(test => test.meta[TEST_NAME].includes('is not retried')) - assert.notProperty(notRetriedTest.meta, DI_ERROR_DEBUG_INFO_CAPTURED) + assert.ok(!Object.hasOwn(notRetriedTest.meta, DI_ERROR_DEBUG_INFO_CAPTURED)) }) const logsPromise = receiver .gatherPayloadsMaxTimeout(({ url }) => url.endsWith('/api/v2/logs'), (payloads) => { const [{ logMessage: [diLog] }] = payloads - assert.deepInclude(diLog, { + assertObjectContains(diLog, { ddsource: 'dd_debugger', level: 'error' }) - assert.include(diLog.ddtags, 'git.repository_url:') - assert.include(diLog.ddtags, 'git.commit.sha:') - assert.equal(diLog.debugger.snapshot.language, 'javascript') + assert.ok(diLog.ddtags.includes('git.repository_url:')) + assert.ok(diLog.ddtags.includes('git.commit.sha:')) + assert.strictEqual(diLog.debugger.snapshot.language, 'javascript') assert.deepInclude(diLog.debugger.snapshot.captures.lines['4'].locals, { a: { type: 'number', @@ -1328,9 +1325,9 @@ versions.forEach((version) => { childProcess.on('exit', () => { Promise.all([eventsPromise, logsPromise]).then(() => { - assert.equal(snapshotIdByTest, snapshotIdByLog) - assert.equal(spanIdByTest, spanIdByLog) - assert.equal(traceIdByTest, traceIdByLog) + assert.strictEqual(snapshotIdByTest, snapshotIdByLog) + assert.strictEqual(spanIdByTest, spanIdByLog) + assert.strictEqual(traceIdByTest, traceIdByLog) done() }).catch(done) }) @@ -1349,7 +1346,7 @@ versions.forEach((version) => { const tests = events.filter(event => event.type === 'test').map(event => event.content) const retriedTests = tests.filter(test => test.meta[TEST_IS_RETRY] === 'true') - assert.equal(retriedTests.length, 1) + assert.strictEqual(retriedTests.length, 1) const [retriedTest] = retriedTests const hasDebugTags = Object.keys(retriedTest.meta) @@ -1357,7 +1354,7 @@ versions.forEach((version) => { property.startsWith(DI_DEBUG_ERROR_PREFIX) || property === DI_ERROR_DEBUG_INFO_CAPTURED ) - assert.isFalse(hasDebugTags) + assert.strictEqual(hasDebugTags, false) }) const logsPromise = receiver @@ -1415,7 +1412,7 @@ versions.forEach((version) => { const tests = events.filter(event => event.type === 'test').map(test => test.content) - assert.equal(tests.length, 4) + assert.strictEqual(tests.length, 4) assert.includeMembers(tests.map(test => test.meta[TEST_NAME]), [ 'early flake detection can retry tests that eventually pass', @@ -1425,17 +1422,17 @@ versions.forEach((version) => { ]) const newTests = tests.filter(test => test.meta[TEST_IS_NEW] === 'true') // all but one are considered new - assert.equal(newTests.length, 3) + assert.strictEqual(newTests.length, 3) const retriedTests = tests.filter(test => test.meta[TEST_IS_RETRY] === 'true') - assert.equal(retriedTests.length, 0) + assert.strictEqual(retriedTests.length, 0) const failedTests = tests.filter(test => test.meta[TEST_STATUS] === 'fail') - assert.equal(failedTests.length, 1) + assert.strictEqual(failedTests.length, 1) const testSessionEvent = events.find(event => event.type === 'test_session_end').content - assert.propertyVal(testSessionEvent.meta, TEST_STATUS, 'fail') - assert.notProperty(testSessionEvent.meta, TEST_EARLY_FLAKE_ENABLED) + assert.strictEqual(testSessionEvent.meta[TEST_STATUS], 'fail') + assert.ok(!Object.hasOwn(testSessionEvent.meta, TEST_EARLY_FLAKE_ENABLED)) }) childProcess = exec( @@ -1453,7 +1450,7 @@ versions.forEach((version) => { childProcess.on('exit', (exitCode) => { eventsPromise.then(() => { - assert.equal(exitCode, 1) + assert.strictEqual(exitCode, 1) done() }).catch(done) }) @@ -1467,7 +1464,7 @@ versions.forEach((version) => { const tests = events.filter(event => event.type === 'test').map(test => test.content) tests.forEach(test => { - assert.equal(test.meta[DD_TEST_IS_USER_PROVIDED_SERVICE], 'true') + assert.strictEqual(test.meta[DD_TEST_IS_USER_PROVIDED_SERVICE], 'true') }) }) @@ -1487,7 +1484,7 @@ versions.forEach((version) => { childProcess.on('exit', (exitCode) => { eventsPromise.then(() => { - assert.equal(exitCode, 1) + assert.strictEqual(exitCode, 1) done() }).catch(done) }) @@ -1528,9 +1525,9 @@ versions.forEach((version) => { const testSession = events.find(event => event.type === 'test_session_end').content if (isAttemptingToFix) { - assert.propertyVal(testSession.meta, TEST_MANAGEMENT_ENABLED, 'true') + assert.strictEqual(testSession.meta[TEST_MANAGEMENT_ENABLED], 'true') } else { - assert.notProperty(testSession.meta, TEST_MANAGEMENT_ENABLED) + assert.ok(!Object.hasOwn(testSession.meta, TEST_MANAGEMENT_ENABLED)) } const resourceNames = tests.map(span => span.resource) @@ -1550,35 +1547,35 @@ versions.forEach((version) => { const isLastAttempt = i === attemptedToFixTests.length - 1 const test = attemptedToFixTests[i] if (isQuarantining) { - assert.propertyVal(test.meta, TEST_MANAGEMENT_IS_QUARANTINED, 'true') + assert.strictEqual(test.meta[TEST_MANAGEMENT_IS_QUARANTINED], 'true') } else if (isDisabling) { - assert.propertyVal(test.meta, TEST_MANAGEMENT_IS_DISABLED, 'true') + assert.strictEqual(test.meta[TEST_MANAGEMENT_IS_DISABLED], 'true') } if (isAttemptingToFix) { - assert.propertyVal(test.meta, TEST_MANAGEMENT_IS_ATTEMPT_TO_FIX, 'true') + assert.strictEqual(test.meta[TEST_MANAGEMENT_IS_ATTEMPT_TO_FIX], 'true') if (isFirstAttempt) { - assert.notProperty(test.meta, TEST_IS_RETRY) - assert.notProperty(test.meta, TEST_RETRY_REASON) + assert.ok(!Object.hasOwn(test.meta, TEST_IS_RETRY)) + assert.ok(!Object.hasOwn(test.meta, TEST_RETRY_REASON)) continue } - assert.propertyVal(test.meta, TEST_IS_RETRY, 'true') - assert.propertyVal(test.meta, TEST_RETRY_REASON, TEST_RETRY_REASON_TYPES.atf) + assert.strictEqual(test.meta[TEST_IS_RETRY], 'true') + assert.strictEqual(test.meta[TEST_RETRY_REASON], TEST_RETRY_REASON_TYPES.atf) if (isLastAttempt) { if (shouldAlwaysPass) { - assert.propertyVal(test.meta, TEST_MANAGEMENT_ATTEMPT_TO_FIX_PASSED, 'true') + assert.strictEqual(test.meta[TEST_MANAGEMENT_ATTEMPT_TO_FIX_PASSED], 'true') } else if (shouldFailSometimes) { - assert.propertyVal(test.meta, TEST_MANAGEMENT_ATTEMPT_TO_FIX_PASSED, 'false') - assert.notProperty(test.meta, TEST_HAS_FAILED_ALL_RETRIES) + assert.strictEqual(test.meta[TEST_MANAGEMENT_ATTEMPT_TO_FIX_PASSED], 'false') + assert.ok(!Object.hasOwn(test.meta, TEST_HAS_FAILED_ALL_RETRIES)) } else { - assert.propertyVal(test.meta, TEST_HAS_FAILED_ALL_RETRIES, 'true') - assert.propertyVal(test.meta, TEST_MANAGEMENT_ATTEMPT_TO_FIX_PASSED, 'false') + assert.strictEqual(test.meta[TEST_HAS_FAILED_ALL_RETRIES], 'true') + assert.strictEqual(test.meta[TEST_MANAGEMENT_ATTEMPT_TO_FIX_PASSED], 'false') } } } else { - assert.notProperty(test.meta, TEST_MANAGEMENT_IS_ATTEMPT_TO_FIX) - assert.notProperty(test.meta, TEST_IS_RETRY) - assert.notProperty(test.meta, TEST_RETRY_REASON) + assert.ok(!Object.hasOwn(test.meta, TEST_MANAGEMENT_IS_ATTEMPT_TO_FIX)) + assert.ok(!Object.hasOwn(test.meta, TEST_IS_RETRY)) + assert.ok(!Object.hasOwn(test.meta, TEST_RETRY_REASON)) } } }) @@ -1621,11 +1618,11 @@ versions.forEach((version) => { childProcess.on('exit', (exitCode) => { testAssertionsPromise.then(() => { - assert.include(stdout, 'I am running') + assert.ok(stdout.includes('I am running')) if (shouldAlwaysPass || (isAttemptingToFix && isQuarantining) || (isAttemptingToFix && isDisabling)) { - assert.equal(exitCode, 0) + assert.strictEqual(exitCode, 0) } else { - assert.equal(exitCode, 1) + assert.strictEqual(exitCode, 1) } done() }).catch(done) @@ -1731,14 +1728,14 @@ versions.forEach((version) => { .gatherPayloadsMaxTimeout(({ url }) => url === '/api/v2/citestcycle', payloads => { const events = payloads.flatMap(({ payload }) => payload.events) const tests = events.filter(event => event.type === 'test').map(event => event.content) - assert.equal(tests.length, 1) + assert.strictEqual(tests.length, 1) const testSession = events.find(event => event.type === 'test_session_end').content if (isDisabling) { - assert.propertyVal(testSession.meta, TEST_MANAGEMENT_ENABLED, 'true') + assert.strictEqual(testSession.meta[TEST_MANAGEMENT_ENABLED], 'true') } else { - assert.notProperty(testSession.meta, TEST_MANAGEMENT_ENABLED) + assert.ok(!Object.hasOwn(testSession.meta, TEST_MANAGEMENT_ENABLED)) } const resourceNames = tests.map(span => span.resource) @@ -1754,11 +1751,11 @@ versions.forEach((version) => { ) if (isDisabling) { - assert.equal(skippedTest.meta[TEST_STATUS], 'skip') - assert.propertyVal(skippedTest.meta, TEST_MANAGEMENT_IS_DISABLED, 'true') + assert.strictEqual(skippedTest.meta[TEST_STATUS], 'skip') + assert.strictEqual(skippedTest.meta[TEST_MANAGEMENT_IS_DISABLED], 'true') } else { - assert.equal(skippedTest.meta[TEST_STATUS], 'fail') - assert.notProperty(skippedTest.meta, TEST_MANAGEMENT_IS_DISABLED) + assert.strictEqual(skippedTest.meta[TEST_STATUS], 'fail') + assert.ok(!Object.hasOwn(skippedTest.meta, TEST_MANAGEMENT_IS_DISABLED)) } }) @@ -1787,11 +1784,11 @@ versions.forEach((version) => { childProcess.on('exit', (exitCode) => { testAssertionsPromise.then(() => { if (isDisabling) { - assert.notInclude(stdout, 'I am running') - assert.equal(exitCode, 0) + assert.ok(!stdout.includes('I am running')) + assert.strictEqual(exitCode, 0) } else { - assert.include(stdout, 'I am running') - assert.equal(exitCode, 1) + assert.ok(stdout.includes('I am running')) + assert.strictEqual(exitCode, 1) } done() }).catch(done) @@ -1841,14 +1838,14 @@ versions.forEach((version) => { .gatherPayloadsMaxTimeout(({ url }) => url === '/api/v2/citestcycle', payloads => { const events = payloads.flatMap(({ payload }) => payload.events) const tests = events.filter(event => event.type === 'test').map(event => event.content) - assert.equal(tests.length, 2) + assert.strictEqual(tests.length, 2) const testSession = events.find(event => event.type === 'test_session_end').content if (isQuarantining) { - assert.propertyVal(testSession.meta, TEST_MANAGEMENT_ENABLED, 'true') + assert.strictEqual(testSession.meta[TEST_MANAGEMENT_ENABLED], 'true') } else { - assert.notProperty(testSession.meta, TEST_MANAGEMENT_ENABLED) + assert.ok(!Object.hasOwn(testSession.meta, TEST_MANAGEMENT_ENABLED)) } const resourceNames = tests.map(span => span.resource) @@ -1866,11 +1863,11 @@ versions.forEach((version) => { if (isQuarantining) { // TODO: do not flip the status of the test but still ignore failures - assert.equal(quarantinedTest.meta[TEST_STATUS], 'pass') - assert.propertyVal(quarantinedTest.meta, TEST_MANAGEMENT_IS_QUARANTINED, 'true') + assert.strictEqual(quarantinedTest.meta[TEST_STATUS], 'pass') + assert.strictEqual(quarantinedTest.meta[TEST_MANAGEMENT_IS_QUARANTINED], 'true') } else { - assert.equal(quarantinedTest.meta[TEST_STATUS], 'fail') - assert.notProperty(quarantinedTest.meta, TEST_MANAGEMENT_IS_QUARANTINED) + assert.strictEqual(quarantinedTest.meta[TEST_STATUS], 'fail') + assert.ok(!Object.hasOwn(quarantinedTest.meta, TEST_MANAGEMENT_IS_QUARANTINED)) } }) @@ -1899,12 +1896,12 @@ versions.forEach((version) => { childProcess.on('exit', (exitCode) => { testAssertionsPromise.then(() => { // it runs regardless of the quarantine status - assert.include(stdout, 'I am running when quarantined') + assert.ok(stdout.includes('I am running when quarantined')) if (isQuarantining) { // exit code 0 even though one of the tests failed - assert.equal(exitCode, 0) + assert.strictEqual(exitCode, 0) } else { - assert.equal(exitCode, 1) + assert.strictEqual(exitCode, 1) } done() }).catch(done) @@ -1942,10 +1939,10 @@ versions.forEach((version) => { .gatherPayloadsMaxTimeout(({ url }) => url.endsWith('/api/v2/citestcycle'), (payloads) => { const events = payloads.flatMap(({ payload }) => payload.events) const testSession = events.find(event => event.type === 'test_session_end').content - assert.notProperty(testSession.meta, TEST_MANAGEMENT_ENABLED) + assert.ok(!Object.hasOwn(testSession.meta, TEST_MANAGEMENT_ENABLED)) const tests = events.filter(event => event.type === 'test').map(event => event.content) // it is not retried - assert.equal(tests.length, 1) + assert.strictEqual(tests.length, 1) }) childProcess = exec( @@ -1975,7 +1972,7 @@ versions.forEach((version) => { once(childProcess.stderr, 'end'), eventsPromise ]) - assert.include(testOutput, 'Test management tests could not be fetched') + assert.ok(testOutput.includes('Test management tests could not be fetched')) }) }) } @@ -1986,18 +1983,18 @@ versions.forEach((version) => { .gatherPayloadsMaxTimeout(({ url }) => url.endsWith('/api/v2/citestcycle'), payloads => { const metadataDicts = payloads.flatMap(({ payload }) => payload.metadata) - assert.isNotEmpty(metadataDicts) + assert.ok(metadataDicts.length > 0) metadataDicts.forEach(metadata => { - assert.equal(metadata.test[DD_CAPABILITIES_TEST_IMPACT_ANALYSIS], undefined) - assert.equal(metadata.test[DD_CAPABILITIES_EARLY_FLAKE_DETECTION], '1') - assert.equal(metadata.test[DD_CAPABILITIES_AUTO_TEST_RETRIES], '1') - assert.equal(metadata.test[DD_CAPABILITIES_IMPACTED_TESTS], '1') - assert.equal(metadata.test[DD_CAPABILITIES_TEST_MANAGEMENT_QUARANTINE], '1') - assert.equal(metadata.test[DD_CAPABILITIES_TEST_MANAGEMENT_DISABLE], '1') - assert.equal(metadata.test[DD_CAPABILITIES_TEST_MANAGEMENT_ATTEMPT_TO_FIX], '5') - assert.equal(metadata.test[DD_CAPABILITIES_FAILED_TEST_REPLAY], '1') + assert.strictEqual(metadata.test[DD_CAPABILITIES_TEST_IMPACT_ANALYSIS], undefined) + assert.strictEqual(metadata.test[DD_CAPABILITIES_EARLY_FLAKE_DETECTION], '1') + assert.strictEqual(metadata.test[DD_CAPABILITIES_AUTO_TEST_RETRIES], '1') + assert.strictEqual(metadata.test[DD_CAPABILITIES_IMPACTED_TESTS], '1') + assert.strictEqual(metadata.test[DD_CAPABILITIES_TEST_MANAGEMENT_QUARANTINE], '1') + assert.strictEqual(metadata.test[DD_CAPABILITIES_TEST_MANAGEMENT_DISABLE], '1') + assert.strictEqual(metadata.test[DD_CAPABILITIES_TEST_MANAGEMENT_ATTEMPT_TO_FIX], '5') + assert.strictEqual(metadata.test[DD_CAPABILITIES_FAILED_TEST_REPLAY], '1') // capabilities logic does not overwrite test session name - assert.equal(metadata.test[TEST_SESSION_NAME], 'my-test-session-name') + assert.strictEqual(metadata.test[TEST_SESSION_NAME], 'my-test-session-name') }) }) @@ -2041,7 +2038,7 @@ versions.forEach((version) => { `import { describe, test, expect } from 'vitest' describe('impacted test', () => { test('can impacted test', () => { - expect(1 + 2).to.equal(4) + assert.strictEqual(1 + 2, 4) }) })` ) @@ -2062,9 +2059,9 @@ versions.forEach((version) => { const testSession = events.find(event => event.type === 'test_session_end').content if (isEfd) { - assert.propertyVal(testSession.meta, TEST_EARLY_FLAKE_ENABLED, 'true') + assert.strictEqual(testSession.meta[TEST_EARLY_FLAKE_ENABLED], 'true') } else { - assert.notProperty(testSession.meta, TEST_EARLY_FLAKE_ENABLED) + assert.ok(!Object.hasOwn(testSession.meta, TEST_EARLY_FLAKE_ENABLED)) } const resourceNames = tests.map(span => span.resource) @@ -2080,27 +2077,27 @@ versions.forEach((version) => { test.meta[TEST_NAME] === 'impacted test can impacted test') if (isEfd) { - assert.equal(impactedTests.length, NUM_RETRIES_EFD + 1) // Retries + original test + assert.strictEqual(impactedTests.length, NUM_RETRIES_EFD + 1) // Retries + original test } else { - assert.equal(impactedTests.length, 1) + assert.strictEqual(impactedTests.length, 1) } for (const impactedTest of impactedTests) { if (isModified) { - assert.propertyVal(impactedTest.meta, TEST_IS_MODIFIED, 'true') + assert.strictEqual(impactedTest.meta[TEST_IS_MODIFIED], 'true') } else { - assert.notProperty(impactedTest.meta, TEST_IS_MODIFIED) + assert.ok(!Object.hasOwn(impactedTest.meta, TEST_IS_MODIFIED)) } if (isNew) { - assert.propertyVal(impactedTest.meta, TEST_IS_NEW, 'true') + assert.strictEqual(impactedTest.meta[TEST_IS_NEW], 'true') } else { - assert.notProperty(impactedTest.meta, TEST_IS_NEW) + assert.ok(!Object.hasOwn(impactedTest.meta, TEST_IS_NEW)) } } if (isEfd) { const retriedTests = tests.filter(test => test.meta[TEST_IS_RETRY] === 'true') - assert.equal(retriedTests.length, NUM_RETRIES_EFD) + assert.strictEqual(retriedTests.length, NUM_RETRIES_EFD) let retriedTestNew = 0 let retriedTestsWithReason = 0 retriedTests.forEach(test => { @@ -2111,8 +2108,8 @@ versions.forEach((version) => { retriedTestsWithReason++ } }) - assert.equal(retriedTestNew, isNew ? NUM_RETRIES_EFD : 0) - assert.equal(retriedTestsWithReason, NUM_RETRIES_EFD) + assert.strictEqual(retriedTestNew, isNew ? NUM_RETRIES_EFD : 0) + assert.strictEqual(retriedTestsWithReason, NUM_RETRIES_EFD) } }) @@ -2200,8 +2197,8 @@ versions.forEach((version) => { testOutput += chunk.toString() }) childProcess.on('exit', (code) => { - assert.include(testOutput, 'result 10') - assert.equal(code, 0) + assert.ok(testOutput.includes('result 10')) + assert.strictEqual(code, 0) done() }) }) @@ -2217,18 +2214,18 @@ versions.forEach((version) => { const testSuiteEvents = events.filter(event => event.type === 'test_suite_end') const testEvents = events.filter(event => event.type === 'test') - assert.equal(testSessionEvent.content.meta[TEST_STATUS], 'fail') - assert.equal(testModuleEvent.content.meta[TEST_STATUS], 'fail') - assert.equal(testSessionEvent.content.meta[TEST_TYPE], 'test') - assert.equal(testModuleEvent.content.meta[TEST_TYPE], 'test') + assert.strictEqual(testSessionEvent.content.meta[TEST_STATUS], 'fail') + assert.strictEqual(testModuleEvent.content.meta[TEST_STATUS], 'fail') + assert.strictEqual(testSessionEvent.content.meta[TEST_TYPE], 'test') + assert.strictEqual(testModuleEvent.content.meta[TEST_TYPE], 'test') const testSuite = testSuiteEvents.find( suite => suite.content.resource === 'test_suite.ci-visibility/vitest-tests-programmatic-api/test-programmatic-api.mjs' ) - assert.equal(testSuite.content.meta[TEST_STATUS], 'fail') + assert.strictEqual(testSuite.content.meta[TEST_STATUS], 'fail') - assert.equal(testEvents.length, 3) + assert.strictEqual(testEvents.length, 3) }) childProcess = exec( diff --git a/packages/datadog-instrumentations/test/body-parser.spec.js b/packages/datadog-instrumentations/test/body-parser.spec.js index 8c27282d1a8..c5572614872 100644 --- a/packages/datadog-instrumentations/test/body-parser.spec.js +++ b/packages/datadog-instrumentations/test/body-parser.spec.js @@ -3,7 +3,6 @@ const assert = require('node:assert/strict') const axios = require('axios') -const { expect } = require('chai') const dc = require('dc-polyfill') const { after, before, beforeEach, describe, it } = require('mocha') const sinon = require('sinon') @@ -72,7 +71,7 @@ withVersions('body-parser', 'body-parser', version => { const res = await axios.post(`http://localhost:${port}/`, { key: 'value' }) - expect(middlewareProcessBodyStub).not.to.be.called + sinon.assert.notCalled(middlewareProcessBodyStub) assert.strictEqual(res.data, 'BLOCKED') bodyParserReadCh.unsubscribe(blockRequest) diff --git a/packages/datadog-instrumentations/test/express-mongo-sanitize.spec.js b/packages/datadog-instrumentations/test/express-mongo-sanitize.spec.js index 371e3123f94..babfbfbaafd 100644 --- a/packages/datadog-instrumentations/test/express-mongo-sanitize.spec.js +++ b/packages/datadog-instrumentations/test/express-mongo-sanitize.spec.js @@ -103,8 +103,7 @@ describe('express-mongo-sanitize', () => { await axios.get(`http://localhost:${port}/?param=paramvalue`) sinon.assert.calledOnce(subscription) - expect(subscription.firstCall.args[0].sanitizedProperties) - .to.be.deep.equal(['body', 'params', 'headers', 'query']) + assert.deepStrictEqual(subscription.firstCall.args[0].sanitizedProperties, ['body', 'params', 'headers', 'query']) assert.strictEqual(subscription.firstCall.args[0].req.query.param, 'paramvalue') }) @@ -114,8 +113,7 @@ describe('express-mongo-sanitize', () => { await axios.get(`http://localhost:${port}/?param[$eq]=paramvalue`) sinon.assert.calledOnce(subscription) - expect(subscription.firstCall.args[0].sanitizedProperties) - .to.be.deep.equal(['body', 'params', 'headers', 'query']) + assert.deepStrictEqual(subscription.firstCall.args[0].sanitizedProperties, ['body', 'params', 'headers', 'query']) assert.strictEqual(subscription.firstCall.args[0].req.query.param.$eq, undefined) }) }) diff --git a/packages/datadog-instrumentations/test/express.spec.js b/packages/datadog-instrumentations/test/express.spec.js index 693e101dbb2..14cb03e0c56 100644 --- a/packages/datadog-instrumentations/test/express.spec.js +++ b/packages/datadog-instrumentations/test/express.spec.js @@ -3,7 +3,6 @@ const assert = require('node:assert/strict') const axios = require('axios') -const { expect } = require('chai') const dc = require('dc-polyfill') const { after, before, beforeEach, describe, it } = require('mocha') const semifies = require('semifies') @@ -70,7 +69,7 @@ withVersions('express', 'express', version => { const res = await axios.post(`http://localhost:${port}/`, { key: 'value' }) - expect(requestBody).not.to.be.called + sinon.assert.notCalled(requestBody) assert.strictEqual(res.data, 'BLOCKED') queryParserReadCh.unsubscribe(blockRequest) diff --git a/packages/datadog-instrumentations/test/helpers/check-require-cache.spec.js b/packages/datadog-instrumentations/test/helpers/check-require-cache.spec.js index 8431aa01102..e09615fa342 100644 --- a/packages/datadog-instrumentations/test/helpers/check-require-cache.spec.js +++ b/packages/datadog-instrumentations/test/helpers/check-require-cache.spec.js @@ -5,6 +5,7 @@ const { exec } = require('node:child_process') const { expect } = require('chai') const { describe, it } = require('mocha') +const { assertObjectContains } = require('../../../../integration-tests/helpers') describe('check-require-cache', () => { const opts = { @@ -25,7 +26,7 @@ describe('check-require-cache', () => { it('should find warnings when tracer loaded late', (done) => { exec(`${process.execPath} ./check-require-cache/bad-order.js`, opts, (error, stdout, stderr) => { assert.strictEqual(error, null) - expect(stderr).to.include("Package 'express' was loaded") + assertObjectContains(stderr, "Package 'express' was loaded") done() }) }) diff --git a/packages/datadog-instrumentations/test/helpers/router-helper.spec.js b/packages/datadog-instrumentations/test/helpers/router-helper.spec.js index 856bec2c837..5ef593d6169 100644 --- a/packages/datadog-instrumentations/test/helpers/router-helper.spec.js +++ b/packages/datadog-instrumentations/test/helpers/router-helper.spec.js @@ -2,10 +2,11 @@ const assert = require('node:assert/strict') -const { expect } = require('chai') const { afterEach, beforeEach, describe, it } = require('mocha') const { channel } = require('../../src/helpers/instrument') +const { assertObjectContains } = require('../../../../integration-tests/helpers') + const { joinPath, normalizeRoutePath, @@ -91,7 +92,7 @@ describe('helpers/router-helper', () => { }) it('should avoid duplicate slashes when base ends with slash', () => { - expect(joinPath('/^\\/regex(?:\\/|$)/', '/mounted')).to.equal('/^\\/regex(?:\\/|$)/mounted') + assert.strictEqual(joinPath('/^\\/regex(?:\\/|$)/', '/mounted'), '/^\\/regex(?:\\/|$)/mounted') }) it('should return null for path without leading slash (not accessible in Express)', () => { @@ -122,7 +123,7 @@ describe('helpers/router-helper', () => { setRouterMountPath(router, '/foo') setRouterMountPath(router, '/bar') - expect(getRouterMountPaths(router)).to.have.members(['/foo', '/bar']) + assertObjectContains(getRouterMountPaths(router), ['/foo', '/bar']) }) it('should avoid duplicate mount paths', () => { diff --git a/packages/datadog-instrumentations/test/multer.spec.js b/packages/datadog-instrumentations/test/multer.spec.js index 2f60d8f542d..c767664fc92 100644 --- a/packages/datadog-instrumentations/test/multer.spec.js +++ b/packages/datadog-instrumentations/test/multer.spec.js @@ -80,7 +80,7 @@ withVersions('multer', 'multer', version => { try { const res = await axios.post(`http://localhost:${port}/`, formData) - expect(middlewareProcessBodyStub).not.to.be.called + sinon.assert.notCalled(middlewareProcessBodyStub) assert.strictEqual(res.data, 'BLOCKED') } finally { multerReadCh.unsubscribe(blockRequest) diff --git a/packages/datadog-instrumentations/test/mysql2.spec.js b/packages/datadog-instrumentations/test/mysql2.spec.js index 74e1fe1db10..8c91f403a8b 100644 --- a/packages/datadog-instrumentations/test/mysql2.spec.js +++ b/packages/datadog-instrumentations/test/mysql2.spec.js @@ -1,19 +1,19 @@ 'use strict' -const { assert, expect } = require('chai') -const { describe, it, beforeEach, afterEach, before } = require('mocha') +const assert = require('node:assert/strict') +const { once } = require('node:events') + +const { afterEach, before, beforeEach, describe, it } = require('mocha') const semver = require('semver') const sinon = require('sinon') -const { once } = require('node:events') -const { channel } = require('../src/helpers/instrument') const agent = require('../../dd-trace/test/plugins/agent') const { withVersions } = require('../../dd-trace/test/setup/mocha') - +const { channel } = require('../src/helpers/instrument') describe('mysql2 instrumentation', () => { withVersions('mysql2', 'mysql2', version => { function abort ({ sql, abortController }) { - assert.isString(sql) + assert.strictEqual(typeof sql, 'string') const error = new Error('Test') abortController.abort(error) } @@ -76,7 +76,7 @@ describe('mysql2 instrumentation', () => { it('should abort the query on abortController.abort()', (done) => { startCh.subscribe(abort) const query = connection.query(sql, (err) => { - assert.propertyVal(err, 'message', 'Test') + assert.strictEqual(err['message'], 'Test') sinon.assert.notCalled(apmQueryStart) if (!shouldEmitEndAfterQueryAbort) done() @@ -88,7 +88,7 @@ describe('mysql2 instrumentation', () => { it('should work without abortController.abort()', (done) => { startCh.subscribe(noop) connection.query(sql, (err) => { - assert.isNull(err) + assert.strictEqual(err, null) sinon.assert.called(apmQueryStart) done() @@ -97,7 +97,7 @@ describe('mysql2 instrumentation', () => { it('should work without subscriptions', (done) => { connection.query(sql, (err) => { - assert.isNull(err) + assert.strictEqual(err, null) sinon.assert.called(apmQueryStart) done() @@ -112,7 +112,7 @@ describe('mysql2 instrumentation', () => { const query = connection.query(sql) query.on('error', (err) => { - assert.propertyVal(err, 'message', 'Test') + assert.strictEqual(err['message'], 'Test') sinon.assert.notCalled(apmQueryStart) if (!shouldEmitEndAfterQueryAbort) done() }) @@ -151,7 +151,7 @@ describe('mysql2 instrumentation', () => { it('should abort the query on abortController.abort()', (done) => { startCh.subscribe(abort) const query = mysql2.Connection.createQuery(sql, (err) => { - assert.propertyVal(err, 'message', 'Test') + assert.strictEqual(err['message'], 'Test') sinon.assert.notCalled(apmQueryStart) if (!shouldEmitEndAfterQueryAbort) done() @@ -165,7 +165,7 @@ describe('mysql2 instrumentation', () => { startCh.subscribe(noop) const query = mysql2.Connection.createQuery(sql, (err) => { - assert.isNull(err) + assert.strictEqual(err, null) sinon.assert.called(apmQueryStart) done() @@ -176,7 +176,7 @@ describe('mysql2 instrumentation', () => { it('should work without subscriptions', (done) => { const query = mysql2.Connection.createQuery(sql, (err) => { - assert.isNull(err) + assert.strictEqual(err, null) sinon.assert.called(apmQueryStart) done() @@ -192,7 +192,7 @@ describe('mysql2 instrumentation', () => { const query = mysql2.Connection.createQuery(sql, null, null, {}) query.on('error', (err) => { - assert.propertyVal(err, 'message', 'Test') + assert.strictEqual(err['message'], 'Test') sinon.assert.notCalled(apmQueryStart) if (!shouldEmitEndAfterQueryAbort) done() @@ -239,13 +239,13 @@ describe('mysql2 instrumentation', () => { const options = { sql } const commandExecute = connection.execute(options, (err) => { - assert.propertyVal(err, 'message', 'Test') + assert.strictEqual(err['message'], 'Test') sinon.assert.notCalled(apmQueryStart) done() }) - assert.equal(commandExecute.sql, options.sql) + assert.strictEqual(commandExecute.sql, options.sql) }) it('should work without abortController.abort()', (done) => { @@ -254,7 +254,7 @@ describe('mysql2 instrumentation', () => { const options = { sql } connection.execute(options, (err) => { - assert.isNull(err) + assert.strictEqual(err, null) sinon.assert.called(apmQueryStart) done() @@ -265,7 +265,7 @@ describe('mysql2 instrumentation', () => { const options = { sql } connection.execute(options, (err) => { - assert.isNull(err) + assert.strictEqual(err, null) sinon.assert.called(apmQueryStart) done() @@ -278,7 +278,7 @@ describe('mysql2 instrumentation', () => { startCh.subscribe(abort) connection.execute(sql, (err) => { - assert.propertyVal(err, 'message', 'Test') + assert.strictEqual(err['message'], 'Test') sinon.assert.notCalled(apmQueryStart) done() }) @@ -288,7 +288,7 @@ describe('mysql2 instrumentation', () => { startCh.subscribe(noop) connection.execute(sql, (err) => { - assert.isNull(err) + assert.strictEqual(err, null) sinon.assert.called(apmQueryStart) done() @@ -299,7 +299,7 @@ describe('mysql2 instrumentation', () => { const options = { sql } connection.execute(options, (err) => { - assert.isNull(err) + assert.strictEqual(err, null) sinon.assert.called(apmQueryStart) done() @@ -322,7 +322,7 @@ describe('mysql2 instrumentation', () => { it('should abort the query on abortController.abort()', (done) => { startCh.subscribe(abort) const query = pool.query({ sql }, (err) => { - assert.propertyVal(err, 'message', 'Test') + assert.strictEqual(err['message'], 'Test') sinon.assert.notCalled(apmQueryStart) if (!shouldEmitEndAfterQueryAbort) done() @@ -335,7 +335,7 @@ describe('mysql2 instrumentation', () => { startCh.subscribe(noop) pool.query({ sql }, (err) => { - assert.isNull(err) + assert.strictEqual(err, null) sinon.assert.called(apmQueryStart) done() @@ -344,7 +344,7 @@ describe('mysql2 instrumentation', () => { it('should work without subscriptions', (done) => { pool.query({ sql }, (err) => { - assert.isNull(err) + assert.strictEqual(err, null) sinon.assert.called(apmQueryStart) done() @@ -357,7 +357,7 @@ describe('mysql2 instrumentation', () => { startCh.subscribe(abort) const query = pool.query({ sql }) query.on('error', err => { - assert.propertyVal(err, 'message', 'Test') + assert.strictEqual(err['message'], 'Test') sinon.assert.notCalled(apmQueryStart) if (!shouldEmitEndAfterQueryAbort) done() }) @@ -379,7 +379,7 @@ describe('mysql2 instrumentation', () => { it('should work without subscriptions', (done) => { pool.query({ sql }, (err) => { - assert.isNull(err) + assert.strictEqual(err, null) sinon.assert.called(apmQueryStart) done() @@ -393,7 +393,7 @@ describe('mysql2 instrumentation', () => { it('should abort the query on abortController.abort()', (done) => { startCh.subscribe(abort) const query = pool.query(sql, (err) => { - assert.propertyVal(err, 'message', 'Test') + assert.strictEqual(err['message'], 'Test') sinon.assert.notCalled(apmQueryStart) if (!shouldEmitEndAfterQueryAbort) done() @@ -406,7 +406,7 @@ describe('mysql2 instrumentation', () => { startCh.subscribe(noop) pool.query(sql, (err) => { - assert.isNull(err) + assert.strictEqual(err, null) sinon.assert.called(apmQueryStart) done() @@ -415,7 +415,7 @@ describe('mysql2 instrumentation', () => { it('should work without subscriptions', (done) => { pool.query(sql, (err) => { - assert.isNull(err) + assert.strictEqual(err, null) sinon.assert.called(apmQueryStart) done() @@ -428,7 +428,7 @@ describe('mysql2 instrumentation', () => { startCh.subscribe(abort) const query = pool.query(sql) query.on('error', err => { - assert.propertyVal(err, 'message', 'Test') + assert.strictEqual(err['message'], 'Test') sinon.assert.notCalled(apmQueryStart) if (!shouldEmitEndAfterQueryAbort) done() }) @@ -440,18 +440,18 @@ describe('mysql2 instrumentation', () => { startCh.subscribe(noop) const query = pool.query(sql) - expect(query.listenerCount('error')).to.equal(0) + assert.strictEqual(query.listenerCount('error'), 0) await once(query, 'end') - expect(query.listenerCount('error')).to.equal(0) + assert.strictEqual(query.listenerCount('error'), 0) sinon.assert.called(apmQueryStart) }) it('should work without subscriptions', (done) => { pool.query(sql, (err) => { - assert.isNull(err) + assert.strictEqual(err, null) sinon.assert.called(apmQueryStart) done() @@ -467,7 +467,7 @@ describe('mysql2 instrumentation', () => { it('should abort the query on abortController.abort()', (done) => { startCh.subscribe(abort) pool.execute({ sql }, (err) => { - assert.propertyVal(err, 'message', 'Test') + assert.strictEqual(err['message'], 'Test') setTimeout(() => { sinon.assert.notCalled(apmQueryStart) @@ -480,7 +480,7 @@ describe('mysql2 instrumentation', () => { startCh.subscribe(noop) pool.execute({ sql }, (err) => { - assert.isNull(err) + assert.strictEqual(err, null) sinon.assert.called(apmQueryStart) done() @@ -489,7 +489,7 @@ describe('mysql2 instrumentation', () => { it('should work without subscriptions', (done) => { pool.execute({ sql }, (err) => { - assert.isNull(err) + assert.strictEqual(err, null) sinon.assert.called(apmQueryStart) done() @@ -503,7 +503,7 @@ describe('mysql2 instrumentation', () => { it('should abort the query on abortController.abort()', (done) => { startCh.subscribe(abort) pool.execute(sql, (err) => { - assert.propertyVal(err, 'message', 'Test') + assert.strictEqual(err['message'], 'Test') setTimeout(() => { sinon.assert.notCalled(apmQueryStart) @@ -516,7 +516,7 @@ describe('mysql2 instrumentation', () => { startCh.subscribe(noop) pool.execute(sql, (err) => { - assert.isNull(err) + assert.strictEqual(err, null) sinon.assert.called(apmQueryStart) done() @@ -525,7 +525,7 @@ describe('mysql2 instrumentation', () => { it('should work without subscriptions', (done) => { pool.execute(sql, (err) => { - assert.isNull(err) + assert.strictEqual(err, null) sinon.assert.called(apmQueryStart) done() @@ -568,7 +568,7 @@ describe('mysql2 instrumentation', () => { startCh.subscribe(abort) const namespace = poolCluster.of() namespace.query(sql, (err) => { - assert.propertyVal(err, 'message', 'Test') + assert.strictEqual(err['message'], 'Test') setTimeout(() => { sinon.assert.notCalled(apmQueryStart) @@ -582,7 +582,7 @@ describe('mysql2 instrumentation', () => { const namespace = poolCluster.of() namespace.query(sql, (err) => { - assert.isNull(err) + assert.strictEqual(err, null) sinon.assert.called(apmQueryStart) done() @@ -592,7 +592,7 @@ describe('mysql2 instrumentation', () => { it('should work without subscriptions', (done) => { const namespace = poolCluster.of() namespace.query(sql, (err) => { - assert.isNull(err) + assert.strictEqual(err, null) sinon.assert.called(apmQueryStart) done() @@ -605,7 +605,7 @@ describe('mysql2 instrumentation', () => { startCh.subscribe(abort) const namespace = poolCluster.of() namespace.query({ sql }, (err) => { - assert.propertyVal(err, 'message', 'Test') + assert.strictEqual(err['message'], 'Test') setTimeout(() => { sinon.assert.notCalled(apmQueryStart) @@ -619,7 +619,7 @@ describe('mysql2 instrumentation', () => { const namespace = poolCluster.of() namespace.query({ sql }, (err) => { - assert.isNull(err) + assert.strictEqual(err, null) sinon.assert.called(apmQueryStart) done() @@ -629,7 +629,7 @@ describe('mysql2 instrumentation', () => { it('should work without subscriptions', (done) => { const namespace = poolCluster.of() namespace.query({ sql }, (err) => { - assert.isNull(err) + assert.strictEqual(err, null) sinon.assert.called(apmQueryStart) done() @@ -645,7 +645,7 @@ describe('mysql2 instrumentation', () => { const namespace = poolCluster.of() namespace.execute(sql, (err) => { - assert.propertyVal(err, 'message', 'Test') + assert.strictEqual(err['message'], 'Test') setTimeout(() => { sinon.assert.notCalled(apmQueryStart) @@ -659,7 +659,7 @@ describe('mysql2 instrumentation', () => { const namespace = poolCluster.of() namespace.execute(sql, (err) => { - assert.isNull(err) + assert.strictEqual(err, null) sinon.assert.called(apmQueryStart) done() @@ -669,7 +669,7 @@ describe('mysql2 instrumentation', () => { it('should work without subscriptions', (done) => { const namespace = poolCluster.of() namespace.execute(sql, (err) => { - assert.isNull(err) + assert.strictEqual(err, null) sinon.assert.called(apmQueryStart) done() @@ -683,7 +683,7 @@ describe('mysql2 instrumentation', () => { const namespace = poolCluster.of() namespace.execute({ sql }, (err) => { - assert.propertyVal(err, 'message', 'Test') + assert.strictEqual(err['message'], 'Test') setTimeout(() => { sinon.assert.notCalled(apmQueryStart) @@ -697,7 +697,7 @@ describe('mysql2 instrumentation', () => { const namespace = poolCluster.of() namespace.execute({ sql }, (err) => { - assert.isNull(err) + assert.strictEqual(err, null) sinon.assert.called(apmQueryStart) done() @@ -707,7 +707,7 @@ describe('mysql2 instrumentation', () => { it('should work without subscriptions', (done) => { const namespace = poolCluster.of() namespace.execute({ sql }, (err) => { - assert.isNull(err) + assert.strictEqual(err, null) sinon.assert.called(apmQueryStart) done() diff --git a/packages/datadog-instrumentations/test/passport-http.spec.js b/packages/datadog-instrumentations/test/passport-http.spec.js index a3306073d55..8d8cd7121c6 100644 --- a/packages/datadog-instrumentations/test/passport-http.spec.js +++ b/packages/datadog-instrumentations/test/passport-http.spec.js @@ -118,7 +118,7 @@ withVersions('passport-http', 'passport-http', version => { }) assert.strictEqual(res.status, 500) - expect(subscriberStub).to.not.be.called + sinon.assert.notCalled(subscriberStub) }) it('should call subscriber with proper arguments on success', async () => { diff --git a/packages/datadog-instrumentations/test/passport-local.spec.js b/packages/datadog-instrumentations/test/passport-local.spec.js index 95aafdafc5b..77eeb8fe1b0 100644 --- a/packages/datadog-instrumentations/test/passport-local.spec.js +++ b/packages/datadog-instrumentations/test/passport-local.spec.js @@ -114,7 +114,7 @@ withVersions('passport-local', 'passport-local', version => { const res = await axios.post(`http://localhost:${port}/`, { username: 'error', password: '1234' }) assert.strictEqual(res.status, 500) - expect(subscriberStub).to.not.be.called + sinon.assert.notCalled(subscriberStub) }) it('should call subscriber with proper arguments on success', async () => { diff --git a/packages/datadog-instrumentations/test/pg.spec.js b/packages/datadog-instrumentations/test/pg.spec.js index 9f203aed364..1fd1d00ed19 100644 --- a/packages/datadog-instrumentations/test/pg.spec.js +++ b/packages/datadog-instrumentations/test/pg.spec.js @@ -1,10 +1,10 @@ 'use strict' +const assert = require('node:assert/strict') + const agent = require('../../dd-trace/test/plugins/agent') const { withVersions } = require('../../dd-trace/test/setup/mocha') const dc = require('dc-polyfill') -const { assert } = require('chai') - const clients = { pg: pg => pg.Client } @@ -73,7 +73,7 @@ describe('pg instrumentation', () => { queryClientStartChannel.subscribe(abortQuery) client.query('SELECT 1', (err) => { - assert.propertyVal(err, 'message', 'Test') + assert.strictEqual(err['message'], 'Test') done() }) }) @@ -90,7 +90,7 @@ describe('pg instrumentation', () => { try { await client.query('SELECT 1') } catch (err) { - assert.propertyVal(err, 'message', 'Test') + assert.strictEqual(err['message'], 'Test') return } @@ -119,7 +119,7 @@ describe('pg instrumentation', () => { client.query(query) query.on('error', err => { - assert.propertyVal(err, 'message', 'Test') + assert.strictEqual(err['message'], 'Test') done() }) @@ -144,7 +144,7 @@ describe('pg instrumentation', () => { const query = new Query('SELECT 1') query.callback = err => { - assert.propertyVal(err, 'message', 'Test') + assert.strictEqual(err['message'], 'Test') done() } @@ -167,7 +167,7 @@ describe('pg instrumentation', () => { const query = new Query('SELECT 1') client.query(query, err => { - assert.propertyVal(err, 'message', 'Test') + assert.strictEqual(err['message'], 'Test') done() }) }) @@ -211,7 +211,7 @@ describe('pg instrumentation', () => { queryPoolStartChannel.subscribe(abortQuery) pool.query('SELECT 1', (err) => { - assert.propertyVal(err, 'message', 'Test') + assert.strictEqual(err['message'], 'Test') done() }) }) @@ -228,7 +228,7 @@ describe('pg instrumentation', () => { try { await pool.query('SELECT 1') } catch (err) { - assert.propertyVal(err, 'message', 'Test') + assert.strictEqual(err['message'], 'Test') return } diff --git a/packages/datadog-plugin-ai/test/integration-test/client.spec.js b/packages/datadog-plugin-ai/test/integration-test/client.spec.js index 9374c61e5c9..ead28467b63 100644 --- a/packages/datadog-plugin-ai/test/integration-test/client.spec.js +++ b/packages/datadog-plugin-ai/test/integration-test/client.spec.js @@ -1,12 +1,13 @@ 'use strict' +const assert = require('node:assert/strict') + const { FakeAgent, sandboxCwd, useSandbox, spawnPluginIntegrationTestProc } = require('../../../../integration-tests/helpers') -const { assert } = require('chai') const semifies = require('semifies') const { withVersions } = require('../../../dd-trace/test/setup/mocha') @@ -41,8 +42,8 @@ describe('esm', () => { it('is instrumented', async () => { const res = agent.assertMessageReceived(({ headers, payload }) => { - assert.propertyVal(headers, 'host', `127.0.0.1:${agent.port}`) - assert.isArray(payload) + assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.ok(Array.isArray(payload)) // special check for ai spans for (const spans of payload) { diff --git a/packages/datadog-plugin-amqp10/test/integration-test/client.spec.js b/packages/datadog-plugin-amqp10/test/integration-test/client.spec.js index 50004d3c046..bcbea83d9cf 100644 --- a/packages/datadog-plugin-amqp10/test/integration-test/client.spec.js +++ b/packages/datadog-plugin-amqp10/test/integration-test/client.spec.js @@ -1,5 +1,7 @@ 'use strict' +const assert = require('node:assert/strict') + const { FakeAgent, sandboxCwd, @@ -8,8 +10,6 @@ const { spawnPluginIntegrationTestProc } = require('../../../../integration-tests/helpers') const { withVersions } = require('../../../dd-trace/test/setup/mocha') -const { assert } = require('chai') - describe('esm', () => { let agent let proc @@ -29,8 +29,8 @@ describe('esm', () => { it('is instrumented', async () => { const res = agent.assertMessageReceived(({ headers, payload }) => { - assert.propertyVal(headers, 'host', `127.0.0.1:${agent.port}`) - assert.isArray(payload) + assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.ok(Array.isArray(payload)) assert.strictEqual(checkSpansForServiceName(payload, 'amqp.send'), true) }) diff --git a/packages/datadog-plugin-amqplib/test/integration-test/client.spec.js b/packages/datadog-plugin-amqplib/test/integration-test/client.spec.js index a27ed520005..94bb52405b1 100644 --- a/packages/datadog-plugin-amqplib/test/integration-test/client.spec.js +++ b/packages/datadog-plugin-amqplib/test/integration-test/client.spec.js @@ -1,5 +1,7 @@ 'use strict' +const assert = require('node:assert/strict') + const { FakeAgent, checkSpansForServiceName, @@ -9,8 +11,6 @@ const { varySandbox } = require('../../../../integration-tests/helpers') const { withVersions } = require('../../../dd-trace/test/setup/mocha') -const { assert } = require('chai') - describe('esm', () => { let agent let proc @@ -37,8 +37,8 @@ describe('esm', () => { for (const variant of varySandbox.VARIANTS) { it(`is instrumented loaded with ${variant}`, async () => { const res = agent.assertMessageReceived(({ headers, payload }) => { - assert.propertyVal(headers, 'host', `127.0.0.1:${agent.port}`) - assert.isArray(payload) + assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.ok(Array.isArray(payload)) assert.strictEqual(checkSpansForServiceName(payload, 'amqp.command'), true) }) diff --git a/packages/datadog-plugin-anthropic/test/integration-test/client.spec.js b/packages/datadog-plugin-anthropic/test/integration-test/client.spec.js index c1c9cac7587..6e68d26d3ca 100644 --- a/packages/datadog-plugin-anthropic/test/integration-test/client.spec.js +++ b/packages/datadog-plugin-anthropic/test/integration-test/client.spec.js @@ -1,5 +1,7 @@ 'use strict' +const assert = require('node:assert/strict') + const { FakeAgent, sandboxCwd, @@ -8,7 +10,6 @@ const { spawnPluginIntegrationTestProc } = require('../../../../integration-tests/helpers') const { withVersions } = require('../../../dd-trace/test/setup/mocha') -const { assert } = require('chai') const { describe, it, beforeEach, afterEach } = require('mocha') describe('esm', () => { @@ -33,8 +34,8 @@ describe('esm', () => { it('is instrumented', async () => { const res = agent.assertMessageReceived(({ headers, payload }) => { - assert.propertyVal(headers, 'host', `127.0.0.1:${agent.port}`) - assert.isArray(payload) + assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.ok(Array.isArray(payload)) assert.strictEqual(checkSpansForServiceName(payload, 'anthropic.request'), true) }) diff --git a/packages/datadog-plugin-apollo/test/index.spec.js b/packages/datadog-plugin-apollo/test/index.spec.js index 13ff234ffb2..c4c86d355ba 100644 --- a/packages/datadog-plugin-apollo/test/index.spec.js +++ b/packages/datadog-plugin-apollo/test/index.spec.js @@ -3,7 +3,6 @@ const assert = require('node:assert/strict') const axios = require('axios') -const { expect } = require('chai') const { ERROR_MESSAGE, ERROR_TYPE, ERROR_STACK } = require('../../dd-trace/src/constants.js') const agent = require('../../dd-trace/test/plugins/agent.js') @@ -288,7 +287,7 @@ describe('Plugin', () => { const variableValues = { who: 'world' } agent .assertSomeTraces((traces) => { - expect(traces[0].length).equal(2) + assert.strictEqual(traces[0].length, 2) assert.strictEqual(traces[0][0].name, expectedSchema.server.opName) assert.strictEqual(traces[0][0].service, expectedSchema.server.serviceName) assert.strictEqual(traces[0][0].error, 1) @@ -323,7 +322,7 @@ describe('Plugin', () => { const variableValues = { who: 'world' } agent .assertSomeTraces((traces) => { - expect(traces[0].length).equal(3) + assert.strictEqual(traces[0].length, 3) assert.strictEqual(traces[0][0].name, expectedSchema.server.opName) assert.strictEqual(traces[0][0].service, expectedSchema.server.serviceName) assert.strictEqual(traces[0][0].error, 1) diff --git a/packages/datadog-plugin-aws-sdk/test/integration-test/client.spec.js b/packages/datadog-plugin-aws-sdk/test/integration-test/client.spec.js index d78865597cf..43dca8ada08 100644 --- a/packages/datadog-plugin-aws-sdk/test/integration-test/client.spec.js +++ b/packages/datadog-plugin-aws-sdk/test/integration-test/client.spec.js @@ -1,5 +1,7 @@ 'use strict' +const assert = require('node:assert/strict') + const { FakeAgent, sandboxCwd, @@ -8,8 +10,6 @@ const { spawnPluginIntegrationTestProc } = require('../../../../integration-tests/helpers') const { withVersions } = require('../../../dd-trace/test/setup/mocha') -const { assert } = require('chai') - describe('esm', () => { let agent let proc @@ -29,8 +29,8 @@ describe('esm', () => { it('is instrumented', async () => { const res = agent.assertMessageReceived(({ headers, payload }) => { - assert.propertyVal(headers, 'host', `127.0.0.1:${agent.port}`) - assert.isArray(payload) + assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.ok(Array.isArray(payload)) assert.strictEqual(checkSpansForServiceName(payload, 'aws.request'), true) }) diff --git a/packages/datadog-plugin-aws-sdk/test/s3.spec.js b/packages/datadog-plugin-aws-sdk/test/s3.spec.js index aef4b666996..1809b13fc53 100644 --- a/packages/datadog-plugin-aws-sdk/test/s3.spec.js +++ b/packages/datadog-plugin-aws-sdk/test/s3.spec.js @@ -3,7 +3,6 @@ const assert = require('node:assert/strict') const axios = require('axios') -const { expect } = require('chai') const { after, before, describe, it } = require('mocha') const { S3_PTR_KIND, SPAN_POINTER_DIRECTION } = require('../../dd-trace/src/constants') @@ -217,7 +216,7 @@ describe('Plugin', () => { agent.assertSomeTraces(traces => { const span = traces[0][0] - expect(span).to.include({ + assertObjectContains(span, { name: 'aws.request', resource: `putObject ${bucketName}` }) diff --git a/packages/datadog-plugin-aws-sdk/test/sqs.spec.js b/packages/datadog-plugin-aws-sdk/test/sqs.spec.js index 31e20f623bd..1b8b6950604 100644 --- a/packages/datadog-plugin-aws-sdk/test/sqs.spec.js +++ b/packages/datadog-plugin-aws-sdk/test/sqs.spec.js @@ -2,8 +2,6 @@ const assert = require('node:assert/strict') const { randomUUID } = require('node:crypto') - -const { expect } = require('chai') const { after, afterEach, before, beforeEach, describe, it } = require('mocha') const semver = require('semver') const sinon = require('sinon') @@ -152,7 +150,7 @@ describe('Plugin', () => { const span = traces[0][0] assert.strictEqual(span.resource.startsWith('sendMessage'), true) - expect(span.meta).to.include({ + assertObjectContains(span.meta, { queuename: queueName, 'cloud.resource_id': `arn:aws:sqs:us-east-1:00000000000000000000:${queueName}` }) @@ -203,7 +201,7 @@ describe('Plugin', () => { const span = traces[0][0] assert.strictEqual(span.resource.startsWith('sendMessageBatch'), true) - expect(span.meta).to.include({ + assertObjectContains(span.meta, { queuename: queueName, 'cloud.resource_id': `arn:aws:sqs:us-east-1:00000000000000000000:${queueName}` }) @@ -371,12 +369,12 @@ describe('Plugin', () => { agent.assertSomeTraces(traces => { const span = traces[0][0] - expect(span).to.include({ + assertObjectContains(span, { name: 'aws.request', resource: `sendMessage ${QueueUrl}` }) - expect(span.meta).to.include({ + assertObjectContains(span.meta, { queuename: queueName, 'cloud.resource_id': `arn:aws:sqs:us-east-1:00000000000000000000:${queueName}`, aws_service: 'SQS', @@ -388,7 +386,7 @@ describe('Plugin', () => { agent.assertSomeTraces(traces => { const span = traces[0][0] - expect(span).to.include({ + assertObjectContains(span, { name: 'aws.request', resource: `receiveMessage ${QueueUrl}` }) diff --git a/packages/datadog-plugin-axios/test/integration-test/client.spec.js b/packages/datadog-plugin-axios/test/integration-test/client.spec.js index 6a5c6bb2570..21b235ce7f3 100644 --- a/packages/datadog-plugin-axios/test/integration-test/client.spec.js +++ b/packages/datadog-plugin-axios/test/integration-test/client.spec.js @@ -1,5 +1,7 @@ 'use strict' +const assert = require('node:assert/strict') + const { FakeAgent, sandboxCwd, @@ -7,8 +9,6 @@ const { checkSpansForServiceName, spawnPluginIntegrationTestProc } = require('../../../../integration-tests/helpers') -const { assert } = require('chai') - describe('esm', () => { let agent let proc @@ -28,8 +28,8 @@ describe('esm', () => { context('axios', () => { it('is instrumented', async () => { const res = agent.assertMessageReceived(({ headers, payload }) => { - assert.propertyVal(headers, 'host', `127.0.0.1:${agent.port}`) - assert.isArray(payload) + assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.ok(Array.isArray(payload)) assert.strictEqual(checkSpansForServiceName(payload, 'http.request'), true) }) diff --git a/packages/datadog-plugin-azure-event-hubs/test/integration-test/client.spec.js b/packages/datadog-plugin-azure-event-hubs/test/integration-test/client.spec.js index 37bee92dce1..340b3152b06 100644 --- a/packages/datadog-plugin-azure-event-hubs/test/integration-test/client.spec.js +++ b/packages/datadog-plugin-azure-event-hubs/test/integration-test/client.spec.js @@ -1,8 +1,8 @@ 'use strict' -const { assert, expect } = require('chai') -const { describe, it, beforeEach, afterEach } = require('mocha') +const assert = require('node:assert/strict') +const { afterEach, beforeEach, describe, it } = require('mocha') const { FakeAgent, sandboxCwd, @@ -35,8 +35,8 @@ describe.skip('esm', () => { it('is instrumented', async () => { const res = agent.assertMessageReceived(({ headers, payload }) => { - assert.propertyVal(headers, 'host', `127.0.0.1:${agent.port}`) - assert.isArray(payload) + assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.ok(Array.isArray(payload)) assert.strictEqual(checkSpansForServiceName(payload, 'azure.eventhubs.send'), true) }) @@ -49,38 +49,38 @@ describe.skip('esm', () => { // list of EventData assert.strictEqual(payload.length, 5) assert.strictEqual(payload[0][0].name, 'azure.eventhubs.send') - assert.propertyVal(payload[0][0].meta, 'messaging.system', 'eventhubs') - assert.propertyVal(payload[0][0].meta, 'messaging.destination.name', 'eh1') - assert.propertyVal(payload[0][0].meta, 'messaging.operation', 'send') - assert.propertyVal(payload[0][0].meta, 'network.destination.name', '127.0.0.1:5673') - assert.propertyVal(payload[0][0].metrics, 'messaging.batch.message_count', 2) + assert.strictEqual(payload[0][0].meta['messaging.system'], 'eventhubs') + assert.strictEqual(payload[0][0].meta['messaging.destination.name'], 'eh1') + assert.strictEqual(payload[0][0].meta['messaging.operation'], 'send') + assert.strictEqual(payload[0][0].meta['network.destination.name'], '127.0.0.1:5673') + assert.strictEqual(payload[0][0].metrics['messaging.batch.message_count'], 2) // list of AMPQ messages assert.strictEqual(payload[1][0].name, 'azure.eventhubs.send') - assert.propertyVal(payload[1][0].meta, 'messaging.system', 'eventhubs') - assert.propertyVal(payload[1][0].meta, 'messaging.destination.name', 'eh1') - assert.propertyVal(payload[1][0].meta, 'messaging.operation', 'send') - assert.propertyVal(payload[1][0].meta, 'network.destination.name', '127.0.0.1:5673') - assert.propertyVal(payload[1][0].metrics, 'messaging.batch.message_count', 2) + assert.strictEqual(payload[1][0].meta['messaging.system'], 'eventhubs') + assert.strictEqual(payload[1][0].meta['messaging.destination.name'], 'eh1') + assert.strictEqual(payload[1][0].meta['messaging.operation'], 'send') + assert.strictEqual(payload[1][0].meta['network.destination.name'], '127.0.0.1:5673') + assert.strictEqual(payload[1][0].metrics['messaging.batch.message_count'], 2) // Batch -> EventDataBatchImpl assert.strictEqual(payload[2][0].name, 'azure.eventhubs.create') - assert.propertyVal(payload[2][0].meta, 'messaging.system', 'eventhubs') - assert.propertyVal(payload[2][0].meta, 'messaging.destination.name', 'eh1') - assert.propertyVal(payload[2][0].meta, 'messaging.operation', 'create') - assert.propertyVal(payload[2][0].meta, 'messaging.system', 'eventhubs') - assert.propertyVal(payload[2][0].meta, 'network.destination.name', '127.0.0.1:5673') + assert.strictEqual(payload[2][0].meta['messaging.system'], 'eventhubs') + assert.strictEqual(payload[2][0].meta['messaging.destination.name'], 'eh1') + assert.strictEqual(payload[2][0].meta['messaging.operation'], 'create') + assert.strictEqual(payload[2][0].meta['messaging.system'], 'eventhubs') + assert.strictEqual(payload[2][0].meta['network.destination.name'], '127.0.0.1:5673') assert.strictEqual(payload[3][0].name, 'azure.eventhubs.create') - assert.propertyVal(payload[3][0].meta, 'messaging.system', 'eventhubs') - assert.propertyVal(payload[3][0].meta, 'messaging.destination.name', 'eh1') - assert.propertyVal(payload[3][0].meta, 'messaging.operation', 'create') - assert.propertyVal(payload[3][0].meta, 'messaging.system', 'eventhubs') - assert.propertyVal(payload[3][0].meta, 'network.destination.name', '127.0.0.1:5673') + assert.strictEqual(payload[3][0].meta['messaging.system'], 'eventhubs') + assert.strictEqual(payload[3][0].meta['messaging.destination.name'], 'eh1') + assert.strictEqual(payload[3][0].meta['messaging.operation'], 'create') + assert.strictEqual(payload[3][0].meta['messaging.system'], 'eventhubs') + assert.strictEqual(payload[3][0].meta['network.destination.name'], '127.0.0.1:5673') assert.strictEqual(payload[4][0].name, 'azure.eventhubs.send') - assert.propertyVal(payload[4][0].meta, 'messaging.system', 'eventhubs') - assert.propertyVal(payload[4][0].meta, 'messaging.destination.name', 'eh1') - assert.propertyVal(payload[4][0].meta, 'messaging.operation', 'send') - assert.propertyVal(payload[4][0].meta, 'messaging.system', 'eventhubs') - assert.propertyVal(payload[4][0].meta, 'network.destination.name', '127.0.0.1:5673') - assert.propertyVal(payload[4][0].metrics, 'messaging.batch.message_count', 4) + assert.strictEqual(payload[4][0].meta['messaging.system'], 'eventhubs') + assert.strictEqual(payload[4][0].meta['messaging.destination.name'], 'eh1') + assert.strictEqual(payload[4][0].meta['messaging.operation'], 'send') + assert.strictEqual(payload[4][0].meta['messaging.system'], 'eventhubs') + assert.strictEqual(payload[4][0].meta['network.destination.name'], '127.0.0.1:5673') + assert.strictEqual(payload[4][0].metrics['messaging.batch.message_count'], 4) assert.strictEqual(parseLinks(payload[4][0]).length, 2) }) @@ -90,7 +90,7 @@ describe.skip('esm', () => { it('does not add span links when they are disabled', async () => { const res = agent.assertMessageReceived(({ headers, payload }) => { - expect(payload[2][0]).to.not.have.property('_dd.span_links') + assert.ok(!('_dd.span_links' in payload[2][0])) }) const envVar = { DD_TRACE_AZURE_EVENTHUBS_BATCH_LINKS_ENABLED: false, ...spawnEnv } proc = await spawnPluginIntegrationTestProc(sandboxCwd(), 'server.mjs', agent.port, undefined, envVar) diff --git a/packages/datadog-plugin-azure-functions/test/integration-test/eventhubs-test/eventhubs.spec.js b/packages/datadog-plugin-azure-functions/test/integration-test/eventhubs-test/eventhubs.spec.js index a93d24e8fb7..87ab3eb19a6 100644 --- a/packages/datadog-plugin-azure-functions/test/integration-test/eventhubs-test/eventhubs.spec.js +++ b/packages/datadog-plugin-azure-functions/test/integration-test/eventhubs-test/eventhubs.spec.js @@ -1,5 +1,7 @@ 'use strict' +const assert = require('node:assert/strict') + const { FakeAgent, hookFile, @@ -9,7 +11,6 @@ const { } = require('../../../../../integration-tests/helpers') const { withVersions } = require('../../../../dd-trace/test/setup/mocha') const { spawn } = require('child_process') -const { expect, assert } = require('chai') const { NODE_MAJOR } = require('../../../../../version') describe('esm', () => { @@ -302,7 +303,7 @@ describe('esm', () => { } proc = await spawnPluginIntegrationTestProc(sandboxCwd(), 'func', ['start'], agent.port, undefined, envArgs) return curlAndAssertMessage(agent, 'http://127.0.0.1:7071/api/eh2-eventdata', ({ headers, payload }) => { - expect(payload[1][0].meta).to.have.property('_dd.span_links') + assert.ok('_dd.span_links' in payload[1][0].meta) }) }).timeout(60000) @@ -315,7 +316,7 @@ describe('esm', () => { return curlAndAssertMessage(agent, 'http://127.0.0.1:7071/api/eh2-batch', ({ headers, payload }) => { const hasCreateSpan = payload[0].some(obj => obj.name === 'azure.functions.create') assert.strictEqual(hasCreateSpan, false) - expect(payload[1][0].meta).to.not.have.property('_dd.span_links') + assert.ok(!('_dd.span_links' in payload[1][0].meta)) }) }).timeout(60000) }) diff --git a/packages/datadog-plugin-azure-functions/test/integration-test/http-test/client.spec.js b/packages/datadog-plugin-azure-functions/test/integration-test/http-test/client.spec.js index 6cd5722e2e9..21356733584 100644 --- a/packages/datadog-plugin-azure-functions/test/integration-test/http-test/client.spec.js +++ b/packages/datadog-plugin-azure-functions/test/integration-test/http-test/client.spec.js @@ -1,5 +1,7 @@ 'use strict' +const assert = require('node:assert/strict') + const { FakeAgent, hookFile, @@ -9,7 +11,6 @@ const { } = require('../../../../../integration-tests/helpers') const { withVersions } = require('../../../../dd-trace/test/setup/mocha') const { spawn } = require('child_process') -const { assert } = require('chai') const { NODE_MAJOR } = require('../../../../../version') describe('esm', () => { @@ -47,12 +48,12 @@ describe('esm', () => { proc = await spawnPluginIntegrationTestProc(sandboxCwd(), 'func', ['start'], agent.port, undefined, envArgs) return curlAndAssertMessage(agent, 'http://127.0.0.1:7071/api/httptest', ({ headers, payload }) => { - assert.propertyVal(headers, 'host', `127.0.0.1:${agent.port}`) - assert.isArray(payload) + assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.ok(Array.isArray(payload)) assert.strictEqual(payload.length, 1) - assert.isArray(payload[0]) + assert.ok(Array.isArray(payload[0])) assert.strictEqual(payload[0].length, 1) - assert.propertyVal(payload[0][0], 'name', 'azure.functions.invoke') + assert.strictEqual(payload[0][0]['name'], 'azure.functions.invoke') }) }).timeout(60_000) diff --git a/packages/datadog-plugin-azure-functions/test/integration-test/servicebus-test/servicebus.spec.js b/packages/datadog-plugin-azure-functions/test/integration-test/servicebus-test/servicebus.spec.js index 9db0c1cad2c..4122c847061 100644 --- a/packages/datadog-plugin-azure-functions/test/integration-test/servicebus-test/servicebus.spec.js +++ b/packages/datadog-plugin-azure-functions/test/integration-test/servicebus-test/servicebus.spec.js @@ -1,5 +1,7 @@ 'use strict' +const assert = require('node:assert/strict') + const { FakeAgent, hookFile, @@ -9,7 +11,6 @@ const { } = require('../../../../../integration-tests/helpers') const { withVersions } = require('../../../../dd-trace/test/setup/mocha') const { spawn } = require('child_process') -const { assert, expect } = require('chai') const { NODE_MAJOR } = require('../../../../../version') describe('esm', () => { @@ -247,7 +248,7 @@ describe('esm', () => { return curlAndAssertMessage(agent, 'http://127.0.0.1:7071/api/send-messages-2', ({ headers, payload }) => { const hasCreateSpan = payload[0].some(obj => obj.name === 'azure.functions.create') assert.strictEqual(hasCreateSpan, false) - expect(payload[1][0].meta).to.not.have.property('_dd.span_links') + assert.ok(!('_dd.span_links' in payload[1][0].meta)) }) }).timeout(60000) @@ -260,7 +261,7 @@ describe('esm', () => { return curlAndAssertMessage(agent, 'http://127.0.0.1:7071/api/send-message-batch-2', ({ headers, payload }) => { const hasCreateSpan = payload[0].some(obj => obj.name === 'azure.functions.create') assert.strictEqual(hasCreateSpan, false) - expect(payload[1][0].meta).to.not.have.property('_dd.span_links') + assert.ok(!('_dd.span_links' in payload[1][0].meta)) }) }).timeout(60000) }) diff --git a/packages/datadog-plugin-azure-service-bus/test/integration-test/client.spec.js b/packages/datadog-plugin-azure-service-bus/test/integration-test/client.spec.js index c097fc66046..de517d2b785 100644 --- a/packages/datadog-plugin-azure-service-bus/test/integration-test/client.spec.js +++ b/packages/datadog-plugin-azure-service-bus/test/integration-test/client.spec.js @@ -1,5 +1,7 @@ 'use strict' +const assert = require('node:assert/strict') + const { FakeAgent, sandboxCwd, @@ -7,8 +9,6 @@ const { spawnPluginIntegrationTestProc } = require('../../../../integration-tests/helpers') const { withVersions } = require('../../../dd-trace/test/setup/mocha') -const { assert } = require('chai') - const spawnEnv = { DD_TRACE_FLUSH_INTERVAL: '2000' } describe('esm', () => { @@ -31,8 +31,8 @@ describe('esm', () => { it('is instrumented', async () => { const res = agent.assertMessageReceived(({ headers, payload }) => { - assert.propertyVal(headers, 'host', `127.0.0.1:${agent.port}`) - assert.isArray(payload) + assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.ok(Array.isArray(payload)) }) proc = await spawnPluginIntegrationTestProc(sandboxCwd(), 'server.mjs', agent.port, spawnEnv) @@ -45,104 +45,104 @@ describe('esm', () => { assert.strictEqual(payload.length, 23) // queue message assert.strictEqual(payload[0][0].name, 'azure.servicebus.send') - assert.propertyVal(payload[0][0].meta, 'span.kind', 'producer') - assert.propertyVal(payload[0][0].meta, 'messaging.system', 'servicebus') - assert.propertyVal(payload[0][0].meta, 'messaging.destination.name', 'queue.1') - assert.propertyVal(payload[0][0].meta, 'messaging.operation', 'send') - assert.propertyVal(payload[0][0].meta, 'network.destination.name', '127.0.0.1') + assert.strictEqual(payload[0][0].meta['span.kind'], 'producer') + assert.strictEqual(payload[0][0].meta['messaging.system'], 'servicebus') + assert.strictEqual(payload[0][0].meta['messaging.destination.name'], 'queue.1') + assert.strictEqual(payload[0][0].meta['messaging.operation'], 'send') + assert.strictEqual(payload[0][0].meta['network.destination.name'], '127.0.0.1') // queue array of messages assert.strictEqual(payload[1][0].name, 'azure.servicebus.create') - assert.propertyVal(payload[1][0].meta, 'span.kind', 'producer') - assert.propertyVal(payload[1][0].meta, 'messaging.system', 'servicebus') - assert.propertyVal(payload[1][0].meta, 'messaging.operation', 'create') - assert.propertyVal(payload[1][0].meta, 'network.destination.name', '127.0.0.1') + assert.strictEqual(payload[1][0].meta['span.kind'], 'producer') + assert.strictEqual(payload[1][0].meta['messaging.system'], 'servicebus') + assert.strictEqual(payload[1][0].meta['messaging.operation'], 'create') + assert.strictEqual(payload[1][0].meta['network.destination.name'], '127.0.0.1') assert.strictEqual(payload[2][0].name, 'azure.servicebus.create') assert.strictEqual(payload[3][0].name, 'azure.servicebus.send') - assert.propertyVal(payload[3][0].meta, 'messaging.operation', 'send') - assert.propertyVal(payload[3][0].meta, 'messaging.destination.name', 'queue.1') + assert.strictEqual(payload[3][0].meta['messaging.operation'], 'send') + assert.strictEqual(payload[3][0].meta['messaging.destination.name'], 'queue.1') // queue amqp messages assert.strictEqual(payload[1][0].name, 'azure.servicebus.create') - assert.propertyVal(payload[4][0].meta, 'span.kind', 'producer') - assert.propertyVal(payload[4][0].meta, 'messaging.system', 'servicebus') - assert.propertyVal(payload[4][0].meta, 'messaging.operation', 'create') - assert.propertyVal(payload[4][0].meta, 'network.destination.name', '127.0.0.1') + assert.strictEqual(payload[4][0].meta['span.kind'], 'producer') + assert.strictEqual(payload[4][0].meta['messaging.system'], 'servicebus') + assert.strictEqual(payload[4][0].meta['messaging.operation'], 'create') + assert.strictEqual(payload[4][0].meta['network.destination.name'], '127.0.0.1') assert.strictEqual(payload[5][0].name, 'azure.servicebus.create') assert.strictEqual(payload[6][0].name, 'azure.servicebus.send') - assert.propertyVal(payload[6][0].meta, 'messaging.operation', 'send') - assert.propertyVal(payload[6][0].meta, 'messaging.destination.name', 'queue.1') + assert.strictEqual(payload[6][0].meta['messaging.operation'], 'send') + assert.strictEqual(payload[6][0].meta['messaging.destination.name'], 'queue.1') // topic message assert.strictEqual(payload[7][0].name, 'azure.servicebus.send') - assert.propertyVal(payload[7][0].meta, 'span.kind', 'producer') - assert.propertyVal(payload[7][0].meta, 'messaging.system', 'servicebus') - assert.propertyVal(payload[7][0].meta, 'messaging.destination.name', 'topic.1') - assert.propertyVal(payload[7][0].meta, 'messaging.operation', 'send') - assert.propertyVal(payload[7][0].meta, 'network.destination.name', '127.0.0.1') + assert.strictEqual(payload[7][0].meta['span.kind'], 'producer') + assert.strictEqual(payload[7][0].meta['messaging.system'], 'servicebus') + assert.strictEqual(payload[7][0].meta['messaging.destination.name'], 'topic.1') + assert.strictEqual(payload[7][0].meta['messaging.operation'], 'send') + assert.strictEqual(payload[7][0].meta['network.destination.name'], '127.0.0.1') // topic array of messages assert.strictEqual(payload[8][0].name, 'azure.servicebus.create') - assert.propertyVal(payload[8][0].meta, 'span.kind', 'producer') - assert.propertyVal(payload[8][0].meta, 'messaging.system', 'servicebus') - assert.propertyVal(payload[8][0].meta, 'messaging.operation', 'create') - assert.propertyVal(payload[8][0].meta, 'network.destination.name', '127.0.0.1') + assert.strictEqual(payload[8][0].meta['span.kind'], 'producer') + assert.strictEqual(payload[8][0].meta['messaging.system'], 'servicebus') + assert.strictEqual(payload[8][0].meta['messaging.operation'], 'create') + assert.strictEqual(payload[8][0].meta['network.destination.name'], '127.0.0.1') assert.strictEqual(payload[9][0].name, 'azure.servicebus.create') assert.strictEqual(payload[10][0].name, 'azure.servicebus.send') - assert.propertyVal(payload[10][0].meta, 'messaging.operation', 'send') - assert.propertyVal(payload[10][0].meta, 'messaging.destination.name', 'topic.1') + assert.strictEqual(payload[10][0].meta['messaging.operation'], 'send') + assert.strictEqual(payload[10][0].meta['messaging.destination.name'], 'topic.1') // topic amqp messages assert.strictEqual(payload[11][0].name, 'azure.servicebus.create') - assert.propertyVal(payload[11][0].meta, 'span.kind', 'producer') - assert.propertyVal(payload[11][0].meta, 'messaging.system', 'servicebus') - assert.propertyVal(payload[11][0].meta, 'messaging.operation', 'create') - assert.propertyVal(payload[11][0].meta, 'network.destination.name', '127.0.0.1') + assert.strictEqual(payload[11][0].meta['span.kind'], 'producer') + assert.strictEqual(payload[11][0].meta['messaging.system'], 'servicebus') + assert.strictEqual(payload[11][0].meta['messaging.operation'], 'create') + assert.strictEqual(payload[11][0].meta['network.destination.name'], '127.0.0.1') assert.strictEqual(payload[12][0].name, 'azure.servicebus.create') assert.strictEqual(payload[13][0].name, 'azure.servicebus.send') - assert.propertyVal(payload[13][0].meta, 'messaging.operation', 'send') - assert.propertyVal(payload[13][0].meta, 'messaging.destination.name', 'topic.1') + assert.strictEqual(payload[13][0].meta['messaging.operation'], 'send') + assert.strictEqual(payload[13][0].meta['messaging.destination.name'], 'topic.1') // scheduled message assert.strictEqual(payload[14][0].name, 'azure.servicebus.send') - assert.propertyVal(payload[14][0].meta, 'span.kind', 'producer') - assert.propertyVal(payload[14][0].meta, 'messaging.system', 'servicebus') - assert.propertyVal(payload[14][0].meta, 'messaging.destination.name', 'queue.1') - assert.propertyVal(payload[14][0].meta, 'messaging.operation', 'send') - assert.propertyVal(payload[14][0].meta, 'network.destination.name', '127.0.0.1') + assert.strictEqual(payload[14][0].meta['span.kind'], 'producer') + assert.strictEqual(payload[14][0].meta['messaging.system'], 'servicebus') + assert.strictEqual(payload[14][0].meta['messaging.destination.name'], 'queue.1') + assert.strictEqual(payload[14][0].meta['messaging.operation'], 'send') + assert.strictEqual(payload[14][0].meta['network.destination.name'], '127.0.0.1') // scheduled array of messages assert.strictEqual(payload[15][0].name, 'azure.servicebus.send') - assert.propertyVal(payload[15][0].meta, 'span.kind', 'producer') - assert.propertyVal(payload[15][0].meta, 'messaging.system', 'servicebus') - assert.propertyVal(payload[15][0].meta, 'messaging.destination.name', 'queue.1') - assert.propertyVal(payload[15][0].meta, 'messaging.operation', 'send') - assert.propertyVal(payload[15][0].meta, 'network.destination.name', '127.0.0.1') + assert.strictEqual(payload[15][0].meta['span.kind'], 'producer') + assert.strictEqual(payload[15][0].meta['messaging.system'], 'servicebus') + assert.strictEqual(payload[15][0].meta['messaging.destination.name'], 'queue.1') + assert.strictEqual(payload[15][0].meta['messaging.operation'], 'send') + assert.strictEqual(payload[15][0].meta['network.destination.name'], '127.0.0.1') // scheduled amqp messages assert.strictEqual(payload[16][0].name, 'azure.servicebus.send') - assert.propertyVal(payload[16][0].meta, 'span.kind', 'producer') - assert.propertyVal(payload[16][0].meta, 'messaging.system', 'servicebus') - assert.propertyVal(payload[16][0].meta, 'messaging.destination.name', 'queue.1') - assert.propertyVal(payload[16][0].meta, 'messaging.operation', 'send') - assert.propertyVal(payload[16][0].meta, 'network.destination.name', '127.0.0.1') + assert.strictEqual(payload[16][0].meta['span.kind'], 'producer') + assert.strictEqual(payload[16][0].meta['messaging.system'], 'servicebus') + assert.strictEqual(payload[16][0].meta['messaging.destination.name'], 'queue.1') + assert.strictEqual(payload[16][0].meta['messaging.operation'], 'send') + assert.strictEqual(payload[16][0].meta['network.destination.name'], '127.0.0.1') // queue batch assert.strictEqual(payload[17][0].name, 'azure.servicebus.create') - assert.propertyVal(payload[17][0].meta, 'span.kind', 'producer') - assert.propertyVal(payload[17][0].meta, 'messaging.system', 'servicebus') - assert.propertyVal(payload[17][0].meta, 'messaging.operation', 'create') - assert.propertyVal(payload[17][0].meta, 'network.destination.name', '127.0.0.1') + assert.strictEqual(payload[17][0].meta['span.kind'], 'producer') + assert.strictEqual(payload[17][0].meta['messaging.system'], 'servicebus') + assert.strictEqual(payload[17][0].meta['messaging.operation'], 'create') + assert.strictEqual(payload[17][0].meta['network.destination.name'], '127.0.0.1') assert.strictEqual(payload[18][0].name, 'azure.servicebus.create') assert.strictEqual(payload[19][0].name, 'azure.servicebus.send') assert.strictEqual(payload[19][0].metrics['messaging.batch.message_count'], 2) - assert.propertyVal(payload[19][0].meta, 'messaging.destination.name', 'queue.1') + assert.strictEqual(payload[19][0].meta['messaging.destination.name'], 'queue.1') assert.strictEqual(parseLinks(payload[19][0]).length, 2) // topic batch assert.strictEqual(payload[20][0].name, 'azure.servicebus.create') - assert.propertyVal(payload[20][0].meta, 'span.kind', 'producer') - assert.propertyVal(payload[20][0].meta, 'messaging.system', 'servicebus') - assert.propertyVal(payload[20][0].meta, 'messaging.operation', 'create') - assert.propertyVal(payload[20][0].meta, 'network.destination.name', '127.0.0.1') + assert.strictEqual(payload[20][0].meta['span.kind'], 'producer') + assert.strictEqual(payload[20][0].meta['messaging.system'], 'servicebus') + assert.strictEqual(payload[20][0].meta['messaging.operation'], 'create') + assert.strictEqual(payload[20][0].meta['network.destination.name'], '127.0.0.1') assert.strictEqual(payload[21][0].name, 'azure.servicebus.create') assert.strictEqual(payload[22][0].name, 'azure.servicebus.send') assert.strictEqual(payload[22][0].metrics['messaging.batch.message_count'], 2) - assert.propertyVal(payload[22][0].meta, 'messaging.destination.name', 'topic.1') + assert.strictEqual(payload[22][0].meta['messaging.destination.name'], 'topic.1') assert.strictEqual(parseLinks(payload[22][0]).length, 2) }) diff --git a/packages/datadog-plugin-cassandra-driver/test/integration-test/client.spec.js b/packages/datadog-plugin-cassandra-driver/test/integration-test/client.spec.js index 72e34f5db4f..de7c3474b2d 100644 --- a/packages/datadog-plugin-cassandra-driver/test/integration-test/client.spec.js +++ b/packages/datadog-plugin-cassandra-driver/test/integration-test/client.spec.js @@ -1,5 +1,7 @@ 'use strict' +const assert = require('node:assert/strict') + const { FakeAgent, checkSpansForServiceName, @@ -9,8 +11,6 @@ const { varySandbox } = require('../../../../integration-tests/helpers') const { withVersions } = require('../../../dd-trace/test/setup/mocha') -const { assert } = require('chai') - describe('esm', () => { let agent let proc @@ -37,8 +37,8 @@ describe('esm', () => { for (const variant of varySandbox.VARIANTS) { it(`is instrumented loaded with ${variant}`, async () => { const res = agent.assertMessageReceived(({ headers, payload }) => { - assert.propertyVal(headers, 'host', `127.0.0.1:${agent.port}`) - assert.isArray(payload) + assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.ok(Array.isArray(payload)) assert.strictEqual(checkSpansForServiceName(payload, 'cassandra.query'), true) }) diff --git a/packages/datadog-plugin-child_process/test/index.spec.js b/packages/datadog-plugin-child_process/test/index.spec.js index ddd157349bf..2450ff341c6 100644 --- a/packages/datadog-plugin-child_process/test/index.spec.js +++ b/packages/datadog-plugin-child_process/test/index.spec.js @@ -1,13 +1,15 @@ 'use strict' -const { expect } = require('chai') -const { describe, it, beforeEach, afterEach, before, after } = require('mocha') +const assert = require('node:assert/strict') + +const { after, afterEach, before, beforeEach, describe, it } = require('mocha') const sinon = require('sinon') -const ChildProcessPlugin = require('../src') const { storage } = require('../../datadog-core') const agent = require('../../dd-trace/test/plugins/agent') const { expectSomeSpan } = require('../../dd-trace/test/plugins/helpers') +const ChildProcessPlugin = require('../src') +const { assertObjectContains } = require('../../../integration-tests/helpers') function noop () {} @@ -53,7 +55,7 @@ describe('Child process plugin', () => { shellPlugin.start({ command: 'ls -l' }) - expect(tracerStub.startSpan).to.have.been.calledOnceWithExactly( + sinon.assert.calledOnceWithExactly(tracerStub.startSpan, 'command_execution', { startTime: undefined, @@ -77,7 +79,7 @@ describe('Child process plugin', () => { shellPlugin.start({ command: 'ls -l', shell: true }) - expect(tracerStub.startSpan).to.have.been.calledOnceWithExactly( + sinon.assert.calledOnceWithExactly(tracerStub.startSpan, 'command_execution', { startTime: undefined, @@ -103,7 +105,7 @@ describe('Child process plugin', () => { shellPlugin.start({ command }) - expect(tracerStub.startSpan).to.have.been.calledOnceWithExactly( + sinon.assert.calledOnceWithExactly(tracerStub.startSpan, 'command_execution', { startTime: undefined, @@ -130,7 +132,7 @@ describe('Child process plugin', () => { shellPlugin.start({ command, shell: true }) - expect(tracerStub.startSpan).to.have.been.calledOnceWithExactly( + sinon.assert.calledOnceWithExactly(tracerStub.startSpan, 'command_execution', { startTime: undefined, @@ -158,7 +160,7 @@ describe('Child process plugin', () => { shellPlugin.start({ command }) - expect(tracerStub.startSpan).to.have.been.calledOnceWithExactly( + sinon.assert.calledOnceWithExactly(tracerStub.startSpan, 'command_execution', { startTime: undefined, @@ -186,7 +188,7 @@ describe('Child process plugin', () => { shellPlugin.start({ command, shell: true }) - expect(tracerStub.startSpan).to.have.been.calledOnceWithExactly( + sinon.assert.calledOnceWithExactly(tracerStub.startSpan, 'command_execution', { startTime: undefined, @@ -211,7 +213,7 @@ describe('Child process plugin', () => { shellPlugin.start({ command: undefined }) - expect(tracerStub.startSpan).not.to.have.been.called + sinon.assert.notCalled(tracerStub.startSpan) }) it('should not crash if command does not exist', () => { @@ -219,7 +221,7 @@ describe('Child process plugin', () => { shellPlugin.start({}) - expect(tracerStub.startSpan).not.to.have.been.called + sinon.assert.notCalled(tracerStub.startSpan) }) }) @@ -230,8 +232,8 @@ describe('Child process plugin', () => { shellPlugin.end({}) - expect(spanStub.setTag).not.to.have.been.called - expect(spanStub.finish).not.to.have.been.called + sinon.assert.notCalled(spanStub.setTag) + sinon.assert.notCalled(spanStub.finish) }) it('should call setTag with proper code when result is a buffer', () => { @@ -240,8 +242,8 @@ describe('Child process plugin', () => { shellPlugin.end({ result: Buffer.from('test') }) - expect(spanStub.setTag).to.have.been.calledOnceWithExactly('cmd.exit_code', '0') - expect(spanStub.finish).to.have.been.calledOnceWithExactly() + sinon.assert.calledOnceWithExactly(spanStub.setTag, 'cmd.exit_code', '0') + sinon.assert.calledOnceWithExactly(spanStub.finish) }) it('should call setTag with proper code when result is a string', () => { @@ -250,8 +252,8 @@ describe('Child process plugin', () => { shellPlugin.end({ result: 'test' }) - expect(spanStub.setTag).to.have.been.calledOnceWithExactly('cmd.exit_code', '0') - expect(spanStub.finish).to.have.been.calledOnceWithExactly() + sinon.assert.calledOnceWithExactly(spanStub.setTag, 'cmd.exit_code', '0') + sinon.assert.calledOnceWithExactly(spanStub.finish) }) it('should call setTag with proper code when an error is thrown', () => { @@ -260,8 +262,8 @@ describe('Child process plugin', () => { shellPlugin.end({ error: { status: -1 } }) - expect(spanStub.setTag).to.have.been.calledOnceWithExactly('cmd.exit_code', '-1') - expect(spanStub.finish).to.have.been.calledOnceWithExactly() + sinon.assert.calledOnceWithExactly(spanStub.setTag, 'cmd.exit_code', '-1') + sinon.assert.calledOnceWithExactly(spanStub.finish) }) }) @@ -272,8 +274,8 @@ describe('Child process plugin', () => { shellPlugin.asyncEnd({}) - expect(spanStub.setTag).to.have.been.calledOnceWithExactly('cmd.exit_code', 'undefined') - expect(spanStub.finish).to.have.been.calledOnce + sinon.assert.calledOnceWithExactly(spanStub.setTag, 'cmd.exit_code', 'undefined') + sinon.assert.calledOnce(spanStub.finish) }) it('should call setTag with proper code when a proper code is returned', () => { @@ -282,18 +284,18 @@ describe('Child process plugin', () => { shellPlugin.asyncEnd({ result: 0 }) - expect(spanStub.setTag).to.have.been.calledOnceWithExactly('cmd.exit_code', '0') - expect(spanStub.finish).to.have.been.calledOnceWithExactly() + sinon.assert.calledOnceWithExactly(spanStub.setTag, 'cmd.exit_code', '0') + sinon.assert.calledOnceWithExactly(spanStub.finish) }) }) describe('channel', () => { it('should return proper prefix', () => { - expect(ChildProcessPlugin.prefix).to.be.equal('tracing:datadog:child_process:execution') + assert.strictEqual(ChildProcessPlugin.prefix, 'tracing:datadog:child_process:execution') }) it('should return proper id', () => { - expect(ChildProcessPlugin.id).to.be.equal('child_process') + assert.strictEqual(ChildProcessPlugin.id, 'child_process') }) }) }) @@ -322,17 +324,17 @@ describe('Child process plugin', () => { it('should preserve context around execSync calls', () => { tracer.scope().activate(parent, () => { - expect(tracer.scope().active()).to.equal(parent) + assert.strictEqual(tracer.scope().active(), parent) childProcess.execSync('ls') - expect(tracer.scope().active()).to.equal(parent) + assert.strictEqual(tracer.scope().active(), parent) }) }) it('should preserve context around exec calls', (done) => { tracer.scope().activate(parent, () => { - expect(tracer.scope().active()).to.equal(parent) + assert.strictEqual(tracer.scope().active(), parent) childProcess.exec('ls', () => { - expect(tracer.scope().active()).to.equal(parent) + assert.strictEqual(tracer.scope().active(), parent) done() }) }) @@ -340,17 +342,17 @@ describe('Child process plugin', () => { it('should preserve context around execFileSync calls', () => { tracer.scope().activate(parent, () => { - expect(tracer.scope().active()).to.equal(parent) + assert.strictEqual(tracer.scope().active(), parent) childProcess.execFileSync('ls') - expect(tracer.scope().active()).to.equal(parent) + assert.strictEqual(tracer.scope().active(), parent) }) }) it('should preserve context around execFile calls', (done) => { tracer.scope().activate(parent, () => { - expect(tracer.scope().active()).to.equal(parent) + assert.strictEqual(tracer.scope().active(), parent) childProcess.execFile('ls', () => { - expect(tracer.scope().active()).to.equal(parent) + assert.strictEqual(tracer.scope().active(), parent) done() }) }) @@ -358,17 +360,17 @@ describe('Child process plugin', () => { it('should preserve context around spawnSync calls', () => { tracer.scope().activate(parent, () => { - expect(tracer.scope().active()).to.equal(parent) + assert.strictEqual(tracer.scope().active(), parent) childProcess.spawnSync('ls') - expect(tracer.scope().active()).to.equal(parent) + assert.strictEqual(tracer.scope().active(), parent) }) }) it('should preserve context around spawn calls', (done) => { tracer.scope().activate(parent, () => { - expect(tracer.scope().active()).to.equal(parent) + assert.strictEqual(tracer.scope().active(), parent) childProcess.spawn('ls') - expect(tracer.scope().active()).to.equal(parent) + assert.strictEqual(tracer.scope().active(), parent) done() }) }) @@ -402,8 +404,8 @@ describe('Child process plugin', () => { it('should not crash with "this._then is not a function" when using Bluebird promises', async () => { const execFileAsync = util.promisify(childProcess.execFile) - expect(global.Promise).to.equal(Bluebird) - expect(global.Promise.version).to.exist + assert.strictEqual(global.Promise, Bluebird) + assert.ok(global.Promise.version != null) const expectedPromise = expectSomeSpan(agent, { type: 'system', @@ -416,8 +418,8 @@ describe('Child process plugin', () => { }) const result = await execFileAsync('echo', ['bluebird-test']) - expect(result).to.exist - expect(result.stdout).to.contain('bluebird-test') + assert.ok(result != null) + assertObjectContains(result.stdout, 'bluebird-test') return expectedPromise }) @@ -430,14 +432,14 @@ describe('Child process plugin', () => { promises.push( execFileAsync('echo', [`concurrent-test-${i}`]) .then(result => { - expect(result.stdout).to.contain(`concurrent-test-${i}`) + assertObjectContains(result.stdout, `concurrent-test-${i}`) return result }) ) } const results = await Promise.all(promises) - expect(results).to.have.length(5) + assert.strictEqual(results.length, 5) }) it('should handle Bluebird promise rejection properly', async () => { @@ -459,8 +461,8 @@ describe('Child process plugin', () => { await execFileAsync('node', ['-invalidFlag'], { stdio: 'pipe' }) throw new Error('Expected command to fail') } catch (error) { - expect(error).to.exist - expect(error.code).to.exist + assert.ok(error != null) + assert.ok(error.code != null) } return expectedPromise @@ -474,11 +476,11 @@ describe('Child process plugin', () => { const execFileAsync = utilWithBluebird.promisify(childProcess.execFile) const promise = execFileAsync('echo', ['util-promisify-test']) - expect(promise.constructor).to.equal(Bluebird) - expect(promise.constructor.version).to.exist + assert.strictEqual(promise.constructor, Bluebird) + assert.ok(promise.constructor.version != null) const result = await promise - expect(result.stdout).to.contain('util-promisify-test') + assertObjectContains(result.stdout, 'util-promisify-test') }) }) @@ -543,10 +545,10 @@ describe('Child process plugin', () => { it('should maintain previous span after the execution', (done) => { const res = childProcess[methodName]('ls') const span = storage('legacy').getStore()?.span - expect(span).to.be.equals(parentSpan) + assert.strictEqual(span, parentSpan) if (async) { res.on('close', () => { - expect(span).to.be.equals(parentSpan) + assert.strictEqual(span, parentSpan) done() }) } else { @@ -558,7 +560,7 @@ describe('Child process plugin', () => { it('should maintain previous span in the callback', (done) => { childProcess[methodName]('ls', () => { const span = storage('legacy').getStore()?.span - expect(span).to.be.equals(parentSpan) + assert.strictEqual(span, parentSpan) done() }) }) diff --git a/packages/datadog-plugin-child_process/test/scrub-cmd-params.spec.js b/packages/datadog-plugin-child_process/test/scrub-cmd-params.spec.js index e1954415cbf..639990e0561 100644 --- a/packages/datadog-plugin-child_process/test/scrub-cmd-params.spec.js +++ b/packages/datadog-plugin-child_process/test/scrub-cmd-params.spec.js @@ -2,11 +2,9 @@ const assert = require('node:assert/strict') -const { expect } = require('chai') const { describe, it } = require('mocha') const scrubCmdParams = require('../src/scrub-cmd-params') - describe('scrub cmds', () => { it('Should not scrub single command', () => { assert.deepStrictEqual(scrubCmdParams('ls -la'), ['ls', '-la']) @@ -24,7 +22,7 @@ describe('scrub cmds', () => { it('Should split correctly texts', () => { assert.deepStrictEqual(scrubCmdParams('echo "Hello\\ text"'), ['echo', 'Hello\\ text']) - expect(scrubCmdParams('node -e "process.exit(1)"')).to.be.deep.equal(['node', '-e', 'process.exit(1)']) + assert.deepStrictEqual(scrubCmdParams('node -e "process.exit(1)"'), ['node', '-e', 'process.exit(1)']) }) it('Should not scrub chained command', () => { @@ -39,21 +37,17 @@ describe('scrub cmds', () => { it('Should scrub secret values', () => { assert.deepStrictEqual(scrubCmdParams('cmd --pass abc --token=def'), ['cmd', '--pass', '?', '--token=?']) - expect(scrubCmdParams('mysqladmin -u root password very_secret')) - .to.be.deep.equal(['mysqladmin', '-u', 'root', 'password', '?']) + assert.deepStrictEqual(scrubCmdParams('mysqladmin -u root password very_secret'), ['mysqladmin', '-u', 'root', 'password', '?']) - expect(scrubCmdParams('test -password very_secret -api_key 1234')) - .to.be.deep.equal(['test', '-password', '?', '-api_key', '?']) + assert.deepStrictEqual(scrubCmdParams('test -password very_secret -api_key 1234'), ['test', '-password', '?', '-api_key', '?']) - expect(scrubCmdParams('test --address https://some.address.com --email testing@to.es --api-key 1234')) - .to.be.deep.equal(['test', '--address', '?', '--email', '?', '--api-key', '?']) + assert.deepStrictEqual(scrubCmdParams('test --address https://some.address.com --email testing@to.es --api-key 1234'), ['test', '--address', '?', '--email', '?', '--api-key', '?']) }) it('Should scrub md5 commands', () => { assert.deepStrictEqual(scrubCmdParams('md5 -s pony'), ['md5', '?', '?']) - expect(scrubCmdParams('cat passwords.txt | while read line; do; md5 -s $line; done')).to.be.deep - .equal([ + assert.deepStrictEqual(scrubCmdParams('cat passwords.txt | while read line; do; md5 -s $line; done'), [ 'cat', 'passwords.txt', '|', diff --git a/packages/datadog-plugin-confluentinc-kafka-javascript/test/integration-test/client.spec.js b/packages/datadog-plugin-confluentinc-kafka-javascript/test/integration-test/client.spec.js index 57f204ac123..5a9ecfcf1bb 100644 --- a/packages/datadog-plugin-confluentinc-kafka-javascript/test/integration-test/client.spec.js +++ b/packages/datadog-plugin-confluentinc-kafka-javascript/test/integration-test/client.spec.js @@ -1,5 +1,7 @@ 'use strict' +const assert = require('node:assert/strict') + const { FakeAgent, sandboxCwd, @@ -8,8 +10,6 @@ const { spawnPluginIntegrationTestProc } = require('../../../../integration-tests/helpers') const { withVersions } = require('../../../dd-trace/test/setup/mocha') -const { assert } = require('chai') - describe('esm', () => { let agent let proc @@ -29,8 +29,8 @@ describe('esm', () => { it('is instrumented', async () => { const res = agent.assertMessageReceived(({ headers, payload }) => { - assert.propertyVal(headers, 'host', `127.0.0.1:${agent.port}`) - assert.isArray(payload) + assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.ok(Array.isArray(payload)) assert.strictEqual(checkSpansForServiceName(payload, 'kafka.produce'), true) }) diff --git a/packages/datadog-plugin-connect/test/integration-test/client.spec.js b/packages/datadog-plugin-connect/test/integration-test/client.spec.js index 65d863095ab..6e9eea7aa30 100644 --- a/packages/datadog-plugin-connect/test/integration-test/client.spec.js +++ b/packages/datadog-plugin-connect/test/integration-test/client.spec.js @@ -1,5 +1,7 @@ 'use strict' +const assert = require('node:assert/strict') + const { FakeAgent, curlAndAssertMessage, @@ -10,8 +12,6 @@ const { varySandbox } = require('../../../../integration-tests/helpers') const { withVersions } = require('../../../dd-trace/test/setup/mocha') -const { assert } = require('chai') - describe('esm', () => { let agent let proc @@ -39,8 +39,8 @@ describe('esm', () => { proc = await spawnPluginIntegrationTestProc(sandboxCwd(), variants[variant], agent.port) return curlAndAssertMessage(agent, proc, ({ headers, payload }) => { - assert.propertyVal(headers, 'host', `127.0.0.1:${agent.port}`) - assert.isArray(payload) + assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.ok(Array.isArray(payload)) assert.strictEqual(checkSpansForServiceName(payload, 'connect.request'), true) }) }).timeout(20000) diff --git a/packages/datadog-plugin-couchbase/test/index.spec.js b/packages/datadog-plugin-couchbase/test/index.spec.js index 9a98ff7c151..431474c2bac 100644 --- a/packages/datadog-plugin-couchbase/test/index.spec.js +++ b/packages/datadog-plugin-couchbase/test/index.spec.js @@ -2,7 +2,6 @@ const assert = require('node:assert/strict') -const { expect } = require('chai') const { after, afterEach, before, beforeEach, describe, it } = require('mocha') const proxyquire = require('proxyquire').noPreserveCache() const semver = require('semver') @@ -261,12 +260,12 @@ describe('Plugin', () => { it('should skip instrumentation for invalid arguments', (done) => { const checkError = (e) => { - expect(e.message).to.be.oneOf([ + assert.ok([ // depending on version of node 'Cannot read property \'toString\' of undefined', 'Cannot read properties of undefined (reading \'toString\')', 'parsing failure' // sdk 4 - ]) + ].includes(e.message)) done() } try { diff --git a/packages/datadog-plugin-couchbase/test/integration-test/client.spec.js b/packages/datadog-plugin-couchbase/test/integration-test/client.spec.js index 2ee7a192ee0..9ad470df3f4 100644 --- a/packages/datadog-plugin-couchbase/test/integration-test/client.spec.js +++ b/packages/datadog-plugin-couchbase/test/integration-test/client.spec.js @@ -1,5 +1,7 @@ 'use strict' +const assert = require('node:assert/strict') + const { FakeAgent, sandboxCwd, @@ -8,8 +10,6 @@ const { spawnPluginIntegrationTestProc } = require('../../../../integration-tests/helpers') const { withVersions } = require('../../../dd-trace/test/setup/mocha') -const { assert } = require('chai') - describe('esm', () => { let agent let proc @@ -30,8 +30,8 @@ describe('esm', () => { it('is instrumented', async () => { const res = agent.assertMessageReceived(({ headers, payload }) => { - assert.propertyVal(headers, 'host', `127.0.0.1:${agent.port}`) - assert.isArray(payload) + assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.ok(Array.isArray(payload)) assert.strictEqual(checkSpansForServiceName(payload, 'couchbase.upsert'), true) }) diff --git a/packages/datadog-plugin-dns/test/integration-test/client.spec.js b/packages/datadog-plugin-dns/test/integration-test/client.spec.js index 18c0f78538d..fe794560831 100644 --- a/packages/datadog-plugin-dns/test/integration-test/client.spec.js +++ b/packages/datadog-plugin-dns/test/integration-test/client.spec.js @@ -1,5 +1,7 @@ 'use strict' +const assert = require('node:assert/strict') + const { FakeAgent, checkSpansForServiceName, @@ -8,8 +10,6 @@ const { useSandbox, varySandbox } = require('../../../../integration-tests/helpers') -const { assert } = require('chai') - describe('esm', () => { let agent let proc @@ -35,8 +35,8 @@ describe('esm', () => { for (const variant of varySandbox.VARIANTS) { it(`is instrumented loaded with ${variant}`, async () => { const res = agent.assertMessageReceived(({ headers, payload }) => { - assert.propertyVal(headers, 'host', `127.0.0.1:${agent.port}`) - assert.isArray(payload) + assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.ok(Array.isArray(payload)) assert.strictEqual(checkSpansForServiceName(payload, 'dns.lookup'), true) assert.strictEqual(payload[0][0].resource, 'fakedomain.faketld') }) diff --git a/packages/datadog-plugin-elasticsearch/test/index.spec.js b/packages/datadog-plugin-elasticsearch/test/index.spec.js index 08da1af0f32..a867dc8bed0 100644 --- a/packages/datadog-plugin-elasticsearch/test/index.spec.js +++ b/packages/datadog-plugin-elasticsearch/test/index.spec.js @@ -2,7 +2,6 @@ const assert = require('node:assert/strict') -const { expect } = require('chai') const { after, afterEach, before, beforeEach, describe, it } = require('mocha') const { ERROR_MESSAGE, ERROR_STACK, ERROR_TYPE } = require('../../dd-trace/src/constants') @@ -10,7 +9,6 @@ const agent = require('../../dd-trace/test/plugins/agent') const { breakThen, unbreakThen } = require('../../dd-trace/test/plugins/helpers') const { withNamingSchema, withPeerService, withVersions } = require('../../dd-trace/test/setup/mocha') const { expectedSchema, rawExpectedSchema } = require('./naming') - describe('Plugin', () => { let elasticsearch let tracer @@ -96,10 +94,8 @@ describe('Plugin', () => { assert.strictEqual(traces[0][0].meta['elasticsearch.body'], '{"query":{"match_all":{}}}') assert.strictEqual(traces[0][0].meta['elasticsearch.params'], '{"sort":"name","size":100}') } else { - expect(traces[0][0].meta).to.have.property( - 'elasticsearch.body', - '{"query":{"match_all":{}},"sort":"name","size":100}' - ) + assert.ok('elasticsearch.body' in traces[0][0].meta); + assert.strictEqual(traces[0][0].meta['elasticsearch.body'], '{"query":{"match_all":{}},"sort":"name","size":100}') } }) .then(done) @@ -127,10 +123,8 @@ describe('Plugin', () => { assert.strictEqual(traces[0][0].meta['span.kind'], 'client') assert.strictEqual(traces[0][0].meta['elasticsearch.method'], 'POST') assert.strictEqual(traces[0][0].meta['elasticsearch.url'], '/_msearch') - expect(traces[0][0].meta).to.have.property( - 'elasticsearch.body', - '[{"index":"docs"},{"query":{"match_all":{}}},{"index":"docs2"},{"query":{"match_all":{}}}]' - ) + assert.ok('elasticsearch.body' in traces[0][0].meta); + assert.strictEqual(traces[0][0].meta['elasticsearch.body'], '[{"index":"docs"},{"query":{"match_all":{}}},{"index":"docs2"},{"query":{"match_all":{}}}]') }) .then(done) .catch(done) @@ -226,9 +220,9 @@ describe('Plugin', () => { }) it('should support aborting the query', () => { - expect(() => { + assert.doesNotThrow(() => { client.ping(() => {}).abort() - }).not.to.throw() + }) }) }) } @@ -285,13 +279,13 @@ describe('Plugin', () => { }) it('should support aborting the query', () => { - expect(() => { + assert.doesNotThrow(() => { const promise = client.ping() if (promise.abort) { promise.abort() } - }).not.to.throw() + }) }) it('should work with userland promises', done => { diff --git a/packages/datadog-plugin-elasticsearch/test/integration-test/client.spec.js b/packages/datadog-plugin-elasticsearch/test/integration-test/client.spec.js index 5c8fe85b615..467bd282963 100644 --- a/packages/datadog-plugin-elasticsearch/test/integration-test/client.spec.js +++ b/packages/datadog-plugin-elasticsearch/test/integration-test/client.spec.js @@ -1,5 +1,7 @@ 'use strict' +const assert = require('node:assert/strict') + const { FakeAgent, checkSpansForServiceName, @@ -9,8 +11,6 @@ const { varySandbox } = require('../../../../integration-tests/helpers') const { withVersions } = require('../../../dd-trace/test/setup/mocha') -const { assert } = require('chai') - describe('esm', () => { let agent let proc @@ -36,8 +36,8 @@ describe('esm', () => { for (const variant of varySandbox.VARIANTS) { it(`is instrumented loaded with ${variant}`, async () => { const res = agent.assertMessageReceived(({ headers, payload }) => { - assert.propertyVal(headers, 'host', `127.0.0.1:${agent.port}`) - assert.isArray(payload) + assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.ok(Array.isArray(payload)) assert.strictEqual(checkSpansForServiceName(payload, 'elasticsearch.query'), true) }) diff --git a/packages/datadog-plugin-express/test/code_origin.spec.js b/packages/datadog-plugin-express/test/code_origin.spec.js index 115561628e2..718658eb8c6 100644 --- a/packages/datadog-plugin-express/test/code_origin.spec.js +++ b/packages/datadog-plugin-express/test/code_origin.spec.js @@ -1,11 +1,12 @@ 'use strict' +const assert = require('node:assert/strict') + const axios = require('axios') -const { expect } = require('chai') -const { describe, it, beforeEach, afterEach, before } = require('mocha') +const { after, afterEach, before, beforeEach, describe, it } = require('mocha') -const agent = require('../../dd-trace/test/plugins/agent') const { assertCodeOriginFromTraces } = require('../../datadog-code-origin/test/helpers') +const agent = require('../../dd-trace/test/plugins/agent') const { getNextLineNumber } = require('../../dd-trace/test/plugins/helpers') const { withVersions } = require('../../dd-trace/test/setup/mocha') @@ -41,7 +42,7 @@ describe('Plugin', () => { agent.assertSomeTraces(traces => { const spans = traces[0] const tagNames = Object.keys(spans[0].meta) - expect(tagNames).to.all.not.match(/code_origin/) + assert.doesNotMatch(tagNames, /code_origin/) }), axios.get(`http://localhost:${listener.address().port}/user`) ]).then(() => done(), done) diff --git a/packages/datadog-plugin-express/test/integration-test/client.spec.js b/packages/datadog-plugin-express/test/integration-test/client.spec.js index 6785e05a735..683733cee7d 100644 --- a/packages/datadog-plugin-express/test/integration-test/client.spec.js +++ b/packages/datadog-plugin-express/test/integration-test/client.spec.js @@ -1,5 +1,7 @@ 'use strict' +const assert = require('node:assert/strict') + const { FakeAgent, curlAndAssertMessage, @@ -9,7 +11,6 @@ const { varySandbox } = require('../../../../integration-tests/helpers') const { withVersions } = require('../../../dd-trace/test/setup/mocha') -const { assert } = require('chai') const semver = require('semver') describe('esm', () => { @@ -43,13 +44,13 @@ describe('esm', () => { : 'router' return curlAndAssertMessage(agent, proc, ({ headers, payload }) => { - assert.propertyVal(headers, 'host', `127.0.0.1:${agent.port}`) - assert.isArray(payload) + assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.ok(Array.isArray(payload)) assert.strictEqual(payload.length, 1) - assert.isArray(payload[0]) + assert.ok(Array.isArray(payload[0])) assert.strictEqual(payload[0].length, numberOfSpans) - assert.propertyVal(payload[0][0], 'name', 'express.request') - assert.propertyVal(payload[0][1], 'name', `${whichMiddleware}.middleware`) + assert.strictEqual(payload[0][0]['name'], 'express.request') + assert.strictEqual(payload[0][1]['name'], `${whichMiddleware}.middleware`) }) }).timeout(50000) }) @@ -68,12 +69,12 @@ describe('esm', () => { const numberOfSpans = 1 return curlAndAssertMessage(agent, proc, ({ headers, payload }) => { - assert.propertyVal(headers, 'host', `127.0.0.1:${agent.port}`) - assert.isArray(payload) + assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.ok(Array.isArray(payload)) assert.strictEqual(payload.length, 1) - assert.isArray(payload[0]) + assert.ok(Array.isArray(payload[0])) assert.strictEqual(payload[0].length, numberOfSpans) - assert.propertyVal(payload[0][0], 'name', 'express.request') + assert.strictEqual(payload[0][0]['name'], 'express.request') }) }).timeout(50000) }) diff --git a/packages/datadog-plugin-fastify/test/code_origin.spec.js b/packages/datadog-plugin-fastify/test/code_origin.spec.js index be5768340a6..43412fcbceb 100644 --- a/packages/datadog-plugin-fastify/test/code_origin.spec.js +++ b/packages/datadog-plugin-fastify/test/code_origin.spec.js @@ -1,15 +1,16 @@ 'use strict' +const assert = require('node:assert/strict') + const axios = require('axios') -const { expect } = require('chai') -const { describe, it, beforeEach, afterEach, before } = require('mocha') +const { after, afterEach, before, beforeEach, describe, it } = require('mocha') const semver = require('semver') -const { withExports, withVersions } = require('../../dd-trace/test/setup/mocha') -const agent = require('../../dd-trace/test/plugins/agent') +const { NODE_MAJOR } = require('../../../version') const { assertCodeOriginFromTraces } = require('../../datadog-code-origin/test/helpers') +const agent = require('../../dd-trace/test/plugins/agent') const { getNextLineNumber } = require('../../dd-trace/test/plugins/helpers') -const { NODE_MAJOR } = require('../../../version') +const { withExports, withVersions } = require('../../dd-trace/test/setup/mocha') describe('Plugin', () => { let fastify, app @@ -49,7 +50,7 @@ describe('Plugin', () => { agent.assertSomeTraces(traces => { const spans = traces[0] const tagNames = Object.keys(spans[0].meta) - expect(tagNames).to.all.not.match(/code_origin/) + assert.doesNotMatch(tagNames, /code_origin/) }), axios.get(`http://localhost:${app.server.address().port}/user`) ]) diff --git a/packages/datadog-plugin-fastify/test/integration-test/client.spec.js b/packages/datadog-plugin-fastify/test/integration-test/client.spec.js index 46ca79bc837..c1e3e4b3eb5 100644 --- a/packages/datadog-plugin-fastify/test/integration-test/client.spec.js +++ b/packages/datadog-plugin-fastify/test/integration-test/client.spec.js @@ -1,5 +1,7 @@ 'use strict' +const assert = require('node:assert/strict') + const { FakeAgent, curlAndAssertMessage, @@ -7,7 +9,6 @@ const { spawnPluginIntegrationTestProc } = require('../../../../integration-tests/helpers') const { withVersions, insertVersionDep } = require('../../../dd-trace/test/setup/mocha') -const { assert } = require('chai') const { join } = require('path') describe('esm', () => { @@ -34,8 +35,8 @@ describe('esm', () => { proc = await spawnPluginIntegrationTestProc(__dirname, 'server.mjs', agent.port, env) return curlAndAssertMessage(agent, proc, ({ headers, payload }) => { - assert.propertyVal(headers, 'host', `127.0.0.1:${agent.port}`) - assert.isArray(payload) + assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.ok(Array.isArray(payload)) assert.strictEqual(checkSpansForServiceName(payload, 'fastify.request'), true) }) }).timeout(20000) @@ -44,8 +45,8 @@ describe('esm', () => { proc = await spawnPluginIntegrationTestProc(__dirname, 'server1.mjs', agent.port, env) return curlAndAssertMessage(agent, proc, ({ headers, payload }) => { - assert.propertyVal(headers, 'host', `127.0.0.1:${agent.port}`) - assert.isArray(payload) + assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.ok(Array.isArray(payload)) assert.strictEqual(checkSpansForServiceName(payload, 'fastify.request'), true) }) }).timeout(20000) @@ -54,8 +55,8 @@ describe('esm', () => { proc = await spawnPluginIntegrationTestProc(__dirname, 'server2.mjs', agent.port, env) return curlAndAssertMessage(agent, proc, ({ headers, payload }) => { - assert.propertyVal(headers, 'host', `127.0.0.1:${agent.port}`) - assert.isArray(payload) + assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.ok(Array.isArray(payload)) assert.strictEqual(checkSpansForServiceName(payload, 'fastify.request'), true) }) }).timeout(20000) diff --git a/packages/datadog-plugin-fetch/test/integration-test/client.spec.js b/packages/datadog-plugin-fetch/test/integration-test/client.spec.js index 2184f2ca18b..095b711eecf 100644 --- a/packages/datadog-plugin-fetch/test/integration-test/client.spec.js +++ b/packages/datadog-plugin-fetch/test/integration-test/client.spec.js @@ -1,13 +1,13 @@ 'use strict' +const assert = require('node:assert/strict') + const { FakeAgent, sandboxCwd, useSandbox, spawnPluginIntegrationTestProc } = require('../../../../integration-tests/helpers') -const { assert } = require('chai') - const describe = globalThis.fetch ? globalThis.describe : globalThis.describe.skip describe('esm', () => { @@ -29,8 +29,8 @@ describe('esm', () => { context('fetch', () => { it('is instrumented', async () => { const res = agent.assertMessageReceived(({ headers, payload }) => { - assert.propertyVal(headers, 'host', `127.0.0.1:${agent.port}`) - assert.isArray(payload) + assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.ok(Array.isArray(payload)) const isFetch = payload.some((span) => span.some((nestedSpan) => nestedSpan.meta.component === 'fetch')) assert.strictEqual(isFetch, true) }) diff --git a/packages/datadog-plugin-google-cloud-pubsub/test/index.spec.js b/packages/datadog-plugin-google-cloud-pubsub/test/index.spec.js index acc7cebbece..47d064c5b91 100644 --- a/packages/datadog-plugin-google-cloud-pubsub/test/index.spec.js +++ b/packages/datadog-plugin-google-cloud-pubsub/test/index.spec.js @@ -2,7 +2,6 @@ const assert = require('node:assert/strict') -const { expect } = require('chai') const { after, afterEach, before, beforeEach, describe, it } = require('mocha') const sinon = require('sinon') @@ -390,7 +389,7 @@ describe('Plugin', () => { } }) assert.ok(statsPointsReceived >= 1) - expect(agent.dsmStatsExist(agent, expectedProducerHash.readBigUInt64BE(0).toString())).to.equal(true) + assert.strictEqual(agent.dsmStatsExist(agent, expectedProducerHash.readBigUInt64BE(0).toString()), true) }, { timeoutMs: TIMEOUT }) }) @@ -408,7 +407,7 @@ describe('Plugin', () => { } }) assert.ok(statsPointsReceived >= 2) - expect(agent.dsmStatsExist(agent, expectedConsumerHash.readBigUInt64BE(0).toString())).to.equal(true) + assert.strictEqual(agent.dsmStatsExist(agent, expectedConsumerHash.readBigUInt64BE(0).toString()), true) }, { timeoutMs: TIMEOUT }) }) }) diff --git a/packages/datadog-plugin-google-cloud-pubsub/test/integration-test/client.spec.js b/packages/datadog-plugin-google-cloud-pubsub/test/integration-test/client.spec.js index f7e74fcdab6..2b84c9eb5d5 100644 --- a/packages/datadog-plugin-google-cloud-pubsub/test/integration-test/client.spec.js +++ b/packages/datadog-plugin-google-cloud-pubsub/test/integration-test/client.spec.js @@ -1,5 +1,7 @@ 'use strict' +const assert = require('node:assert/strict') + const { FakeAgent, sandboxCwd, @@ -8,8 +10,6 @@ const { spawnPluginIntegrationTestProc } = require('../../../../integration-tests/helpers') const { withVersions } = require('../../../dd-trace/test/setup/mocha') -const { assert } = require('chai') - describe('esm', () => { let agent let proc @@ -29,8 +29,8 @@ describe('esm', () => { it('is instrumented', async () => { const res = agent.assertMessageReceived(({ headers, payload }) => { - assert.propertyVal(headers, 'host', `127.0.0.1:${agent.port}`) - assert.isArray(payload) + assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.ok(Array.isArray(payload)) assert.strictEqual(checkSpansForServiceName(payload, 'pubsub.request'), true) }) diff --git a/packages/datadog-plugin-google-cloud-vertexai/test/index.spec.js b/packages/datadog-plugin-google-cloud-vertexai/test/index.spec.js index 8bd6afecfa2..7202e543666 100644 --- a/packages/datadog-plugin-google-cloud-vertexai/test/index.spec.js +++ b/packages/datadog-plugin-google-cloud-vertexai/test/index.spec.js @@ -4,7 +4,6 @@ const assert = require('node:assert/strict') const fs = require('node:fs') const path = require('node:path') -const { expect } = require('chai') const { after, afterEach, before, beforeEach, describe, it } = require('mocha') const sinon = require('sinon') @@ -163,7 +162,7 @@ describe('Plugin', () => { const { stream, response } = await model.generateContentStream('Hello, how are you?') // check that response is a promise - expect(response).to.be.a('promise') + assert.ok(response && typeof response.then === 'function') const promState = await promiseState(response) assert.strictEqual(promState, 'pending') // we shouldn't have consumed the promise @@ -252,7 +251,7 @@ describe('Plugin', () => { const { stream, response } = await chat.sendMessageStream('Hello, how are you?') // check that response is a promise - expect(response).to.be.a('promise') + assert.ok(response && typeof response.then === 'function') const promState = await promiseState(response) assert.strictEqual(promState, 'pending') // we shouldn't have consumed the promise diff --git a/packages/datadog-plugin-google-cloud-vertexai/test/integration-test/client.spec.js b/packages/datadog-plugin-google-cloud-vertexai/test/integration-test/client.spec.js index faa5765ea99..cacb17f84dc 100644 --- a/packages/datadog-plugin-google-cloud-vertexai/test/integration-test/client.spec.js +++ b/packages/datadog-plugin-google-cloud-vertexai/test/integration-test/client.spec.js @@ -1,5 +1,7 @@ 'use strict' +const assert = require('node:assert/strict') + const { FakeAgent, sandboxCwd, @@ -8,8 +10,6 @@ const { spawnPluginIntegrationTestProc } = require('../../../../integration-tests/helpers') const { withVersions } = require('../../../dd-trace/test/setup/mocha') -const { assert } = require('chai') - describe('esm', () => { let agent let proc @@ -33,8 +33,8 @@ describe('esm', () => { it('is instrumented', async () => { const res = agent.assertMessageReceived(({ headers, payload }) => { - assert.propertyVal(headers, 'host', `127.0.0.1:${agent.port}`) - assert.isArray(payload) + assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.ok(Array.isArray(payload)) assert.strictEqual(checkSpansForServiceName(payload, 'vertexai.request'), true) }) diff --git a/packages/datadog-plugin-graphql/test/esm-test/esm.spec.js b/packages/datadog-plugin-graphql/test/esm-test/esm.spec.js index 573fb937d63..127c6a43cbd 100644 --- a/packages/datadog-plugin-graphql/test/esm-test/esm.spec.js +++ b/packages/datadog-plugin-graphql/test/esm-test/esm.spec.js @@ -1,5 +1,7 @@ 'use strict' +const assert = require('node:assert/strict') + const { FakeAgent, sandboxCwd, @@ -7,7 +9,6 @@ const { checkSpansForServiceName, spawnPluginIntegrationTestProc } = require('../../../../integration-tests/helpers') -const { assert } = require('chai') const { withVersions } = require('../../../dd-trace/test/setup/mocha') const axios = require('axios') const semver = require('semver') @@ -32,8 +33,8 @@ describe('Plugin (ESM)', () => { it('should instrument GraphQL execution with ESM', async () => { const res = agent.assertMessageReceived(({ headers, payload }) => { - assert.propertyVal(headers, 'host', `127.0.0.1:${agent.port}`) - assert.isArray(payload) + assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.ok(Array.isArray(payload)) assert.strictEqual(checkSpansForServiceName(payload, 'graphql.execute'), true) }) @@ -71,8 +72,8 @@ describe('Plugin (ESM)', () => { if (coercedVersion && semver.gte(coercedVersion, '15.0.0')) { it('should instrument GraphQL Yoga execution with ESM', async () => { const res = agent.assertMessageReceived(({ headers, payload }) => { - assert.propertyVal(headers, 'host', `127.0.0.1:${agent.port}`) - assert.isArray(payload) + assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.ok(Array.isArray(payload)) assert.strictEqual(checkSpansForServiceName(payload, 'graphql.execute'), true) }) diff --git a/packages/datadog-plugin-graphql/test/index.spec.js b/packages/datadog-plugin-graphql/test/index.spec.js index 49871f59de2..9f6062d4bf2 100644 --- a/packages/datadog-plugin-graphql/test/index.spec.js +++ b/packages/datadog-plugin-graphql/test/index.spec.js @@ -5,18 +5,17 @@ const http = require('node:http') const { performance } = require('perf_hooks') const axios = require('axios') -const { expect } = require('chai') const dc = require('dc-polyfill') const { after, afterEach, before, beforeEach, describe, it } = require('mocha') const semver = require('semver') const sinon = require('sinon') +const { assertObjectContains } = require('../../../integration-tests/helpers') const { ERROR_MESSAGE, ERROR_TYPE, ERROR_STACK } = require('../../dd-trace/src/constants') const agent = require('../../dd-trace/test/plugins/agent') const { withNamingSchema, withVersions } = require('../../dd-trace/test/setup/mocha') const plugin = require('../src') const { expectedSchema, rawExpectedSchema } = require('./naming') -const { assertObjectContains } = require('../../../integration-tests/helpers') describe('Plugin', () => { let tracer @@ -821,7 +820,7 @@ describe('Plugin', () => { return tracer.scope().activate(span, () => { return graphql.graphql({ schema, source, rootValue }) .then(value => { - expect(value).to.have.nested.property('data.hello', 'test') + assert.strictEqual(value?.data?.hello, 'test') assert.strictEqual(tracer.scope().active(), span) }) }) @@ -1509,7 +1508,8 @@ describe('Plugin', () => { try { assert.notStrictEqual(span, null) - expect(span.context()).to.have.property('_name', expectedSchema.server.opName) + assert.ok('_name' in span.context()); + assert.strictEqual(span.context()['_name'], expectedSchema.server.opName) done() } catch (e) { done(e) diff --git a/packages/datadog-plugin-graphql/test/integration-test/client.spec.js b/packages/datadog-plugin-graphql/test/integration-test/client.spec.js index 06bd537d388..291eb800f7e 100644 --- a/packages/datadog-plugin-graphql/test/integration-test/client.spec.js +++ b/packages/datadog-plugin-graphql/test/integration-test/client.spec.js @@ -1,5 +1,7 @@ 'use strict' +const assert = require('node:assert/strict') + const { FakeAgent, sandboxCwd, @@ -8,8 +10,6 @@ const { spawnPluginIntegrationTestProc } = require('../../../../integration-tests/helpers') const { withVersions } = require('../../../dd-trace/test/setup/mocha') -const { assert } = require('chai') - describe('esm', () => { let agent let proc @@ -29,8 +29,8 @@ describe('esm', () => { it('is instrumented', async () => { const res = agent.assertMessageReceived(({ headers, payload }) => { - assert.propertyVal(headers, 'host', `127.0.0.1:${agent.port}`) - assert.isArray(payload) + assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.ok(Array.isArray(payload)) assert.strictEqual(checkSpansForServiceName(payload, 'graphql.parse'), true) }) diff --git a/packages/datadog-plugin-grpc/test/integration-test/client.spec.js b/packages/datadog-plugin-grpc/test/integration-test/client.spec.js index d75eb36ab95..ee94c5811b1 100644 --- a/packages/datadog-plugin-grpc/test/integration-test/client.spec.js +++ b/packages/datadog-plugin-grpc/test/integration-test/client.spec.js @@ -1,5 +1,7 @@ 'use strict' +const assert = require('node:assert/strict') + const { FakeAgent, sandboxCwd, @@ -8,7 +10,6 @@ const { spawnPluginIntegrationTestProc } = require('../../../../integration-tests/helpers') const { withVersions } = require('../../../dd-trace/test/setup/mocha') -const { assert } = require('chai') const { NODE_MAJOR } = require('../../../../version') describe('esm', () => { @@ -30,8 +31,8 @@ describe('esm', () => { it('is instrumented', async () => { const res = agent.assertMessageReceived(({ headers, payload }) => { - assert.propertyVal(headers, 'host', `127.0.0.1:${agent.port}`) - assert.isArray(payload) + assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.ok(Array.isArray(payload)) assert.strictEqual(checkSpansForServiceName(payload, 'grpc.client'), true) }) proc = await spawnPluginIntegrationTestProc(sandboxCwd(), 'integration-test/server.mjs', agent.port) diff --git a/packages/datadog-plugin-grpc/test/server.spec.js b/packages/datadog-plugin-grpc/test/server.spec.js index 8373e85bd7a..1921af05727 100644 --- a/packages/datadog-plugin-grpc/test/server.spec.js +++ b/packages/datadog-plugin-grpc/test/server.spec.js @@ -2,10 +2,9 @@ const assert = require('node:assert/strict') -const { expect } = require('chai') const { after, afterEach, before, beforeEach, describe, it } = require('mocha') -const { assertObjectContains } = require('../../../integration-tests/helpers') +const { assertObjectContains } = require('../../../integration-tests/helpers') const Readable = require('node:stream').Readable const path = require('node:path') @@ -491,7 +490,8 @@ describe('Plugin', () => { callback(null, {}) try { - expect(call.metadata.getMap()).to.have.property('foo', 'bar') + assert.ok('foo' in call.metadata.getMap()); + assert.strictEqual(call.metadata.getMap()['foo'], 'bar') done() } catch (e) { done(e) diff --git a/packages/datadog-plugin-hapi/test/index.spec.js b/packages/datadog-plugin-hapi/test/index.spec.js index ea2b10231ad..a04bd686688 100644 --- a/packages/datadog-plugin-hapi/test/index.spec.js +++ b/packages/datadog-plugin-hapi/test/index.spec.js @@ -4,7 +4,6 @@ const assert = require('node:assert/strict') const { AsyncLocalStorage } = require('node:async_hooks') const axios = require('axios') -const { expect } = require('chai') const { after, afterEach, before, beforeEach, describe, it } = require('mocha') const semver = require('semver') @@ -109,7 +108,7 @@ describe('Plugin', () => { assert.ok(Object.hasOwn(traces[0][0].meta, 'http.status_code')) assert.strictEqual(traces[0][0].meta.component, 'hapi') assert.strictEqual(traces[0][0].meta['_dd.integration'], 'hapi') - expect(Number(traces[0][0].meta['http.status_code'])).to.be.within(200, 299) + assert.ok(((Number(traces[0][0].meta['http.status_code'])) >= (200) && (Number(traces[0][0].meta['http.status_code'])) <= (299))) }) .then(done) .catch(done) diff --git a/packages/datadog-plugin-http/test/integration-test/client.spec.js b/packages/datadog-plugin-http/test/integration-test/client.spec.js index c8d6e9fb3c4..35bd1b714aa 100644 --- a/packages/datadog-plugin-http/test/integration-test/client.spec.js +++ b/packages/datadog-plugin-http/test/integration-test/client.spec.js @@ -1,5 +1,7 @@ 'use strict' +const assert = require('node:assert/strict') + const { FakeAgent, sandboxCwd, @@ -7,8 +9,6 @@ const { curlAndAssertMessage, spawnPluginIntegrationTestProc } = require('../../../../integration-tests/helpers') -const { assert } = require('chai') - describe('esm', () => { let agent let proc @@ -30,12 +30,12 @@ describe('esm', () => { proc = await spawnPluginIntegrationTestProc(sandboxCwd(), 'server.mjs', agent.port) return curlAndAssertMessage(agent, proc, ({ headers, payload }) => { - assert.propertyVal(headers, 'host', `127.0.0.1:${agent.port}`) - assert.isArray(payload) + assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.ok(Array.isArray(payload)) assert.strictEqual(payload.length, 1) - assert.isArray(payload[0]) + assert.ok(Array.isArray(payload[0])) assert.strictEqual(payload[0].length, 1) - assert.propertyVal(payload[0][0], 'name', 'web.request') + assert.strictEqual(payload[0][0]['name'], 'web.request') }) }).timeout(20000) }) diff --git a/packages/datadog-plugin-http2/test/integration-test/client.spec.js b/packages/datadog-plugin-http2/test/integration-test/client.spec.js index 107b9712fdf..150b5bff9d9 100644 --- a/packages/datadog-plugin-http2/test/integration-test/client.spec.js +++ b/packages/datadog-plugin-http2/test/integration-test/client.spec.js @@ -1,5 +1,7 @@ 'use strict' +const assert = require('node:assert/strict') + const { FakeAgent, spawnPluginIntegrationTestProc, @@ -7,7 +9,6 @@ const { useSandbox, varySandbox } = require('../../../../integration-tests/helpers') -const { assert } = require('chai') const http2 = require('http2') describe('esm', () => { @@ -36,13 +37,13 @@ describe('esm', () => { it(`is instrumented loaded with ${variant}`, async () => { proc = await spawnPluginIntegrationTestProc(sandboxCwd(), variants[variant], agent.port) const resultPromise = agent.assertMessageReceived(({ headers, payload }) => { - assert.propertyVal(headers, 'host', `127.0.0.1:${agent.port}`) - assert.isArray(payload) + assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.ok(Array.isArray(payload)) assert.strictEqual(payload.length, 1) - assert.isArray(payload[0]) + assert.ok(Array.isArray(payload[0])) assert.strictEqual(payload[0].length, 1) - assert.propertyVal(payload[0][0], 'name', 'web.request') - assert.propertyVal(payload[0][0].meta, 'component', 'http2') + assert.strictEqual(payload[0][0]['name'], 'web.request') + assert.strictEqual(payload[0][0].meta['component'], 'http2') }) await curl(proc) return resultPromise diff --git a/packages/datadog-plugin-ioredis/test/integration-test/client.spec.js b/packages/datadog-plugin-ioredis/test/integration-test/client.spec.js index 3040361fbf9..abe4c76e95f 100644 --- a/packages/datadog-plugin-ioredis/test/integration-test/client.spec.js +++ b/packages/datadog-plugin-ioredis/test/integration-test/client.spec.js @@ -1,5 +1,7 @@ 'use strict' +const assert = require('node:assert/strict') + const { FakeAgent, checkSpansForServiceName, @@ -9,8 +11,6 @@ const { varySandbox } = require('../../../../integration-tests/helpers') const { withVersions } = require('../../../dd-trace/test/setup/mocha') -const { assert } = require('chai') - describe('esm', () => { let agent let proc @@ -35,8 +35,8 @@ describe('esm', () => { for (const variant of varySandbox.VARIANTS) { it(`is instrumented loaded with ${variant}`, async () => { const res = agent.assertMessageReceived(({ headers, payload }) => { - assert.propertyVal(headers, 'host', `127.0.0.1:${agent.port}`) - assert.isArray(payload) + assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.ok(Array.isArray(payload)) assert.strictEqual(checkSpansForServiceName(payload, 'redis.command'), true) }) diff --git a/packages/datadog-plugin-iovalkey/test/integration-test/client.spec.js b/packages/datadog-plugin-iovalkey/test/integration-test/client.spec.js index 748bee56069..5a214d2a9a0 100644 --- a/packages/datadog-plugin-iovalkey/test/integration-test/client.spec.js +++ b/packages/datadog-plugin-iovalkey/test/integration-test/client.spec.js @@ -1,5 +1,7 @@ 'use strict' +const assert = require('node:assert/strict') + const { FakeAgent, sandboxCwd, @@ -8,8 +10,6 @@ const { spawnPluginIntegrationTestProc } = require('../../../../integration-tests/helpers') const { withVersions } = require('../../../dd-trace/test/setup/mocha') -const { assert } = require('chai') - describe('esm', () => { let agent let proc @@ -29,8 +29,8 @@ describe('esm', () => { it('is instrumented', async () => { const res = agent.assertMessageReceived(({ headers, payload }) => { - assert.propertyVal(headers, 'host', `127.0.0.1:${agent.port}`) - assert.isArray(payload) + assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.ok(Array.isArray(payload)) assert.strictEqual(checkSpansForServiceName(payload, 'valkey.command'), true) }) diff --git a/packages/datadog-plugin-jest/test/util.spec.js b/packages/datadog-plugin-jest/test/util.spec.js index a86b5148dc2..b5759470455 100644 --- a/packages/datadog-plugin-jest/test/util.spec.js +++ b/packages/datadog-plugin-jest/test/util.spec.js @@ -3,11 +3,9 @@ const assert = require('node:assert/strict') const path = require('node:path') -const { expect } = require('chai') const { describe, it } = require('mocha') const { getFormattedJestTestParameters, getJestSuitesToRun } = require('../src/util') - describe('getFormattedJestTestParameters', () => { it('returns formatted parameters for arrays', () => { const result = getFormattedJestTestParameters([[[1, 2], [3, 4]]]) @@ -180,9 +178,7 @@ describe('getJestSuitesToRun', () => { const rootDir = __dirname getJestSuitesToRun(skippableSuites, tests, rootDir) - expect(globalConfig.testEnvironmentOptions._ddUnskippable) - .to.eql(JSON.stringify({ 'fixtures/test-unskippable.js': true })) - expect(globalConfig.testEnvironmentOptions._ddForcedToRun) - .to.eql(JSON.stringify({ 'fixtures/test-unskippable.js': true })) + assert.deepStrictEqual(globalConfig.testEnvironmentOptions._ddUnskippable, JSON.stringify({ 'fixtures/test-unskippable.js': true })) + assert.deepStrictEqual(globalConfig.testEnvironmentOptions._ddForcedToRun, JSON.stringify({ 'fixtures/test-unskippable.js': true })) }) }) diff --git a/packages/datadog-plugin-kafkajs/test/integration-test/client.spec.js b/packages/datadog-plugin-kafkajs/test/integration-test/client.spec.js index 5a1620b0e1d..4470aae6a2e 100644 --- a/packages/datadog-plugin-kafkajs/test/integration-test/client.spec.js +++ b/packages/datadog-plugin-kafkajs/test/integration-test/client.spec.js @@ -1,5 +1,7 @@ 'use strict' +const assert = require('node:assert/strict') + const { FakeAgent, sandboxCwd, @@ -8,8 +10,6 @@ const { spawnPluginIntegrationTestProc } = require('../../../../integration-tests/helpers') const { withVersions } = require('../../../dd-trace/test/setup/mocha') -const { assert } = require('chai') - describe('esm', () => { let agent let proc @@ -29,8 +29,8 @@ describe('esm', () => { it('is instrumented', async () => { const res = agent.assertMessageReceived(({ headers, payload }) => { - assert.propertyVal(headers, 'host', `127.0.0.1:${agent.port}`) - assert.isArray(payload) + assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.ok(Array.isArray(payload)) assert.strictEqual(checkSpansForServiceName(payload, 'kafka.produce'), true) }) diff --git a/packages/datadog-plugin-koa/test/index.spec.js b/packages/datadog-plugin-koa/test/index.spec.js index 770b5b7d6ba..892f1c32e08 100644 --- a/packages/datadog-plugin-koa/test/index.spec.js +++ b/packages/datadog-plugin-koa/test/index.spec.js @@ -9,10 +9,10 @@ const { after, afterEach, before, beforeEach, describe, it } = require('mocha') const semver = require('semver') const sinon = require('sinon') +const { assertObjectContains } = require('../../../integration-tests/helpers') const { ERROR_TYPE } = require('../../dd-trace/src/constants') const agent = require('../../dd-trace/test/plugins/agent') const { withVersions } = require('../../dd-trace/test/setup/mocha') -const { assertObjectContains } = require('../../../integration-tests/helpers') const sort = spans => spans.sort((a, b) => a.start.toString() >= b.start.toString() ? 1 : -1) @@ -520,8 +520,8 @@ describe('Plugin', () => { const spans = sort(traces[0]) assert.strictEqual(spans[0].resource, 'GET /forums/:fid/discussions/:did/posts/:pid') - expect(spans[0].meta) - .to.have.property('http.url', `http://localhost:${port}/forums/123/discussions/456/posts/789`) + assert.ok('http.url' in spans[0].meta); + assert.strictEqual(spans[0].meta['http.url'], `http://localhost:${port}/forums/123/discussions/456/posts/789`) }) .then(done) .catch(done) @@ -557,8 +557,8 @@ describe('Plugin', () => { const spans = sort(traces[0]) assert.strictEqual(spans[0].resource, 'GET /first/child') - expect(spans[0].meta) - .to.have.property('http.url', `http://localhost:${port}/first/child`) + assert.ok('http.url' in spans[0].meta); + assert.strictEqual(spans[0].meta['http.url'], `http://localhost:${port}/first/child`) }) .then(done) .catch(done) diff --git a/packages/datadog-plugin-koa/test/integration-test/client.spec.js b/packages/datadog-plugin-koa/test/integration-test/client.spec.js index 0853bdf8f82..41286fd8f24 100644 --- a/packages/datadog-plugin-koa/test/integration-test/client.spec.js +++ b/packages/datadog-plugin-koa/test/integration-test/client.spec.js @@ -1,5 +1,7 @@ 'use strict' +const assert = require('node:assert/strict') + const { FakeAgent, sandboxCwd, @@ -9,8 +11,6 @@ const { spawnPluginIntegrationTestProc } = require('../../../../integration-tests/helpers') const { withVersions } = require('../../../dd-trace/test/setup/mocha') -const { assert } = require('chai') - describe('esm', () => { let agent let proc @@ -32,8 +32,8 @@ describe('esm', () => { proc = await spawnPluginIntegrationTestProc(sandboxCwd(), 'server.mjs', agent.port) return curlAndAssertMessage(agent, proc, ({ headers, payload }) => { - assert.propertyVal(headers, 'host', `127.0.0.1:${agent.port}`) - assert.isArray(payload) + assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.ok(Array.isArray(payload)) assert.strictEqual(checkSpansForServiceName(payload, 'koa.request'), true) }) }).timeout(50000) diff --git a/packages/datadog-plugin-langchain/test/integration-test/client.spec.js b/packages/datadog-plugin-langchain/test/integration-test/client.spec.js index 62d3e63c445..18707d16955 100644 --- a/packages/datadog-plugin-langchain/test/integration-test/client.spec.js +++ b/packages/datadog-plugin-langchain/test/integration-test/client.spec.js @@ -1,5 +1,7 @@ 'use strict' +const assert = require('node:assert/strict') + const { FakeAgent, sandboxCwd, @@ -8,8 +10,6 @@ const { spawnPluginIntegrationTestProc } = require('../../../../integration-tests/helpers') const { withVersions } = require('../../../dd-trace/test/setup/mocha') -const { assert } = require('chai') - describe('esm', () => { let agent let proc @@ -34,8 +34,8 @@ describe('esm', () => { it('is instrumented', async () => { const res = agent.assertMessageReceived(({ headers, payload }) => { - assert.propertyVal(headers, 'host', `127.0.0.1:${agent.port}`) - assert.isArray(payload) + assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.ok(Array.isArray(payload)) assert.strictEqual(checkSpansForServiceName(payload, 'langchain.request'), true) }) diff --git a/packages/datadog-plugin-limitd-client/test/integration-test/client.spec.js b/packages/datadog-plugin-limitd-client/test/integration-test/client.spec.js index 1d92b029312..13e59731211 100644 --- a/packages/datadog-plugin-limitd-client/test/integration-test/client.spec.js +++ b/packages/datadog-plugin-limitd-client/test/integration-test/client.spec.js @@ -1,5 +1,7 @@ 'use strict' +const assert = require('node:assert/strict') + const { FakeAgent, checkSpansForServiceName, @@ -9,8 +11,6 @@ const { varySandbox } = require('../../../../integration-tests/helpers') const { withVersions } = require('../../../dd-trace/test/setup/mocha') -const { assert } = require('chai') - describe('esm', () => { let agent let proc @@ -35,8 +35,8 @@ describe('esm', () => { for (const variant of varySandbox.VARIANTS) { it(`is instrumented loaded with ${variant}`, async () => { const res = agent.assertMessageReceived(({ headers, payload }) => { - assert.propertyVal(headers, 'host', `127.0.0.1:${agent.port}`) - assert.isArray(payload) + assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.ok(Array.isArray(payload)) // not asserting for a limitd-client trace, // just asserting that we're not completely breaking when loading limitd-client with esm assert.strictEqual(checkSpansForServiceName(payload, 'tcp.connect'), true) diff --git a/packages/datadog-plugin-mariadb/test/integration-test/client.spec.js b/packages/datadog-plugin-mariadb/test/integration-test/client.spec.js index 8513c7a0525..e73f9cca684 100644 --- a/packages/datadog-plugin-mariadb/test/integration-test/client.spec.js +++ b/packages/datadog-plugin-mariadb/test/integration-test/client.spec.js @@ -1,5 +1,7 @@ 'use strict' +const assert = require('node:assert/strict') + const { FakeAgent, sandboxCwd, @@ -8,8 +10,6 @@ const { spawnPluginIntegrationTestProc } = require('../../../../integration-tests/helpers') const { withVersions } = require('../../../dd-trace/test/setup/mocha') -const { assert } = require('chai') - describe('esm', () => { let agent let proc @@ -30,8 +30,8 @@ describe('esm', () => { it('is instrumented', async () => { const res = agent.assertMessageReceived(({ headers, payload }) => { - assert.propertyVal(headers, 'host', `127.0.0.1:${agent.port}`) - assert.isArray(payload) + assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.ok(Array.isArray(payload)) assert.strictEqual(checkSpansForServiceName(payload, 'mariadb.query'), true) }) diff --git a/packages/datadog-plugin-memcached/test/integration-test/client.spec.js b/packages/datadog-plugin-memcached/test/integration-test/client.spec.js index 0b4e8ed2777..3eb8985d089 100644 --- a/packages/datadog-plugin-memcached/test/integration-test/client.spec.js +++ b/packages/datadog-plugin-memcached/test/integration-test/client.spec.js @@ -1,5 +1,7 @@ 'use strict' +const assert = require('node:assert/strict') + const { FakeAgent, sandboxCwd, @@ -8,8 +10,6 @@ const { spawnPluginIntegrationTestProc } = require('../../../../integration-tests/helpers') const { withVersions } = require('../../../dd-trace/test/setup/mocha') -const { assert } = require('chai') - describe('esm', () => { let agent let proc @@ -29,8 +29,8 @@ describe('esm', () => { it('is instrumented', async () => { const res = agent.assertMessageReceived(({ headers, payload }) => { - assert.propertyVal(headers, 'host', `127.0.0.1:${agent.port}`) - assert.isArray(payload) + assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.ok(Array.isArray(payload)) assert.strictEqual(checkSpansForServiceName(payload, 'memcached.command'), true) }) diff --git a/packages/datadog-plugin-microgateway-core/test/integration-test/client.spec.js b/packages/datadog-plugin-microgateway-core/test/integration-test/client.spec.js index af4a48c5378..4db1442ec38 100644 --- a/packages/datadog-plugin-microgateway-core/test/integration-test/client.spec.js +++ b/packages/datadog-plugin-microgateway-core/test/integration-test/client.spec.js @@ -1,5 +1,7 @@ 'use strict' +const assert = require('node:assert/strict') + const { FakeAgent, sandboxCwd, @@ -9,8 +11,6 @@ const { spawnPluginIntegrationTestProc } = require('../../../../integration-tests/helpers') const { withVersions } = require('../../../dd-trace/test/setup/mocha') -const { assert } = require('chai') - describe('esm', () => { let agent let proc @@ -33,8 +33,8 @@ describe('esm', () => { proc = await spawnPluginIntegrationTestProc(sandboxCwd(), 'server.mjs', agent.port) return curlAndAssertMessage(agent, proc, ({ headers, payload }) => { - assert.propertyVal(headers, 'host', `127.0.0.1:${agent.port}`) - assert.isArray(payload) + assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.ok(Array.isArray(payload)) assert.strictEqual(checkSpansForServiceName(payload, 'microgateway.request'), true) }) }).timeout(20000) diff --git a/packages/datadog-plugin-moleculer/test/integration-test/client.spec.js b/packages/datadog-plugin-moleculer/test/integration-test/client.spec.js index 752437eb185..44a50884c3e 100644 --- a/packages/datadog-plugin-moleculer/test/integration-test/client.spec.js +++ b/packages/datadog-plugin-moleculer/test/integration-test/client.spec.js @@ -1,5 +1,7 @@ 'use strict' +const assert = require('node:assert/strict') + const { FakeAgent, sandboxCwd, @@ -8,8 +10,6 @@ const { spawnPluginIntegrationTestProc } = require('../../../../integration-tests/helpers') const { withVersions } = require('../../../dd-trace/test/setup/mocha') -const { assert } = require('chai') - describe('esm', () => { let agent let proc @@ -30,8 +30,8 @@ describe('esm', () => { it('is instrumented', async () => { const res = agent.assertMessageReceived(({ headers, payload }) => { - assert.propertyVal(headers, 'host', `127.0.0.1:${agent.port}`) - assert.isArray(payload) + assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.ok(Array.isArray(payload)) assert.strictEqual(checkSpansForServiceName(payload, 'moleculer.action'), true) }) diff --git a/packages/datadog-plugin-mongodb-core/test/integration-test/client.spec.js b/packages/datadog-plugin-mongodb-core/test/integration-test/client.spec.js index 083bfb7847b..26b07127277 100644 --- a/packages/datadog-plugin-mongodb-core/test/integration-test/client.spec.js +++ b/packages/datadog-plugin-mongodb-core/test/integration-test/client.spec.js @@ -1,5 +1,7 @@ 'use strict' +const assert = require('node:assert/strict') + const { FakeAgent, checkSpansForServiceName, @@ -9,8 +11,6 @@ const { varySandbox } = require('../../../../integration-tests/helpers') const { withVersions } = require('../../../dd-trace/test/setup/mocha') -const { assert } = require('chai') - describe('esm', () => { let agent let proc @@ -36,8 +36,8 @@ describe('esm', () => { for (const variant of varySandbox.VARIANTS) { it(`is instrumented loaded with ${variant}`, async () => { const res = agent.assertMessageReceived(({ headers, payload }) => { - assert.propertyVal(headers, 'host', `127.0.0.1:${agent.port}`) - assert.isArray(payload) + assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.ok(Array.isArray(payload)) assert.strictEqual(checkSpansForServiceName(payload, 'mongodb.query'), true) }) @@ -69,8 +69,8 @@ describe('esm', () => { for (const variant of varySandbox.VARIANTS) { it(`is instrumented loaded with ${variant}`, async () => { const res = agent.assertMessageReceived(({ headers, payload }) => { - assert.propertyVal(headers, 'host', `127.0.0.1:${agent.port}`) - assert.isArray(payload) + assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.ok(Array.isArray(payload)) assert.strictEqual(checkSpansForServiceName(payload, 'mongodb.query'), true) }) diff --git a/packages/datadog-plugin-mongoose/test/integration-test/client.spec.js b/packages/datadog-plugin-mongoose/test/integration-test/client.spec.js index 1a2376eb31a..223124011b9 100644 --- a/packages/datadog-plugin-mongoose/test/integration-test/client.spec.js +++ b/packages/datadog-plugin-mongoose/test/integration-test/client.spec.js @@ -1,5 +1,7 @@ 'use strict' +const assert = require('node:assert/strict') + const { FakeAgent, checkSpansForServiceName, @@ -9,8 +11,6 @@ const { varySandbox } = require('../../../../integration-tests/helpers') const { withVersions } = require('../../../dd-trace/test/setup/mocha') -const { assert } = require('chai') - describe('esm', () => { let agent let proc @@ -35,8 +35,8 @@ describe('esm', () => { for (const variant of varySandbox.VARIANTS) { it(`is instrumented loaded with ${variant}`, async () => { const res = agent.assertMessageReceived(({ headers, payload }) => { - assert.propertyVal(headers, 'host', `127.0.0.1:${agent.port}`) - assert.isArray(payload) + assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.ok(Array.isArray(payload)) assert.strictEqual(checkSpansForServiceName(payload, 'mongodb.query'), true) }) diff --git a/packages/datadog-plugin-mysql/test/integration-test/client.spec.js b/packages/datadog-plugin-mysql/test/integration-test/client.spec.js index 00f76b4b30a..03e8b539449 100644 --- a/packages/datadog-plugin-mysql/test/integration-test/client.spec.js +++ b/packages/datadog-plugin-mysql/test/integration-test/client.spec.js @@ -1,5 +1,7 @@ 'use strict' +const assert = require('node:assert/strict') + const { FakeAgent, checkSpansForServiceName, @@ -9,8 +11,6 @@ const { varySandbox } = require('../../../../integration-tests/helpers') const { withVersions } = require('../../../dd-trace/test/setup/mocha') -const { assert } = require('chai') - describe('esm', () => { let agent let proc @@ -36,8 +36,8 @@ describe('esm', () => { for (const variant of varySandbox.VARIANTS) { it(`is instrumented loaded with ${variant}`, async () => { const res = agent.assertMessageReceived(({ headers, payload }) => { - assert.propertyVal(headers, 'host', `127.0.0.1:${agent.port}`) - assert.isArray(payload) + assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.ok(Array.isArray(payload)) assert.strictEqual(checkSpansForServiceName(payload, 'mysql.query'), true) }) diff --git a/packages/datadog-plugin-mysql2/test/integration-test/client.spec.js b/packages/datadog-plugin-mysql2/test/integration-test/client.spec.js index e93eee4969a..b1ffa891036 100644 --- a/packages/datadog-plugin-mysql2/test/integration-test/client.spec.js +++ b/packages/datadog-plugin-mysql2/test/integration-test/client.spec.js @@ -1,5 +1,7 @@ 'use strict' +const assert = require('node:assert/strict') + const { FakeAgent, sandboxCwd, @@ -8,8 +10,6 @@ const { spawnPluginIntegrationTestProc } = require('../../../../integration-tests/helpers') const { withVersions } = require('../../../dd-trace/test/setup/mocha') -const { assert } = require('chai') - describe('esm', () => { let agent let proc @@ -29,8 +29,8 @@ describe('esm', () => { it('is instrumented', async () => { const res = agent.assertMessageReceived(({ headers, payload }) => { - assert.propertyVal(headers, 'host', `127.0.0.1:${agent.port}`) - assert.isArray(payload) + assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.ok(Array.isArray(payload)) assert.strictEqual(checkSpansForServiceName(payload, 'mysql.query'), true) }) diff --git a/packages/datadog-plugin-net/test/index.spec.js b/packages/datadog-plugin-net/test/index.spec.js index 614620898c2..8c81bd8a4a8 100644 --- a/packages/datadog-plugin-net/test/index.spec.js +++ b/packages/datadog-plugin-net/test/index.spec.js @@ -3,15 +3,13 @@ const assert = require('node:assert/strict') const dns = require('node:dns') -const { expect } = require('chai') const { afterEach, beforeEach, describe, it } = require('mocha') +const { assertObjectContains } = require('../../../integration-tests/helpers') const { ERROR_MESSAGE, ERROR_TYPE, ERROR_STACK } = require('../../dd-trace/src/constants') const agent = require('../../dd-trace/test/plugins/agent') const { expectSomeSpan } = require('../../dd-trace/test/plugins/helpers') const { withPeerService } = require('../../dd-trace/test/setup/mocha') -const { assertObjectContains } = require('../../../integration-tests/helpers') - describe('Plugin', () => { let net let tcp @@ -195,7 +193,7 @@ describe('Plugin', () => { agent .assertSomeTraces(traces => { - expect(traces[0][0]).to.deep.include({ + assertObjectContains(traces[0][0], { name: 'tcp.connect', service: 'test', resource: `localhost:${port}` @@ -240,7 +238,7 @@ describe('Plugin', () => { socket.once('close', () => { setImmediate(() => { // Node.js 21.2 broke this function. We'll have to do the more manual way for now. - // expect(socket.eventNames()).to.not.include.members(events) + // assert.ok((socket.eventNames(), events) for (const event of events) { assert.strictEqual(socket.listeners(event).length, 0) } diff --git a/packages/datadog-plugin-net/test/integration-test/client.spec.js b/packages/datadog-plugin-net/test/integration-test/client.spec.js index 95767ee1265..79a3c522791 100644 --- a/packages/datadog-plugin-net/test/integration-test/client.spec.js +++ b/packages/datadog-plugin-net/test/integration-test/client.spec.js @@ -1,5 +1,7 @@ 'use strict' +const assert = require('node:assert/strict') + const { FakeAgent, checkSpansForServiceName, @@ -8,8 +10,6 @@ const { useSandbox, varySandbox } = require('../../../../integration-tests/helpers') -const { assert } = require('chai') - describe('esm', () => { let agent let proc @@ -35,8 +35,8 @@ describe('esm', () => { for (const variant of varySandbox.VARIANTS) { it(`is instrumented loaded with ${variant}`, async () => { const res = agent.assertMessageReceived(({ headers, payload }) => { - assert.propertyVal(headers, 'host', `127.0.0.1:${agent.port}`) - assert.isArray(payload) + assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.ok(Array.isArray(payload)) assert.strictEqual(checkSpansForServiceName(payload, 'tcp.connect'), true) const metaContainsNet = payload.some((span) => span.some((nestedSpan) => nestedSpan.meta.component === 'net')) assert.strictEqual(metaContainsNet, true) diff --git a/packages/datadog-plugin-openai/test/index.spec.js b/packages/datadog-plugin-openai/test/index.spec.js index 8ff363979c2..479d90224e5 100644 --- a/packages/datadog-plugin-openai/test/index.spec.js +++ b/packages/datadog-plugin-openai/test/index.spec.js @@ -5,7 +5,6 @@ const fs = require('fs') const assert = require('node:assert/strict') const Path = require('path') -const { expect } = require('chai') const semver = require('semver') const sinon = require('sinon') @@ -237,9 +236,8 @@ describe('Plugin', () => { } assert.strictEqual(traces[0][0].error, 0) assert.strictEqual(traces[0][0].meta['openai.request.method'], 'POST') - expect(traces[0][0].meta).to.have.property( - 'openai.request.endpoint', '/vcr/openai/completions' - ) + assert.ok('openai.request.endpoint' in traces[0][0].meta); + assert.strictEqual(traces[0][0].meta['openai.request.endpoint'], '/vcr/openai/completions') assert.strictEqual(traces[0][0].meta.component, 'openai') assert.strictEqual(traces[0][0].meta['_dd.integration'], 'openai') @@ -503,9 +501,8 @@ describe('Plugin', () => { assert.strictEqual(traces[0][0].meta['openai.request.endpoint'], '/v1/models/*') assert.strictEqual(traces[0][0].metrics['openai.response.deleted'], 1) - expect(traces[0][0].meta).to.have.property( - 'openai.response.id', 'ft:gpt-4.1-mini-2025-04-14:datadog-staging::BkaILRSh' - ) + assert.ok('openai.response.id' in traces[0][0].meta); + assert.strictEqual(traces[0][0].meta['openai.response.id'], 'ft:gpt-4.1-mini-2025-04-14:datadog-staging::BkaILRSh') }) if (semver.satisfies(realVersion, '>=4.0.0')) { @@ -718,9 +715,8 @@ describe('Plugin', () => { } assert.strictEqual(traces[0][0].error, 0) assert.strictEqual(traces[0][0].meta['openai.request.method'], 'POST') - expect(traces[0][0].meta).to.have.property( - 'openai.request.endpoint', '/vcr/openai/fine_tuning/jobs' - ) + assert.ok('openai.request.endpoint' in traces[0][0].meta); + assert.strictEqual(traces[0][0].meta['openai.request.endpoint'], '/vcr/openai/fine_tuning/jobs') assert.strictEqual(traces[0][0].meta['openai.request.model'], 'gpt-4.1-mini-2025-04-14') assert.match(traces[0][0].meta['openai.response.id'], /^ftjob-/) @@ -840,9 +836,8 @@ describe('Plugin', () => { } assert.strictEqual(traces[0][0].error, 0) assert.strictEqual(traces[0][0].meta['openai.request.method'], 'GET') - expect(traces[0][0].meta).to.have.property( - 'openai.request.endpoint', '/vcr/openai/fine_tuning/jobs' - ) + assert.ok('openai.request.endpoint' in traces[0][0].meta); + assert.strictEqual(traces[0][0].meta['openai.request.endpoint'], '/vcr/openai/fine_tuning/jobs') assert.ok(Object.hasOwn(traces[0][0].metrics, 'openai.response.count')) }) @@ -909,9 +904,8 @@ describe('Plugin', () => { } assert.strictEqual(traces[0][0].error, 0) assert.strictEqual(traces[0][0].meta['openai.request.method'], 'POST') - expect(traces[0][0].meta).to.have.property( - 'openai.request.endpoint', '/vcr/openai/images/generations' - ) + assert.ok('openai.request.endpoint' in traces[0][0].meta); + assert.strictEqual(traces[0][0].meta['openai.request.endpoint'], '/vcr/openai/images/generations') assert.strictEqual(traces[0][0].meta['openai.request.model'], 'dall-e-3') }) @@ -971,9 +965,8 @@ describe('Plugin', () => { } assert.strictEqual(traces[0][0].error, 0) assert.strictEqual(traces[0][0].meta['openai.request.method'], 'POST') - expect(traces[0][0].meta).to.have.property( - 'openai.request.endpoint', '/vcr/openai/images/edits' - ) + assert.ok('openai.request.endpoint' in traces[0][0].meta); + assert.strictEqual(traces[0][0].meta['openai.request.endpoint'], '/vcr/openai/images/edits') // TODO(sabrenner): fix in a follow-up (super simple - img.name) }) @@ -1015,9 +1008,8 @@ describe('Plugin', () => { } assert.strictEqual(traces[0][0].error, 0) assert.strictEqual(traces[0][0].meta['openai.request.method'], 'POST') - expect(traces[0][0].meta).to.have.property( - 'openai.request.endpoint', '/vcr/openai/images/variations' - ) + assert.ok('openai.request.endpoint' in traces[0][0].meta); + assert.strictEqual(traces[0][0].meta['openai.request.endpoint'], '/vcr/openai/images/variations') }) if (semver.satisfies(realVersion, '>=4.0.0')) { @@ -1060,9 +1052,8 @@ describe('Plugin', () => { } assert.strictEqual(traces[0][0].error, 0) - expect(traces[0][0].meta).to.have.property( - 'openai.request.endpoint', '/vcr/openai/audio/transcriptions' - ) + assert.ok('openai.request.endpoint' in traces[0][0].meta); + assert.strictEqual(traces[0][0].meta['openai.request.endpoint'], '/vcr/openai/audio/transcriptions') assert.strictEqual(traces[0][0].meta['openai.request.method'], 'POST') assert.strictEqual(traces[0][0].meta['openai.request.model'], 'gpt-4o-mini-transcribe') }) @@ -1103,9 +1094,8 @@ describe('Plugin', () => { } assert.strictEqual(traces[0][0].error, 0) - expect(traces[0][0].meta).to.have.property( - 'openai.request.endpoint', '/vcr/openai/audio/translations' - ) + assert.ok('openai.request.endpoint' in traces[0][0].meta); + assert.strictEqual(traces[0][0].meta['openai.request.endpoint'], '/vcr/openai/audio/translations') assert.strictEqual(traces[0][0].meta['openai.request.method'], 'POST') assert.strictEqual(traces[0][0].meta['openai.request.model'], 'whisper-1') }) @@ -1156,9 +1146,8 @@ describe('Plugin', () => { assert.strictEqual(traces[0][0].error, 0) assert.strictEqual(traces[0][0].meta['openai.request.method'], 'POST') - expect(traces[0][0].meta).to.have.property( - 'openai.request.endpoint', '/vcr/openai/chat/completions' - ) + assert.ok('openai.request.endpoint' in traces[0][0].meta); + assert.strictEqual(traces[0][0].meta['openai.request.endpoint'], '/vcr/openai/chat/completions') assert.strictEqual(traces[0][0].meta['openai.request.model'], 'gpt-3.5-turbo') assert.ok(Object.hasOwn(traces[0][0].meta, 'openai.response.model')) diff --git a/packages/datadog-plugin-openai/test/integration-test/client.spec.js b/packages/datadog-plugin-openai/test/integration-test/client.spec.js index 39e39e587d0..6fd6ab0b3a1 100644 --- a/packages/datadog-plugin-openai/test/integration-test/client.spec.js +++ b/packages/datadog-plugin-openai/test/integration-test/client.spec.js @@ -1,5 +1,7 @@ 'use strict' +const assert = require('node:assert/strict') + const { FakeAgent, sandboxCwd, @@ -8,8 +10,6 @@ const { spawnPluginIntegrationTestProc, } = require('../../../../integration-tests/helpers') const { withVersions } = require('../../../dd-trace/test/setup/mocha') -const { assert } = require('chai') - describe('esm', () => { let agent let proc @@ -40,8 +40,8 @@ describe('esm', () => { it('is instrumented', async () => { const res = agent.assertMessageReceived(({ headers, payload }) => { - assert.propertyVal(headers, 'host', `127.0.0.1:${agent.port}`) - assert.isArray(payload) + assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.ok(Array.isArray(payload)) assert.strictEqual( checkSpansForServiceName(payload, 'openai.request'), true diff --git a/packages/datadog-plugin-opensearch/test/index.spec.js b/packages/datadog-plugin-opensearch/test/index.spec.js index d5c062b6b4f..30fc5df742e 100644 --- a/packages/datadog-plugin-opensearch/test/index.spec.js +++ b/packages/datadog-plugin-opensearch/test/index.spec.js @@ -2,7 +2,6 @@ const assert = require('node:assert/strict') -const { expect } = require('chai') const { after, afterEach, before, beforeEach, describe, it } = require('mocha') const { ERROR_MESSAGE, ERROR_TYPE, ERROR_STACK } = require('../../dd-trace/src/constants') @@ -10,7 +9,6 @@ const agent = require('../../dd-trace/test/plugins/agent') const { breakThen, unbreakThen } = require('../../dd-trace/test/plugins/helpers') const { withNamingSchema, withPeerService, withVersions } = require('../../dd-trace/test/setup/mocha') const { expectedSchema, rawExpectedSchema } = require('./naming') - describe('Plugin', () => { let opensearch let tracer @@ -99,10 +97,8 @@ describe('Plugin', () => { assert.strictEqual(traces[0][0].meta['span.kind'], 'client') assert.strictEqual(traces[0][0].meta['opensearch.method'], 'POST') assert.strictEqual(traces[0][0].meta['opensearch.url'], '/_msearch') - expect(traces[0][0].meta).to.have.property( - 'opensearch.body', - '[{"index":"docs"},{"query":{"match_all":{}}},{"index":"docs2"},{"query":{"match_all":{}}}]' - ) + assert.ok('opensearch.body' in traces[0][0].meta); + assert.strictEqual(traces[0][0].meta['opensearch.body'], '[{"index":"docs"},{"query":{"match_all":{}}},{"index":"docs2"},{"query":{"match_all":{}}}]') assert.strictEqual(traces[0][0].meta['opensearch.params'], '{"size":100}') assert.strictEqual(traces[0][0].meta.component, 'opensearch') assert.strictEqual(traces[0][0].meta['_dd.integration'], 'opensearch') @@ -192,13 +188,13 @@ describe('Plugin', () => { }) it('should support aborting the query', () => { - expect(() => { + assert.doesNotThrow(() => { const promise = client.ping() if (promise.abort) { promise.abort() } - }).not.to.throw() + }) }) it('should work with userland promises', done => { diff --git a/packages/datadog-plugin-opensearch/test/integration-test/client.spec.js b/packages/datadog-plugin-opensearch/test/integration-test/client.spec.js index 8b940c65e03..faf9d6d71f9 100644 --- a/packages/datadog-plugin-opensearch/test/integration-test/client.spec.js +++ b/packages/datadog-plugin-opensearch/test/integration-test/client.spec.js @@ -1,5 +1,7 @@ 'use strict' +const assert = require('node:assert/strict') + const { FakeAgent, sandboxCwd, @@ -8,8 +10,6 @@ const { spawnPluginIntegrationTestProc } = require('../../../../integration-tests/helpers') const { withVersions } = require('../../../dd-trace/test/setup/mocha') -const { assert } = require('chai') - describe('esm', () => { let agent let proc @@ -29,8 +29,8 @@ describe('esm', () => { it('is instrumented', async () => { const res = agent.assertMessageReceived(({ headers, payload }) => { - assert.propertyVal(headers, 'host', `127.0.0.1:${agent.port}`) - assert.isArray(payload) + assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.ok(Array.isArray(payload)) assert.strictEqual(checkSpansForServiceName(payload, 'opensearch.query'), true) }) diff --git a/packages/datadog-plugin-oracledb/test/integration-test/client.spec.js b/packages/datadog-plugin-oracledb/test/integration-test/client.spec.js index 18e6fcd7bd3..b8b1ce90138 100644 --- a/packages/datadog-plugin-oracledb/test/integration-test/client.spec.js +++ b/packages/datadog-plugin-oracledb/test/integration-test/client.spec.js @@ -1,5 +1,7 @@ 'use strict' +const assert = require('node:assert/strict') + const { FakeAgent, sandboxCwd, @@ -8,8 +10,6 @@ const { spawnPluginIntegrationTestProc } = require('../../../../integration-tests/helpers') const { withVersions } = require('../../../dd-trace/test/setup/mocha') -const { assert } = require('chai') - describe('esm', () => { let agent let proc @@ -29,8 +29,8 @@ describe('esm', () => { it('is instrumented', async () => { const res = agent.assertMessageReceived(({ headers, payload }) => { - assert.propertyVal(headers, 'host', `127.0.0.1:${agent.port}`) - assert.isArray(payload) + assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.ok(Array.isArray(payload)) assert.strictEqual(checkSpansForServiceName(payload, 'oracle.query'), true) }) diff --git a/packages/datadog-plugin-pg/test/integration-test/client.spec.js b/packages/datadog-plugin-pg/test/integration-test/client.spec.js index 088b5a8e15d..a14bda65ec2 100644 --- a/packages/datadog-plugin-pg/test/integration-test/client.spec.js +++ b/packages/datadog-plugin-pg/test/integration-test/client.spec.js @@ -1,5 +1,7 @@ 'use strict' +const assert = require('node:assert/strict') + const { FakeAgent, checkSpansForServiceName, @@ -9,7 +11,6 @@ const { varySandbox } = require('../../../../integration-tests/helpers') const { withVersions } = require('../../../dd-trace/test/setup/mocha') -const { assert } = require('chai') const semver = require('semver') describe('esm', () => { @@ -45,8 +46,8 @@ describe('esm', () => { for (const variant of varySandbox.VARIANTS) { it(`is instrumented loaded with ${variant}`, async () => { const res = agent.assertMessageReceived(({ headers, payload }) => { - assert.propertyVal(headers, 'host', `127.0.0.1:${agent.port}`) - assert.isArray(payload) + assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.ok(Array.isArray(payload)) assert.strictEqual(checkSpansForServiceName(payload, 'pg.query'), true) }) diff --git a/packages/datadog-plugin-pino/test/index.spec.js b/packages/datadog-plugin-pino/test/index.spec.js index 149b205ffcf..d1d2da7972f 100644 --- a/packages/datadog-plugin-pino/test/index.spec.js +++ b/packages/datadog-plugin-pino/test/index.spec.js @@ -1,15 +1,16 @@ 'use strict' -const { expect } = require('chai') -const { describe, it, beforeEach, afterEach } = require('mocha') +const assert = require('node:assert/strict') +const { Writable } = require('node:stream') + +const { afterEach, beforeEach, describe, it } = require('mocha') const semver = require('semver') const sinon = require('sinon') -const { Writable } = require('node:stream') - -const { withExports, withVersions } = require('../../dd-trace/test/setup/mocha') -const agent = require('../../dd-trace/test/plugins/agent') const { NODE_MAJOR } = require('../../../version') +const agent = require('../../dd-trace/test/plugins/agent') +const { withExports, withVersions } = require('../../dd-trace/test/setup/mocha') +const { assertObjectContains } = require('../../../integration-tests/helpers') describe('Plugin', () => { let logger @@ -66,12 +67,13 @@ describe('Plugin', () => { tracer.scope().activate(span, () => { logger.info('message') - expect(stream.write).to.have.been.called + sinon.assert.called(stream.write) const record = JSON.parse(stream.write.firstCall.args[0].toString()) - expect(record).to.have.property('dd') - expect(record).to.have.deep.property('msg', 'message') + assert.ok('dd' in record) + assert.ok('msg' in record); +assert.deepStrictEqual(record['msg'], 'message') }) }) @@ -82,13 +84,13 @@ describe('Plugin', () => { tracer.scope().activate(span, () => { logger.info('message') - expect(stream.write).to.have.been.called + sinon.assert.called(stream.write) const record = stream.write.firstCall.args[0].toString() - expect(record).to.include('trace_id') - expect(record).to.include('span_id') - expect(record).to.include('message') + assertObjectContains(record, 'trace_id') + assertObjectContains(record, 'span_id') + assertObjectContains(record, 'message') }) }) } @@ -111,16 +113,17 @@ describe('Plugin', () => { tracer.scope().activate(span, () => { logger.info('message') - expect(stream.write).to.have.been.called + sinon.assert.called(stream.write) const record = JSON.parse(stream.write.firstCall.args[0].toString()) - expect(record.dd).to.deep.include({ + assertObjectContains(record.dd, { trace_id: span.context().toTraceId(true), span_id: span.context().toSpanId() }) - expect(record).to.have.deep.property('msg', 'message') + assert.ok('msg' in record); +assert.deepStrictEqual(record['msg'], 'message') }) }) @@ -133,15 +136,21 @@ describe('Plugin', () => { const record = JSON.parse(stream.write.firstCall.args[0].toString()) if (record.err) { // pino >=7 - expect(record.err).to.have.property('message', error.message) - expect(record.err).to.have.property('type', 'Error') - expect(record.err).to.have.property('stack', error.stack) + assert.ok('message' in record.err); + assert.strictEqual(record.err['message'], error.message) + assert.ok('type' in record.err); + assert.strictEqual(record.err['type'], 'Error') + assert.ok('stack' in record.err); + assert.strictEqual(record.err['stack'], error.stack) } else { // pino <7 - expect(record).to.have.property('msg', error.message) + assert.ok('msg' in record); + assert.strictEqual(record['msg'], error.message) // ** TODO ** add this back once we fix it if (NODE_MAJOR < 21) { - expect(record).to.have.property('type', 'Error') - expect(record).to.have.property('stack', error.stack) + assert.ok('type' in record); + assert.strictEqual(record['type'], 'Error') + assert.ok('stack' in record); + assert.strictEqual(record['stack'], error.stack) } } }) @@ -155,21 +164,22 @@ describe('Plugin', () => { logger.info(record) - expect(record).to.not.have.property('dd') + assert.ok(!('dd' in record)) }) }) it('should not inject trace_id or span_id without an active span', () => { logger.info('message') - expect(stream.write).to.have.been.called + sinon.assert.called(stream.write) const record = JSON.parse(stream.write.firstCall.args[0].toString()) - expect(record).to.have.property('dd') - expect(record.dd).to.not.have.property('trace_id') - expect(record.dd).to.not.have.property('span_id') - expect(record).to.have.deep.property('msg', 'message') + assert.ok('dd' in record) + assert.ok(!('trace_id' in record.dd)) + assert.ok(!('span_id' in record.dd)) + assert.ok('msg' in record); +assert.deepStrictEqual(record['msg'], 'message') }) if (semver.intersects(version, '>=5.14.0')) { @@ -183,19 +193,21 @@ describe('Plugin', () => { tracer.scope().activate(span, () => { logger.info('message') - expect(opts.mixin).to.have.been.called + sinon.assert.called(opts.mixin) - expect(stream.write).to.have.been.called + sinon.assert.called(stream.write) const record = JSON.parse(stream.write.firstCall.args[0].toString()) - expect(record.dd).to.deep.include({ + assertObjectContains(record.dd, { trace_id: span.context().toTraceId(true), span_id: span.context().toSpanId() }) - expect(record).to.have.deep.property('msg', 'message') - expect(record).to.have.deep.property('addedMixin', true) + assert.ok('msg' in record); +assert.deepStrictEqual(record['msg'], 'message') + assert.ok('addedMixin' in record); +assert.deepStrictEqual(record['addedMixin'], true) }) }) } @@ -209,14 +221,14 @@ describe('Plugin', () => { tracer.scope().activate(span, () => { logger.info('message') - expect(stream.write).to.have.been.called + sinon.assert.called(stream.write) const record = stream.write.firstCall.args[0].toString() - expect(record).to.match(new RegExp(`trace_id\\W+?${span.context().toTraceId(true)}`)) - expect(record).to.match(new RegExp(`span_id\\W+?${span.context().toSpanId()}`)) + assert.match(record, new RegExp(`trace_id\\W+?${span.context().toTraceId(true)}`)) + assert.match(record, new RegExp(`span_id\\W+?${span.context().toSpanId()}`)) - expect(record).to.include('message') + assertObjectContains(record, 'message') }) }) } diff --git a/packages/datadog-plugin-prisma/test/index.spec.js b/packages/datadog-plugin-prisma/test/index.spec.js index 13117b16f0f..969ee6d5e34 100644 --- a/packages/datadog-plugin-prisma/test/index.spec.js +++ b/packages/datadog-plugin-prisma/test/index.spec.js @@ -5,7 +5,6 @@ const { execSync } = require('node:child_process') const fs = require('node:fs/promises') const path = require('node:path') -const { expect } = require('chai') const { after, before, beforeEach, describe, it } = require('mocha') const semifies = require('semifies') @@ -14,7 +13,6 @@ const { ERROR_MESSAGE, ERROR_TYPE, ERROR_STACK } = require('../../dd-trace/src/c const agent = require('../../dd-trace/test/plugins/agent') const { withNamingSchema, withVersions } = require('../../dd-trace/test/setup/mocha') const { expectedSchema, rawExpectedSchema } = require('./naming') - describe('Plugin', () => { let prisma let prismaClient @@ -252,7 +250,7 @@ describe('Plugin', () => { it('should disable prisma client', async () => { const tracingPromise = agent.assertSomeTraces(traces => { const clientSpans = traces[0].find(span => span.meta['prisma.type'] === 'client') - expect(clientSpans).not.to.exist + assert.ok(clientSpans == null) }) await Promise.all([ @@ -286,7 +284,7 @@ describe('Plugin', () => { it('should disable prisma engine', async () => { const tracingPromise = agent.assertSomeTraces(traces => { const engineSpans = traces[0].find(span => span.meta['prisma.type'] === 'engine') - expect(engineSpans).not.to.exist + assert.ok(engineSpans == null) }) await Promise.all([ diff --git a/packages/datadog-plugin-redis/test/integration-test/client.spec.js b/packages/datadog-plugin-redis/test/integration-test/client.spec.js index 1bd13f7c273..b70ac54c87b 100644 --- a/packages/datadog-plugin-redis/test/integration-test/client.spec.js +++ b/packages/datadog-plugin-redis/test/integration-test/client.spec.js @@ -1,5 +1,7 @@ 'use strict' +const assert = require('node:assert/strict') + const { FakeAgent, sandboxCwd, @@ -8,8 +10,6 @@ const { spawnPluginIntegrationTestProc } = require('../../../../integration-tests/helpers') const { withVersions } = require('../../../dd-trace/test/setup/mocha') -const { assert } = require('chai') - describe('esm', () => { let agent let proc @@ -30,8 +30,8 @@ describe('esm', () => { it('is instrumented', async () => { const res = agent.assertMessageReceived(({ headers, payload }) => { - assert.propertyVal(headers, 'host', `127.0.0.1:${agent.port}`) - assert.isArray(payload) + assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.ok(Array.isArray(payload)) assert.strictEqual(checkSpansForServiceName(payload, 'redis.command'), true) }) diff --git a/packages/datadog-plugin-restify/test/integration-test/client.spec.js b/packages/datadog-plugin-restify/test/integration-test/client.spec.js index d35f448b975..9a5e00ff171 100644 --- a/packages/datadog-plugin-restify/test/integration-test/client.spec.js +++ b/packages/datadog-plugin-restify/test/integration-test/client.spec.js @@ -1,5 +1,7 @@ 'use strict' +const assert = require('node:assert/strict') + const { FakeAgent, sandboxCwd, @@ -9,8 +11,6 @@ const { spawnPluginIntegrationTestProc } = require('../../../../integration-tests/helpers') const { withVersions } = require('../../../dd-trace/test/setup/mocha') -const { assert } = require('chai') - describe('esm', () => { let agent let proc @@ -33,8 +33,8 @@ describe('esm', () => { proc = await spawnPluginIntegrationTestProc(sandboxCwd(), 'server.mjs', agent.port) return curlAndAssertMessage(agent, proc, ({ headers, payload }) => { - assert.propertyVal(headers, 'host', `127.0.0.1:${agent.port}`) - assert.isArray(payload) + assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.ok(Array.isArray(payload)) assert.strictEqual(checkSpansForServiceName(payload, 'restify.request'), true) }) }).timeout(20000) diff --git a/packages/datadog-plugin-rhea/test/index.spec.js b/packages/datadog-plugin-rhea/test/index.spec.js index 75789173735..821800d101d 100644 --- a/packages/datadog-plugin-rhea/test/index.spec.js +++ b/packages/datadog-plugin-rhea/test/index.spec.js @@ -1,13 +1,15 @@ 'use strict' -const { expect } = require('chai') -const { describe, it, beforeEach, afterEach } = require('mocha') +const assert = require('node:assert/strict') + +const { after, afterEach, before, beforeEach, describe, it } = require('mocha') const sinon = require('sinon') -const { withNamingSchema, withPeerService, withVersions } = require('../../dd-trace/test/setup/mocha') -const agent = require('../../dd-trace/test/plugins/agent') const { ERROR_MESSAGE, ERROR_TYPE, ERROR_STACK } = require('../../dd-trace/src/constants') +const agent = require('../../dd-trace/test/plugins/agent') +const { withNamingSchema, withPeerService, withVersions } = require('../../dd-trace/test/setup/mocha') const { expectedSchema, rawExpectedSchema } = require('./naming') +const { assertObjectContains } = require('../../../integration-tests/helpers') describe('Plugin', () => { let tracer @@ -65,7 +67,7 @@ describe('Plugin', () => { produceSpanMeta = span.meta } - expect(produceSpanMeta).to.include({ + assertObjectContains(produceSpanMeta, { 'pathway.hash': expectedProducerHash }) }, { timeoutMs: 2000 }).then(done, done) @@ -85,7 +87,7 @@ describe('Plugin', () => { consumeSpanMeta = span.meta } - expect(consumeSpanMeta).to.include({ + assertObjectContains(consumeSpanMeta, { 'pathway.hash': expectedConsumerHash }) }, { timeoutMs: 2000 }).then(done, done) @@ -103,8 +105,8 @@ describe('Plugin', () => { }) } }, { timeoutMs: 2000 }) - expect(statsPointsReceived).to.be.at.least(1) - expect(agent.dsmStatsExist(agent, expectedProducerHash)).to.equal(true) + assert.ok(((statsPointsReceived) >= (1))) + assert.strictEqual(agent.dsmStatsExist(agent, expectedProducerHash), true) }).then(done, done) context.sender.send({ body: 'hello from DSM' }) @@ -121,8 +123,8 @@ describe('Plugin', () => { }) } }) - expect(statsPointsReceived).to.be.at.least(2) - expect(agent.dsmStatsExist(agent, expectedConsumerHash)).to.equal(true) + assert.ok(((statsPointsReceived) >= (2))) + assert.strictEqual(agent.dsmStatsExist(agent, expectedConsumerHash), true) }, { timeoutMs: 2000 }).then(done, done) context.sender.send({ body: 'hello from DSM' }) @@ -146,14 +148,14 @@ describe('Plugin', () => { it('should automatically instrument', (done) => { agent.assertSomeTraces(traces => { const span = traces[0][0] - expect(span).to.include({ + assertObjectContains(span, { name: expectedSchema.send.opName, resource: 'amq.topic', error: 0, service: expectedSchema.send.serviceName }) - expect(span).to.not.have.property('type') - expect(span.meta).to.include({ + assert.ok(!('type' in span)) + assertObjectContains(span.meta, { 'span.kind': 'producer', 'amqp.link.target.address': 'amq.topic', 'amqp.link.role': 'sender', @@ -161,7 +163,7 @@ describe('Plugin', () => { 'out.host': 'localhost', component: 'rhea' }) - expect(span.metrics).to.include({ + assertObjectContains(span.metrics, { 'network.destination.port': 5673 }) }) @@ -172,8 +174,8 @@ describe('Plugin', () => { it('should inject span context', (done) => { container.once('message', msg => { const keys = Object.keys(msg.message.delivery_annotations) - expect(keys).to.include('x-datadog-trace-id') - expect(keys).to.include('x-datadog-parent-id') + assertObjectContains(keys, 'x-datadog-trace-id') + assertObjectContains(keys, 'x-datadog-parent-id') done() }) context.sender.send({ body: 'Hello World!' }) @@ -182,8 +184,8 @@ describe('Plugin', () => { it('should inject span context with encoded messages', (done) => { container.once('message', msg => { const keys = Object.keys(msg.message.delivery_annotations) - expect(keys).to.include('x-datadog-trace-id') - expect(keys).to.include('x-datadog-parent-id') + assertObjectContains(keys, 'x-datadog-trace-id') + assertObjectContains(keys, 'x-datadog-parent-id') done() }) tracer.trace('web.request', () => { @@ -202,14 +204,14 @@ describe('Plugin', () => { it('should automatically instrument', done => { agent.assertSomeTraces(traces => { const span = traces[0][0] - expect(span).to.include({ + assertObjectContains(span, { name: expectedSchema.receive.opName, resource: 'amq.topic', error: 0, service: expectedSchema.receive.serviceName, type: 'worker' }) - expect(span.meta).to.include({ + assertObjectContains(span.meta, { 'span.kind': 'consumer', 'amqp.link.source.address': 'amq.topic', 'amqp.link.role': 'receiver', @@ -223,7 +225,7 @@ describe('Plugin', () => { it('should extract the span context', done => { container.once('message', msg => { const span = tracer.scope().active() - expect(span._spanContext._parentId).to.not.be.null + assert.notStrictEqual(span._spanContext._parentId, null) done() }) context.sender.send({ body: 'Hello World!' }) @@ -275,8 +277,10 @@ describe('Plugin', () => { it('should use the configuration for the receiver', (done) => { agent.assertSomeTraces(traces => { const span = traces[0][0] - expect(span).to.have.property('name', expectedSchema.receive.opName) - expect(span).to.have.property('service', 'a_test_service') + assert.ok('name' in span); + assert.strictEqual(span['name'], expectedSchema.receive.opName) + assert.ok('service' in span); + assert.strictEqual(span['service'], 'a_test_service') }) .then(done, done) context.sender.send({ body: 'Hello World!' }) @@ -285,8 +289,10 @@ describe('Plugin', () => { it('should use the configuration for the sender', (done) => { agent.assertSomeTraces(traces => { const span = traces[0][0] - expect(span).to.have.property('name', expectedSchema.send.opName) - expect(span).to.have.property('service', 'a_test_service') + assert.ok('name' in span); + assert.strictEqual(span['name'], expectedSchema.send.opName) + assert.ok('service' in span); + assert.strictEqual(span['service'], 'a_test_service') }) .then(done, done) context.sender.send({ body: 'Hello World!' }) @@ -324,11 +330,11 @@ describe('Plugin', () => { it('should automatically instrument', (done) => { agent.assertSomeTraces(traces => { const beforeFinishContext = rheaInstumentation.contexts.get(spy.firstCall.firstArg) - expect(spy).to.have.been.called - expect(beforeFinishContext).to.have.property('connection') - expect(beforeFinishContext.connection).to.have.property(rheaInstumentation.inFlightDeliveries) - expect(beforeFinishContext.connection[rheaInstumentation.inFlightDeliveries]).to.be.instanceof(Set) - expect(beforeFinishContext.connection[rheaInstumentation.inFlightDeliveries].size).to.equal(0) + sinon.assert.called(spy) + assert.ok('connection' in beforeFinishContext) + assert.ok(rheaInstumentation.inFlightDeliveries in beforeFinishContext.connection) + assert.ok(beforeFinishContext.connection[rheaInstumentation.inFlightDeliveries] instanceof Set) + assert.strictEqual(beforeFinishContext.connection[rheaInstumentation.inFlightDeliveries].size, 0) }) .then(done, done) context.sender.send({ body: 'Hello World!' }) @@ -445,8 +451,8 @@ describe('Plugin', () => { agent.assertSomeTraces(traces => { const span = traces[0][0] - expect(span.error).to.equal(1) - expect(span.meta).to.include({ + assert.strictEqual(span.error, 1) + assertObjectContains(span.meta, { [ERROR_MESSAGE]: 'this is an error', [ERROR_TYPE]: 'Error', [ERROR_STACK]: error.stack, @@ -645,13 +651,13 @@ describe('Plugin', () => { const err = new Error('fake protocol error') agent.assertSomeTraces(traces => { const span = traces[0][0] - expect(span).to.include({ + assertObjectContains(span, { name: expectedSchema.send.opName, resource: 'amq.topic', error: 1, service: expectedSchema.send.serviceName }) - expect(span.meta).to.include({ + assertObjectContains(span.meta, { 'span.kind': 'producer', 'amqp.link.target.address': 'amq.topic', 'amqp.link.role': 'sender', @@ -660,7 +666,7 @@ describe('Plugin', () => { [ERROR_STACK]: err.stack, component: 'rhea' }) - expect(span.metrics).to.include({ + assertObjectContains(span.metrics, { 'network.destination.port': expectedServerPort }) }).then(done, done) @@ -677,13 +683,13 @@ describe('Plugin', () => { const err = new Error('fake protocol error') agent.assertSomeTraces(traces => { const span = traces[0][0] - expect(span).to.include({ + assertObjectContains(span, { name: expectedSchema.receive.opName, resource: 'amq.topic', error: 1, service: expectedSchema.receive.serviceName }) - expect(span.meta).to.include({ + assertObjectContains(span.meta, { 'span.kind': 'consumer', 'amqp.link.source.address': 'amq.topic', 'amqp.link.role': 'receiver', @@ -712,7 +718,7 @@ function expectReceiving (agent, expectedSchema, deliveryState, topic) { topic = topic || 'amq.topic' return Promise.resolve().then(() => agent.assertSomeTraces(traces => { const span = traces[0][0] - expect(span).to.include({ + assertObjectContains(span, { name: expectedSchema.receive.opName, resource: topic, error: 0, @@ -728,7 +734,7 @@ function expectReceiving (agent, expectedSchema, deliveryState, topic) { if (deliveryState) { expectedMeta['amqp.delivery.state'] = deliveryState } - expect(span.meta).to.include(expectedMeta) + assertObjectContains(span.meta, expectedMeta) })) } @@ -737,13 +743,13 @@ function expectSending (agent, expectedSchema, deliveryState, topic) { topic = topic || 'amq.topic' return Promise.resolve().then(() => agent.assertSomeTraces(traces => { const span = traces[0][0] - expect(span).to.include({ + assertObjectContains(span, { name: expectedSchema.send.opName, resource: topic, error: 0, service: expectedSchema.send.serviceName }) - expect(span).to.not.have.property('type') + assert.ok(!('type' in span)) const expectedMeta = { 'span.kind': 'producer', 'amqp.link.target.address': topic, @@ -753,6 +759,6 @@ function expectSending (agent, expectedSchema, deliveryState, topic) { if (deliveryState) { expectedMeta['amqp.delivery.state'] = deliveryState } - expect(span.meta).to.include(expectedMeta) + assertObjectContains(span.meta, expectedMeta) })) } diff --git a/packages/datadog-plugin-rhea/test/integration-test/client.spec.js b/packages/datadog-plugin-rhea/test/integration-test/client.spec.js index 54e82f6d25c..8bc19734da5 100644 --- a/packages/datadog-plugin-rhea/test/integration-test/client.spec.js +++ b/packages/datadog-plugin-rhea/test/integration-test/client.spec.js @@ -1,5 +1,7 @@ 'use strict' +const assert = require('node:assert/strict') + const { FakeAgent, sandboxCwd, @@ -8,8 +10,6 @@ const { spawnPluginIntegrationTestProc } = require('../../../../integration-tests/helpers') const { withVersions } = require('../../../dd-trace/test/setup/mocha') -const { assert } = require('chai') - describe('esm', () => { let agent let proc @@ -29,8 +29,8 @@ describe('esm', () => { it('is instrumented', async () => { const res = agent.assertMessageReceived(({ headers, payload }) => { - assert.propertyVal(headers, 'host', `127.0.0.1:${agent.port}`) - assert.isArray(payload) + assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.ok(Array.isArray(payload)) assert.strictEqual(checkSpansForServiceName(payload, 'amqp.send'), true) }) diff --git a/packages/datadog-plugin-router/test/integration-test/client.spec.js b/packages/datadog-plugin-router/test/integration-test/client.spec.js index a597763ab1d..228daf5cf82 100644 --- a/packages/datadog-plugin-router/test/integration-test/client.spec.js +++ b/packages/datadog-plugin-router/test/integration-test/client.spec.js @@ -1,5 +1,7 @@ 'use strict' +const assert = require('node:assert/strict') + const { FakeAgent, sandboxCwd, @@ -9,8 +11,6 @@ const { spawnPluginIntegrationTestProc } = require('../../../../integration-tests/helpers') const { withVersions } = require('../../../dd-trace/test/setup/mocha') -const { assert } = require('chai') - describe('esm', () => { let agent let proc @@ -32,8 +32,8 @@ describe('esm', () => { proc = await spawnPluginIntegrationTestProc(sandboxCwd(), 'server.mjs', agent.port) return curlAndAssertMessage(agent, proc, ({ headers, payload }) => { - assert.propertyVal(headers, 'host', `127.0.0.1:${agent.port}`) - assert.isArray(payload) + assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.ok(Array.isArray(payload)) assert.strictEqual(checkSpansForServiceName(payload, 'router.middleware'), true) }) }).timeout(20000) diff --git a/packages/datadog-plugin-sharedb/test/index.spec.js b/packages/datadog-plugin-sharedb/test/index.spec.js index fae3010be15..abef60f4937 100644 --- a/packages/datadog-plugin-sharedb/test/index.spec.js +++ b/packages/datadog-plugin-sharedb/test/index.spec.js @@ -2,14 +2,12 @@ const assert = require('node:assert/strict') -const { expect } = require('chai') const { after, afterEach, before, beforeEach, describe, it } = require('mocha') const sinon = require('sinon') const { ERROR_MESSAGE, ERROR_TYPE, ERROR_STACK } = require('../../dd-trace/src/constants') const agent = require('../../dd-trace/test/plugins/agent') const { withVersions } = require('../../dd-trace/test/setup/mocha') - describe('Plugin', () => { let ShareDB @@ -97,11 +95,8 @@ describe('Plugin', () => { agent.assertSomeTraces(traces => { assert.strictEqual(traces[0][0].service, 'test') - expect(traces[0][0]) - .to - .have - .property('resource', - 'query-fetch some-collection {"randomValues":{"property":"?","one":"?"}}') + assert.ok('resource' in traces[0][0]); + assert.strictEqual(traces[0][0]['resource'], 'query-fetch some-collection {"randomValues":{"property":"?","one":"?"}}') assert.strictEqual(traces[0][0].meta['span.kind'], 'server') assert.strictEqual(traces[0][0].meta.service, 'test') assert.strictEqual(traces[0][0].meta['sharedb.action'], 'query-fetch') diff --git a/packages/datadog-plugin-sharedb/test/integration-test/client.spec.js b/packages/datadog-plugin-sharedb/test/integration-test/client.spec.js index 8f189d43b75..bfa3529dd16 100644 --- a/packages/datadog-plugin-sharedb/test/integration-test/client.spec.js +++ b/packages/datadog-plugin-sharedb/test/integration-test/client.spec.js @@ -1,5 +1,7 @@ 'use strict' +const assert = require('node:assert/strict') + const { FakeAgent, sandboxCwd, @@ -8,8 +10,6 @@ const { spawnPluginIntegrationTestProc } = require('../../../../integration-tests/helpers') const { withVersions } = require('../../../dd-trace/test/setup/mocha') -const { assert } = require('chai') - describe('esm', () => { let agent let proc @@ -30,8 +30,8 @@ describe('esm', () => { it('is instrumented', async () => { const res = agent.assertMessageReceived(({ headers, payload }) => { - assert.propertyVal(headers, 'host', `127.0.0.1:${agent.port}`) - assert.isArray(payload) + assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.ok(Array.isArray(payload)) assert.strictEqual(checkSpansForServiceName(payload, 'sharedb.request'), true) }) diff --git a/packages/datadog-plugin-tedious/test/integration-test/client.spec.js b/packages/datadog-plugin-tedious/test/integration-test/client.spec.js index f15322e6554..4e3a595ef1d 100644 --- a/packages/datadog-plugin-tedious/test/integration-test/client.spec.js +++ b/packages/datadog-plugin-tedious/test/integration-test/client.spec.js @@ -1,5 +1,7 @@ 'use strict' +const assert = require('node:assert/strict') + const { FakeAgent, sandboxCwd, @@ -7,7 +9,6 @@ const { checkSpansForServiceName, spawnPluginIntegrationTestProc } = require('../../../../integration-tests/helpers') -const { assert } = require('chai') const version = require('../../../../version.js') const { withVersions } = require('../../../dd-trace/test/setup/mocha') @@ -36,8 +37,8 @@ describe('esm', () => { it('is instrumented', async () => { const res = agent.assertMessageReceived(({ headers, payload }) => { - assert.propertyVal(headers, 'host', `127.0.0.1:${agent.port}`) - assert.isArray(payload) + assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.ok(Array.isArray(payload)) assert.strictEqual(checkSpansForServiceName(payload, 'tedious.request'), true) }) diff --git a/packages/datadog-plugin-winston/test/index.spec.js b/packages/datadog-plugin-winston/test/index.spec.js index 7b4940e93d0..da75184cef2 100644 --- a/packages/datadog-plugin-winston/test/index.spec.js +++ b/packages/datadog-plugin-winston/test/index.spec.js @@ -1,7 +1,11 @@ 'use strict' +const assert = require('node:assert/strict') + const { expect } = require('chai') -const { describe, it, beforeEach, afterEach } = require('mocha') +const { afterEach, beforeEach, describe, it } = require('mocha') +const { assertObjectContains } = require('../../../integration-tests/helpers') + const proxyquire = require('proxyquire').noPreserveCache() const semver = require('semver') const sinon = require('sinon') @@ -136,7 +140,7 @@ describe('Plugin', () => { tracer.scope().activate(span, () => { winston.info('message') - expect(spy).to.have.been.calledWithMatch(meta.dd) + sinon.assert.calledWithMatch(spy, meta.dd) }) }) }) @@ -164,9 +168,9 @@ describe('Plugin', () => { tracer.scope().activate(span, async () => { winston.info('message') - expect(spy).to.have.been.calledWithMatch(meta.dd) + sinon.assert.calledWithMatch(spy, meta.dd) }) - expect(await logServer.logPromise).to.include(meta.dd) + assertObjectContains(await logServer.logPromise, meta.dd) }) it('should add the trace identifiers to logger instances', async () => { @@ -188,9 +192,9 @@ describe('Plugin', () => { tracer.scope().activate(span, () => { logger.info('message') - expect(spy).to.have.been.calledWithMatch(meta.dd) + sinon.assert.calledWithMatch(spy, meta.dd) }) - expect(await logServer.logPromise).to.include(meta.dd) + assertObjectContains(await logServer.logPromise, meta.dd) }) it('should support errors', async () => { @@ -208,11 +212,11 @@ describe('Plugin', () => { const index = semver.intersects(version, '>=3') ? 0 : 2 const record = log.firstCall.args[index] - expect(record).to.be.an.instanceof(Error) - expect(error).to.not.have.property('dd') - expect(spy).to.have.been.calledWithMatch(meta.dd) + assert.ok(record instanceof Error) + assert.ok(!('dd' in error)) + sinon.assert.calledWithMatch(spy, meta.dd) }) - expect(await logServer.logPromise).to.include(meta.dd) + assertObjectContains(await logServer.logPromise, meta.dd) }) if (semver.intersects(version, '>=3')) { @@ -236,12 +240,12 @@ describe('Plugin', () => { const record = log.firstCall.args[0] - expect(record).to.be.an.instanceof(Set) - expect(inspect(record)).to.match(/"getter":1,/) - expect(set).to.not.have.property('dd') - expect(spy).to.have.been.calledWithMatch(meta.dd) + assert.ok(record instanceof Set) + assert.match(inspect(record), /"getter":1,/) + assert.ok(!('dd' in set)) + sinon.assert.calledWithMatch(spy, meta.dd) }) - expect(await logServer.logPromise).to.include(meta.dd) + assertObjectContains(await logServer.logPromise, meta.dd) }) it('should add the trace identifiers when streaming', async () => { @@ -259,9 +263,9 @@ describe('Plugin', () => { message: 'message' }) - expect(spy).to.have.been.calledWithMatch(dd) + sinon.assert.calledWithMatch(spy, dd) }) - expect(await logServer.logPromise).to.include(dd) + assertObjectContains(await logServer.logPromise, dd) }) } @@ -271,11 +275,11 @@ describe('Plugin', () => { dd: 'something else' } winston.log('info', 'test', meta) - expect(meta.dd).to.equal('something else') + assert.strictEqual(meta.dd, 'something else') - expect(spy).to.have.been.calledWithMatch('something else') + sinon.assert.calledWithMatch(spy, 'something else') }) - expect(await logServer.logPromise).to.include('something else') + assertObjectContains(await logServer.logPromise, 'something else') }) // New versions clone the meta object so it's always extensible. @@ -285,16 +289,16 @@ describe('Plugin', () => { const meta = {} Object.preventExtensions(meta) winston.log('info', 'test', meta) - expect(meta.dd).to.be.undefined + assert.strictEqual(meta.dd, undefined) expect(spy).to.have.been.calledWith() }) - expect(await logServer.logPromise).to.be.undefined + assert.strictEqual(await logServer.logPromise, undefined) }) } it('should skip injection without a store', async () => { - expect(() => winston.info('message')).to.not.throw() + assert.doesNotThrow(() => winston.info('message')) }) }) @@ -329,16 +333,16 @@ describe('Plugin', () => { winston.info(splatFormmatedLog, extra) if (semver.intersects(version, '>=3')) { - expect(log).to.have.been.calledWithMatch({ + sinon.assert.calledWithMatch(log, { message: interpolatedLog }) } else { - expect(log).to.have.been.calledWithMatch('info', interpolatedLog) + sinon.assert.calledWithMatch(log, 'info', interpolatedLog) } - expect(spy).to.have.been.calledWithMatch(meta.dd) + sinon.assert.calledWithMatch(spy, meta.dd) }) - expect(await logServer.logPromise).to.include(meta.dd) + assertObjectContains(await logServer.logPromise, meta.dd) }) }) @@ -375,21 +379,23 @@ describe('Plugin', () => { tracer.scope().activate(span, () => { logger.error(error) - expect(spy).to.have.been.called + sinon.assert.called(spy) const loggedInfo = spy.firstCall.args[0] - expect(loggedInfo).to.have.property('message') + assert.ok('message' in loggedInfo) - expect(loggedInfo).to.have.property('stack') - expect(loggedInfo.stack).to.be.a('string') - expect(loggedInfo.stack).to.include('test error with stack') - expect(loggedInfo.stack).to.include('Error:') + assert.ok('stack' in loggedInfo) + assert.strictEqual(typeof loggedInfo.stack, 'string') + assertObjectContains(loggedInfo.stack, 'test error with stack') + assertObjectContains(loggedInfo.stack, 'Error:') - expect(loggedInfo.message).to.equal('test error with stack') + assert.strictEqual(loggedInfo.message, 'test error with stack') - expect(loggedInfo).to.have.property('dd') - expect(loggedInfo.dd).to.have.property('trace_id', span.context().toTraceId(true)) - expect(loggedInfo.dd).to.have.property('span_id', span.context().toSpanId()) + assert.ok('dd' in loggedInfo) + assert.ok('trace_id' in loggedInfo.dd); + assert.strictEqual(loggedInfo.dd['trace_id'], span.context().toTraceId(true)) + assert.ok('span_id' in loggedInfo.dd); + assert.strictEqual(loggedInfo.dd['span_id'], span.context().toSpanId()) }) }) }) diff --git a/packages/datadog-plugin-ws/test/index.spec.js b/packages/datadog-plugin-ws/test/index.spec.js index 2c0002211ad..4a0d968e80f 100644 --- a/packages/datadog-plugin-ws/test/index.spec.js +++ b/packages/datadog-plugin-ws/test/index.spec.js @@ -3,12 +3,10 @@ const assert = require('node:assert') const { once } = require('node:events') -const { expect } = require('chai') const { after, afterEach, before, beforeEach, describe, it } = require('mocha') const agent = require('../../dd-trace/test/plugins/agent') const { withVersions } = require('../../dd-trace/test/setup/mocha') - describe('Plugin', () => { let WebSocket let wsServer @@ -357,7 +355,7 @@ describe('Plugin', () => { }) return agent.assertSomeTraces(traces => { - expect(traces[0][0].meta).to.not.have.property('_dd.dm.inherited', 1) + assert.ok(!('_dd.dm.inherited' in traces[0][0].meta) || traces[0][0].meta['_dd.dm.inherited'] !== 1) assert.strictEqual(traces[0][0].meta['span.kind'], 'consumer') assert.strictEqual(traces[0][0].name, 'websocket.receive') assert.strictEqual(traces[0][0].type, 'websocket') diff --git a/packages/datadog-shimmer/test/shimmer.spec.js b/packages/datadog-shimmer/test/shimmer.spec.js index 0d045bdd8c5..8529c8f0d46 100644 --- a/packages/datadog-shimmer/test/shimmer.spec.js +++ b/packages/datadog-shimmer/test/shimmer.spec.js @@ -170,7 +170,7 @@ describe('shimmer', () => { const counter = new obj.Counter(1) assert.strictEqual(counter.value, 2) - expect(counter).to.be.an.instanceof(Counter) + assert.ok(counter instanceof Counter) }) it('should wrap a class constructor', () => { @@ -353,25 +353,25 @@ describe('shimmer', () => { }) it('should validate that a method exists on the target object', () => { - expect(() => shimmer.wrap({}, 'invalid', () => () => {})).to.throw() + assert.throws(() => shimmer.wrap({}, 'invalid', () => () => {})) }) it('should validate that the target method is a function', () => { - expect(() => shimmer.wrap({ a: 1234 }, 'a', () => () => {})).to.throw() + assert.throws(() => shimmer.wrap({ a: 1234 }, 'a', () => () => {})) }) it('should validate that the method wrapper is passed', () => { - expect(() => shimmer.wrap({ a: () => {} }, 'a')).to.throw() + assert.throws(() => shimmer.wrap({ a: () => {} }, 'a')) }) it('should validate that the method wrapper is a function', () => { - expect(() => shimmer.wrap({ a: () => {} }, 'a', 'notafunction')).to.throw() + assert.throws(() => shimmer.wrap({ a: () => {} }, 'a', 'notafunction')) }) }) describe('with a function', () => { it('should not work with a wrap()', () => { - expect(() => shimmer.wrap(() => {}, () => {})).to.throw() + assert.throws(() => shimmer.wrap(() => {}, () => {})) }) it('should not work with null instead of function', () => { @@ -408,7 +408,7 @@ describe('shimmer', () => { const counter = new WrappedCounter(1) assert.strictEqual(counter.value, 2) - expect(counter).to.be.an.instanceof(Counter) + assert.ok(counter instanceof Counter) }) it('should not wrap the class constructor', () => { @@ -418,9 +418,7 @@ describe('shimmer', () => { } } - expect(() => shimmer.wrapFunction(Counter, Counter => function () {})).to.throw( - 'Target is a native class constructor and cannot be wrapped.' - ) + assert.throws(() => shimmer.wrapFunction(Counter, Counter => function () {}), /Target is a native class constructor and cannot be wrapped\./) }) it('should not wrap the class constructor with invalid toString()', () => { @@ -432,9 +430,7 @@ describe('shimmer', () => { Counter.toString = 'invalid' - expect(() => shimmer.wrapFunction(Counter, Counter => function () {})).to.throw( - 'Target is a native class constructor and cannot be wrapped.' - ) + assert.throws(() => shimmer.wrapFunction(Counter, Counter => function () {}), /Target is a native class constructor and cannot be wrapped\./) }) it('should preserve property descriptors from the original', () => { @@ -504,11 +500,11 @@ describe('shimmer', () => { }) it('should validate that the function wrapper exists', () => { - expect(() => shimmer.wrap(() => {})).to.throw() + assert.throws(() => shimmer.wrap(() => {})) }) it('should validate that the function wrapper is a function', () => { - expect(() => shimmer.wrap(() => {}, 'a')).to.throw() + assert.throws(() => shimmer.wrap(() => {}, 'a')) }) }) }) diff --git a/packages/dd-trace/test/aiguard/index.spec.js b/packages/dd-trace/test/aiguard/index.spec.js index 447e8a7c432..fd80fd05742 100644 --- a/packages/dd-trace/test/aiguard/index.spec.js +++ b/packages/dd-trace/test/aiguard/index.spec.js @@ -4,13 +4,14 @@ const assert = require('node:assert/strict') const { rejects } = require('node:assert/strict') const msgpack = require('@msgpack/msgpack') -const { expect } = require('chai') const { afterEach, beforeEach, describe, it } = require('mocha') const sinon = require('sinon') const NoopAIGuard = require('../../src/aiguard/noop') const AIGuard = require('../../src/aiguard/sdk') const agent = require('../plugins/agent') +const { assertObjectContains } = require('../../../../integration-tests/helpers') + const tracerVersion = require('../../../../package.json').version const telemetryMetrics = require('../../src/telemetry/metrics') const appsecNamespace = telemetryMetrics.manager.namespace('appsec') @@ -129,7 +130,7 @@ describe('AIGuard SDK', () => { await agent.assertFirstTraceSpan(span => { assert.strictEqual(span.name, 'ai_guard') assert.strictEqual(span.resource, 'ai_guard') - expect(span.meta).to.deep.include(meta) + assertObjectContains(span.meta, meta) if (metaStruct) { assert.deepStrictEqual(msgpack.decode(span.meta_struct.ai_guard), metaStruct) } diff --git a/packages/dd-trace/test/appsec/api_security_sampler.spec.js b/packages/dd-trace/test/appsec/api_security_sampler.spec.js index f5665ed8a1c..22fd17c03f0 100644 --- a/packages/dd-trace/test/appsec/api_security_sampler.spec.js +++ b/packages/dd-trace/test/appsec/api_security_sampler.spec.js @@ -1,10 +1,10 @@ 'use strict' +const assert = require('node:assert/strict') + const { describe, it, beforeEach, afterEach } = require('mocha') const sinon = require('sinon') const proxyquire = require('proxyquire') - -const { assert } = require('chai') const { performance } = require('node:perf_hooks') const { USER_KEEP, AUTO_KEEP, AUTO_REJECT, USER_REJECT } = require('../../../../ext/priority') @@ -50,27 +50,27 @@ describe('API Security Sampler', () => { it('should return false if not enabled', () => { apiSecuritySampler.disable() - assert.isFalse(apiSecuritySampler.sampleRequest({}, {})) + assert.strictEqual(apiSecuritySampler.sampleRequest({}, {}), false) }) it('should return false if no root span', () => { webStub.root.returns(null) - assert.isFalse(apiSecuritySampler.sampleRequest({}, {})) + assert.strictEqual(apiSecuritySampler.sampleRequest({}, {}), false) }) it('should return false for AUTO_REJECT priority', () => { span.context.returns({ _sampling: { priority: AUTO_REJECT } }) - assert.isFalse(apiSecuritySampler.sampleRequest(req, res)) + assert.strictEqual(apiSecuritySampler.sampleRequest(req, res), false) }) it('should return false for USER_REJECT priority', () => { span.context.returns({ _sampling: { priority: USER_REJECT } }) - assert.isFalse(apiSecuritySampler.sampleRequest(req, res)) + assert.strictEqual(apiSecuritySampler.sampleRequest(req, res), false) }) it('should not sample when method or statusCode is not available', () => { - assert.isFalse(apiSecuritySampler.sampleRequest(req, {}, true)) - assert.isFalse(apiSecuritySampler.sampleRequest({}, res, true)) + assert.strictEqual(apiSecuritySampler.sampleRequest(req, {}, true), false) + assert.strictEqual(apiSecuritySampler.sampleRequest({}, res, true), false) }) describe('with TTLCache', () => { @@ -79,80 +79,80 @@ describe('API Security Sampler', () => { }) it('should not sample before 30 seconds', () => { - assert.isTrue(apiSecuritySampler.sampleRequest(req, res, true)) + assert.strictEqual(apiSecuritySampler.sampleRequest(req, res, true), true) clock.tick(25000) - assert.isFalse(apiSecuritySampler.sampleRequest(req, res, true)) + assert.strictEqual(apiSecuritySampler.sampleRequest(req, res, true), false) const key = apiSecuritySampler.computeKey(req, res) - assert.isTrue(apiSecuritySampler.isSampled(key)) + assert.strictEqual(apiSecuritySampler.isSampled(key), true) }) it('should sample after 30 seconds', () => { - assert.isTrue(apiSecuritySampler.sampleRequest(req, res, true)) + assert.strictEqual(apiSecuritySampler.sampleRequest(req, res, true), true) clock.tick(35000) - assert.isTrue(apiSecuritySampler.sampleRequest(req, res, true)) + assert.strictEqual(apiSecuritySampler.sampleRequest(req, res, true), true) }) it('should remove oldest entry when max size is exceeded', () => { for (let i = 0; i < 4097; i++) { const path = `/test${i}` webStub.getContext.returns({ paths: [path] }) - assert.isTrue(apiSecuritySampler.sampleRequest(req, res, true)) + assert.strictEqual(apiSecuritySampler.sampleRequest(req, res, true), true) } webStub.getContext.returns({ paths: ['/test0'] }) const key1 = apiSecuritySampler.computeKey(req, res) - assert.isFalse(apiSecuritySampler.isSampled(key1)) + assert.strictEqual(apiSecuritySampler.isSampled(key1), false) webStub.getContext.returns({ paths: ['/test4096'] }) const key2 = apiSecuritySampler.computeKey(req, res) - assert.isTrue(apiSecuritySampler.isSampled(key2)) + assert.strictEqual(apiSecuritySampler.isSampled(key2), true) }) it('should set enabled to false and clear the cache', () => { - assert.isTrue(apiSecuritySampler.sampleRequest(req, res, true)) + assert.strictEqual(apiSecuritySampler.sampleRequest(req, res, true), true) apiSecuritySampler.disable() - assert.isFalse(apiSecuritySampler.sampleRequest(req, res, true)) + assert.strictEqual(apiSecuritySampler.sampleRequest(req, res, true), false) }) it('should create different keys for different methods', () => { const getReq = { method: 'GET' } const postReq = { method: 'POST' } - assert.isTrue(apiSecuritySampler.sampleRequest(getReq, res, true)) - assert.isTrue(apiSecuritySampler.sampleRequest(postReq, res, true)) + assert.strictEqual(apiSecuritySampler.sampleRequest(getReq, res, true), true) + assert.strictEqual(apiSecuritySampler.sampleRequest(postReq, res, true), true) const key1 = apiSecuritySampler.computeKey(getReq, res) - assert.isTrue(apiSecuritySampler.isSampled(key1)) + assert.strictEqual(apiSecuritySampler.isSampled(key1), true) const key2 = apiSecuritySampler.computeKey(postReq, res) - assert.isTrue(apiSecuritySampler.isSampled(key2)) + assert.strictEqual(apiSecuritySampler.isSampled(key2), true) }) it('should create different keys for different status codes', () => { const res200 = { statusCode: 200 } const res404 = { statusCode: 404 } - assert.isTrue(apiSecuritySampler.sampleRequest(req, res200, true)) - assert.isTrue(apiSecuritySampler.sampleRequest(req, res404, true)) + assert.strictEqual(apiSecuritySampler.sampleRequest(req, res200, true), true) + assert.strictEqual(apiSecuritySampler.sampleRequest(req, res404, true), true) const key1 = apiSecuritySampler.computeKey(req, res200) - assert.isTrue(apiSecuritySampler.isSampled(key1)) + assert.strictEqual(apiSecuritySampler.isSampled(key1), true) const key2 = apiSecuritySampler.computeKey(req, res404) - assert.isTrue(apiSecuritySampler.isSampled(key2)) + assert.strictEqual(apiSecuritySampler.isSampled(key2), true) }) it('should sample for AUTO_KEEP priority without checking prioritySampler', () => { span.context.returns({ _sampling: { priority: AUTO_KEEP } }) - assert.isTrue(apiSecuritySampler.sampleRequest(req, res)) + assert.strictEqual(apiSecuritySampler.sampleRequest(req, res), true) }) it('should sample for USER_KEEP priority without checking prioritySampler', () => { span.context.returns({ _sampling: { priority: USER_KEEP } }) - assert.isTrue(apiSecuritySampler.sampleRequest(req, res)) + assert.strictEqual(apiSecuritySampler.sampleRequest(req, res), true) }) }) @@ -162,18 +162,18 @@ describe('API Security Sampler', () => { }) it('should always return true for sampleRequest', () => { - assert.isTrue(apiSecuritySampler.sampleRequest(req, res, true)) + assert.strictEqual(apiSecuritySampler.sampleRequest(req, res, true), true) - assert.isTrue(apiSecuritySampler.sampleRequest(req, res, true)) + assert.strictEqual(apiSecuritySampler.sampleRequest(req, res, true), true) clock.tick(50000) - assert.isTrue(apiSecuritySampler.sampleRequest(req, res, true)) + assert.strictEqual(apiSecuritySampler.sampleRequest(req, res, true), true) }) it('should never mark requests as sampled', () => { apiSecuritySampler.sampleRequest(req, res, true) const key = apiSecuritySampler.computeKey(req, res) - assert.isFalse(apiSecuritySampler.isSampled(key)) + assert.strictEqual(apiSecuritySampler.isSampled(key), false) }) it('should handle multiple different requests', () => { @@ -184,23 +184,23 @@ describe('API Security Sampler', () => { ] requests.forEach(({ req, res }) => { - assert.isTrue(apiSecuritySampler.sampleRequest(req, res, true)) + assert.strictEqual(apiSecuritySampler.sampleRequest(req, res, true), true) const key = apiSecuritySampler.computeKey(req, res) - assert.isFalse(apiSecuritySampler.isSampled(key)) + assert.strictEqual(apiSecuritySampler.isSampled(key), false) }) }) it('should not be affected by max size', () => { for (let i = 0; i < 5000; i++) { webStub.getContext.returns({ paths: [`/test${i}`] }) - assert.isTrue(apiSecuritySampler.sampleRequest(req, res, true)) + assert.strictEqual(apiSecuritySampler.sampleRequest(req, res, true), true) } webStub.getContext.returns({ paths: ['/test0'] }) - assert.isTrue(apiSecuritySampler.sampleRequest(req, res, true)) + assert.strictEqual(apiSecuritySampler.sampleRequest(req, res, true), true) webStub.getContext.returns({ paths: ['/test4999'] }) - assert.isTrue(apiSecuritySampler.sampleRequest(req, res, true)) + assert.strictEqual(apiSecuritySampler.sampleRequest(req, res, true), true) }) }) @@ -230,16 +230,16 @@ describe('API Security Sampler', () => { }) it('should keep trace with ASM product when in standalone mode', () => { - assert.isTrue(apiSecuritySampler.sampleRequest(req, res, true)) - assert.isFalse(apiSecuritySampler.sampleRequest(req, res, true)) - assert.isTrue(keepTraceStub.calledOnceWith(span, 'asm')) + assert.strictEqual(apiSecuritySampler.sampleRequest(req, res, true), true) + assert.strictEqual(apiSecuritySampler.sampleRequest(req, res, true), false) + assert.strictEqual(keepTraceStub.calledOnceWith(span, 'asm'), true) }) it('should not check priority sampling in standalone mode', () => { span.context.returns({ _sampling: { priority: AUTO_REJECT } }) - assert.isTrue(apiSecuritySampler.sampleRequest(req, res, true)) - assert.isFalse(apiSecuritySampler.sampleRequest(req, res, true)) - assert.isTrue(keepTraceStub.calledOnceWith(span, 'asm')) + assert.strictEqual(apiSecuritySampler.sampleRequest(req, res, true), true) + assert.strictEqual(apiSecuritySampler.sampleRequest(req, res, true), false) + assert.strictEqual(keepTraceStub.calledOnceWith(span, 'asm'), true) }) }) }) diff --git a/packages/dd-trace/test/appsec/attacker-fingerprinting.express.plugin.spec.js b/packages/dd-trace/test/appsec/attacker-fingerprinting.express.plugin.spec.js index d4f174c7ac9..ff14fe95728 100644 --- a/packages/dd-trace/test/appsec/attacker-fingerprinting.express.plugin.spec.js +++ b/packages/dd-trace/test/appsec/attacker-fingerprinting.express.plugin.spec.js @@ -1,10 +1,10 @@ 'use strict' +const assert = require('node:assert/strict') + const path = require('node:path') const axios = require('axios') -const { assert } = require('chai') - const agent = require('../plugins/agent') const appsec = require('../../src/appsec') const { getConfigFresh } = require('../helpers/config') @@ -72,12 +72,12 @@ withVersions('express', 'express', expressVersion => { await agent.assertSomeTraces((traces) => { const span = traces[0][0] - assert.property(span.meta, '_dd.appsec.fp.http.header') - assert.equal(span.meta['_dd.appsec.fp.http.header'], 'hdr-0110000110-74c2908f-5-55682ec1') - assert.property(span.meta, '_dd.appsec.fp.http.network') - assert.equal(span.meta['_dd.appsec.fp.http.network'], 'net-1-0100000000') - assert.property(span.meta, '_dd.appsec.fp.http.endpoint') - assert.equal(span.meta['_dd.appsec.fp.http.endpoint'], 'http-post-8a5edab2-2c70e12b-be31090f') + assert.ok(Object.hasOwn(span.meta, '_dd.appsec.fp.http.header')) + assert.strictEqual(span.meta['_dd.appsec.fp.http.header'], 'hdr-0110000110-74c2908f-5-55682ec1') + assert.ok(Object.hasOwn(span.meta, '_dd.appsec.fp.http.network')) + assert.strictEqual(span.meta['_dd.appsec.fp.http.network'], 'net-1-0100000000') + assert.ok(Object.hasOwn(span.meta, '_dd.appsec.fp.http.endpoint')) + assert.strictEqual(span.meta['_dd.appsec.fp.http.endpoint'], 'http-post-8a5edab2-2c70e12b-be31090f') }) }) }) diff --git a/packages/dd-trace/test/appsec/attacker-fingerprinting.fastify.plugin.spec.js b/packages/dd-trace/test/appsec/attacker-fingerprinting.fastify.plugin.spec.js index f7d35de074c..03d8cb48139 100644 --- a/packages/dd-trace/test/appsec/attacker-fingerprinting.fastify.plugin.spec.js +++ b/packages/dd-trace/test/appsec/attacker-fingerprinting.fastify.plugin.spec.js @@ -1,10 +1,10 @@ 'use strict' +const assert = require('node:assert/strict') + const path = require('node:path') const Axios = require('axios') -const { assert } = require('chai') - const agent = require('../plugins/agent') const appsec = require('../../src/appsec') const { getConfigFresh } = require('../helpers/config') @@ -71,12 +71,12 @@ withVersions('fastify', 'fastify', fastifyVersion => { await agent.assertSomeTraces((traces) => { const span = traces[0][0] - assert.property(span.meta, '_dd.appsec.fp.http.header') - assert.equal(span.meta['_dd.appsec.fp.http.header'], 'hdr-0110000110-74c2908f-5-55682ec1') - assert.property(span.meta, '_dd.appsec.fp.http.network') - assert.equal(span.meta['_dd.appsec.fp.http.network'], 'net-1-0100000000') - assert.property(span.meta, '_dd.appsec.fp.http.endpoint') - assert.equal(span.meta['_dd.appsec.fp.http.endpoint'], 'http-post-8a5edab2-2c70e12b-be31090f') + assert.ok(Object.hasOwn(span.meta, '_dd.appsec.fp.http.header')) + assert.strictEqual(span.meta['_dd.appsec.fp.http.header'], 'hdr-0110000110-74c2908f-5-55682ec1') + assert.ok(Object.hasOwn(span.meta, '_dd.appsec.fp.http.network')) + assert.strictEqual(span.meta['_dd.appsec.fp.http.network'], 'net-1-0100000000') + assert.ok(Object.hasOwn(span.meta, '_dd.appsec.fp.http.endpoint')) + assert.strictEqual(span.meta['_dd.appsec.fp.http.endpoint'], 'http-post-8a5edab2-2c70e12b-be31090f') }) }) }) diff --git a/packages/dd-trace/test/appsec/attacker-fingerprinting.passport-http.plugin.spec.js b/packages/dd-trace/test/appsec/attacker-fingerprinting.passport-http.plugin.spec.js index 534a0e4ef9b..f7d60240ff1 100644 --- a/packages/dd-trace/test/appsec/attacker-fingerprinting.passport-http.plugin.spec.js +++ b/packages/dd-trace/test/appsec/attacker-fingerprinting.passport-http.plugin.spec.js @@ -1,8 +1,8 @@ 'use strict' -const Axios = require('axios') -const { assert } = require('chai') +const assert = require('node:assert/strict') +const Axios = require('axios') const agent = require('../plugins/agent') const appsec = require('../../src/appsec') const { getConfigFresh } = require('../helpers/config') @@ -10,12 +10,12 @@ const { withVersions } = require('../setup/mocha') function assertFingerprintInTraces (traces) { const span = traces[0][0] - assert.property(span.meta, '_dd.appsec.fp.http.header') - assert.equal(span.meta['_dd.appsec.fp.http.header'], 'hdr-0110000110-74c2908f-5-e58aa9dd') - assert.property(span.meta, '_dd.appsec.fp.http.network') - assert.equal(span.meta['_dd.appsec.fp.http.network'], 'net-0-0000000000') - assert.property(span.meta, '_dd.appsec.fp.http.endpoint') - assert.equal(span.meta['_dd.appsec.fp.http.endpoint'], 'http-post-7e93fba0--') + assert.ok(Object.hasOwn(span.meta, '_dd.appsec.fp.http.header')) + assert.strictEqual(span.meta['_dd.appsec.fp.http.header'], 'hdr-0110000110-74c2908f-5-e58aa9dd') + assert.ok(Object.hasOwn(span.meta, '_dd.appsec.fp.http.network')) + assert.strictEqual(span.meta['_dd.appsec.fp.http.network'], 'net-0-0000000000') + assert.ok(Object.hasOwn(span.meta, '_dd.appsec.fp.http.endpoint')) + assert.strictEqual(span.meta['_dd.appsec.fp.http.endpoint'], 'http-post-7e93fba0--') } withVersions('passport-http', 'passport-http', version => { diff --git a/packages/dd-trace/test/appsec/attacker-fingerprinting.passport-local.plugin.spec.js b/packages/dd-trace/test/appsec/attacker-fingerprinting.passport-local.plugin.spec.js index 4ef9490ff11..d551d54583d 100644 --- a/packages/dd-trace/test/appsec/attacker-fingerprinting.passport-local.plugin.spec.js +++ b/packages/dd-trace/test/appsec/attacker-fingerprinting.passport-local.plugin.spec.js @@ -1,8 +1,8 @@ 'use strict' -const Axios = require('axios') -const { assert } = require('chai') +const assert = require('node:assert/strict') +const Axios = require('axios') const agent = require('../plugins/agent') const appsec = require('../../src/appsec') const { getConfigFresh } = require('../helpers/config') @@ -10,12 +10,12 @@ const { withVersions } = require('../setup/mocha') function assertFingerprintInTraces (traces) { const span = traces[0][0] - assert.property(span.meta, '_dd.appsec.fp.http.header') - assert.equal(span.meta['_dd.appsec.fp.http.header'], 'hdr-0110000110-74c2908f-4-c348f529') - assert.property(span.meta, '_dd.appsec.fp.http.network') - assert.equal(span.meta['_dd.appsec.fp.http.network'], 'net-0-0000000000') - assert.property(span.meta, '_dd.appsec.fp.http.endpoint') - assert.equal(span.meta['_dd.appsec.fp.http.endpoint'], 'http-post-7e93fba0--f29f6224') + assert.ok(Object.hasOwn(span.meta, '_dd.appsec.fp.http.header')) + assert.strictEqual(span.meta['_dd.appsec.fp.http.header'], 'hdr-0110000110-74c2908f-4-c348f529') + assert.ok(Object.hasOwn(span.meta, '_dd.appsec.fp.http.network')) + assert.strictEqual(span.meta['_dd.appsec.fp.http.network'], 'net-0-0000000000') + assert.ok(Object.hasOwn(span.meta, '_dd.appsec.fp.http.endpoint')) + assert.strictEqual(span.meta['_dd.appsec.fp.http.endpoint'], 'http-post-7e93fba0--f29f6224') } withVersions('passport-local', 'passport-local', version => { diff --git a/packages/dd-trace/test/appsec/attacker-fingerprinting.spec.js b/packages/dd-trace/test/appsec/attacker-fingerprinting.spec.js index 03208835278..ee9d8e9b4c1 100644 --- a/packages/dd-trace/test/appsec/attacker-fingerprinting.spec.js +++ b/packages/dd-trace/test/appsec/attacker-fingerprinting.spec.js @@ -1,8 +1,8 @@ 'use strict' -const axios = require('axios') -const { assert } = require('chai') +const assert = require('node:assert/strict') +const axios = require('axios') const agent = require('../plugins/agent') const tracer = require('../../../../index') const appsec = require('../../src/appsec') @@ -56,10 +56,10 @@ describe('Attacker fingerprinting', () => { } agent.assertSomeTraces(traces => { - assert.property(traces[0][0].meta, '_dd.appsec.fp.http.header') - assert.equal(traces[0][0].meta['_dd.appsec.fp.http.header'], 'hdr-0110000010-74c2908f-3-98425651') - assert.property(traces[0][0].meta, '_dd.appsec.fp.http.network') - assert.equal(traces[0][0].meta['_dd.appsec.fp.http.network'], 'net-0-0000000000') + assert.ok(Object.hasOwn(traces[0][0].meta, '_dd.appsec.fp.http.header')) + assert.strictEqual(traces[0][0].meta['_dd.appsec.fp.http.header'], 'hdr-0110000010-74c2908f-3-98425651') + assert.ok(Object.hasOwn(traces[0][0].meta, '_dd.appsec.fp.http.network')) + assert.strictEqual(traces[0][0].meta['_dd.appsec.fp.http.network'], 'net-0-0000000000') }).then(done).catch(done) axios.get(`http://localhost:${port}/`, { @@ -76,10 +76,10 @@ describe('Attacker fingerprinting', () => { } agent.assertSomeTraces(traces => { - assert.property(traces[0][0].meta, '_dd.appsec.fp.http.header') - assert.equal(traces[0][0].meta['_dd.appsec.fp.http.header'], 'hdr-0110000010-74c2908f-3-98425651') - assert.property(traces[0][0].meta, '_dd.appsec.fp.http.network') - assert.equal(traces[0][0].meta['_dd.appsec.fp.http.network'], 'net-0-0000000000') + assert.ok(Object.hasOwn(traces[0][0].meta, '_dd.appsec.fp.http.header')) + assert.strictEqual(traces[0][0].meta['_dd.appsec.fp.http.header'], 'hdr-0110000010-74c2908f-3-98425651') + assert.ok(Object.hasOwn(traces[0][0].meta, '_dd.appsec.fp.http.network')) + assert.strictEqual(traces[0][0].meta['_dd.appsec.fp.http.network'], 'net-0-0000000000') }).then(done).catch(done) axios.get(`http://localhost:${port}/`, { diff --git a/packages/dd-trace/test/appsec/blocking.spec.js b/packages/dd-trace/test/appsec/blocking.spec.js index d6587462597..62af7130d64 100644 --- a/packages/dd-trace/test/appsec/blocking.spec.js +++ b/packages/dd-trace/test/appsec/blocking.spec.js @@ -218,7 +218,7 @@ describe('blocking', () => { it('should do nothing if no blocking delegation exists', () => { const blocked = callBlockDelegation(res) - expect(blocked).to.not.be.ok + assert.ok(!(blocked)) sinon.assert.notCalled(log.warn) sinon.assert.notCalled(rootSpan.setTag) sinon.assert.notCalled(res.writeHead) @@ -241,7 +241,7 @@ describe('blocking', () => { const result = callBlockDelegation(res) - expect(result).to.not.be.ok + assert.ok(!(result)) sinon.assert.calledOnce(rootSpan.setTag) sinon.assert.calledOnce(res.writeHead) sinon.assert.calledOnce(res.constructor.prototype.end) diff --git a/packages/dd-trace/test/appsec/iast/analyzers/hardcoded-password-analyzer.spec.js b/packages/dd-trace/test/appsec/iast/analyzers/hardcoded-password-analyzer.spec.js index aac062b111e..9a595dfb7ec 100644 --- a/packages/dd-trace/test/appsec/iast/analyzers/hardcoded-password-analyzer.spec.js +++ b/packages/dd-trace/test/appsec/iast/analyzers/hardcoded-password-analyzer.spec.js @@ -1,8 +1,11 @@ +const assert = require('node:assert/strict') +const { assertObjectContains } = require('../../../../../../integration-tests/helpers') + /* eslint-disable @stylistic/max-len */ 'use strict' const { expect } = require('chai') -const { describe, it, beforeEach, afterEach } = require('mocha') +const { after, afterEach, before, beforeEach, describe, it } = require('mocha') const sinon = require('sinon') const path = require('node:path') @@ -66,11 +69,11 @@ describe('Hardcoded Password Analyzer', () => { }) it('should not fail with a malformed secret', () => { - expect(() => hardcodedPasswordAnalyzer.analyze(undefined)).not.to.throw() - expect(() => hardcodedPasswordAnalyzer.analyze({ file: undefined })).not.to.throw() - expect(() => hardcodedPasswordAnalyzer.analyze({ file, literals: undefined })).not.to.throw() - expect(() => hardcodedPasswordAnalyzer.analyze({ file, literals: [{ value: undefined }] })).not.to.throw() - expect(() => hardcodedPasswordAnalyzer.analyze({ file, literals: [{ value: 'test' }] })).not.to.throw() + assert.doesNotThrow(() => hardcodedPasswordAnalyzer.analyze(undefined)) + assert.doesNotThrow(() => hardcodedPasswordAnalyzer.analyze({ file: undefined })) + assert.doesNotThrow(() => hardcodedPasswordAnalyzer.analyze({ file, literals: undefined })) + assert.doesNotThrow(() => hardcodedPasswordAnalyzer.analyze({ file, literals: [{ value: undefined }] })) + assert.doesNotThrow(() => hardcodedPasswordAnalyzer.analyze({ file, literals: [{ value: 'test' }] })) }) it('should not report secrets in line 0', () => { @@ -151,8 +154,8 @@ describe('Hardcoded Password Analyzer', () => { it('should detect vulnerability', (done) => { agent .assertSomeTraces(traces => { - expect(traces[0][0].meta['_dd.iast.json']).to.include('"HARDCODED_PASSWORD"') - expect(traces[0][0].meta['_dd.iast.json']).to.include('"evidence":{"value":"pswd"}') + assertObjectContains(traces[0][0].meta['_dd.iast.json'], '"HARDCODED_PASSWORD"') + assertObjectContains(traces[0][0].meta['_dd.iast.json'], '"evidence":{"value":"pswd"}') }) .then(done) .catch(done) diff --git a/packages/dd-trace/test/appsec/iast/analyzers/hardcoded-secret-analyzer.spec.js b/packages/dd-trace/test/appsec/iast/analyzers/hardcoded-secret-analyzer.spec.js index 8ebde0a6269..bd370e1c611 100644 --- a/packages/dd-trace/test/appsec/iast/analyzers/hardcoded-secret-analyzer.spec.js +++ b/packages/dd-trace/test/appsec/iast/analyzers/hardcoded-secret-analyzer.spec.js @@ -1,21 +1,22 @@ 'use strict' -const { expect } = require('chai') -const { describe, it, beforeEach, afterEach } = require('mocha') -const sinon = require('sinon') - -const path = require('node:path') +const assert = require('node:assert/strict') const fs = require('node:fs') const os = require('node:os') +const path = require('node:path') -const agent = require('../../../plugins/agent') -const { getConfigFresh } = require('../../../helpers/config') +const { after, afterEach, before, beforeEach, describe, it } = require('mocha') +const sinon = require('sinon') +const iast = require('../../../../src/appsec/iast') const { NameAndValue, ValueOnly } = require('../../../../src/appsec/iast/analyzers/hardcoded-rule-type') const hardcodedSecretAnalyzer = require('../../../../src/appsec/iast/analyzers/hardcoded-secret-analyzer') -const { suite } = require('./resources/hardcoded-secrets-suite.json') -const iast = require('../../../../src/appsec/iast') const vulnerabilityReporter = require('../../../../src/appsec/iast/vulnerability-reporter') +const { getConfigFresh } = require('../../../helpers/config') +const agent = require('../../../plugins/agent') +const { suite } = require('./resources/hardcoded-secrets-suite.json') + +const { assertObjectContains } = require('../../../../../../integration-tests/helpers') describe('Hardcoded Secret Analyzer', () => { describe('unit test', () => { @@ -51,18 +52,18 @@ describe('Hardcoded Secret Analyzer', () => { }] }) - expect([NameAndValue, ValueOnly]).to.be.include(testCase.type) + assert.ok([NameAndValue, ValueOnly].includes(testCase.type)) sinon.assert.calledOnceWithExactly(report, { file: relFile, line, column, ident, data: testCase.id }) }) }) }) it('should not fail with an malformed secrets', () => { - expect(() => hardcodedSecretAnalyzer.analyze(undefined)).not.to.throw() - expect(() => hardcodedSecretAnalyzer.analyze({ file: undefined })).not.to.throw() - expect(() => hardcodedSecretAnalyzer.analyze({ file, literals: undefined })).not.to.throw() - expect(() => hardcodedSecretAnalyzer.analyze({ file, literals: [{ value: undefined }] })).not.to.throw() - expect(() => hardcodedSecretAnalyzer.analyze({ file, literals: [{ value: 'test' }] })).not.to.throw() + assert.doesNotThrow(() => hardcodedSecretAnalyzer.analyze(undefined)) + assert.doesNotThrow(() => hardcodedSecretAnalyzer.analyze({ file: undefined })) + assert.doesNotThrow(() => hardcodedSecretAnalyzer.analyze({ file, literals: undefined })) + assert.doesNotThrow(() => hardcodedSecretAnalyzer.analyze({ file, literals: [{ value: undefined }] })) + assert.doesNotThrow(() => hardcodedSecretAnalyzer.analyze({ file, literals: [{ value: 'test' }] })) }) it('should not report secrets in line 0', () => { @@ -121,7 +122,7 @@ describe('Hardcoded Secret Analyzer', () => { it('should detect vulnerability', (done) => { agent .assertSomeTraces(traces => { - expect(traces[0][0].meta['_dd.iast.json']).to.include('"HARDCODED_SECRET"') + assertObjectContains(traces[0][0].meta['_dd.iast.json'], '"HARDCODED_SECRET"') }) .then(done) .catch(done) diff --git a/packages/dd-trace/test/appsec/iast/analyzers/ldap-injection-analyzer.ldapjs.plugin.spec.js b/packages/dd-trace/test/appsec/iast/analyzers/ldap-injection-analyzer.ldapjs.plugin.spec.js index 30b6bea34df..2fc5f4d141f 100644 --- a/packages/dd-trace/test/appsec/iast/analyzers/ldap-injection-analyzer.ldapjs.plugin.spec.js +++ b/packages/dd-trace/test/appsec/iast/analyzers/ldap-injection-analyzer.ldapjs.plugin.spec.js @@ -5,7 +5,6 @@ const fs = require('node:fs') const os = require('node:os') const path = require('node:path') -const { expect } = require('chai') const { afterEach, beforeEach, describe } = require('mocha') const { storage } = require('../../../../../datadog-core') @@ -126,7 +125,7 @@ describe('ldap-injection-analyzer with ldapjs', () => { .emit('end') // if .off method wouldn't work the test will never reach this lines because it will loop forever :S - expect(searchResOnEndInvocations).to.be.eq(1) + assert.strictEqual(searchResOnEndInvocations, 1) resolve() } diff --git a/packages/dd-trace/test/appsec/iast/analyzers/sql-injection-analyzer.mysql2.plugin.spec.js b/packages/dd-trace/test/appsec/iast/analyzers/sql-injection-analyzer.mysql2.plugin.spec.js index bb1a89c55c7..0523b3af638 100644 --- a/packages/dd-trace/test/appsec/iast/analyzers/sql-injection-analyzer.mysql2.plugin.spec.js +++ b/packages/dd-trace/test/appsec/iast/analyzers/sql-injection-analyzer.mysql2.plugin.spec.js @@ -1,9 +1,10 @@ 'use strict' +const assert = require('node:assert/strict') + const path = require('path') const os = require('os') const fs = require('fs') -const { assert } = require('chai') const { prepareTestServerForIast } = require('../utils') const { storage } = require('../../../../../datadog-core') const { withVersions } = require('../../../setup/mocha') @@ -66,8 +67,8 @@ describe('sql-injection-analyzer with mysql2', () => { return vulnerableMethod(connection, sql) }, 'SQL_INJECTION', 1, function ([vulnerability]) { - assert.isTrue(vulnerability.location.path.endsWith(vulnerableMethodFilename)) - assert.equal(vulnerability.location.line, 5) + assert.strictEqual(vulnerability.location.path.endsWith(vulnerableMethodFilename), true) + assert.strictEqual(vulnerability.location.line, 5) }) }) diff --git a/packages/dd-trace/test/appsec/iast/analyzers/sql-injection-analyzer.spec.js b/packages/dd-trace/test/appsec/iast/analyzers/sql-injection-analyzer.spec.js index 514f3f754c6..287631f9028 100644 --- a/packages/dd-trace/test/appsec/iast/analyzers/sql-injection-analyzer.spec.js +++ b/packages/dd-trace/test/appsec/iast/analyzers/sql-injection-analyzer.spec.js @@ -165,7 +165,7 @@ describe('sql-injection-analyzer', () => { sqlInjectionAnalyzer.configure(true) dc.channel('datadog:sequelize:query:finish').publish() sqlInjectionAnalyzer.configure(false) - expect(log.error).not.to.be.called + sinon.assert.notCalled(log.error) }) describe('analyze', () => { diff --git a/packages/dd-trace/test/appsec/iast/analyzers/unvalidated-redirect-analyzer.spec.js b/packages/dd-trace/test/appsec/iast/analyzers/unvalidated-redirect-analyzer.spec.js index 7bc9bf28f2a..173e22f31ee 100644 --- a/packages/dd-trace/test/appsec/iast/analyzers/unvalidated-redirect-analyzer.spec.js +++ b/packages/dd-trace/test/appsec/iast/analyzers/unvalidated-redirect-analyzer.spec.js @@ -1,8 +1,6 @@ 'use strict' const assert = require('node:assert/strict') - -const { expect } = require('chai') const { afterEach, beforeEach, describe, it } = require('mocha') const proxyquire = require('proxyquire') const sinon = require('sinon') @@ -113,19 +111,19 @@ describe('unvalidated-redirect-analyzer', () => { it('should not report headers other than Location', () => { unvalidatedRedirectAnalyzer.analyze('X-test', NOT_TAINTED_LOCATION) - expect(report).not.to.be.called + sinon.assert.notCalled(report) }) it('should not report Location header with non string values', () => { unvalidatedRedirectAnalyzer.analyze('X-test', [TAINTED_LOCATION]) - expect(report).not.to.be.called + sinon.assert.notCalled(report) }) it('should not report Location header with not tainted string value', () => { unvalidatedRedirectAnalyzer.analyze('Location', NOT_TAINTED_LOCATION) - expect(report).not.to.be.called + sinon.assert.notCalled(report) }) it('should report Location header with tainted string value', () => { @@ -137,25 +135,25 @@ describe('unvalidated-redirect-analyzer', () => { it('should not report if tainted origin is referer header exclusively', () => { unvalidatedRedirectAnalyzer.analyze('Location', TAINTED_HEADER_REFERER_ONLY) - expect(report).not.to.be.called + sinon.assert.notCalled(report) }) it('should not report if tainted origin is path param exclusively', () => { unvalidatedRedirectAnalyzer.analyze('Location', TAINTED_PATH_PARAMS_ONLY) - expect(report).not.to.be.called + sinon.assert.notCalled(report) }) it('should not report if tainted origin is url exclusively', () => { unvalidatedRedirectAnalyzer.analyze('Location', TAINTED_URL_ONLY) - expect(report).not.to.be.called + sinon.assert.notCalled(report) }) it('should not report if all tainted origin are safe', () => { unvalidatedRedirectAnalyzer.analyze('Location', TAINTED_SAFE_RANGES) - expect(report).not.to.be.called + sinon.assert.notCalled(report) }) it('should report if tainted origin contains referer header among others', () => { diff --git a/packages/dd-trace/test/appsec/iast/analyzers/vulnerability-analyzer.spec.js b/packages/dd-trace/test/appsec/iast/analyzers/vulnerability-analyzer.spec.js index 35176d39995..7c5b615cd3c 100644 --- a/packages/dd-trace/test/appsec/iast/analyzers/vulnerability-analyzer.spec.js +++ b/packages/dd-trace/test/appsec/iast/analyzers/vulnerability-analyzer.spec.js @@ -91,7 +91,7 @@ describe('vulnerability-analyzer', () => { if (shouldReportCaseData.reported) { sinon.assert.calledOnce(vulnerabilityAnalyzer._report) } else { - expect(vulnerabilityAnalyzer._report).not.to.be.called + sinon.assert.notCalled(vulnerabilityAnalyzer._report) } }) }) diff --git a/packages/dd-trace/test/appsec/iast/code_injection.integration.spec.js b/packages/dd-trace/test/appsec/iast/code_injection.integration.spec.js index f45d295823b..7e1f4fbcc07 100644 --- a/packages/dd-trace/test/appsec/iast/code_injection.integration.spec.js +++ b/packages/dd-trace/test/appsec/iast/code_injection.integration.spec.js @@ -1,8 +1,9 @@ 'use strict' +const assert = require('node:assert/strict') + const path = require('path') const Axios = require('axios') -const { assert } = require('chai') const { sandboxCwd, useSandbox, FakeAgent, spawnProc } = require('../../../../../integration-tests/helpers') describe('IAST - code_injection - integration', () => { @@ -42,27 +43,27 @@ describe('IAST - code_injection - integration', () => { metric === 'instrumented.sink' && tags[0] === 'vulnerability_type:code_injection' }) - assert.isNotNull(instrumentedSink) + assert.notStrictEqual(instrumentedSink, null) } }, 'generate-metrics', 30_000, 2) const checkMessages = agent.assertMessageReceived(({ headers, payload }) => { assert.strictEqual(payload[0][0].metrics['_dd.iast.enabled'], 1) - assert.property(payload[0][0].meta, '_dd.iast.json') + assert.ok(Object.hasOwn(payload[0][0].meta, '_dd.iast.json')) const vulnerabilitiesTrace = JSON.parse(payload[0][0].meta['_dd.iast.json']) - assert.isNotNull(vulnerabilitiesTrace) + assert.notStrictEqual(vulnerabilitiesTrace, null) const vulnerabilities = new Set() vulnerabilitiesTrace.vulnerabilities.forEach(v => { vulnerabilities.add(v.type) }) - assert.isTrue(vulnerabilities.has('CODE_INJECTION')) + assert.strictEqual(vulnerabilities.has('CODE_INJECTION'), true) }) await Promise.all([checkMessages, checkTelemetry]) - assert.equal(iastTelemetryReceived, true) + assert.strictEqual(iastTelemetryReceived, true) } describe('SourceTextModule', () => { diff --git a/packages/dd-trace/test/appsec/iast/iast-context.spec.js b/packages/dd-trace/test/appsec/iast/iast-context.spec.js index dda9feb70e1..b9cfe398a0e 100644 --- a/packages/dd-trace/test/appsec/iast/iast-context.spec.js +++ b/packages/dd-trace/test/appsec/iast/iast-context.spec.js @@ -2,11 +2,9 @@ const assert = require('node:assert/strict') -const { expect } = require('chai') const { describe, it } = require('mocha') const iastContextHandler = require('../../../src/appsec/iast/iast-context') - describe('IAST context', () => { const iastContext = 'IAST_CONTEXT' @@ -16,7 +14,7 @@ describe('IAST context', () => { [iastContextHandler.IAST_CONTEXT_KEY]: iastContext } const returnedIastContext = iastContextHandler.getIastContext(store) - expect(returnedIastContext).to.be.not.null + assert.notStrictEqual(returnedIastContext, null) assert.strictEqual(returnedIastContext, iastContext) }) @@ -44,11 +42,11 @@ describe('IAST context', () => { const store = {} const topContext = {} const returnedIastContext = iastContextHandler.saveIastContext(store, topContext, iastContext) - expect(returnedIastContext).to.be.not.null + assert.notStrictEqual(returnedIastContext, null) assert.strictEqual(returnedIastContext, iastContext) - expect(store[iastContextHandler.IAST_CONTEXT_KEY]).to.be.not.null + assert.notStrictEqual(store[iastContextHandler.IAST_CONTEXT_KEY], null) assert.strictEqual(store[iastContextHandler.IAST_CONTEXT_KEY], iastContext) - expect(topContext[iastContextHandler.IAST_CONTEXT_KEY]).to.be.not.null + assert.notStrictEqual(topContext[iastContextHandler.IAST_CONTEXT_KEY], null) assert.strictEqual(topContext[iastContextHandler.IAST_CONTEXT_KEY], iastContext) }) diff --git a/packages/dd-trace/test/appsec/iast/iast-plugin.spec.js b/packages/dd-trace/test/appsec/iast/iast-plugin.spec.js index a0bb73daaf7..0e65bb669bb 100644 --- a/packages/dd-trace/test/appsec/iast/iast-plugin.spec.js +++ b/packages/dd-trace/test/appsec/iast/iast-plugin.spec.js @@ -78,7 +78,7 @@ describe('IAST Plugin', () => { sinon.assert.calledOnce(addSubMock) const args = addSubMock.getCall(0).args - expect(args[0]).equal('test') + assert.strictEqual(args[0], 'test') assert.strictEqual(args[1], handler) }) @@ -88,7 +88,7 @@ describe('IAST Plugin', () => { sinon.assert.calledOnce(addSubMock) const args = addSubMock.getCall(0).args - expect(args[0]).equal('test') + assert.strictEqual(args[0], 'test') assert.strictEqual(args[1], handler) }) @@ -97,7 +97,7 @@ describe('IAST Plugin', () => { iastPlugin.addSub(iastPluginSub, handler) assert.strictEqual(iastPlugin.pluginSubs.length, 1) - expect(iastPlugin.pluginSubs[0].moduleName).eq('test') + assert.strictEqual(iastPlugin.pluginSubs[0].moduleName, 'test') }) it('should infer moduleName from channelName after registering iastPluginSub with real channelName', () => { @@ -105,7 +105,7 @@ describe('IAST Plugin', () => { iastPlugin.addSub(iastPluginSub, handler) assert.strictEqual(iastPlugin.pluginSubs.length, 1) - expect(iastPlugin.pluginSubs[0].moduleName).eq('test') + assert.strictEqual(iastPlugin.pluginSubs[0].moduleName, 'test') }) it('should not call _getTelemetryHandler', () => { @@ -166,7 +166,7 @@ describe('IAST Plugin', () => { }) sinon.assert.calledOnce(handler) - expect(metric.increase).to.not.be.called + sinon.assert.notCalled(metric.increase) }) }) }) diff --git a/packages/dd-trace/test/appsec/iast/index.spec.js b/packages/dd-trace/test/appsec/iast/index.spec.js index 212f4f7e41e..66c252a53ff 100644 --- a/packages/dd-trace/test/appsec/iast/index.spec.js +++ b/packages/dd-trace/test/appsec/iast/index.spec.js @@ -16,6 +16,7 @@ const { IAST_MODULE } = require('../../../src/appsec/rasp/fs-plugin') const { getConfigFresh } = require('../../helpers/config') const agent = require('../../plugins/agent') const { testInRequest } = require('./utils') +const { assertObjectContains } = require('../../../../../integration-tests/helpers') describe('IAST Index', () => { beforeEach(() => { @@ -69,7 +70,7 @@ describe('IAST Index', () => { it('should detect vulnerability', (done) => { agent .assertSomeTraces(traces => { - expect(traces[0][0].meta['_dd.iast.json']).to.include('"WEAK_HASH"') + assertObjectContains(traces[0][0].meta['_dd.iast.json'], '"WEAK_HASH"') }) .then(done) .catch(done) @@ -81,7 +82,7 @@ describe('IAST Index', () => { iastContextFunctions.cleanIastContext = mockedCleanIastContext agent .assertSomeTraces(traces => { - expect(traces[0][0].meta['_dd.iast.json']).to.include('"WEAK_HASH"') + assertObjectContains(traces[0][0].meta['_dd.iast.json'], '"WEAK_HASH"') sinon.assert.calledOnce(mockedCleanIastContext) }) .then(done) @@ -94,7 +95,7 @@ describe('IAST Index', () => { overheadController.releaseRequest = releaseRequest agent .assertSomeTraces(traces => { - expect(traces[0][0].meta['_dd.iast.json']).to.include('"WEAK_HASH"') + assertObjectContains(traces[0][0].meta['_dd.iast.json'], '"WEAK_HASH"') sinon.assert.calledOnce(releaseRequest) }) .then(done) @@ -235,17 +236,17 @@ describe('IAST Index', () => { it('should not call send vulnerabilities without context', () => { mockIast.onIncomingHttpRequestEnd({ req: {} }) - expect(mockVulnerabilityReporter.sendVulnerabilities).not.to.be.called + sinon.assert.notCalled(mockVulnerabilityReporter.sendVulnerabilities) }) it('should not call send vulnerabilities with context but without iast context', () => { mockIast.onIncomingHttpRequestEnd({ req: {} }) - expect(mockVulnerabilityReporter.sendVulnerabilities).not.to.be.called + sinon.assert.notCalled(mockVulnerabilityReporter.sendVulnerabilities) }) it('should not call releaseRequest without iast context', () => { mockIast.onIncomingHttpRequestEnd({ req: {} }) - expect(mockOverheadController.releaseRequest).not.to.be.called + sinon.assert.notCalled(mockOverheadController.releaseRequest) }) }) }) diff --git a/packages/dd-trace/test/appsec/iast/overhead-controller.integration.spec.js b/packages/dd-trace/test/appsec/iast/overhead-controller.integration.spec.js index 43fc6e46ef8..68fe9a79f67 100644 --- a/packages/dd-trace/test/appsec/iast/overhead-controller.integration.spec.js +++ b/packages/dd-trace/test/appsec/iast/overhead-controller.integration.spec.js @@ -1,8 +1,9 @@ 'use strict' +const assert = require('node:assert/strict') + const path = require('path') const Axios = require('axios') -const { assert } = require('chai') const { sandboxCwd, useSandbox, FakeAgent, spawnProc } = require('../../../../../integration-tests/helpers') describe('IAST - overhead-controller - integration', () => { @@ -48,9 +49,9 @@ describe('IAST - overhead-controller - integration', () => { await agent.assertMessageReceived(({ payload }) => { assert.strictEqual(payload[0][0].type, 'web') assert.strictEqual(payload[0][0].metrics['_dd.iast.enabled'], 1) - assert.property(payload[0][0].meta, '_dd.iast.json') + assert.ok(Object.hasOwn(payload[0][0].meta, '_dd.iast.json')) const vulnerabilitiesTrace = JSON.parse(payload[0][0].meta['_dd.iast.json']) - assert.isNotNull(vulnerabilitiesTrace) + assert.notStrictEqual(vulnerabilitiesTrace, null) const vulnerabilities = {} vulnerabilitiesTrace.vulnerabilities.forEach(v => { @@ -72,7 +73,7 @@ describe('IAST - overhead-controller - integration', () => { await agent.assertMessageReceived(({ payload }) => { assert.strictEqual(payload[0][0].type, 'web') assert.strictEqual(payload[0][0].metrics['_dd.iast.enabled'], 1) - assert.notProperty(payload[0][0].meta, '_dd.iast.json') + assert.ok(!Object.hasOwn(payload[0][0].meta, '_dd.iast.json')) }, 1000, 1, true) } diff --git a/packages/dd-trace/test/appsec/iast/overhead-controller.spec.js b/packages/dd-trace/test/appsec/iast/overhead-controller.spec.js index 7fce982a79a..731d2ea1e50 100644 --- a/packages/dd-trace/test/appsec/iast/overhead-controller.spec.js +++ b/packages/dd-trace/test/appsec/iast/overhead-controller.spec.js @@ -4,7 +4,6 @@ const assert = require('node:assert/strict') const { EventEmitter } = require('node:events') const axios = require('axios') -const { expect } = require('chai') const { after, afterEach, before, beforeEach, describe, it } = require('mocha') const proxyquire = require('proxyquire') const sinon = require('sinon') @@ -50,7 +49,7 @@ describe('Overhead controller', () => { it('should populate request context', () => { const iastContext = {} overheadController.initializeRequestContext(iastContext) - expect(iastContext).to.have.nested.property(overheadController.OVERHEAD_CONTROLLER_CONTEXT_KEY) + assert.ok(overheadController.OVERHEAD_CONTROLLER_CONTEXT_KEY in iastContext) }) }) }) @@ -230,14 +229,15 @@ describe('Overhead controller', () => { }) it('should populate initial context with available tokens', () => { - expect(iastContext[oceContextKey]) - .to.have.nested.property(`tokens.${OPERATION.name}`, OPERATION.initialTokenBucketSize()) + assert.ok(`tokens.${OPERATION.name}` in iastContext[oceContextKey]); + assert.strictEqual(iastContext[oceContextKey][`tokens.${OPERATION.name}`], OPERATION.initialTokenBucketSize()) }) it('should allow when available tokens', () => { iastContext[overheadController.OVERHEAD_CONTROLLER_CONTEXT_KEY].tokens[OPERATION.name] = 2 assert.strictEqual(overheadController.hasQuota(OPERATION, iastContext, vulnerabilities.SSRF), true) - expect(iastContext[oceContextKey]).to.have.nested.property(`tokens.${OPERATION.name}`, 1) + assert.ok(`tokens.${OPERATION.name}` in iastContext[oceContextKey]); + assert.strictEqual(iastContext[oceContextKey][`tokens.${OPERATION.name}`], 1) }) it('should detect the first vulnerability of the type ' + @@ -246,7 +246,8 @@ describe('Overhead controller', () => { iastContext[overheadController.OVERHEAD_CONTROLLER_CONTEXT_KEY].tokens[OPERATION.name] = 1 assert.strictEqual(overheadController.hasQuota(OPERATION, iastContext, vulnerabilities.SSRF), true) overheadController.consolidateVulnerabilities(iastContext) - expect(iastContext[oceContextKey]).to.have.nested.property(`tokens.${OPERATION.name}`, 0) + assert.ok(`tokens.${OPERATION.name}` in iastContext[oceContextKey]); + assert.strictEqual(iastContext[oceContextKey][`tokens.${OPERATION.name}`], 0) // Ignoring the first SSRF in the next request iastContext = { req } @@ -266,7 +267,8 @@ describe('Overhead controller', () => { iastContext[overheadController.OVERHEAD_CONTROLLER_CONTEXT_KEY].tokens[OPERATION.name] = 1 assert.strictEqual(overheadController.hasQuota(OPERATION, iastContext, vulnerabilities.SSRF), true) overheadController.consolidateVulnerabilities(iastContext) - expect(iastContext[oceContextKey]).to.have.nested.property(`tokens.${OPERATION.name}`, 0) + assert.ok(`tokens.${OPERATION.name}` in iastContext[oceContextKey]); + assert.strictEqual(iastContext[oceContextKey][`tokens.${OPERATION.name}`], 0) // Ignoring the first SSRF in the next request iastContext = { req } @@ -284,7 +286,8 @@ describe('Overhead controller', () => { iastContext[overheadController.OVERHEAD_CONTROLLER_CONTEXT_KEY].tokens[OPERATION.name] = 1 assert.strictEqual(overheadController.hasQuota(OPERATION, iastContext, vulnerabilities.SSRF), true) overheadController.consolidateVulnerabilities(iastContext) - expect(iastContext[oceContextKey]).to.have.nested.property(`tokens.${OPERATION.name}`, 0) + assert.ok(`tokens.${OPERATION.name}` in iastContext[oceContextKey]); + assert.strictEqual(iastContext[oceContextKey][`tokens.${OPERATION.name}`], 0) // Detecting the first CODE_INJECTION in the next request iastContext = { req } @@ -304,7 +307,8 @@ describe('Overhead controller', () => { iastContext[overheadController.OVERHEAD_CONTROLLER_CONTEXT_KEY].tokens[OPERATION.name] = 1 assert.strictEqual(overheadController.hasQuota(OPERATION, iastContext, vulnerabilities.SSRF), true) overheadController.consolidateVulnerabilities(iastContext) - expect(iastContext[oceContextKey]).to.have.nested.property(`tokens.${OPERATION.name}`, 0) + assert.ok(`tokens.${OPERATION.name}` in iastContext[oceContextKey]); + assert.strictEqual(iastContext[oceContextKey][`tokens.${OPERATION.name}`], 0) // Detecting the first CODE_INJECTION in the next request iastContext = { req } @@ -319,7 +323,8 @@ describe('Overhead controller', () => { iastContext[overheadController.OVERHEAD_CONTROLLER_CONTEXT_KEY].tokens[OPERATION.name] = 1 assert.strictEqual(overheadController.hasQuota(OPERATION, iastContext, vulnerabilities.SSRF), true) overheadController.consolidateVulnerabilities(iastContext) - expect(iastContext[oceContextKey]).to.have.nested.property(`tokens.${OPERATION.name}`, 0) + assert.ok(`tokens.${OPERATION.name}` in iastContext[oceContextKey]); + assert.strictEqual(iastContext[oceContextKey][`tokens.${OPERATION.name}`], 0) // Detecting the first CODE_INJECTION in the next request req.method = 'POST' @@ -335,7 +340,8 @@ describe('Overhead controller', () => { iastContext[overheadController.OVERHEAD_CONTROLLER_CONTEXT_KEY].tokens[OPERATION.name] = 2 assert.strictEqual(overheadController.hasQuota(OPERATION, iastContext, vulnerabilities.SSRF), true) overheadController.consolidateVulnerabilities(iastContext) - expect(iastContext[oceContextKey]).to.have.nested.property(`tokens.${OPERATION.name}`, 1) + assert.ok(`tokens.${OPERATION.name}` in iastContext[oceContextKey]); + assert.strictEqual(iastContext[oceContextKey][`tokens.${OPERATION.name}`], 1) // Detecting the first CODE_INJECTION in the next request iastContext = { req } @@ -349,7 +355,8 @@ describe('Overhead controller', () => { iastContext[overheadController.OVERHEAD_CONTROLLER_CONTEXT_KEY].tokens[OPERATION.name] = 1 assert.strictEqual(overheadController.hasQuota(OPERATION, iastContext, vulnerabilities.SSRF), true) overheadController.consolidateVulnerabilities(iastContext) - expect(iastContext[oceContextKey]).to.have.nested.property(`tokens.${OPERATION.name}`, 0) + assert.ok(`tokens.${OPERATION.name}` in iastContext[oceContextKey]); + assert.strictEqual(iastContext[oceContextKey][`tokens.${OPERATION.name}`], 0) // second request using the whole budget iastContext = { req } @@ -357,7 +364,8 @@ describe('Overhead controller', () => { iastContext[overheadController.OVERHEAD_CONTROLLER_CONTEXT_KEY].tokens[OPERATION.name] = 1 assert.strictEqual(overheadController.hasQuota(OPERATION, iastContext, vulnerabilities.SSRF), false) assert.strictEqual(overheadController.hasQuota(OPERATION, iastContext, vulnerabilities.SSRF), true) - expect(iastContext[oceContextKey]).to.have.nested.property(`tokens.${OPERATION.name}`, 0) + assert.ok(`tokens.${OPERATION.name}` in iastContext[oceContextKey]); + assert.strictEqual(iastContext[oceContextKey][`tokens.${OPERATION.name}`], 0) overheadController.consolidateVulnerabilities(iastContext) // third request detecting only the third SSRF @@ -372,7 +380,8 @@ describe('Overhead controller', () => { it('should not allow when no available tokens', () => { iastContext[overheadController.OVERHEAD_CONTROLLER_CONTEXT_KEY].tokens[OPERATION.name] = 0 assert.strictEqual(overheadController.hasQuota(OPERATION, iastContext), false) - expect(iastContext[oceContextKey]).to.have.nested.property(`tokens.${OPERATION.name}`, 0) + assert.ok(`tokens.${OPERATION.name}` in iastContext[oceContextKey]); + assert.strictEqual(iastContext[oceContextKey][`tokens.${OPERATION.name}`], 0) }) }) @@ -459,11 +468,11 @@ describe('Overhead controller', () => { const url = trace.meta['http.url'] if (url.includes(FIRST_REQUEST)) { assert.notStrictEqual(trace.meta['_dd.iast.json'], undefined) - expect(trace.metrics['_dd.iast.enabled']).eq(1) + assert.strictEqual(trace.metrics['_dd.iast.enabled'], 1) urlCounter++ } else if (url.includes(SECOND_REQUEST)) { assert.strictEqual(trace.meta['_dd.iast.json'], undefined) - expect(trace.metrics['_dd.iast.enabled']).eq(0) + assert.strictEqual(trace.metrics['_dd.iast.enabled'], 0) urlCounter++ } if (urlCounter === 2) { @@ -511,7 +520,7 @@ describe('Overhead controller', () => { if (trace.type === 'web') { urlCounter++ assert.notStrictEqual(trace.meta['_dd.iast.json'], undefined) - expect(trace.metrics['_dd.iast.enabled']).eq(1) + assert.strictEqual(trace.metrics['_dd.iast.enabled'], 1) if (urlCounter === 2) { done() } @@ -639,7 +648,7 @@ describe('Overhead controller', () => { const url = trace.meta['http.url'] if (url.includes(SECURE_REQUEST)) { assert.strictEqual(trace.meta['_dd.iast.json'], undefined) - expect(trace.metrics['_dd.iast.enabled']).eq(1) + assert.strictEqual(trace.metrics['_dd.iast.enabled'], 1) done() } } diff --git a/packages/dd-trace/test/appsec/iast/path-line.spec.js b/packages/dd-trace/test/appsec/iast/path-line.spec.js index 08577325599..63325d03a5f 100644 --- a/packages/dd-trace/test/appsec/iast/path-line.spec.js +++ b/packages/dd-trace/test/appsec/iast/path-line.spec.js @@ -4,7 +4,6 @@ const assert = require('node:assert/strict') const os = require('os') const path = require('path') -const { expect } = require('chai') const proxyquire = require('proxyquire') const { getCallsiteFrames } = require('../../../src/appsec/stack_trace') @@ -341,7 +340,7 @@ describe('path-line', function () { const paths = pathLine.getNodeModulesPaths('/this/is/a/path', '/another/path') assert.strictEqual(paths.length, 2) - expect(paths[0].startsWith('node_modules')).to.true + assert.strictEqual(paths[0].startsWith('node_modules'), true) }) }) }) diff --git a/packages/dd-trace/test/appsec/iast/security-controls/parser.spec.js b/packages/dd-trace/test/appsec/iast/security-controls/parser.spec.js index 9238e07e2ea..78a7b219495 100644 --- a/packages/dd-trace/test/appsec/iast/security-controls/parser.spec.js +++ b/packages/dd-trace/test/appsec/iast/security-controls/parser.spec.js @@ -1,11 +1,10 @@ 'use strict' const assert = require('node:assert') -const { expect } = require('chai') + const { describe, it } = require('mocha') const { parse } = require('../../../../src/appsec/iast/security-controls/parser') - const { COMMAND_INJECTION_MARK, CODE_INJECTION_MARK, @@ -60,7 +59,7 @@ describe('IAST Security Controls parser', () => { const civ = securityControls.get(civFilename)[0] - expect(civ).not.undefined + assert.notStrictEqual(civ, undefined) assert.deepStrictEqual(civ, { type: 'INPUT_VALIDATOR', file: civFilename, diff --git a/packages/dd-trace/test/appsec/iast/taint-tracking/plugin.spec.js b/packages/dd-trace/test/appsec/iast/taint-tracking/plugin.spec.js index 89c11eb8aab..4cd955e3ec6 100644 --- a/packages/dd-trace/test/appsec/iast/taint-tracking/plugin.spec.js +++ b/packages/dd-trace/test/appsec/iast/taint-tracking/plugin.spec.js @@ -148,7 +148,7 @@ describe('IAST Taint tracking plugin', () => { } taintTrackingPlugin._taintTrackingHandler(originType, objToBeTainted, propertyToBeTainted) - expect(taintTrackingOperations.taintObject).not.to.be.called + sinon.assert.notCalled(taintTrackingOperations.taintObject) }) it('Should taint request parameter when qs event is published', () => { @@ -265,7 +265,7 @@ describe('IAST Taint tracking plugin', () => { const req = {} processParamsStartCh.publish({ req }) - expect(taintTrackingOperations.taintObject).to.not.be.called + sinon.assert.notCalled(taintTrackingOperations.taintObject) }) it('Should taint headers and uri from request', () => { diff --git a/packages/dd-trace/test/appsec/iast/taint-tracking/rewriter-telemetry.spec.js b/packages/dd-trace/test/appsec/iast/taint-tracking/rewriter-telemetry.spec.js index 12ff8bc7deb..17ba5d9b00f 100644 --- a/packages/dd-trace/test/appsec/iast/taint-tracking/rewriter-telemetry.spec.js +++ b/packages/dd-trace/test/appsec/iast/taint-tracking/rewriter-telemetry.spec.js @@ -35,7 +35,7 @@ describe('rewriter telemetry', () => { } incrementTelemetryIfNeeded(metrics) - expect(instrumentedPropagationInc).not.to.be.called + sinon.assert.notCalled(instrumentedPropagationInc) }) it('should increment telemetry when verbosity is not OFF', () => { diff --git a/packages/dd-trace/test/appsec/iast/taint-tracking/rewriter.spec.js b/packages/dd-trace/test/appsec/iast/taint-tracking/rewriter.spec.js index 1ac5974ac9a..85c99dda5f6 100644 --- a/packages/dd-trace/test/appsec/iast/taint-tracking/rewriter.spec.js +++ b/packages/dd-trace/test/appsec/iast/taint-tracking/rewriter.spec.js @@ -18,9 +18,9 @@ const iastEnabledConfig = { describe('IAST Rewriter', () => { it('Addon should return a rewritter instance', () => { let rewriter = null - expect(() => { + assert.doesNotThrow(() => { rewriter = require('@datadog/wasm-js-rewriter') - }).to.not.throw(Error) + }, Error) assert.notStrictEqual(rewriter, null) }) @@ -115,7 +115,7 @@ describe('IAST Rewriter', () => { it('Should wrap module compile method on taint tracking enable', () => { rewriter.enable(iastEnabledConfig) sinon.assert.calledOnce(shimmer.wrap) - expect(shimmer.wrap.getCall(0).args[1]).eq('_compile') + assert.strictEqual(shimmer.wrap.getCall(0).args[1], '_compile') rewriter.disable() }) @@ -145,7 +145,7 @@ describe('IAST Rewriter', () => { rewriter.disable() - expect(Error.prepareStackTrace).to.be.eq(testPrepareStackTrace) + assert.strictEqual(Error.prepareStackTrace, testPrepareStackTrace) Error.prepareStackTrace = orig }) @@ -160,7 +160,7 @@ describe('IAST Rewriter', () => { rewriter.disable() - expect(Error.prepareStackTrace).to.be.eq(testPrepareStackTrace) + assert.strictEqual(Error.prepareStackTrace, testPrepareStackTrace) Error.prepareStackTrace = orig }) @@ -180,7 +180,7 @@ describe('IAST Rewriter', () => { rewriter.disable() - expect(Error.prepareStackTrace).to.be.eq(testPrepareStackTrace) + assert.strictEqual(Error.prepareStackTrace, testPrepareStackTrace) Error.prepareStackTrace = orig }) @@ -204,7 +204,7 @@ describe('IAST Rewriter', () => { it('Should not enable esm rewriter when ESM is not instrumented', () => { rewriter.enable(iastEnabledConfig) - expect(Module.register).not.to.be.called + sinon.assert.notCalled(Module.register) }) it('Should enable esm rewriter when ESM is configured with --loader exec arg', () => { @@ -388,7 +388,7 @@ describe('IAST Rewriter', () => { const location = { path: 'test', line: 42, column: 4 } rewriter.getOriginalPathAndLineFromSourceMap(location) - expect(getOriginalPathAndLineFromSourceMap).to.not.be.called + sinon.assert.notCalled(getOriginalPathAndLineFromSourceMap) }) it('should not call native getOriginalPathAndLineFromSourceMap if --enable-source-maps as NODE_OPTION', () => { @@ -405,7 +405,7 @@ describe('IAST Rewriter', () => { const location = { path: 'test', line: 42, column: 4 } rewriter.getOriginalPathAndLineFromSourceMap(location) - expect(getOriginalPathAndLineFromSourceMap).to.not.be.called + sinon.assert.notCalled(getOriginalPathAndLineFromSourceMap) process.env.NODE_OPTIONS = origNodeOptions }) diff --git a/packages/dd-trace/test/appsec/iast/taint-tracking/secure-marks.spec.js b/packages/dd-trace/test/appsec/iast/taint-tracking/secure-marks.spec.js index b6f61f8bed0..a42cd9c1034 100644 --- a/packages/dd-trace/test/appsec/iast/taint-tracking/secure-marks.spec.js +++ b/packages/dd-trace/test/appsec/iast/taint-tracking/secure-marks.spec.js @@ -1,6 +1,6 @@ 'use strict' -const { assert } = require('chai') +const assert = require('node:assert/strict') const { SQL_INJECTION_MARK, getMarkFromVulnerabilityType, @@ -12,23 +12,23 @@ const { SQL_INJECTION } = require('../../../../src/appsec/iast/vulnerabilities') describe('IAST secure marks', () => { it('should generate a mark for each vulnerability', () => { const mark = getMarkFromVulnerabilityType(SQL_INJECTION) - assert.equal(mark, SQL_INJECTION_MARK) + assert.strictEqual(mark, SQL_INJECTION_MARK) }) it('should generate a mark for every vulnerability', () => { const mark = getMarkFromVulnerabilityType('*') - assert.equal(mark, ASTERISK_MARK) + assert.strictEqual(mark, ASTERISK_MARK) }) it('should not be repeated marks (probably due to truncation)', () => { const markValues = Object.values(ALL) - assert.equal(markValues.length, [...new Set(markValues)].length) + assert.strictEqual(markValues.length, [...new Set(markValues)].length) }) it('should generate marks under 0x100000000 due taint-tracking secure mark length', () => { // in theory secure-marks generator can not reach this value with bitwise operations due to 32-bit integer linmits const limitMark = 0x100000000 - Object.values(ALL).forEach(mark => assert.isTrue(mark < limitMark)) + Object.values(ALL).forEach(mark => assert.strictEqual(mark < limitMark, true)) }) }) diff --git a/packages/dd-trace/test/appsec/iast/taint-tracking/taint-tracking-impl.spec.js b/packages/dd-trace/test/appsec/iast/taint-tracking/taint-tracking-impl.spec.js index e2c285b3d01..43979afaa1c 100644 --- a/packages/dd-trace/test/appsec/iast/taint-tracking/taint-tracking-impl.spec.js +++ b/packages/dd-trace/test/appsec/iast/taint-tracking/taint-tracking-impl.spec.js @@ -4,8 +4,6 @@ const fs = require('fs') const assert = require('node:assert/strict') const path = require('path') -const { expect } = require('chai') - const { storage } = require('../../../../../datadog-core') const iastContextFunctions = require('../../../../src/appsec/iast/iast-context') const { newTaintedString, isTainted, getRanges } = require('../../../../src/appsec/iast/taint-tracking/operations') @@ -78,7 +76,7 @@ describe('TaintTracking', () => { assert.strictEqual(isTainted(iastContext, commandResult), true) const commandResultOrig = propFnOriginal(commandTainted) - expect(commandResult).eq(commandResultOrig) + assert.strictEqual(commandResult, commandResultOrig) try { const childProcess = require('child_process') @@ -105,8 +103,7 @@ describe('TaintTracking', () => { const result = propFnInstrumented(jsonTainted) assert.strictEqual(isTainted(iastContext, result.command), true) - expect(getRanges(iastContext, result.command)).to.be.deep - .eq([{ + assert.deepStrictEqual(getRanges(iastContext, result.command), [{ start: 0, end: 6, iinfo: { @@ -118,7 +115,7 @@ describe('TaintTracking', () => { }]) const resultOrig = propFnOriginal(jsonTainted) - expect(result).deep.eq(resultOrig) + assert.deepStrictEqual(result, resultOrig) try { const childProcess = require('child_process') diff --git a/packages/dd-trace/test/appsec/iast/taint-tracking/taint-tracking-operations.spec.js b/packages/dd-trace/test/appsec/iast/taint-tracking/taint-tracking-operations.spec.js index fdcea490ccd..95000a49ad5 100644 --- a/packages/dd-trace/test/appsec/iast/taint-tracking/taint-tracking-operations.spec.js +++ b/packages/dd-trace/test/appsec/iast/taint-tracking/taint-tracking-operations.spec.js @@ -75,9 +75,9 @@ describe('IAST TaintTracking Operations', () => { it('Addon should return a TaintedUtils instance', () => { let TaintedUtils = null - expect(() => { + assert.doesNotThrow(() => { TaintedUtils = require('@datadog/native-iast-taint-tracking') - }).to.not.throw(Error) + }, Error) assert.notStrictEqual(TaintedUtils, null) }) @@ -206,7 +206,7 @@ describe('IAST TaintTracking Operations', () => { const iastContext = {} const transactionId = null taintTrackingOperations.createTransaction(transactionId, iastContext) - expect(taintedUtils.createTransaction).not.to.be.called + sinon.assert.notCalled(taintedUtils.createTransaction) assert.strictEqual(iastContext[taintTrackingOperations.IAST_TRANSACTION_ID], undefined) }) @@ -214,7 +214,7 @@ describe('IAST TaintTracking Operations', () => { const iastContext = null const transactionId = 'id' taintTrackingOperations.createTransaction(transactionId, iastContext) - expect(taintedUtils.createTransaction).not.to.be.called + sinon.assert.notCalled(taintedUtils.createTransaction) assert.strictEqual(iastContext, null) }) }) @@ -235,13 +235,13 @@ describe('IAST TaintTracking Operations', () => { it('Given iastContext with undefined IAST_TRANSACTION_ID should not removeTransaction', () => { const iastContext = {} taintTrackingOperations.removeTransaction(iastContext) - expect(taintedUtils.removeTransaction).not.to.be.called + sinon.assert.notCalled(taintedUtils.removeTransaction) }) it('Given null iastContext should call not removeTransaction', () => { const iastContext = null taintTrackingOperations.removeTransaction(iastContext) - expect(taintedUtils.removeTransaction).not.to.be.called + sinon.assert.notCalled(taintedUtils.removeTransaction) }) it('Should increment REQUEST_TAINTED metric if INFORMATION or greater verbosity is enabled', () => { @@ -308,7 +308,7 @@ describe('IAST TaintTracking Operations', () => { // taintedUtils methods are not called global._ddiast.plusOperator('helloworld', 'hello', 'world') - expect(taintedUtils.concat).not.to.be.called + sinon.assert.notCalled(taintedUtils.concat) }) it('Should set debug global._ddiast object', () => { @@ -345,13 +345,13 @@ describe('IAST TaintTracking Operations', () => { it('Given iastContext with undefined IAST_TRANSACTION_ID should not call TaintedUtils.newTaintedString', () => { const iastContext = {} taintTrackingOperations.newTaintedString(iastContext) - expect(taintedUtils.newTaintedString).not.to.be.called + sinon.assert.notCalled(taintedUtils.newTaintedString) }) it('Given null iastContext should call not TaintedUtils.newTaintedString', () => { const iastContext = null taintTrackingOperations.newTaintedString(iastContext) - expect(taintedUtils.newTaintedString).not.to.be.called + sinon.assert.notCalled(taintedUtils.newTaintedString) }) it('Given null iastContext should return the string passed as parameter', () => { @@ -379,13 +379,13 @@ describe('IAST TaintTracking Operations', () => { it('Given iastContext with undefined IAST_TRANSACTION_ID should not call TaintedUtils.newTaintedObject', () => { const iastContext = {} taintTrackingOperations.newTaintedObject(iastContext) - expect(taintedUtils.newTaintedObject).not.to.be.called + sinon.assert.notCalled(taintedUtils.newTaintedObject) }) it('Given null iastContext should call not TaintedUtils.newTaintedObject', () => { const iastContext = null taintTrackingOperations.newTaintedObject(iastContext) - expect(taintedUtils.newTaintedObject).not.to.be.called + sinon.assert.notCalled(taintedUtils.newTaintedObject) }) it('Given null iastContext should return the string passed as parameter', () => { @@ -413,13 +413,13 @@ describe('IAST TaintTracking Operations', () => { it('Given iastContext with undefined IAST_TRANSACTION_ID should not call TaintedUtils.isTainted', () => { const iastContext = {} taintTrackingOperations.isTainted(iastContext) - expect(taintedUtils.isTainted).not.to.be.called + sinon.assert.notCalled(taintedUtils.isTainted) }) it('Given null iastContext should call not TaintedUtils.isTainted', () => { const iastContext = null taintTrackingOperations.isTainted(iastContext) - expect(taintedUtils.isTainted).not.to.be.called + sinon.assert.notCalled(taintedUtils.isTainted) }) }) @@ -440,13 +440,13 @@ describe('IAST TaintTracking Operations', () => { it('Given iastContext with undefined IAST_TRANSACTION_ID should not call TaintedUtils.getRanges', () => { const iastContext = {} taintTrackingOperations.getRanges(iastContext) - expect(taintedUtils.getRanges).not.to.be.called + sinon.assert.notCalled(taintedUtils.getRanges) }) it('Given null iastContext should call not TaintedUtils.getRanges', () => { const iastContext = null taintTrackingOperations.getRanges(iastContext) - expect(taintedUtils.getRanges).not.to.be.called + sinon.assert.notCalled(taintedUtils.getRanges) }) it('Given null iastContext should return empty array', () => { @@ -464,27 +464,27 @@ describe('IAST TaintTracking Operations', () => { it('Should not call taintedUtils.concat method if result is not a string', () => { global._ddiast.plusOperator(1 + 2, 1, 2) - expect(taintedUtils.concat).not.to.be.called + sinon.assert.notCalled(taintedUtils.concat) }) it('Should not call taintedUtils.concat method if both operands are not string', () => { const a = { x: 'hello' } const b = { y: 'world' } global._ddiast.plusOperator(a + b, a, b) - expect(taintedUtils.concat).not.to.be.called + sinon.assert.notCalled(taintedUtils.concat) }) it('Should not call taintedUtils.concat method if there is not an active transaction', () => { iastContextFunctions.saveIastContext(store, {}, { [taintTrackingOperations.IAST_TRANSACTION_ID]: null }) global._ddiast.plusOperator('helloworld', 'hello', 'world') - expect(taintedUtils.concat).not.to.be.called + sinon.assert.notCalled(taintedUtils.concat) }) it('Should not fail if taintTracking is not enabled', () => { taintTrackingOperations.disableTaintOperations() const res = global._ddiast.plusOperator('helloworld', 'hello', 'world') - expect(taintedUtils.concat).not.to.be.called - expect(res).equal('helloworld') + sinon.assert.notCalled(taintedUtils.concat) + assert.strictEqual(res, 'helloworld') }) }) @@ -519,8 +519,8 @@ describe('IAST TaintTracking Operations', () => { const a = { trim: function (a) { return a } } const fn = a.trim const result = global._ddiast.trim(fn.call(a, 'hello'), fn, a, 'hello') - expect(taintedUtils.trim).not.to.be.called - expect(result).eq('hello') + sinon.assert.notCalled(taintedUtils.trim) + assert.strictEqual(result, 'hello') }) it('Should not call taintedUtils.trim method if there is not an active transaction', () => { @@ -528,7 +528,7 @@ describe('IAST TaintTracking Operations', () => { const a = 'hello ' const fn = a.trim global._ddiast.trim(fn.call(a), fn, a) - expect(taintedUtils.trim).not.to.be.called + sinon.assert.notCalled(taintedUtils.trim) }) it('Should not call taintedUtils.trim method if an Error happens', () => { @@ -555,8 +555,8 @@ describe('IAST TaintTracking Operations', () => { const a = 'hello ' const fn = a.trim const result = global._ddiast.trim(fn.call(a), fn, a) - expect(taintedUtils.trim).not.to.be.called - expect(result).eq(a.trim()) + sinon.assert.notCalled(taintedUtils.trim) + assert.strictEqual(result, a.trim()) }) }) @@ -565,14 +565,16 @@ describe('IAST TaintTracking Operations', () => { const tt = taintTrackingImpl.getTaintTrackingImpl() const noop = taintTrackingImpl.getTaintTrackingNoop() - expect(noop).to.have.all.keys(Object.keys(tt)) + assert.strictEqual(Object.keys(noop).length, ((Array.isArray(Object.keys(tt)) ? Object.keys(tt) : [Object.keys(tt)])).length) +assert.ok(((Array.isArray(Object.keys(tt)) ? Object.keys(tt) : [Object.keys(tt)])).every(k => Object.hasOwn(noop, k))) }) it('should have the same properties as TaintTrackingDebug', () => { const ttDebug = taintTrackingImpl.getTaintTrackingImpl(Verbosity.DEBUG) const noop = taintTrackingImpl.getTaintTrackingNoop() - expect(noop).to.have.all.keys(Object.keys(ttDebug)) + assert.strictEqual(Object.keys(noop).length, ((Array.isArray(Object.keys(ttDebug)) ? Object.keys(ttDebug) : [Object.keys(ttDebug)])).length) +assert.ok(((Array.isArray(Object.keys(ttDebug)) ? Object.keys(ttDebug) : [Object.keys(ttDebug)])).every(k => Object.hasOwn(noop, k))) }) it('should have the same properties as csiMethods', () => { @@ -580,7 +582,8 @@ describe('IAST TaintTracking Operations', () => { const csiExpectedMethods = getExpectedMethods() - expect(tt).to.have.all.keys(csiExpectedMethods) + assert.strictEqual(Object.keys(tt).length, ((Array.isArray(csiExpectedMethods) ? csiExpectedMethods : [csiExpectedMethods])).length) +assert.ok(((Array.isArray(csiExpectedMethods) ? csiExpectedMethods : [csiExpectedMethods])).every(k => Object.hasOwn(tt, k))) }) }) }) diff --git a/packages/dd-trace/test/appsec/iast/taint-tracking/taint-tracking.lodash.plugin.spec.js b/packages/dd-trace/test/appsec/iast/taint-tracking/taint-tracking.lodash.plugin.spec.js index 5887faf94be..e63499c6cbe 100644 --- a/packages/dd-trace/test/appsec/iast/taint-tracking/taint-tracking.lodash.plugin.spec.js +++ b/packages/dd-trace/test/appsec/iast/taint-tracking/taint-tracking.lodash.plugin.spec.js @@ -4,7 +4,6 @@ const assert = require('node:assert/strict') const fs = require('node:fs') const path = require('node:path') -const { expect } = require('chai') const { afterEach, beforeEach, describe, it } = require('mocha') const { storage } = require('../../../../../datadog-core') @@ -67,7 +66,7 @@ describe('TaintTracking lodash', () => { assert.strictEqual(isTainted(iastContext, commandResult), true) const commandResultOrig = propFnOriginal(_, commandTainted) - expect(commandResult).eq(commandResultOrig) + assert.strictEqual(commandResult, commandResultOrig) try { const childProcess = require('child_process') diff --git a/packages/dd-trace/test/appsec/iast/telemetry/iast-metric.spec.js b/packages/dd-trace/test/appsec/iast/telemetry/iast-metric.spec.js index 21ae20e9db9..3db8e17ac07 100644 --- a/packages/dd-trace/test/appsec/iast/telemetry/iast-metric.spec.js +++ b/packages/dd-trace/test/appsec/iast/telemetry/iast-metric.spec.js @@ -87,8 +87,8 @@ describe('Metrics', () => { metric.formatTags('tag1', 'tag2').forEach(tag => metric.inc(context, tag, 42)) expect(reqNamespace.count).to.be.calledTwice - expect(reqNamespace.count.firstCall.args).to.be.deep.equals([metric.name, ['tagKey:tag1']]) - expect(reqNamespace.count.secondCall.args).to.be.deep.equals([metric.name, ['tagKey:tag2']]) + assert.deepStrictEqual(reqNamespace.count.firstCall.args, [metric.name, ['tagKey:tag1']]) + assert.deepStrictEqual(reqNamespace.count.secondCall.args, [metric.name, ['tagKey:tag2']]) }) it('getExecutedMetric should return a metric depending on tag', () => { @@ -113,9 +113,9 @@ describe('Metrics', () => { it('should define an empty array as its tags', () => { const noTagged = new NoTaggedIastMetric('notagged', 'scope') - expect(noTagged.name).to.be.eq('notagged') - expect(noTagged.scope).to.be.eq('scope') - expect(noTagged.tags).to.be.deep.eq([]) + assert.strictEqual(noTagged.name, 'notagged') + assert.strictEqual(noTagged.scope, 'scope') + assert.deepStrictEqual(noTagged.tags, []) }) it('should increment in 1 the metric', () => { diff --git a/packages/dd-trace/test/appsec/iast/telemetry/index.spec.js b/packages/dd-trace/test/appsec/iast/telemetry/index.spec.js index 5ad6ebc3c2c..be9949710d5 100644 --- a/packages/dd-trace/test/appsec/iast/telemetry/index.spec.js +++ b/packages/dd-trace/test/appsec/iast/telemetry/index.spec.js @@ -73,7 +73,7 @@ describe('Telemetry', () => { assert.strictEqual(iastTelemetry.enabled, false) assert.strictEqual(iastTelemetry.verbosity, Verbosity.OFF) - expect(telemetryMetrics.manager.set).to.not.be.called + sinon.assert.notCalled(telemetryMetrics.manager.set) }) it('should enable telemetry if telemetry.metrics is true', () => { @@ -95,7 +95,7 @@ describe('Telemetry', () => { assert.strictEqual(iastTelemetry.enabled, false) assert.strictEqual(iastTelemetry.verbosity, Verbosity.OFF) - expect(telemetryMetrics.manager.set).to.not.be.called + sinon.assert.notCalled(telemetryMetrics.manager.set) }) }) diff --git a/packages/dd-trace/test/appsec/iast/telemetry/namespaces.spec.js b/packages/dd-trace/test/appsec/iast/telemetry/namespaces.spec.js index 4c655641e02..dce859d3d2c 100644 --- a/packages/dd-trace/test/appsec/iast/telemetry/namespaces.spec.js +++ b/packages/dd-trace/test/appsec/iast/telemetry/namespaces.spec.js @@ -51,7 +51,7 @@ describe('IAST metric namespaces', () => { sinon.assert.called(rootSpan.addTags) const tag = rootSpan.addTags.getCalls()[0].args[0] - expect(tag).to.has.property(`${TAG_PREFIX}.${REQUEST_TAINTED}`) + assert.ok(`${TAG_PREFIX}.${REQUEST_TAINTED}` in tag) assert.strictEqual(tag[`${TAG_PREFIX}.${REQUEST_TAINTED}`], 10) assert.strictEqual(context[DD_IAST_METRICS_NAMESPACE], undefined) @@ -68,11 +68,11 @@ describe('IAST metric namespaces', () => { const calls = rootSpan.addTags.getCalls() const reqTaintedTag = calls[0].args[0] - expect(reqTaintedTag).to.has.property(`${TAG_PREFIX}.${REQUEST_TAINTED}`) + assert.ok(`${TAG_PREFIX}.${REQUEST_TAINTED}` in reqTaintedTag) assert.strictEqual(reqTaintedTag[`${TAG_PREFIX}.${REQUEST_TAINTED}`], 15) const execSinkTag = calls[1].args[0] - expect(execSinkTag).to.has.property(`${TAG_PREFIX}.${EXECUTED_SINK}`) + assert.ok(`${TAG_PREFIX}.${EXECUTED_SINK}` in execSinkTag) assert.strictEqual(execSinkTag[`${TAG_PREFIX}.${EXECUTED_SINK}`], 1) }) diff --git a/packages/dd-trace/test/appsec/iast/telemetry/span-tags.spec.js b/packages/dd-trace/test/appsec/iast/telemetry/span-tags.spec.js index e6f27a0a8fc..51103445ce2 100644 --- a/packages/dd-trace/test/appsec/iast/telemetry/span-tags.spec.js +++ b/packages/dd-trace/test/appsec/iast/telemetry/span-tags.spec.js @@ -1,7 +1,9 @@ 'use strict' +const assert = require('node:assert/strict') + const { expect } = require('chai') -const { describe, it, beforeEach, afterEach } = require('mocha') +const { afterEach, beforeEach, describe, it } = require('mocha') const sinon = require('sinon') const { EXECUTED_SINK, EXECUTED_SOURCE, REQUEST_TAINTED } = require('../../../../src/appsec/iast/telemetry/iast-metric') @@ -34,8 +36,8 @@ describe('Telemetry Span tags', () => { addMetricsToSpan(rootSpan, metrics.series, tagPrefix) expect(rootSpan.addTags).to.be.calledTwice - expect(rootSpan.addTags.firstCall.args[0]).to.deep.eq({ '_dd.test.executed.source.source_type_1': 42 }) - expect(rootSpan.addTags.secondCall.args[0]).to.deep.eq({ '_dd.test.executed.sink.sink_type_1': 3 }) + assert.deepStrictEqual(rootSpan.addTags.firstCall.args[0], { '_dd.test.executed.source.source_type_1': 42 }) + assert.deepStrictEqual(rootSpan.addTags.secondCall.args[0], { '_dd.test.executed.sink.sink_type_1': 3 }) }) it('should add span tags with tag name like \'tagPrefix.metricName.tagKey\' for tagged metrics flattened', () => { @@ -62,8 +64,8 @@ describe('Telemetry Span tags', () => { addMetricsToSpan(rootSpan, metrics.series, tagPrefix) expect(rootSpan.addTags).to.be.calledTwice - expect(rootSpan.addTags.firstCall.args[0]).to.deep.eq({ '_dd.test.executed.source.source_type_1': 74 }) - expect(rootSpan.addTags.secondCall.args[0]).to.deep.eq({ '_dd.test.executed.source.source_type_2': 2 }) + assert.deepStrictEqual(rootSpan.addTags.firstCall.args[0], { '_dd.test.executed.source.source_type_1': 74 }) + assert.deepStrictEqual(rootSpan.addTags.secondCall.args[0], { '_dd.test.executed.source.source_type_2': 2 }) }) it('should add span tags with tag name like \'tagPrefix.metricName\' for not tagged metrics', () => { diff --git a/packages/dd-trace/test/appsec/iast/telemetry/verbosity.spec.js b/packages/dd-trace/test/appsec/iast/telemetry/verbosity.spec.js index cfec1ea6455..04d30675b2c 100644 --- a/packages/dd-trace/test/appsec/iast/telemetry/verbosity.spec.js +++ b/packages/dd-trace/test/appsec/iast/telemetry/verbosity.spec.js @@ -1,8 +1,6 @@ 'use strict' const assert = require('node:assert/strict') - -const { expect } = require('chai') const { getVerbosity, getName, Verbosity, isDebugAllowed, isInfoAllowed } = require('../../../../src/appsec/iast/telemetry/verbosity') @@ -14,15 +12,15 @@ describe('Telemetry Verbosity', () => { }) it('should get verbosity regardless of capitalization', () => { - expect(getVerbosity('dEBug')).to.be.eq(Verbosity.DEBUG) + assert.strictEqual(getVerbosity('dEBug'), Verbosity.DEBUG) }) it('should get verbosity default verbosity if invalid env var', () => { - expect(getVerbosity('Invalid')).to.be.eq(Verbosity.INFORMATION) + assert.strictEqual(getVerbosity('Invalid'), Verbosity.INFORMATION) }) it('should get verbosity default verbosity if empty env var', () => { - expect(getVerbosity()).to.be.eq(Verbosity.INFORMATION) + assert.strictEqual(getVerbosity(), Verbosity.INFORMATION) }) }) diff --git a/packages/dd-trace/test/appsec/iast/utils.js b/packages/dd-trace/test/appsec/iast/utils.js index b8577bdad06..0e48c814634 100644 --- a/packages/dd-trace/test/appsec/iast/utils.js +++ b/packages/dd-trace/test/appsec/iast/utils.js @@ -1,20 +1,23 @@ 'use strict' +const assert = require('node:assert/strict') const fs = require('node:fs') const os = require('node:os') const path = require('node:path') + const msgpack = require('@msgpack/msgpack') const axios = require('axios') -const { assert, expect } = require('chai') -const { describe, it, beforeEach, afterEach, before, after } = require('mocha') +const { expect } = require('chai') +const { after, afterEach, before, beforeEach, describe, it } = require('mocha') -const agent = require('../../plugins/agent') -const rewriter = require('../../../src/appsec/iast/taint-tracking/rewriter') const iast = require('../../../src/appsec/iast') -const { getConfigFresh } = require('../../helpers/config') -const vulnerabilityReporter = require('../../../src/appsec/iast/vulnerability-reporter') const overheadController = require('../../../src/appsec/iast/overhead-controller') +const rewriter = require('../../../src/appsec/iast/taint-tracking/rewriter') +const vulnerabilityReporter = require('../../../src/appsec/iast/vulnerability-reporter') +const { getConfigFresh } = require('../../helpers/config') +const agent = require('../../plugins/agent') const { getWebSpan } = require('../utils') +const { assertObjectContains } = require('../../../../../integration-tests/helpers') function testInRequest (app, tests) { let http @@ -96,8 +99,8 @@ function testOutsideRequestHasVulnerability (fnToTest, vulnerability, plugins, t } agent .assertSomeTraces(traces => { - expect(traces[0][0].meta['_dd.iast.json']).to.include(`"${vulnerability}"`) - expect(traces[0][0].metrics['_dd.iast.enabled']).to.be.equal(1) + assertObjectContains(traces[0][0].meta['_dd.iast.json'], `"${vulnerability}"`) + assert.strictEqual(traces[0][0].metrics['_dd.iast.enabled'], 1) }, { timeoutMs: 10000 }) .then(done) .catch(done) @@ -185,23 +188,23 @@ function checkVulnerabilityInRequest ( } agent .assertSomeTraces(traces => { - expect(traces[0][0].metrics['_dd.iast.enabled']).to.be.equal(1) - expect(traces[0][0].meta).to.have.property('_dd.iast.json') + assert.strictEqual(traces[0][0].metrics['_dd.iast.enabled'], 1) + assert.ok('_dd.iast.json' in traces[0][0].meta) const span = getWebSpan(traces) - assert.property(span.meta_struct, '_dd.stack') + assert.ok(Object.hasOwn(span.meta_struct, '_dd.stack')) const vulnerabilitiesTrace = JSON.parse(traces[0][0].meta['_dd.iast.json']) - expect(vulnerabilitiesTrace).to.not.be.null + assert.notStrictEqual(vulnerabilitiesTrace, null) const vulnerabilitiesCount = new Map() vulnerabilitiesTrace.vulnerabilities.forEach(v => { let count = vulnerabilitiesCount.get(v.type) || 0 vulnerabilitiesCount.set(v.type, ++count) }) - expect(vulnerabilitiesCount.get(vulnerability)).to.be.greaterThan(0) + assert.ok(((vulnerabilitiesCount.get(vulnerability)) > (0))) if (occurrences) { - expect(vulnerabilitiesCount.get(vulnerability)).to.equal(occurrences) + assert.strictEqual(vulnerabilitiesCount.get(vulnerability), occurrences) } if (location) { @@ -226,7 +229,7 @@ function checkVulnerabilityInRequest ( if (matchLocation) { const matchFound = locationHasMatchingFrame(span, vulnerability, vulnerabilitiesTrace.vulnerabilities) - assert.isTrue(matchFound) + assert.strictEqual(matchFound, true) } if (cb) { diff --git a/packages/dd-trace/test/appsec/iast/vulnerability-reporter.spec.js b/packages/dd-trace/test/appsec/iast/vulnerability-reporter.spec.js index e32d635487e..bab27b643bc 100644 --- a/packages/dd-trace/test/appsec/iast/vulnerability-reporter.spec.js +++ b/packages/dd-trace/test/appsec/iast/vulnerability-reporter.spec.js @@ -74,14 +74,14 @@ describe('vulnerability-reporter', () => { vulnerabilityAnalyzer._createVulnerability('INSECURE_HASHING', { value: 'md5' }, -123, { path: 'path.js', line: 12 }), []) assert.strictEqual(iastContext.vulnerabilities.length, 2) - expect(iastContext).to.have.nested.property('vulnerabilities.0.type', 'INSECURE_HASHING') - expect(iastContext).to.have.nested.property('vulnerabilities.0.evidence.value', 'sha1') - expect(iastContext).to.have.nested.property('vulnerabilities.0.location.spanId', 888) - expect(iastContext).to.have.nested.property('vulnerabilities.1.type', 'INSECURE_HASHING') - expect(iastContext).to.have.nested.property('vulnerabilities.1.evidence.value', 'md5') - expect(iastContext).to.have.nested.property('vulnerabilities.1.location.spanId', -123) - expect(iastContext).to.have.nested.property('vulnerabilities.1.location.path', 'path.js') - expect(iastContext).to.have.nested.property('vulnerabilities.1.location.line', 12) + assert.strictEqual(iastContext?.vulnerabilities?.['0']?.type, 'INSECURE_HASHING') + assert.strictEqual(iastContext?.vulnerabilities?.['0']?.evidence?.value, 'sha1') + assert.strictEqual(iastContext?.vulnerabilities?.['0']?.location?.spanId, 888) + assert.strictEqual(iastContext?.vulnerabilities?.['1']?.type, 'INSECURE_HASHING') + assert.strictEqual(iastContext?.vulnerabilities?.['1']?.evidence?.value, 'md5') + assert.strictEqual(iastContext?.vulnerabilities?.['1']?.location?.spanId, -123) + assert.strictEqual(iastContext?.vulnerabilities?.['1']?.location?.path, 'path.js') + assert.strictEqual(iastContext?.vulnerabilities?.['1']?.location?.line, 12) }) }) diff --git a/packages/dd-trace/test/appsec/index.body-parser.plugin.spec.js b/packages/dd-trace/test/appsec/index.body-parser.plugin.spec.js index 5626b7b2440..9c48775b209 100644 --- a/packages/dd-trace/test/appsec/index.body-parser.plugin.spec.js +++ b/packages/dd-trace/test/appsec/index.body-parser.plugin.spec.js @@ -4,7 +4,6 @@ const assert = require('node:assert/strict') const path = require('node:path') const axios = require('axios') -const { expect } = require('chai') const sinon = require('sinon') const appsec = require('../../src/appsec') @@ -71,7 +70,7 @@ withVersions('body-parser', 'body-parser', version => { } catch (e) { assert.strictEqual(e.response.status, 403) assert.deepStrictEqual(e.response.data, JSON.parse(json)) - expect(requestBody).not.to.be.called + sinon.assert.notCalled(requestBody) } }) @@ -98,7 +97,7 @@ withVersions('body-parser', 'body-parser', version => { } catch (e) { assert.strictEqual(e.response.status, 403) assert.deepStrictEqual(e.response.data, JSON.parse(json)) - expect(requestBody).not.to.be.called + sinon.assert.notCalled(requestBody) await agent.assertSomeTraces((traces) => { const span = traces[0][0] diff --git a/packages/dd-trace/test/appsec/index.fastify.plugin.spec.js b/packages/dd-trace/test/appsec/index.fastify.plugin.spec.js index ae23458b00a..fbacea933bd 100644 --- a/packages/dd-trace/test/appsec/index.fastify.plugin.spec.js +++ b/packages/dd-trace/test/appsec/index.fastify.plugin.spec.js @@ -1,11 +1,12 @@ 'use strict' +const assert = require('node:assert/strict') + const path = require('node:path') const zlib = require('node:zlib') const fs = require('node:fs') const Axios = require('axios') -const { assert } = require('chai') const semver = require('semver') const sinon = require('sinon') @@ -64,8 +65,8 @@ withVersions('fastify', 'fastify', '>=2', (fastifyVersion, _, fastifyLoadedVersi it('should not block the request without an attack', async () => { const res = await axios.get('/?key=value') - assert.equal(res.status, 200) - assert.equal(res.data, 'DONE') + assert.strictEqual(res.status, 200) + assert.strictEqual(res.data, 'DONE') sinon.assert.calledOnce(requestBody) }) @@ -75,8 +76,8 @@ withVersions('fastify', 'fastify', '>=2', (fastifyVersion, _, fastifyLoadedVersi return Promise.reject(new Error('Request should not return 200')) } catch (e) { - assert.equal(e.response.status, 403) - assert.deepEqual(e.response.data, JSON.parse(json)) + assert.strictEqual(e.response.status, 403) + assert.deepStrictEqual(e.response.data, JSON.parse(json)) sinon.assert.notCalled(requestBody) } }) @@ -129,8 +130,8 @@ withVersions('fastify', 'fastify', '>=2', (fastifyVersion, _, fastifyLoadedVersi it('should not block the request without an attack', async () => { const res = await axios.post('/', { key: 'value' }) - assert.equal(res.status, 200) - assert.equal(res.data, 'DONE') + assert.strictEqual(res.status, 200) + assert.strictEqual(res.data, 'DONE') sinon.assert.calledOnce(requestBody) }) @@ -140,8 +141,8 @@ withVersions('fastify', 'fastify', '>=2', (fastifyVersion, _, fastifyLoadedVersi return Promise.reject(new Error('Request should not return 200')) } catch (e) { - assert.equal(e.response.status, 403) - assert.deepEqual(e.response.data, JSON.parse(json)) + assert.strictEqual(e.response.status, 403) + assert.deepStrictEqual(e.response.data, JSON.parse(json)) sinon.assert.notCalled(requestBody) } }) @@ -167,8 +168,8 @@ withVersions('fastify', 'fastify', '>=2', (fastifyVersion, _, fastifyLoadedVersi return Promise.reject(new Error('Request should not return 200')) } catch (e) { - assert.equal(e.response.status, 403) - assert.deepEqual(e.response.data, JSON.parse(json)) + assert.strictEqual(e.response.status, 403) + assert.deepStrictEqual(e.response.data, JSON.parse(json)) sinon.assert.notCalled(requestBody) await agent.assertFirstTraceSpan({ @@ -240,8 +241,8 @@ withVersions('fastify', 'fastify', '>=2', (fastifyVersion, _, fastifyLoadedVersi return Promise.reject(new Error('Request should not return 200')) } catch (e) { - assert.equal(e.response.status, 403) - assert.deepEqual(e.response.data, JSON.parse(json)) + assert.strictEqual(e.response.status, 403) + assert.deepStrictEqual(e.response.data, JSON.parse(json)) } }) @@ -251,8 +252,8 @@ withVersions('fastify', 'fastify', '>=2', (fastifyVersion, _, fastifyLoadedVersi return Promise.reject(new Error('Request should not return 200')) } catch (e) { - assert.equal(e.response.status, 403) - assert.deepEqual(e.response.data, JSON.parse(json)) + assert.strictEqual(e.response.status, 403) + assert.deepStrictEqual(e.response.data, JSON.parse(json)) } }) }) @@ -328,8 +329,8 @@ withVersions('fastify', 'fastify', '>=2', (fastifyVersion, _, fastifyLoadedVersi it('should not block the request when attack is not detected', async () => { const res = await axios.get('/multiple-path-params/safe_param/safe_param') - assert.equal(res.status, 200) - assert.equal(res.data, 'DONE') + assert.strictEqual(res.status, 200) + assert.strictEqual(res.data, 'DONE') }) it('should block the request when attack is detected in both parameters', async () => { @@ -338,8 +339,8 @@ withVersions('fastify', 'fastify', '>=2', (fastifyVersion, _, fastifyLoadedVersi return Promise.reject(new Error('Request should not return 200')) } catch (e) { - assert.equal(e.response.status, 403) - assert.deepEqual(e.response.data, JSON.parse(json)) + assert.strictEqual(e.response.status, 403) + assert.deepStrictEqual(e.response.data, JSON.parse(json)) } }) @@ -349,8 +350,8 @@ withVersions('fastify', 'fastify', '>=2', (fastifyVersion, _, fastifyLoadedVersi return Promise.reject(new Error('Request should not return 200')) } catch (e) { - assert.equal(e.response.status, 403) - assert.deepEqual(e.response.data, JSON.parse(json)) + assert.strictEqual(e.response.status, 403) + assert.deepStrictEqual(e.response.data, JSON.parse(json)) } }) @@ -360,8 +361,8 @@ withVersions('fastify', 'fastify', '>=2', (fastifyVersion, _, fastifyLoadedVersi return Promise.reject(new Error('Request should not return 200')) } catch (e) { - assert.equal(e.response.status, 403) - assert.deepEqual(e.response.data, JSON.parse(json)) + assert.strictEqual(e.response.status, 403) + assert.deepStrictEqual(e.response.data, JSON.parse(json)) } }) }) @@ -370,8 +371,8 @@ withVersions('fastify', 'fastify', '>=2', (fastifyVersion, _, fastifyLoadedVersi it('should not block the request when attack is not detected', async () => { const res = await axios.get('/nested/safe_param/safe_param') - assert.equal(res.status, 200) - assert.equal(res.data, 'DONE') + assert.strictEqual(res.status, 200) + assert.strictEqual(res.data, 'DONE') }) it('should block the request when attack is detected in the nested parameter', async () => { @@ -380,8 +381,8 @@ withVersions('fastify', 'fastify', '>=2', (fastifyVersion, _, fastifyLoadedVersi return Promise.reject(new Error('Request should not return 200')) } catch (e) { - assert.equal(e.response.status, 403) - assert.deepEqual(e.response.data, JSON.parse(json)) + assert.strictEqual(e.response.status, 403) + assert.deepStrictEqual(e.response.data, JSON.parse(json)) } }) @@ -391,8 +392,8 @@ withVersions('fastify', 'fastify', '>=2', (fastifyVersion, _, fastifyLoadedVersi return Promise.reject(new Error('Request should not return 200')) } catch (e) { - assert.equal(e.response.status, 403) - assert.deepEqual(e.response.data, JSON.parse(json)) + assert.strictEqual(e.response.status, 403) + assert.deepStrictEqual(e.response.data, JSON.parse(json)) } }) @@ -402,8 +403,8 @@ withVersions('fastify', 'fastify', '>=2', (fastifyVersion, _, fastifyLoadedVersi return Promise.reject(new Error('Request should not return 200')) } catch (e) { - assert.equal(e.response.status, 403) - assert.deepEqual(e.response.data, JSON.parse(json)) + assert.strictEqual(e.response.status, 403) + assert.deepStrictEqual(e.response.data, JSON.parse(json)) } }) }) @@ -412,8 +413,8 @@ withVersions('fastify', 'fastify', '>=2', (fastifyVersion, _, fastifyLoadedVersi it('should not block the request when attack is not detected', async () => { const res = await axios.get('/callback-path-param/safe_param') - assert.equal(res.status, 200) - assert.equal(res.data, 'DONE') + assert.strictEqual(res.status, 200) + assert.strictEqual(res.data, 'DONE') sinon.assert.calledOnce(preHandlerHookSpy) sinon.assert.calledOnce(preValidationHookSpy) }) @@ -424,8 +425,8 @@ withVersions('fastify', 'fastify', '>=2', (fastifyVersion, _, fastifyLoadedVersi return Promise.reject(new Error('Request should not return 200')) } catch (e) { - assert.equal(e.response.status, 403) - assert.deepEqual(e.response.data, JSON.parse(json)) + assert.strictEqual(e.response.status, 403) + assert.deepStrictEqual(e.response.data, JSON.parse(json)) sinon.assert.notCalled(preHandlerHookSpy) sinon.assert.notCalled(preValidationHookSpy) } @@ -526,7 +527,7 @@ withVersions('fastify', 'fastify', '>=2', (fastifyVersion, _, fastifyLoadedVersi return Promise.reject(new Error('Request should not return 200')) } catch (e) { assert.strictEqual(e.response.status, 403) - assert.deepEqual(e.response.data, JSON.parse(json)) + assert.deepStrictEqual(e.response.data, JSON.parse(json)) sinon.assert.notCalled(requestCookie) } }) @@ -712,8 +713,8 @@ describe('Api Security - Fastify', () => { } }) - assert.equal(res.status, 200) - assert.deepEqual(res.data, { sendResKey: 'sendResValue' }) + assert.strictEqual(res.status, 200) + assert.deepStrictEqual(res.data, { sendResKey: 'sendResValue' }) }) it('should get the response body schema with return', async () => { @@ -726,19 +727,19 @@ describe('Api Security - Fastify', () => { } }) - assert.equal(res.status, 200) - assert.deepEqual(res.data, { returnResKey: 'returnResValue' }) + assert.strictEqual(res.status, 200) + assert.deepStrictEqual(res.data, { returnResKey: 'returnResValue' }) }) it('should not get the schema for string', async () => { const res = await axios.get('/') await agent.assertFirstTraceSpan(span => { - assert.notProperty(span.meta, '_dd.appsec.s.res.body') + assert.ok(!Object.hasOwn(span.meta, '_dd.appsec.s.res.body')) }) - assert.equal(res.status, 200) - assert.equal(res.data, 'DONE') + assert.strictEqual(res.status, 200) + assert.strictEqual(res.data, 'DONE') }) it('should not get the schema for Buffer', async () => { @@ -746,12 +747,12 @@ describe('Api Security - Fastify', () => { await agent.assertFirstTraceSpan(span => { if (span.meta) { - assert.notProperty(span.meta, '_dd.appsec.s.res.body') + assert.ok(!Object.hasOwn(span.meta, '_dd.appsec.s.res.body')) } }) - assert.equal(res.status, 200) - assert.equal(res.data, 'DONE') + assert.strictEqual(res.status, 200) + assert.strictEqual(res.data, 'DONE') }) it('should not get the schema for stream', async () => { @@ -759,11 +760,11 @@ describe('Api Security - Fastify', () => { await agent.assertFirstTraceSpan(span => { if (span.meta) { - assert.notProperty(span.meta, '_dd.appsec.s.res.body') + assert.ok(!Object.hasOwn(span.meta, '_dd.appsec.s.res.body')) } }) - assert.equal(res.status, 200) + assert.strictEqual(res.status, 200) }) it('should not get the schema for TypedArray', async () => { @@ -771,11 +772,11 @@ describe('Api Security - Fastify', () => { await agent.assertFirstTraceSpan(span => { if (span.meta) { - assert.notProperty(span.meta, '_dd.appsec.s.res.body') + assert.ok(!Object.hasOwn(span.meta, '_dd.appsec.s.res.body')) } }) - assert.equal(res.status, 200) + assert.strictEqual(res.status, 200) }) }) }) diff --git a/packages/dd-trace/test/appsec/index.spec.js b/packages/dd-trace/test/appsec/index.spec.js index 8f7eeeee37e..800e44f10f3 100644 --- a/packages/dd-trace/test/appsec/index.spec.js +++ b/packages/dd-trace/test/appsec/index.spec.js @@ -270,7 +270,7 @@ describe('AppSec Index', function () { config.appsec.rasp.enabled = false AppSec.enable(config) - expect(rasp.enable).to.not.be.called + sinon.assert.notCalled(rasp.enable) }) }) diff --git a/packages/dd-trace/test/appsec/rasp/command_injection.integration.spec.js b/packages/dd-trace/test/appsec/rasp/command_injection.integration.spec.js index 815c17ec323..9b83b42778a 100644 --- a/packages/dd-trace/test/appsec/rasp/command_injection.integration.spec.js +++ b/packages/dd-trace/test/appsec/rasp/command_injection.integration.spec.js @@ -1,7 +1,8 @@ 'use strict' +const assert = require('node:assert/strict') + const Axios = require('axios') -const { assert } = require('chai') const { describe, it, before, beforeEach, afterEach } = require('mocha') const path = require('node:path') @@ -56,8 +57,8 @@ describe('RASP - command_injection - integration', () => { let appsecTelemetryReceived = false const checkMessages = agent.assertMessageReceived(({ headers, payload }) => { - assert.property(payload[0][0].meta, '_dd.appsec.json') - assert.include(payload[0][0].meta['_dd.appsec.json'], `"rasp-command_injection-rule-id-${ruleId}"`) + assert.ok(Object.hasOwn(payload[0][0].meta, '_dd.appsec.json')) + assert.ok(payload[0][0].meta['_dd.appsec.json'].includes(`"rasp-command_injection-rule-id-${ruleId}"`)) }) const checkTelemetry = agent.assertTelemetryReceived(({ headers, payload }) => { @@ -70,21 +71,21 @@ describe('RASP - command_injection - integration', () => { const evalSerie = series.find(s => s.metric === 'rasp.rule.eval') const matchSerie = series.find(s => s.metric === 'rasp.rule.match') - assert.exists(evalSerie, 'eval serie should exist') - assert.include(evalSerie.tags, 'rule_type:command_injection') - assert.include(evalSerie.tags, `rule_variant:${variant}`) + assert.ok(evalSerie != null) + assert.ok(evalSerie.tags.includes('rule_type:command_injection')) + assert.ok(evalSerie.tags.includes(`rule_variant:${variant}`)) assert.strictEqual(evalSerie.type, 'count') - assert.exists(matchSerie, 'match serie should exist') - assert.include(matchSerie.tags, 'rule_type:command_injection') - assert.include(matchSerie.tags, `rule_variant:${variant}`) + assert.ok(matchSerie != null) + assert.ok(matchSerie.tags.includes('rule_type:command_injection')) + assert.ok(matchSerie.tags.includes(`rule_variant:${variant}`)) assert.strictEqual(matchSerie.type, 'count') } }, 'generate-metrics', 30_000, 2) await Promise.all([checkMessages, checkTelemetry]) - assert.equal(appsecTelemetryReceived, true) + assert.strictEqual(appsecTelemetryReceived, true) return } diff --git a/packages/dd-trace/test/appsec/rasp/fs-plugin.spec.js b/packages/dd-trace/test/appsec/rasp/fs-plugin.spec.js index 3c7e173f624..7db78462f48 100644 --- a/packages/dd-trace/test/appsec/rasp/fs-plugin.spec.js +++ b/packages/dd-trace/test/appsec/rasp/fs-plugin.spec.js @@ -1,6 +1,6 @@ 'use strict' -const { assert } = require('chai') +const assert = require('node:assert/strict') const { describe, it, beforeEach, afterEach } = require('mocha') const sinon = require('sinon') const proxyquire = require('proxyquire') @@ -103,14 +103,14 @@ describe('AppsecFsPlugin', () => { let store = appsecFsPlugin._onFsOperationStart() - assert.property(store, 'fs') - assert.propertyVal(store.fs, 'parentStore', origStore) - assert.propertyVal(store.fs, 'root', true) + assert.ok(Object.hasOwn(store, 'fs')) + assert.strictEqual(store.fs['parentStore'], origStore) + assert.strictEqual(store.fs['root'], true) store = appsecFsPlugin._onFsOperationFinishOrRenderEnd() - assert.equal(store, origStore) - assert.notProperty(store, 'fs') + assert.strictEqual(store, origStore) + assert.ok(!Object.hasOwn(store, 'fs')) }) it('should mark fs children', () => { @@ -119,29 +119,29 @@ describe('AppsecFsPlugin', () => { const rootStore = appsecFsPlugin._onFsOperationStart() - assert.property(rootStore, 'fs') - assert.propertyVal(rootStore.fs, 'parentStore', origStore) - assert.propertyVal(rootStore.fs, 'root', true) + assert.ok(Object.hasOwn(rootStore, 'fs')) + assert.strictEqual(rootStore.fs['parentStore'], origStore) + assert.strictEqual(rootStore.fs['root'], true) storage('legacy').enterWith(rootStore) let store = appsecFsPlugin._onFsOperationStart() - assert.property(store, 'fs') - assert.propertyVal(store.fs, 'parentStore', rootStore) - assert.propertyVal(store.fs, 'root', false) - assert.propertyVal(store, 'orig', true) + assert.ok(Object.hasOwn(store, 'fs')) + assert.strictEqual(store.fs['parentStore'], rootStore) + assert.strictEqual(store.fs['root'], false) + assert.strictEqual(store['orig'], true) storage('legacy').enterWith(store) store = appsecFsPlugin._onFsOperationFinishOrRenderEnd() - assert.equal(store, rootStore) + assert.strictEqual(store, rootStore) storage('legacy').enterWith(store) store = appsecFsPlugin._onFsOperationFinishOrRenderEnd() - assert.equal(store, origStore) + assert.strictEqual(store, origStore) }) }) @@ -154,16 +154,16 @@ describe('AppsecFsPlugin', () => { let store = appsecFsPlugin._onResponseRenderStart() - assert.property(store, 'fs') - assert.propertyVal(store.fs, 'parentStore', origStore) - assert.propertyVal(store.fs, 'opExcluded', true) + assert.ok(Object.hasOwn(store, 'fs')) + assert.strictEqual(store.fs['parentStore'], origStore) + assert.strictEqual(store.fs['opExcluded'], true) storage('legacy').enterWith(store) store = appsecFsPlugin._onFsOperationFinishOrRenderEnd() - assert.equal(store, origStore) - assert.notProperty(store, 'fs') + assert.strictEqual(store, origStore) + assert.ok(!Object.hasOwn(store, 'fs')) }) }) @@ -181,7 +181,7 @@ describe('AppsecFsPlugin', () => { let count = 0 const onStart = () => { const store = storage('legacy').getStore() - assert.isNotNull(store.fs) + assert.notStrictEqual(store.fs, null) count++ assert.strictEqual(count === 1, store.fs.root) @@ -205,10 +205,10 @@ describe('AppsecFsPlugin', () => { let count = 0 const onStart = () => { const store = storage('legacy').getStore() - assert.isNotNull(store.fs) + assert.notStrictEqual(store.fs, null) count++ - assert.isUndefined(store.fs.root) + assert.strictEqual(store.fs.root, undefined) } try { @@ -234,7 +234,7 @@ describe('AppsecFsPlugin', () => { count-- if (count === 0) { - assert.isUndefined(store.fs) + assert.strictEqual(store.fs, undefined) } } try { diff --git a/packages/dd-trace/test/appsec/rasp/lfi.express.plugin.spec.js b/packages/dd-trace/test/appsec/rasp/lfi.express.plugin.spec.js index 0f389a8b79d..f0ff5929d4e 100644 --- a/packages/dd-trace/test/appsec/rasp/lfi.express.plugin.spec.js +++ b/packages/dd-trace/test/appsec/rasp/lfi.express.plugin.spec.js @@ -1,11 +1,12 @@ 'use strict' +const assert = require('node:assert/strict') + const os = require('node:os') const fs = require('node:fs') const path = require('node:path') const Axios = require('axios') -const { assert } = require('chai') const semver = require('semver') const { NODE_MAJOR } = require('../../../../../version') diff --git a/packages/dd-trace/test/appsec/rasp/lfi.integration.express.plugin.spec.js b/packages/dd-trace/test/appsec/rasp/lfi.integration.express.plugin.spec.js index d7e684df145..c52b407a407 100644 --- a/packages/dd-trace/test/appsec/rasp/lfi.integration.express.plugin.spec.js +++ b/packages/dd-trace/test/appsec/rasp/lfi.integration.express.plugin.spec.js @@ -1,10 +1,10 @@ 'use strict' +const assert = require('node:assert/strict') + const { sandboxCwd, useSandbox, FakeAgent, spawnProc } = require('../../../../../integration-tests/helpers') const path = require('path') const Axios = require('axios') -const { assert } = require('chai') - describe('RASP - lfi - integration - sync', () => { let axios, cwd, appFile, agent, proc @@ -47,8 +47,8 @@ describe('RASP - lfi - integration - sync', () => { assert.strictEqual(e.response.status, 403) return await agent.assertMessageReceived(({ headers, payload }) => { - assert.property(payload[0][0].meta, '_dd.appsec.json') - assert.include(payload[0][0].meta['_dd.appsec.json'], '"rasp-lfi-rule-id-1"') + assert.ok(Object.hasOwn(payload[0][0].meta, '_dd.appsec.json')) + assert.ok(payload[0][0].meta['_dd.appsec.json'].includes('"rasp-lfi-rule-id-1"')) }) } diff --git a/packages/dd-trace/test/appsec/rasp/rasp-metrics.integration.spec.js b/packages/dd-trace/test/appsec/rasp/rasp-metrics.integration.spec.js index cf5c8ebbb2b..744b035323e 100644 --- a/packages/dd-trace/test/appsec/rasp/rasp-metrics.integration.spec.js +++ b/packages/dd-trace/test/appsec/rasp/rasp-metrics.integration.spec.js @@ -1,10 +1,10 @@ 'use strict' +const assert = require('node:assert/strict') + const { sandboxCwd, useSandbox, FakeAgent, spawnProc } = require('../../../../../integration-tests/helpers') const path = require('path') const Axios = require('axios') -const { assert } = require('chai') - describe('RASP metrics', () => { let axios, cwd, appFile @@ -62,13 +62,13 @@ describe('RASP metrics', () => { const series = payload.payload.series const errorSerie = series.find(s => s.metric === 'rasp.error') - assert.exists(errorSerie, 'error serie should exist') - assert.include(errorSerie.tags, 'waf_error:-127') + assert.ok(errorSerie != null) + assert.ok(errorSerie.tags.includes('waf_error:-127')) assert.strictEqual(errorSerie.type, 'count') } }, 'generate-metrics', 30_000, 2) - assert.equal(appsecTelemetryMetricsReceived, true) + assert.strictEqual(appsecTelemetryMetricsReceived, true) }) }) @@ -101,7 +101,7 @@ describe('RASP metrics', () => { let appsecTelemetryReceived = false const checkMessages = agent.assertMessageReceived(({ payload }) => { - assert.isTrue(payload[0][0].metrics['_dd.appsec.rasp.timeout'] > 0) + assert.strictEqual(payload[0][0].metrics['_dd.appsec.rasp.timeout'] > 0, true) }) const checkTelemetry = agent.assertTelemetryReceived(({ payload }) => { @@ -112,16 +112,16 @@ describe('RASP metrics', () => { const series = payload.payload.series const timeoutSerie = series.find(s => s.metric === 'rasp.timeout') - assert.exists(timeoutSerie, 'Timeout serie should exist') - assert.include(timeoutSerie.tags, 'rule_type:command_injection') - assert.include(timeoutSerie.tags, 'rule_variant:shell') + assert.ok(timeoutSerie != null) + assert.ok(timeoutSerie.tags.includes('rule_type:command_injection')) + assert.ok(timeoutSerie.tags.includes('rule_variant:shell')) assert.strictEqual(timeoutSerie.type, 'count') } }, 'generate-metrics', 30_000, 2) await Promise.all([checkMessages, checkTelemetry]) - assert.equal(appsecTelemetryReceived, true) + assert.strictEqual(appsecTelemetryReceived, true) }) }) }) diff --git a/packages/dd-trace/test/appsec/rasp/rasp_blocking.fastify.plugin.spec.js b/packages/dd-trace/test/appsec/rasp/rasp_blocking.fastify.plugin.spec.js index eae7b94f2f2..d691954fefc 100644 --- a/packages/dd-trace/test/appsec/rasp/rasp_blocking.fastify.plugin.spec.js +++ b/packages/dd-trace/test/appsec/rasp/rasp_blocking.fastify.plugin.spec.js @@ -1,12 +1,13 @@ 'use strict' +const assert = require('node:assert/strict') + const path = require('node:path') const agent = require('../../plugins/agent') const { getConfigFresh } = require('../../helpers/config') const appsec = require('../../../src/appsec') const Axios = require('axios') -const { assert } = require('chai') const { describe, it, afterEach, before, after } = require('mocha') const sinon = require('sinon') diff --git a/packages/dd-trace/test/appsec/rasp/sql_injection.integration.pg.plugin.spec.js b/packages/dd-trace/test/appsec/rasp/sql_injection.integration.pg.plugin.spec.js index 49743af9d9c..1f97e4e00b6 100644 --- a/packages/dd-trace/test/appsec/rasp/sql_injection.integration.pg.plugin.spec.js +++ b/packages/dd-trace/test/appsec/rasp/sql_injection.integration.pg.plugin.spec.js @@ -1,10 +1,10 @@ 'use strict' +const assert = require('node:assert/strict') + const { sandboxCwd, useSandbox, FakeAgent, spawnProc } = require('../../../../../integration-tests/helpers') const path = require('path') const Axios = require('axios') -const { assert } = require('chai') - // These test are here and not in the integration tests // because they require postgres instance describe('RASP - sql_injection - integration', () => { @@ -49,8 +49,8 @@ describe('RASP - sql_injection - integration', () => { assert.strictEqual(e.response.status, 403) return await agent.assertMessageReceived(({ headers, payload }) => { - assert.property(payload[0][0].meta, '_dd.appsec.json') - assert.include(payload[0][0].meta['_dd.appsec.json'], '"rasp-sqli-rule-id-2"') + assert.ok(Object.hasOwn(payload[0][0].meta, '_dd.appsec.json')) + assert.ok(payload[0][0].meta['_dd.appsec.json'].includes('"rasp-sqli-rule-id-2"')) }) } @@ -67,8 +67,8 @@ describe('RASP - sql_injection - integration', () => { assert.strictEqual(e.response.status, 403) return await agent.assertMessageReceived(({ headers, payload }) => { - assert.property(payload[0][0].meta, '_dd.appsec.json') - assert.include(payload[0][0].meta['_dd.appsec.json'], '"rasp-sqli-rule-id-2"') + assert.ok(Object.hasOwn(payload[0][0].meta, '_dd.appsec.json')) + assert.ok(payload[0][0].meta['_dd.appsec.json'].includes('"rasp-sqli-rule-id-2"')) }) } @@ -85,8 +85,8 @@ describe('RASP - sql_injection - integration', () => { assert.strictEqual(e.response.status, 403) return await agent.assertMessageReceived(({ headers, payload }) => { - assert.property(payload[0][0].meta, '_dd.appsec.json') - assert.include(payload[0][0].meta['_dd.appsec.json'], '"rasp-sqli-rule-id-2"') + assert.ok(Object.hasOwn(payload[0][0].meta, '_dd.appsec.json')) + assert.ok(payload[0][0].meta['_dd.appsec.json'].includes('"rasp-sqli-rule-id-2"')) }) } diff --git a/packages/dd-trace/test/appsec/rasp/sql_injection.mysql2.plugin.spec.js b/packages/dd-trace/test/appsec/rasp/sql_injection.mysql2.plugin.spec.js index d13bc3ae2e6..283fb3f972a 100644 --- a/packages/dd-trace/test/appsec/rasp/sql_injection.mysql2.plugin.spec.js +++ b/packages/dd-trace/test/appsec/rasp/sql_injection.mysql2.plugin.spec.js @@ -1,12 +1,13 @@ 'use strict' +const assert = require('node:assert/strict') + const agent = require('../../plugins/agent') const appsec = require('../../../src/appsec') const getConfig = require('../../../src/config') const { withVersions } = require('../../setup/mocha') const path = require('path') const Axios = require('axios') -const { assert } = require('chai') const { checkRaspExecutedAndNotThreat, checkRaspExecutedAndHasThreat } = require('./utils') describe('RASP - sql_injection', () => { diff --git a/packages/dd-trace/test/appsec/rasp/ssrf.express.plugin.spec.js b/packages/dd-trace/test/appsec/rasp/ssrf.express.plugin.spec.js index 5075a9fb16b..243f1f6792c 100644 --- a/packages/dd-trace/test/appsec/rasp/ssrf.express.plugin.spec.js +++ b/packages/dd-trace/test/appsec/rasp/ssrf.express.plugin.spec.js @@ -1,9 +1,10 @@ 'use strict' +const assert = require('node:assert/strict') + const path = require('node:path') const Axios = require('axios') -const { assert } = require('chai') const { describe, it, beforeEach, before, after } = require('mocha') const { getConfigFresh } = require('../../helpers/config') @@ -290,7 +291,7 @@ describe('RASP - ssrf', () => { } }) - assert.equal(response.status, 200) + assert.strictEqual(response.status, 200) return checkRaspExecutedAndHasThreat(agent, 'rasp-ssrf-rule-id-1') }) diff --git a/packages/dd-trace/test/appsec/rasp/utils.js b/packages/dd-trace/test/appsec/rasp/utils.js index 5f94fdf749f..e6d1969ca2b 100644 --- a/packages/dd-trace/test/appsec/rasp/utils.js +++ b/packages/dd-trace/test/appsec/rasp/utils.js @@ -1,15 +1,15 @@ 'use strict' -const { assert } = require('chai') +const assert = require('node:assert/strict') const { getWebSpan } = require('../utils') function checkRaspExecutedAndNotThreat (agent, checkRuleEval = true) { return agent.assertSomeTraces((traces) => { const span = getWebSpan(traces) - assert.notProperty(span.meta, '_dd.appsec.json') - assert.notProperty(span.meta_struct || {}, '_dd.stack') + assert.ok(!Object.hasOwn(span.meta, '_dd.appsec.json')) + assert.ok(!Object.hasOwn(span.meta_struct || {}, '_dd.stack')) if (checkRuleEval) { - assert.equal(span.metrics['_dd.appsec.rasp.rule.eval'], 1) + assert.strictEqual(span.metrics['_dd.appsec.rasp.rule.eval'], 1) } }) } @@ -17,12 +17,12 @@ function checkRaspExecutedAndNotThreat (agent, checkRuleEval = true) { function checkRaspExecutedAndHasThreat (agent, ruleId, ruleEvalCount = 1) { return agent.assertSomeTraces((traces) => { const span = getWebSpan(traces) - assert.property(span.meta, '_dd.appsec.json') + assert.ok(Object.hasOwn(span.meta, '_dd.appsec.json')) assert(span.meta['_dd.appsec.json'].includes(ruleId)) - assert.equal(span.metrics['_dd.appsec.rasp.rule.eval'], ruleEvalCount) + assert.strictEqual(span.metrics['_dd.appsec.rasp.rule.eval'], ruleEvalCount) assert(span.metrics['_dd.appsec.rasp.duration'] > 0) assert(span.metrics['_dd.appsec.rasp.duration_ext'] > 0) - assert.property(span.meta_struct, '_dd.stack') + assert.ok(Object.hasOwn(span.meta_struct, '_dd.stack')) return span }) diff --git a/packages/dd-trace/test/appsec/reporter.spec.js b/packages/dd-trace/test/appsec/reporter.spec.js index cb026bcff20..c534875866a 100644 --- a/packages/dd-trace/test/appsec/reporter.spec.js +++ b/packages/dd-trace/test/appsec/reporter.spec.js @@ -136,7 +136,7 @@ describe('reporter', () => { assert.strictEqual(Reporter.formatHeaderName(' Content-Type '), 'content-type') assert.strictEqual(Reporter.formatHeaderName('C!!!ont_____ent----tYp!/!e'), 'c___ont_____ent----typ_/_e') assert.strictEqual(Reporter.formatHeaderName('Some.Header'), 'some_header') - expect(Reporter.formatHeaderName(''.padEnd(300, 'a'))).to.have.lengthOf(200) + assert.strictEqual(Reporter.formatHeaderName(''.padEnd(300, 'a')).length, 200) }) }) @@ -152,7 +152,7 @@ describe('reporter', () => { it('should add some entries to metricsQueue', () => { Reporter.reportWafInit(wafVersion, rulesVersion, diagnosticsRules, true) - expect(Reporter.metricsQueue.get('_dd.appsec.waf.version')).to.be.eq(wafVersion) + assert.strictEqual(Reporter.metricsQueue.get('_dd.appsec.waf.version'), wafVersion) }) it('should not add entries to metricsQueue with success false', () => { @@ -713,7 +713,7 @@ describe('reporter', () => { describe('reportAttributes', () => { it('should not call addTags if parameter is undefined', () => { Reporter.reportAttributes(undefined) - expect(span.addTags).not.to.be.called + sinon.assert.notCalled(span.addTags) }) it('should call addTags with an empty array', () => { @@ -816,7 +816,7 @@ describe('reporter', () => { sinon.assert.calledOnceWithExactly(web.root, req) sinon.assert.calledWithExactly(span.addTags, { a: 1, b: 2 }) - expect(Reporter.metricsQueue).to.be.empty + assert.strictEqual(Reporter.metricsQueue.length, 0) }) it('should only add mandatory headers when no attack or event was previously found', () => { diff --git a/packages/dd-trace/test/appsec/rule_manager.spec.js b/packages/dd-trace/test/appsec/rule_manager.spec.js index 3e8e7b37f3c..02317e93095 100644 --- a/packages/dd-trace/test/appsec/rule_manager.spec.js +++ b/packages/dd-trace/test/appsec/rule_manager.spec.js @@ -1,20 +1,20 @@ 'use strict' -const { expect, assert } = require('chai') -const proxyquire = require('proxyquire') -const sinon = require('sinon') - +const assert = require('node:assert/strict') const fs = require('node:fs') const path = require('node:path') -const { loadRules, clearAllRules } = require('../../src/appsec/rule_manager') -const { ACKNOWLEDGED, UNACKNOWLEDGED, ERROR } = require('../../src/remote_config/apply_states') +const proxyquire = require('proxyquire') +const sinon = require('sinon') +const blocking = require('../../src/appsec/blocking') const rules = require('../../src/appsec/recommended.json') +const { loadRules, clearAllRules } = require('../../src/appsec/rule_manager') const waf = require('../../src/appsec/waf') -const blocking = require('../../src/appsec/blocking') +const { ACKNOWLEDGED, UNACKNOWLEDGED, ERROR } = require('../../src/remote_config/apply_states') const { getConfigFresh } = require('../helpers/config') + describe('AppSec Rule Manager', () => { let config @@ -37,16 +37,16 @@ describe('AppSec Rule Manager', () => { it('should call waf init with proper params', () => { loadRules(config.appsec) - expect(waf.init).to.have.been.calledOnceWithExactly(rules, config.appsec) + sinon.assert.calledOnceWithExactly(waf.init, rules, config.appsec) }) it('should throw if null/undefined are passed', () => { // TODO: fix the exception thrown in the waf or catch it in rule_manager? config.appsec.rules = './not/existing/file.json' - expect(() => { loadRules(config.appsec) }).to.throw() + assert.throws(() => { loadRules(config.appsec) }) config.appsec.rules = './bad-formatted-rules.json' - expect(() => { loadRules(config.appsec) }).to.throw() + assert.throws(() => { loadRules(config.appsec) }) }) it('should call updateBlockingConfiguration with proper params', () => { @@ -57,21 +57,21 @@ describe('AppSec Rule Manager', () => { loadRules(config.appsec) - expect(waf.init).to.have.been.calledOnceWithExactly(testRules, config.appsec) - expect(blocking.setDefaultBlockingActionParameters).to.have.been.calledOnceWithExactly(testRules.actions) + sinon.assert.calledOnceWithExactly(waf.init, testRules, config.appsec) + sinon.assert.calledOnceWithExactly(blocking.setDefaultBlockingActionParameters, testRules.actions) }) }) describe('clearAllRules', () => { it('should call clear method on all applied rules', () => { loadRules(config.appsec) - expect(waf.init).to.have.been.calledOnce + sinon.assert.calledOnce(waf.init) blocking.setDefaultBlockingActionParameters.resetHistory() clearAllRules() - expect(waf.destroy).to.have.been.calledOnce - expect(blocking.setDefaultBlockingActionParameters).to.have.been.calledOnceWithExactly(undefined) + sinon.assert.calledOnce(waf.destroy) + sinon.assert.calledOnceWithExactly(blocking.setDefaultBlockingActionParameters, undefined) }) }) @@ -198,16 +198,16 @@ describe('AppSec Rule Manager', () => { RuleManager.updateWafFromRC(rcConfigsForNonAsmProducts) assert.strictEqual(rcConfigsForNonAsmProducts.toUnapply[0].apply_state, UNACKNOWLEDGED) - assert.notProperty(rcConfigsForNonAsmProducts.toUnapply[0], 'apply_error') + assert.ok(!Object.hasOwn(rcConfigsForNonAsmProducts.toUnapply[0], 'apply_error')) assert.strictEqual(rcConfigsForNonAsmProducts.toModify[0].apply_state, UNACKNOWLEDGED) - assert.notProperty(rcConfigsForNonAsmProducts.toModify[0], 'apply_error') + assert.ok(!Object.hasOwn(rcConfigsForNonAsmProducts.toModify[0], 'apply_error')) assert.strictEqual(rcConfigsForNonAsmProducts.toApply[0].apply_state, UNACKNOWLEDGED) - assert.notProperty(rcConfigsForNonAsmProducts.toApply[0], 'apply_error') + assert.ok(!Object.hasOwn(rcConfigsForNonAsmProducts.toApply[0], 'apply_error')) sinon.assert.notCalled(waf.updateConfig) sinon.assert.notCalled(waf.removeConfig) - assert.deepEqual(waf.wafManager.ddwaf.configPaths, [waf.wafManager.constructor.defaultWafConfigPath]) + assert.deepStrictEqual(waf.wafManager.ddwaf.configPaths, [waf.wafManager.constructor.defaultWafConfigPath]) }) it('should apply configs from ASM products', () => { @@ -236,9 +236,9 @@ describe('AppSec Rule Manager', () => { ) assert.strictEqual(waf.wafManager.ddwaf.configPaths.length, 3) - assert.include(waf.wafManager.ddwaf.configPaths, waf.wafManager.constructor.defaultWafConfigPath) - assert.include(waf.wafManager.ddwaf.configPaths, rcConfigs.toApply[0].path) - assert.include(waf.wafManager.ddwaf.configPaths, rcConfigs.toModify[0].path) + assert.ok(waf.wafManager.ddwaf.configPaths.includes(waf.wafManager.constructor.defaultWafConfigPath)) + assert.ok(waf.wafManager.ddwaf.configPaths.includes(rcConfigs.toApply[0].path)) + assert.ok(waf.wafManager.ddwaf.configPaths.includes(rcConfigs.toModify[0].path)) }) it('should update apply_state and apply_error on successful apply', () => { @@ -250,11 +250,11 @@ describe('AppSec Rule Manager', () => { RuleManager.updateWafFromRC(rcConfigs) assert.strictEqual(rcConfigs.toUnapply[0].apply_state, ACKNOWLEDGED) - assert.notProperty(rcConfigs.toUnapply[0], 'apply_error') + assert.ok(!Object.hasOwn(rcConfigs.toUnapply[0], 'apply_error')) assert.strictEqual(rcConfigs.toModify[0].apply_state, ACKNOWLEDGED) - assert.notProperty(rcConfigs.toModify[0], 'apply_error') + assert.ok(!Object.hasOwn(rcConfigs.toModify[0], 'apply_error')) assert.strictEqual(rcConfigs.toApply[0].apply_state, ACKNOWLEDGED) - assert.notProperty(rcConfigs.toApply[0], 'apply_error') + assert.ok(!Object.hasOwn(rcConfigs.toApply[0], 'apply_error')) }) it('should update apply_state and apply_error on failed config remove', () => { @@ -380,10 +380,7 @@ describe('AppSec Rule Manager', () => { assert.strictEqual(rcConfigs.toApply[0].apply_state, ERROR) - assert.deepEqual( - waf.wafManager.ddwaf.configPaths, - [waf.wafManager.constructor.defaultWafConfigPath] - ) + assert.deepStrictEqual(waf.wafManager.ddwaf.configPaths, [waf.wafManager.constructor.defaultWafConfigPath]) }) }) diff --git a/packages/dd-trace/test/appsec/sdk/track_event-integration.spec.js b/packages/dd-trace/test/appsec/sdk/track_event-integration.spec.js index f9c0cde3b75..fbb9b7e619d 100644 --- a/packages/dd-trace/test/appsec/sdk/track_event-integration.spec.js +++ b/packages/dd-trace/test/appsec/sdk/track_event-integration.spec.js @@ -3,7 +3,6 @@ const assert = require('node:assert/strict') const axios = require('axios') -const { expect } = require('chai') const { after, before, describe, it } = require('mocha') const { USER_KEEP } = require('../../../../../ext/priority') @@ -64,7 +63,7 @@ describe('track_event - Integration with the tracer', () => { res.end() } agent.assertSomeTraces(traces => { - expect(traces[0][0].meta).to.not.have.property('appsec.events.users.login.success.track', 'true') + assert.ok(!('appsec.events.users.login.success.track' in traces[0][0].meta) || traces[0][0].meta['appsec.events.users.login.success.track'] !== 'true') }).then(done).catch(done) axios.get(`http://localhost:${port}/`) }) @@ -74,7 +73,7 @@ describe('track_event - Integration with the tracer', () => { res.end() } agent.assertSomeTraces(traces => { - expect(traces[0][0].meta).to.not.have.property('appsec.events.users.login.success.track', 'true') + assert.ok(!('appsec.events.users.login.success.track' in traces[0][0].meta) || traces[0][0].meta['appsec.events.users.login.success.track'] !== 'true') }).then(done).catch(done) axios.get(`http://localhost:${port}/`) }) @@ -117,7 +116,7 @@ describe('track_event - Integration with the tracer', () => { res.end() } agent.assertSomeTraces(traces => { - expect(traces[0][0].meta).to.not.have.property('appsec.events.users.login.failure.track', 'true') + assert.ok(!('appsec.events.users.login.failure.track' in traces[0][0].meta) || traces[0][0].meta['appsec.events.users.login.failure.track'] !== 'true') }).then(done).catch(done) axios.get(`http://localhost:${port}/`) }) @@ -127,7 +126,7 @@ describe('track_event - Integration with the tracer', () => { res.end() } agent.assertSomeTraces(traces => { - expect(traces[0][0].meta).to.not.have.property('appsec.events.users.login.failure.track', 'true') + assert.ok(!('appsec.events.users.login.failure.track' in traces[0][0].meta) || traces[0][0].meta['appsec.events.users.login.failure.track'] !== 'true') }).then(done).catch(done) axios.get(`http://localhost:${port}/`) }) @@ -154,7 +153,7 @@ describe('track_event - Integration with the tracer', () => { res.end() } agent.assertSomeTraces(traces => { - expect(traces[0][0].metrics).to.not.have.property('_sampling_priority_v1', USER_KEEP) + assert.ok(!('_sampling_priority_v1' in traces[0][0].metrics) || traces[0][0].metrics['_sampling_priority_v1'] !== USER_KEEP) }).then(done).catch(done) axios.get(`http://localhost:${port}/`) }) diff --git a/packages/dd-trace/test/appsec/sdk/user_blocking-integration.spec.js b/packages/dd-trace/test/appsec/sdk/user_blocking-integration.spec.js index e2a803724d5..f4cee3ddbe9 100644 --- a/packages/dd-trace/test/appsec/sdk/user_blocking-integration.spec.js +++ b/packages/dd-trace/test/appsec/sdk/user_blocking-integration.spec.js @@ -4,7 +4,6 @@ const assert = require('node:assert/strict') const path = require('path') const axios = require('axios') -const { expect } = require('chai') const { after, afterEach, before, beforeEach, describe, it } = require('mocha') const tracer = require('../../../../../index') @@ -153,7 +152,7 @@ describe('user_blocking - Integration with the tracer', () => { assert.strictEqual(ret, false) } agent.assertSomeTraces(traces => { - expect(traces[0][0].meta).to.not.have.property('appsec.blocked', 'true') + assert.ok(!('appsec.blocked' in traces[0][0].meta) || traces[0][0].meta['appsec.blocked'] !== 'true') assert.strictEqual(traces[0][0].meta['http.status_code'], '200') assert.strictEqual(traces[0][0].metrics['_dd.appsec.block.failed'], 1) }).then(done).catch(done) diff --git a/packages/dd-trace/test/appsec/sdk/utils.spec.js b/packages/dd-trace/test/appsec/sdk/utils.spec.js index 44823804779..67e2df5e26f 100644 --- a/packages/dd-trace/test/appsec/sdk/utils.spec.js +++ b/packages/dd-trace/test/appsec/sdk/utils.spec.js @@ -1,7 +1,6 @@ 'use strict' -const { assert } = require('chai') - +const assert = require('node:assert/strict') const { getRootSpan } = require('../../../src/appsec/sdk/utils') const DatadogTracer = require('../../../src/tracer') const { getConfigFresh } = require('../../helpers/config') @@ -21,7 +20,7 @@ describe('Appsec SDK utils', () => { tracer.trace('parent', { }, parent => { const root = getRootSpan(tracer) - assert.equal(root, parent) + assert.strictEqual(root, parent) }) }) @@ -31,7 +30,7 @@ describe('Appsec SDK utils', () => { tracer.trace('child1', { childOf }, child1 => { const root = getRootSpan(tracer) - assert.equal(root, childOf) + assert.strictEqual(root, childOf) }) }) @@ -42,7 +41,7 @@ describe('Appsec SDK utils', () => { tracer.trace('child1', { childOf }, child1 => { const root = getRootSpan(tracer) - assert.equal(root, childOf) + assert.strictEqual(root, childOf) }) }) @@ -55,7 +54,7 @@ describe('Appsec SDK utils', () => { tracer.trace('child1.2', { childOf }, child12 => { const root = getRootSpan(tracer) - assert.equal(root, childOf) + assert.strictEqual(root, childOf) }) }) @@ -66,7 +65,7 @@ describe('Appsec SDK utils', () => { tracer.trace('child1', { childOf }, child1 => { const root = getRootSpan(tracer) - assert.equal(root, child1) + assert.strictEqual(root, child1) }) }) @@ -78,7 +77,7 @@ describe('Appsec SDK utils', () => { const root = getRootSpan(tracer) - assert.equal(root, childOf) + assert.strictEqual(root, childOf) }) }) @@ -91,7 +90,7 @@ describe('Appsec SDK utils', () => { const root = getRootSpan(tracer) - assert.equal(root, child1) + assert.strictEqual(root, child1) }) }) @@ -104,7 +103,7 @@ describe('Appsec SDK utils', () => { tracer.trace('child1.2.1', { childOf: child12 }, child121 => { const root = getRootSpan(tracer) - assert.equal(root, child12) + assert.strictEqual(root, child12) }) }) }) @@ -119,7 +118,7 @@ describe('Appsec SDK utils', () => { tracer.trace('child1.2.1', { childOf: child12 }, child121 => { const root = getRootSpan(tracer) - assert.equal(root, childOf) + assert.strictEqual(root, childOf) }) }) }) @@ -137,7 +136,7 @@ describe('Appsec SDK utils', () => { tracer.trace('child1.2.1.1', { childOf: child121 }, child1211 => { const root = getRootSpan(tracer) - assert.equal(root, childOf) + assert.strictEqual(root, childOf) }) }) }) @@ -157,7 +156,7 @@ describe('Appsec SDK utils', () => { tracer.trace('child1.2.1.1', { childOf: child121 }, child1211 => { const root = getRootSpan(tracer) - assert.equal(root, child1211) + assert.strictEqual(root, child1211) }) }) }) diff --git a/packages/dd-trace/test/appsec/stack_trace.spec.js b/packages/dd-trace/test/appsec/stack_trace.spec.js index 6599d0caa66..b68d8945346 100644 --- a/packages/dd-trace/test/appsec/stack_trace.spec.js +++ b/packages/dd-trace/test/appsec/stack_trace.spec.js @@ -1,6 +1,6 @@ 'use strict' -const { assert } = require('chai') +const assert = require('node:assert/strict') const path = require('path') const { reportStackTrace, getCallsiteFrames } = require('../../src/appsec/stack_trace') @@ -70,7 +70,7 @@ describe('Stack trace reporter', () => { reportStackTrace(rootSpan, stackId, frames) - assert.deepEqual(rootSpan.meta_struct['_dd.stack'].exploit[0].frames, expectedFrames) + assert.deepStrictEqual(rootSpan.meta_struct['_dd.stack'].exploit[0].frames, expectedFrames) }) }) @@ -118,7 +118,7 @@ describe('Stack trace reporter', () => { assert.strictEqual(rootSpan.meta_struct['_dd.stack'].exploit[0].id, stackId) assert.strictEqual(rootSpan.meta_struct['_dd.stack'].exploit[0].language, 'nodejs') - assert.deepEqual(rootSpan.meta_struct['_dd.stack'].exploit[0].frames, expectedFrames) + assert.deepStrictEqual(rootSpan.meta_struct['_dd.stack'].exploit[0].frames, expectedFrames) }) it('should add stack trace to rootSpan when meta_struct is already present', () => { @@ -147,8 +147,8 @@ describe('Stack trace reporter', () => { assert.strictEqual(rootSpan.meta_struct['_dd.stack'].exploit[0].id, stackId) assert.strictEqual(rootSpan.meta_struct['_dd.stack'].exploit[0].language, 'nodejs') - assert.deepEqual(rootSpan.meta_struct['_dd.stack'].exploit[0].frames, expectedFrames) - assert.property(rootSpan.meta_struct, 'another_tag') + assert.deepStrictEqual(rootSpan.meta_struct['_dd.stack'].exploit[0].frames, expectedFrames) + assert.ok(Object.hasOwn(rootSpan.meta_struct, 'another_tag')) }) it('should add stack trace to rootSpan when meta_struct is already present and contains another stack', () => { @@ -180,8 +180,8 @@ describe('Stack trace reporter', () => { assert.strictEqual(rootSpan.meta_struct['_dd.stack'].exploit[1].id, stackId) assert.strictEqual(rootSpan.meta_struct['_dd.stack'].exploit[1].language, 'nodejs') - assert.deepEqual(rootSpan.meta_struct['_dd.stack'].exploit[1].frames, expectedFrames) - assert.property(rootSpan.meta_struct, 'another_tag') + assert.deepStrictEqual(rootSpan.meta_struct['_dd.stack'].exploit[1].frames, expectedFrames) + assert.ok(Object.hasOwn(rootSpan.meta_struct, 'another_tag')) }) it('should add stack trace when the max stack trace is 0', () => { @@ -200,8 +200,8 @@ describe('Stack trace reporter', () => { reportStackTrace(rootSpan, stackId, frames) - assert.equal(rootSpan.meta_struct['_dd.stack'].exploit.length, 3) - assert.property(rootSpan.meta_struct, 'another_tag') + assert.strictEqual(rootSpan.meta_struct['_dd.stack'].exploit.length, 3) + assert.ok(Object.hasOwn(rootSpan.meta_struct, 'another_tag')) }) it('should add stack trace when the max stack trace is negative', () => { @@ -220,8 +220,8 @@ describe('Stack trace reporter', () => { reportStackTrace(rootSpan, stackId, frames) - assert.equal(rootSpan.meta_struct['_dd.stack'].exploit.length, 3) - assert.property(rootSpan.meta_struct, 'another_tag') + assert.strictEqual(rootSpan.meta_struct['_dd.stack'].exploit.length, 3) + assert.ok(Object.hasOwn(rootSpan.meta_struct, 'another_tag')) }) it('should not report stackTraces if callSiteList is undefined', () => { @@ -232,8 +232,8 @@ describe('Stack trace reporter', () => { } const stackId = 'test_stack_id' reportStackTrace(rootSpan, stackId, undefined) - assert.property(rootSpan.meta_struct, 'another_tag') - assert.notProperty(rootSpan.meta_struct, '_dd.stack') + assert.ok(Object.hasOwn(rootSpan.meta_struct, 'another_tag')) + assert.ok(!Object.hasOwn(rootSpan.meta_struct, '_dd.stack')) }) }) @@ -269,7 +269,7 @@ describe('Stack trace reporter', () => { reportStackTrace(rootSpan, stackId, frames) - assert.deepEqual(rootSpan.meta_struct['_dd.stack'].exploit[0].frames, expectedFrames) + assert.deepStrictEqual(rootSpan.meta_struct['_dd.stack'].exploit[0].frames, expectedFrames) }) it('limit frames to max depth with filtered frames', () => { @@ -320,7 +320,7 @@ describe('Stack trace reporter', () => { reportStackTrace(rootSpan, stackId, frames) - assert.deepEqual(rootSpan.meta_struct['_dd.stack'].exploit[0].frames, expectedFrames) + assert.deepStrictEqual(rootSpan.meta_struct['_dd.stack'].exploit[0].frames, expectedFrames) }) it('no limit if maxDepth is 0', () => { @@ -343,7 +343,7 @@ describe('Stack trace reporter', () => { reportStackTrace(rootSpan, stackId, frames) - assert.deepEqual(rootSpan.meta_struct['_dd.stack'].exploit[0].frames, expectedFrames) + assert.deepStrictEqual(rootSpan.meta_struct['_dd.stack'].exploit[0].frames, expectedFrames) }) it('no limit if maxDepth is negative', () => { @@ -366,7 +366,7 @@ describe('Stack trace reporter', () => { reportStackTrace(rootSpan, stackId, frames) - assert.deepEqual(rootSpan.meta_struct['_dd.stack'].exploit[0].frames, expectedFrames) + assert.deepStrictEqual(rootSpan.meta_struct['_dd.stack'].exploit[0].frames, expectedFrames) }) }) }) diff --git a/packages/dd-trace/test/appsec/telemetry/rasp.spec.js b/packages/dd-trace/test/appsec/telemetry/rasp.spec.js index 626ee95b580..5f4eb34c2a9 100644 --- a/packages/dd-trace/test/appsec/telemetry/rasp.spec.js +++ b/packages/dd-trace/test/appsec/telemetry/rasp.spec.js @@ -2,7 +2,6 @@ const assert = require('node:assert/strict') -const { expect } = require('chai') const { afterEach, beforeEach, describe, it } = require('mocha') const sinon = require('sinon') @@ -133,11 +132,11 @@ describe('Appsec Rasp Telemetry metrics', () => { raspEvalCount } = appsecTelemetry.getRequestMetrics(req) - expect(duration).to.be.eq(0) - expect(durationExt).to.be.eq(0) - expect(raspDuration).to.be.eq(66) - expect(raspDurationExt).to.be.eq(77) - expect(raspEvalCount).to.be.eq(2) + assert.strictEqual(duration, 0) + assert.strictEqual(durationExt, 0) + assert.strictEqual(raspDuration, 66) + assert.strictEqual(raspDurationExt, 77) + assert.strictEqual(raspEvalCount, 2) }) it('should increment raspTimeouts if wafTimeout is true', () => { @@ -251,7 +250,7 @@ describe('Appsec Rasp Telemetry metrics', () => { rulesVersion }, req, { type: 'rule-type' }) - expect(count).to.have.not.been.calledWith('waf.requests') + sinon.assert.neverCalledWith(count, 'waf.requests') appsecTelemetry.incrementWafRequestsMetric(req) sinon.assert.calledWithExactly(count, 'waf.requests', { @@ -313,9 +312,9 @@ describe('Appsec Rasp Telemetry metrics', () => { const { raspDuration, raspDurationExt, raspEvalCount } = appsecTelemetry.getRequestMetrics(req) - expect(raspDuration).to.be.eq(66) - expect(raspDurationExt).to.be.eq(77) - expect(raspEvalCount).to.be.eq(2) + assert.strictEqual(raspDuration, 66) + assert.strictEqual(raspDurationExt, 77) + assert.strictEqual(raspEvalCount, 2) }) it('should sum rasp.duration and rasp.durationExt with telemetry enabled and metrics disabled', () => { @@ -336,9 +335,9 @@ describe('Appsec Rasp Telemetry metrics', () => { const { raspDuration, raspDurationExt, raspEvalCount } = appsecTelemetry.getRequestMetrics(req) - expect(raspDuration).to.be.eq(66) - expect(raspDurationExt).to.be.eq(77) - expect(raspEvalCount).to.be.eq(2) + assert.strictEqual(raspDuration, 66) + assert.strictEqual(raspDurationExt, 77) + assert.strictEqual(raspEvalCount, 2) }) it('should not increment any metric if telemetry metrics are disabled', () => { diff --git a/packages/dd-trace/test/appsec/telemetry/waf.spec.js b/packages/dd-trace/test/appsec/telemetry/waf.spec.js index 43fe7503795..9d3b81fb55a 100644 --- a/packages/dd-trace/test/appsec/telemetry/waf.spec.js +++ b/packages/dd-trace/test/appsec/telemetry/waf.spec.js @@ -1,10 +1,13 @@ 'use strict' -const { expect } = require('chai') -const { describe, it, beforeEach, afterEach } = require('mocha') +const assert = require('node:assert/strict') + +const { afterEach, beforeEach, describe, it } = require('mocha') const sinon = require('sinon') const telemetryMetrics = require('../../../src/telemetry/metrics') +const { assertObjectContains } = require('../../../../../integration-tests/helpers') + const appsecNamespace = telemetryMetrics.manager.namespace('appsec') const appsecTelemetry = require('../../../src/appsec/telemetry') @@ -52,13 +55,13 @@ describe('Appsec Waf Telemetry metrics', () => { it('should skip update if no request is provided', () => { const result = appsecTelemetry.updateWafRequestsMetricTags(metrics) - expect(result).to.be.undefined + assert.strictEqual(result, undefined) }) it('should create a default tag', () => { const result = appsecTelemetry.updateWafRequestsMetricTags(metrics, req) - expect(result).to.be.deep.eq({ + assert.deepStrictEqual(result, { block_failure: false, event_rules_version: rulesVersion, input_truncated: false, @@ -82,7 +85,7 @@ describe('Appsec Waf Telemetry metrics', () => { ...metrics }, req) - expect(result).to.be.deep.eq({ + assert.deepStrictEqual(result, { block_failure: false, event_rules_version: rulesVersion, input_truncated: true, @@ -104,9 +107,9 @@ describe('Appsec Waf Telemetry metrics', () => { ...metrics }, req) - expect(result).to.be.eq(result2) + assert.strictEqual(result, result2) - expect(result).to.be.deep.eq({ + assert.deepStrictEqual(result, { block_failure: false, event_rules_version: rulesVersion, input_truncated: false, @@ -138,9 +141,9 @@ describe('Appsec Waf Telemetry metrics', () => { ...metrics }, req2) - expect(result).to.be.not.eq(result2) + assert.notStrictEqual(result, result2) - expect(result).to.be.deep.eq({ + assert.deepStrictEqual(result, { block_failure: false, event_rules_version: rulesVersion, input_truncated: true, @@ -166,8 +169,8 @@ describe('Appsec Waf Telemetry metrics', () => { const { duration, durationExt } = appsecTelemetry.getRequestMetrics(req) - expect(duration).to.be.eq(66) - expect(durationExt).to.be.eq(77) + assert.strictEqual(duration, 66) + assert.strictEqual(durationExt, 77) }) it('should increment wafTimeouts if wafTimeout is true', () => { @@ -175,26 +178,26 @@ describe('Appsec Waf Telemetry metrics', () => { appsecTelemetry.updateWafRequestsMetricTags({ wafTimeout: true }, req) const { wafTimeouts } = appsecTelemetry.getRequestMetrics(req) - expect(wafTimeouts).to.equal(2) + assert.strictEqual(wafTimeouts, 2) }) it('should keep the maximum wafErrorCode', () => { appsecTelemetry.updateWafRequestsMetricTags({ wafVersion, rulesVersion, errorCode: -1 }, req) - expect(count).to.have.been.calledWithExactly('waf.error', { + sinon.assert.calledWithExactly(count, 'waf.error', { waf_version: wafVersion, event_rules_version: rulesVersion, waf_error: -1 }) appsecTelemetry.updateWafRequestsMetricTags({ wafVersion, rulesVersion, errorCode: -3 }, req) - expect(count).to.have.been.calledWithExactly('waf.error', { + sinon.assert.calledWithExactly(count, 'waf.error', { waf_version: wafVersion, event_rules_version: rulesVersion, waf_error: -3 }) const { wafErrorCode } = appsecTelemetry.getRequestMetrics(req) - expect(wafErrorCode).to.equal(-1) + assert.strictEqual(wafErrorCode, -1) }) }) @@ -202,12 +205,12 @@ describe('Appsec Waf Telemetry metrics', () => { it('should increment waf.init metric', () => { appsecTelemetry.incrementWafInitMetric(wafVersion, rulesVersion, true) - expect(count).to.have.been.calledOnceWithExactly('waf.init', { + sinon.assert.calledOnceWithExactly(count, 'waf.init', { waf_version: wafVersion, event_rules_version: rulesVersion, success: true }) - expect(inc).to.have.been.calledOnce + sinon.assert.calledOnce(inc) }) it('should increment waf.init metric multiple times', () => { @@ -218,13 +221,13 @@ describe('Appsec Waf Telemetry metrics', () => { appsecTelemetry.incrementWafInitMetric(wafVersion, rulesVersion, true) const { metrics } = appsecNamespace.toJSON() - expect(metrics.series.length).to.be.eq(1) - expect(metrics.series[0].metric).to.be.eq('waf.init') - expect(metrics.series[0].points.length).to.be.eq(1) - expect(metrics.series[0].points[0][1]).to.be.eq(3) - expect(metrics.series[0].tags).to.include('waf_version:0.0.1') - expect(metrics.series[0].tags).to.include('event_rules_version:0.0.2') - expect(metrics.series[0].tags).to.include('success:true') + assert.strictEqual(metrics.series.length, 1) + assert.strictEqual(metrics.series[0].metric, 'waf.init') + assert.strictEqual(metrics.series[0].points.length, 1) + assert.strictEqual(metrics.series[0].points[0][1], 3) + assertObjectContains(metrics.series[0].tags, 'waf_version:0.0.1') + assertObjectContains(metrics.series[0].tags, 'event_rules_version:0.0.2') + assertObjectContains(metrics.series[0].tags, 'success:true') }) it('should increment waf.init and waf.config_errors on failed init', () => { @@ -233,16 +236,16 @@ describe('Appsec Waf Telemetry metrics', () => { appsecTelemetry.incrementWafInitMetric(wafVersion, rulesVersion, false) const { metrics } = appsecNamespace.toJSON() - expect(metrics.series.length).to.be.eq(2) - expect(metrics.series[0].metric).to.be.eq('waf.init') - expect(metrics.series[0].tags).to.include('waf_version:0.0.1') - expect(metrics.series[0].tags).to.include('event_rules_version:0.0.2') - expect(metrics.series[0].tags).to.include('success:false') - - expect(metrics.series[1].metric).to.be.eq('waf.config_errors') - expect(metrics.series[1].tags).to.include('waf_version:0.0.1') - expect(metrics.series[1].tags).to.include('event_rules_version:0.0.2') - expect(metrics.series[1].tags).to.include('action:init') + assert.strictEqual(metrics.series.length, 2) + assert.strictEqual(metrics.series[0].metric, 'waf.init') + assertObjectContains(metrics.series[0].tags, 'waf_version:0.0.1') + assertObjectContains(metrics.series[0].tags, 'event_rules_version:0.0.2') + assertObjectContains(metrics.series[0].tags, 'success:false') + + assert.strictEqual(metrics.series[1].metric, 'waf.config_errors') + assertObjectContains(metrics.series[1].tags, 'waf_version:0.0.1') + assertObjectContains(metrics.series[1].tags, 'event_rules_version:0.0.2') + assertObjectContains(metrics.series[1].tags, 'action:init') }) }) @@ -250,12 +253,12 @@ describe('Appsec Waf Telemetry metrics', () => { it('should increment waf.updates metric', () => { appsecTelemetry.incrementWafUpdatesMetric(wafVersion, rulesVersion, true) - expect(count).to.have.been.calledOnceWithExactly('waf.updates', { + sinon.assert.calledOnceWithExactly(count, 'waf.updates', { waf_version: wafVersion, event_rules_version: rulesVersion, success: true }) - expect(inc).to.have.been.calledOnce + sinon.assert.calledOnce(inc) }) it('should increment waf.updates metric multiple times', () => { @@ -266,13 +269,13 @@ describe('Appsec Waf Telemetry metrics', () => { appsecTelemetry.incrementWafUpdatesMetric(wafVersion, rulesVersion, true) const { metrics } = appsecNamespace.toJSON() - expect(metrics.series.length).to.be.eq(1) - expect(metrics.series[0].metric).to.be.eq('waf.updates') - expect(metrics.series[0].points.length).to.be.eq(1) - expect(metrics.series[0].points[0][1]).to.be.eq(3) - expect(metrics.series[0].tags).to.include('waf_version:0.0.1') - expect(metrics.series[0].tags).to.include('event_rules_version:0.0.2') - expect(metrics.series[0].tags).to.include('success:true') + assert.strictEqual(metrics.series.length, 1) + assert.strictEqual(metrics.series[0].metric, 'waf.updates') + assert.strictEqual(metrics.series[0].points.length, 1) + assert.strictEqual(metrics.series[0].points[0][1], 3) + assertObjectContains(metrics.series[0].tags, 'waf_version:0.0.1') + assertObjectContains(metrics.series[0].tags, 'event_rules_version:0.0.2') + assertObjectContains(metrics.series[0].tags, 'success:true') }) }) @@ -280,12 +283,12 @@ describe('Appsec Waf Telemetry metrics', () => { it('should increment waf.config_errors metric', () => { appsecTelemetry.incrementWafConfigErrorsMetric(wafVersion, rulesVersion) - expect(count).to.have.been.calledOnceWithExactly('waf.config_errors', { + sinon.assert.calledOnceWithExactly(count, 'waf.config_errors', { waf_version: wafVersion, event_rules_version: rulesVersion, action: 'update' }) - expect(inc).to.have.been.calledOnce + sinon.assert.calledOnce(inc) }) it('should increment waf.config_errors metric multiple times', () => { @@ -296,13 +299,13 @@ describe('Appsec Waf Telemetry metrics', () => { appsecTelemetry.incrementWafConfigErrorsMetric(wafVersion, rulesVersion, true) const { metrics } = appsecNamespace.toJSON() - expect(metrics.series.length).to.be.eq(1) - expect(metrics.series[0].metric).to.be.eq('waf.config_errors') - expect(metrics.series[0].points.length).to.be.eq(1) - expect(metrics.series[0].points[0][1]).to.be.eq(3) - expect(metrics.series[0].tags).to.include('waf_version:0.0.1') - expect(metrics.series[0].tags).to.include('event_rules_version:0.0.2') - expect(metrics.series[0].tags).to.include('action:update') + assert.strictEqual(metrics.series.length, 1) + assert.strictEqual(metrics.series[0].metric, 'waf.config_errors') + assert.strictEqual(metrics.series[0].points.length, 1) + assert.strictEqual(metrics.series[0].points[0][1], 3) + assertObjectContains(metrics.series[0].tags, 'waf_version:0.0.1') + assertObjectContains(metrics.series[0].tags, 'event_rules_version:0.0.2') + assertObjectContains(metrics.series[0].tags, 'action:update') }) }) @@ -322,8 +325,8 @@ describe('Appsec Waf Telemetry metrics', () => { appsecTelemetry.incrementWafRequestsMetric(req) - expect(count).to.have.been.calledWithExactly('waf.input_truncated', { truncation_reason: 1 }) - expect(count).to.have.been.calledWithExactly('waf.requests', { + sinon.assert.calledWithExactly(count, 'waf.input_truncated', { truncation_reason: 1 }) + sinon.assert.calledWithExactly(count, 'waf.requests', { request_blocked: true, block_failure: true, rule_triggered: true, @@ -339,7 +342,7 @@ describe('Appsec Waf Telemetry metrics', () => { it('should not fail if req has no previous tag', () => { appsecTelemetry.incrementWafRequestsMetric(req) - expect(count).to.not.have.been.called + sinon.assert.notCalled(count) }) }) @@ -347,7 +350,7 @@ describe('Appsec Waf Telemetry metrics', () => { it('should set rate_limited to true on the request tags', () => { appsecTelemetry.updateRateLimitedMetric(req, metrics) const result = appsecTelemetry.updateWafRequestsMetricTags({ wafVersion, rulesVersion }, req) - expect(result.rate_limited).to.be.true + assert.strictEqual(result.rate_limited, true) }) }) @@ -355,33 +358,36 @@ describe('Appsec Waf Telemetry metrics', () => { it('should set block_failure to true on the request tags', () => { appsecTelemetry.updateBlockFailureMetric(req) const result = appsecTelemetry.updateWafRequestsMetricTags({ wafVersion, rulesVersion }, req) - expect(result.block_failure).to.be.true + assert.strictEqual(result.block_failure, true) }) }) describe('WAF Truncation metrics', () => { it('should report truncated string metrics', () => { const result = appsecTelemetry.updateWafRequestsMetricTags({ maxTruncatedString: 5000 }, req) - expect(result).to.have.property('input_truncated', true) + assert.ok('input_truncated' in result); + assert.strictEqual(result['input_truncated'], true) - expect(count).to.have.been.calledWith('waf.input_truncated', { truncation_reason: 1 }) - expect(inc).to.have.been.calledWith(1) + sinon.assert.calledWith(count, 'waf.input_truncated', { truncation_reason: 1 }) + sinon.assert.calledWith(inc, 1) }) it('should report truncated container size metrics', () => { const result = appsecTelemetry.updateWafRequestsMetricTags({ maxTruncatedContainerSize: 300 }, req) - expect(result).to.have.property('input_truncated', true) + assert.ok('input_truncated' in result); + assert.strictEqual(result['input_truncated'], true) - expect(count).to.have.been.calledWith('waf.input_truncated', { truncation_reason: 2 }) - expect(inc).to.have.been.calledWith(1) + sinon.assert.calledWith(count, 'waf.input_truncated', { truncation_reason: 2 }) + sinon.assert.calledWith(inc, 1) }) it('should report truncated container depth metrics', () => { const result = appsecTelemetry.updateWafRequestsMetricTags({ maxTruncatedContainerDepth: 20 }, req) - expect(result).to.have.property('input_truncated', true) + assert.ok('input_truncated' in result); + assert.strictEqual(result['input_truncated'], true) - expect(count).to.have.been.calledWith('waf.input_truncated', { truncation_reason: 4 }) - expect(inc).to.have.been.calledWith(1) + sinon.assert.calledWith(count, 'waf.input_truncated', { truncation_reason: 4 }) + sinon.assert.calledWith(inc, 1) }) it('should combine truncation reasons when multiple truncations occur', () => { @@ -390,17 +396,19 @@ describe('Appsec Waf Telemetry metrics', () => { maxTruncatedContainerSize: 300, maxTruncatedContainerDepth: 20 }, req) - expect(result).to.have.property('input_truncated', true) + assert.ok('input_truncated' in result); + assert.strictEqual(result['input_truncated'], true) - expect(count).to.have.been.calledWith('waf.input_truncated', { truncation_reason: 7 }) + sinon.assert.calledWith(count, 'waf.input_truncated', { truncation_reason: 7 }) }) it('should not report truncation metrics when no truncation occurs', () => { const result = appsecTelemetry.updateWafRequestsMetricTags(metrics, req) - expect(result).to.have.property('input_truncated', false) + assert.ok('input_truncated' in result); + assert.strictEqual(result['input_truncated'], false) - expect(count).to.not.have.been.calledWith('waf.input_truncated') - expect(distribution).to.not.have.been.calledWith('waf.truncated_value_size') + sinon.assert.neverCalledWith(count, 'waf.input_truncated') + sinon.assert.neverCalledWith(distribution, 'waf.truncated_value_size') }) }) }) @@ -414,8 +422,8 @@ describe('Appsec Waf Telemetry metrics', () => { appsecTelemetry.incrementWafInitMetric(wafVersion, rulesVersion, true) - expect(count).to.not.have.been.called - expect(inc).to.not.have.been.called + sinon.assert.notCalled(count) + sinon.assert.notCalled(inc) }) it('should not increment any metric if telemetry metrics are disabled', () => { @@ -426,20 +434,20 @@ describe('Appsec Waf Telemetry metrics', () => { appsecTelemetry.incrementWafInitMetric(wafVersion, rulesVersion, true) - expect(count).to.not.have.been.called - expect(inc).to.not.have.been.called + sinon.assert.notCalled(count) + sinon.assert.notCalled(inc) }) it('should not set rate_limited if telemetry is disabled', () => { appsecTelemetry.updateRateLimitedMetric(req, { wafVersion, rulesVersion }) const result = appsecTelemetry.updateWafRequestsMetricTags({ wafVersion, rulesVersion }, req) - expect(result).to.be.undefined + assert.strictEqual(result, undefined) }) it('should not set block_failure if telemetry is disabled', () => { appsecTelemetry.updateBlockFailureMetric(req) const result = appsecTelemetry.updateWafRequestsMetricTags({ wafVersion, rulesVersion }, req) - expect(result).to.be.undefined + assert.strictEqual(result, undefined) }) describe('updateWafRequestMetricTags', () => { @@ -461,8 +469,8 @@ describe('Appsec Waf Telemetry metrics', () => { const { duration, durationExt } = appsecTelemetry.getRequestMetrics(req) - expect(duration).to.be.eq(66) - expect(durationExt).to.be.eq(77) + assert.strictEqual(duration, 66) + assert.strictEqual(durationExt, 77) }) it('should sum waf.duration and waf.durationExt with telemetry enabled and metrics disabled', () => { @@ -483,8 +491,8 @@ describe('Appsec Waf Telemetry metrics', () => { const { duration, durationExt } = appsecTelemetry.getRequestMetrics(req) - expect(duration).to.be.eq(66) - expect(durationExt).to.be.eq(77) + assert.strictEqual(duration, 66) + assert.strictEqual(durationExt, 77) }) }) }) diff --git a/packages/dd-trace/test/appsec/waf-metrics.integration.spec.js b/packages/dd-trace/test/appsec/waf-metrics.integration.spec.js index d1fe8b7d8ff..c6b086256e4 100644 --- a/packages/dd-trace/test/appsec/waf-metrics.integration.spec.js +++ b/packages/dd-trace/test/appsec/waf-metrics.integration.spec.js @@ -1,10 +1,10 @@ 'use strict' +const assert = require('node:assert/strict') + const { sandboxCwd, useSandbox, FakeAgent, spawnProc } = require('../../../../integration-tests/helpers') const path = require('path') const Axios = require('axios') -const { assert } = require('chai') - describe('WAF Metrics', () => { let axios, cwd, appFile @@ -63,21 +63,21 @@ describe('WAF Metrics', () => { const series = payload.payload.series const wafRequests = series.find(s => s.metric === 'waf.requests') - assert.exists(wafRequests, 'Waf requests serie should exist') + assert.ok(wafRequests != null) assert.strictEqual(wafRequests.type, 'count') - assert.include(wafRequests.tags, 'waf_error:true') - assert.include(wafRequests.tags, 'rate_limited:false') + assert.ok(wafRequests.tags.includes('waf_error:true')) + assert.ok(wafRequests.tags.includes('rate_limited:false')) const wafError = series.find(s => s.metric === 'waf.error') - assert.exists(wafError, 'Waf error serie should exist') + assert.ok(wafError != null) assert.strictEqual(wafError.type, 'count') - assert.include(wafError.tags, 'waf_error:-127') + assert.ok(wafError.tags.includes('waf_error:-127')) } }, 'generate-metrics', 30_000, 2) await Promise.all([checkMessages, checkTelemetryMetrics]) - assert.equal(appsecTelemetryMetricsReceived, true) + assert.strictEqual(appsecTelemetryMetricsReceived, true) }) }) @@ -111,7 +111,7 @@ describe('WAF Metrics', () => { const checkMessages = agent.assertMessageReceived(({ payload }) => { assert.strictEqual(payload[0][0].metrics['_dd.appsec.enabled'], 1) - assert.isTrue(payload[0][0].metrics['_dd.appsec.waf.timeouts'] > 0) + assert.strictEqual(payload[0][0].metrics['_dd.appsec.waf.timeouts'] > 0, true) }) const checkTelemetryMetrics = agent.assertTelemetryReceived(({ payload }) => { @@ -122,15 +122,15 @@ describe('WAF Metrics', () => { const series = payload.payload.series const wafRequests = series.find(s => s.metric === 'waf.requests') - assert.exists(wafRequests, 'Waf requests serie should exist') + assert.ok(wafRequests != null) assert.strictEqual(wafRequests.type, 'count') - assert.include(wafRequests.tags, 'waf_timeout:true') + assert.ok(wafRequests.tags.includes('waf_timeout:true')) } }, 'generate-metrics', 30_000, 2) await Promise.all([checkMessages, checkTelemetryMetrics]) - assert.equal(appsecTelemetryMetricsReceived, true) + assert.strictEqual(appsecTelemetryMetricsReceived, true) }) }) @@ -176,19 +176,19 @@ describe('WAF Metrics', () => { const series = payload.payload.series const inputTruncated = series.find(s => s.metric === 'waf.input_truncated') - assert.exists(inputTruncated, 'input truncated serie should exist') + assert.ok(inputTruncated != null) assert.strictEqual(inputTruncated.type, 'count') - assert.include(inputTruncated.tags, 'truncation_reason:7') + assert.ok(inputTruncated.tags.includes('truncation_reason:7')) const wafRequests = series.find(s => s.metric === 'waf.requests') - assert.exists(wafRequests, 'waf requests serie should exist') - assert.include(wafRequests.tags, 'input_truncated:true') + assert.ok(wafRequests != null) + assert.ok(wafRequests.tags.includes('input_truncated:true')) } }, 'generate-metrics', 30_000, 2) await Promise.all([checkMessages, checkTelemetryMetrics]) - assert.equal(appsecTelemetryMetricsReceived, true) + assert.strictEqual(appsecTelemetryMetricsReceived, true) }) }) }) diff --git a/packages/dd-trace/test/appsec/waf/index.spec.js b/packages/dd-trace/test/appsec/waf/index.spec.js index e0c65adeeb8..ed6629e6674 100644 --- a/packages/dd-trace/test/appsec/waf/index.spec.js +++ b/packages/dd-trace/test/appsec/waf/index.spec.js @@ -377,7 +377,7 @@ describe('WAF Manager', () => { it('should pass waf version when invoking ddwaf.createContext', () => { const req = {} const context = waf.wafManager.getWAFContext(req) - expect(context.wafVersion).to.be.eq('4.5.6') + assert.strictEqual(context.wafVersion, '4.5.6') }) }) @@ -422,7 +422,7 @@ describe('WAF Manager', () => { describe('run', () => { it('should not call ddwafContext.run without params', () => { waf.run() - expect(ddwafContext.run).not.to.be.called + sinon.assert.notCalled(ddwafContext.run) }) it('should call ddwafContext.run with params', () => { @@ -534,7 +534,7 @@ describe('WAF Manager', () => { wafContextWrapper.run(params) - expect(Reporter.reportAttack).not.to.be.called + sinon.assert.notCalled(Reporter.reportAttack) }) it('should not report attack when ddwafContext returns empty data', () => { @@ -547,7 +547,7 @@ describe('WAF Manager', () => { wafContextWrapper.run(params) - expect(Reporter.reportAttack).not.to.be.called + sinon.assert.notCalled(Reporter.reportAttack) }) it('should return waf result', () => { diff --git a/packages/dd-trace/test/azure_metadata.spec.js b/packages/dd-trace/test/azure_metadata.spec.js index 0211fdbd0a0..c26b6846ac7 100644 --- a/packages/dd-trace/test/azure_metadata.spec.js +++ b/packages/dd-trace/test/azure_metadata.spec.js @@ -1,8 +1,6 @@ 'use strict' const assert = require('node:assert/strict') - -const { expect } = require('chai') const { describe, it } = require('tap').mocha const os = require('node:os') @@ -107,6 +105,6 @@ describe('Azure metadata', () => { 'aas.site.type': 'app', 'aas.subscription.id': 'subscription_id' } - expect(getAzureTagsFromMetadata(getAzureAppMetadata())).to.deep.equal(expected) + assert.deepStrictEqual(getAzureTagsFromMetadata(getAzureAppMetadata()), expected) }) }) diff --git a/packages/dd-trace/test/ci-visibility/dynamic-instrumentation/dynamic-instrumentation.spec.js b/packages/dd-trace/test/ci-visibility/dynamic-instrumentation/dynamic-instrumentation.spec.js index 6686a1b2ecf..5b142146dd7 100644 --- a/packages/dd-trace/test/ci-visibility/dynamic-instrumentation/dynamic-instrumentation.spec.js +++ b/packages/dd-trace/test/ci-visibility/dynamic-instrumentation/dynamic-instrumentation.spec.js @@ -1,6 +1,6 @@ 'use strict' -const { assert } = require('chai') +const assert = require('node:assert/strict') const { describe, it, afterEach } = require('tap').mocha const { fork } = require('node:child_process') const path = require('node:path') @@ -24,12 +24,12 @@ describe('test visibility with dynamic instrumentation', () => { childProcess = fork(path.join(__dirname, 'target-app', 'test-visibility-dynamic-instrumentation-script.js')) childProcess.on('message', ({ snapshot: { language, stack, probe, captures }, probeId }) => { - assert.exists(probeId) - assert.exists(probe) - assert.exists(stack) - assert.equal(language, 'javascript') + assert.ok(probeId != null) + assert.ok(probe != null) + assert.ok(stack != null) + assert.strictEqual(language, 'javascript') - assert.deepEqual(captures, { + assert.deepStrictEqual(captures, { lines: { 9: { locals: { diff --git a/packages/dd-trace/test/ci-visibility/encode/json-encoder.spec.js b/packages/dd-trace/test/ci-visibility/encode/json-encoder.spec.js index 428454db033..9a75e056d51 100644 --- a/packages/dd-trace/test/ci-visibility/encode/json-encoder.spec.js +++ b/packages/dd-trace/test/ci-visibility/encode/json-encoder.spec.js @@ -1,8 +1,8 @@ 'use strict' const assert = require('node:assert/strict') +const { assertObjectContains } = require('../../../../../integration-tests/helpers') -const { expect } = require('chai') const { describe, it, beforeEach, afterEach } = require('tap').mocha const sinon = require('sinon') @@ -29,7 +29,7 @@ describe('CI Visibility JSON encoder', () => { const encoder = new JSONEncoder() encoder.encode(payload) encoder.encode(payloadSecond) - expect(encoder.payloads).to.include.members([payload, payloadSecond]) + assertObjectContains(encoder.payloads, [payload, payloadSecond]) assert.strictEqual(encoder.count(), 2) const serializedPayload = encoder.makePayload() assert.strictEqual(serializedPayload, JSON.stringify([payload, payloadSecond])) diff --git a/packages/dd-trace/test/ci-visibility/exporters/agent-proxy/agent-proxy.spec.js b/packages/dd-trace/test/ci-visibility/exporters/agent-proxy/agent-proxy.spec.js index 4acd4555326..7d6d088fc40 100644 --- a/packages/dd-trace/test/ci-visibility/exporters/agent-proxy/agent-proxy.spec.js +++ b/packages/dd-trace/test/ci-visibility/exporters/agent-proxy/agent-proxy.spec.js @@ -3,6 +3,8 @@ const assert = require('node:assert/strict') const { expect } = require('chai') +const { assertObjectContains } = require('../../../../../../integration-tests/helpers') + const { describe, it, beforeEach, context } = require('tap').mocha const sinon = require('sinon') const nock = require('nock') @@ -54,8 +56,8 @@ describe('AgentProxyCiVisibilityExporter', () => { agentProxyCiVisibilityExporter.export(trace) agentProxyCiVisibilityExporter.exportCoverage(coverage) - expect(agentProxyCiVisibilityExporter.getUncodedTraces()).to.include(trace) - expect(agentProxyCiVisibilityExporter._coverageBuffer).to.include(coverage) + assertObjectContains(agentProxyCiVisibilityExporter.getUncodedTraces(), trace) + assertObjectContains(agentProxyCiVisibilityExporter._coverageBuffer, coverage) agentProxyCiVisibilityExporter.export = sinon.spy() agentProxyCiVisibilityExporter.exportCoverage = sinon.spy() diff --git a/packages/dd-trace/test/ci-visibility/exporters/agentless/exporter.spec.js b/packages/dd-trace/test/ci-visibility/exporters/agentless/exporter.spec.js index 1a195ed7ad0..de497a62169 100644 --- a/packages/dd-trace/test/ci-visibility/exporters/agentless/exporter.spec.js +++ b/packages/dd-trace/test/ci-visibility/exporters/agentless/exporter.spec.js @@ -1,6 +1,8 @@ 'use strict' -const { expect } = require('chai') +const assert = require('node:assert/strict') +const { assertObjectContains } = require('../../../../../../integration-tests/helpers') + const { describe, it, beforeEach, afterEach, before, after, context } = require('tap').mocha const sinon = require('sinon') const nock = require('nock') @@ -34,7 +36,7 @@ describe('CI Visibility Agentless Exporter', () => { it('can use CI Vis protocol right away', () => { const agentlessExporter = new AgentlessCiVisibilityExporter({ url, isGitUploadEnabled: true, tags: {} }) - expect(agentlessExporter.canReportSessionTraces()).to.be.true + assert.strictEqual(agentlessExporter.canReportSessionTraces(), true) }) describe('when ITR is enabled', () => { @@ -57,9 +59,9 @@ describe('CI Visibility Agentless Exporter', () => { tags: {} }) agentlessExporter.getLibraryConfiguration({}, () => { - expect(scope.isDone()).to.be.true - expect(agentlessExporter.canReportCodeCoverage()).to.be.true - expect(agentlessExporter.shouldRequestSkippableSuites()).to.be.true + assert.strictEqual(scope.isDone(), true) + assert.strictEqual(agentlessExporter.canReportCodeCoverage(), true) + assert.strictEqual(agentlessExporter.shouldRequestSkippableSuites(), true) done() }) }) @@ -90,7 +92,7 @@ describe('CI Visibility Agentless Exporter', () => { agentlessExporter._resolveGit() agentlessExporter.getLibraryConfiguration({}, () => { agentlessExporter.getSkippableSuites({}, () => { - expect(scope.isDone()).to.be.true + assert.strictEqual(scope.isDone(), true) done() }) }) @@ -112,9 +114,9 @@ describe('CI Visibility Agentless Exporter', () => { url, isGitUploadEnabled: true, isIntelligentTestRunnerEnabled: true, tags: {} }) agentlessExporter.getLibraryConfiguration({}, () => { - expect(scope.isDone()).to.be.true - expect(agentlessExporter.canReportCodeCoverage()).to.be.true - expect(agentlessExporter.shouldRequestSkippableSuites()).to.be.true + assert.strictEqual(scope.isDone(), true) + assert.strictEqual(agentlessExporter.canReportCodeCoverage(), true) + assert.strictEqual(agentlessExporter.shouldRequestSkippableSuites(), true) done() }) }) @@ -135,8 +137,8 @@ describe('CI Visibility Agentless Exporter', () => { url, isGitUploadEnabled: true, isIntelligentTestRunnerEnabled: true, tags: {} }) agentlessExporter.getLibraryConfiguration({}, () => { - expect(scope.isDone()).to.be.true - expect(agentlessExporter.canReportCodeCoverage()).to.be.true + assert.strictEqual(scope.isDone(), true) + assert.strictEqual(agentlessExporter.canReportCodeCoverage(), true) done() }) }) @@ -168,11 +170,9 @@ describe('CI Visibility Agentless Exporter', () => { } agentlessExporter.getLibraryConfiguration({}, (err) => { - expect(scope.isDone()).not.to.be.true - expect(err.message).to.contain( - 'Request to settings endpoint was not done because Datadog API key is not defined' - ) - expect(agentlessExporter.shouldRequestSkippableSuites()).to.be.false + assert.notStrictEqual(scope.isDone(), true) + assertObjectContains(err.message, 'Request to settings endpoint was not done because Datadog API key is not defined') + assert.strictEqual(agentlessExporter.shouldRequestSkippableSuites(), false) process.env.DD_API_KEY = '1' done() }) @@ -186,7 +186,7 @@ describe('CI Visibility Agentless Exporter', () => { isTestDynamicInstrumentationEnabled: true }) await agentProxyCiVisibilityExporter._canUseCiVisProtocolPromise - expect(agentProxyCiVisibilityExporter._logsWriter).to.be.instanceOf(DynamicInstrumentationLogsWriter) + assert.ok(agentProxyCiVisibilityExporter._logsWriter instanceof DynamicInstrumentationLogsWriter) }) it('should process logs', async () => { @@ -202,7 +202,7 @@ describe('CI Visibility Agentless Exporter', () => { agentProxyCiVisibilityExporter._logsWriter = mockWriter const log = { message: 'hello' } agentProxyCiVisibilityExporter.exportDiLogs({}, log) - expect(mockWriter.append).to.have.been.calledWith(sinon.match(log)) + sinon.assert.calledWith(mockWriter.append, sinon.match(log)) }) }) @@ -210,8 +210,8 @@ describe('CI Visibility Agentless Exporter', () => { it('sets the default if URL param is not specified', () => { const site = 'd4tad0g.com' const agentlessExporter = new AgentlessCiVisibilityExporter({ site, tags: {} }) - expect(agentlessExporter._url.href).to.equal(`https://citestcycle-intake.${site}/`) - expect(agentlessExporter._coverageUrl.href).to.equal(`https://citestcov-intake.${site}/`) + assert.strictEqual(agentlessExporter._url.href, `https://citestcycle-intake.${site}/`) + assert.strictEqual(agentlessExporter._coverageUrl.href, `https://citestcov-intake.${site}/`) }) }) }) diff --git a/packages/dd-trace/test/ci-visibility/exporters/ci-visibility-exporter.spec.js b/packages/dd-trace/test/ci-visibility/exporters/ci-visibility-exporter.spec.js index 3264aa2387d..30987496ce4 100644 --- a/packages/dd-trace/test/ci-visibility/exporters/ci-visibility-exporter.spec.js +++ b/packages/dd-trace/test/ci-visibility/exporters/ci-visibility-exporter.spec.js @@ -1,6 +1,10 @@ 'use strict' +const assert = require('node:assert/strict') + const { expect } = require('chai') +const { assertObjectContains } = require('../../../../../integration-tests/helpers') + const { describe, it, beforeEach, afterEach, context } = require('tap').mocha const sinon = require('sinon') const nock = require('nock') @@ -42,8 +46,8 @@ describe('CI Visibility Exporter', () => { const ciVisibilityExporter = new CiVisibilityExporter({ url: urlObj, isGitUploadEnabled: true }) ciVisibilityExporter._gitUploadPromise.then((err) => { - expect(err).not.to.exist - expect(scope.isDone()).to.be.true + assert.ok(err == null) + assert.strictEqual(scope.isDone(), true) done() }) ciVisibilityExporter._resolveCanUseCiVisProtocol(true) @@ -59,8 +63,8 @@ describe('CI Visibility Exporter', () => { const ciVisibilityExporter = new CiVisibilityExporter({ url: urlObj, isGitUploadEnabled: true }) ciVisibilityExporter._gitUploadPromise.then((err) => { - expect(err.message).to.include('Error fetching commits to exclude') - expect(scope.isDone()).to.be.true + assertObjectContains(err.message, 'Error fetching commits to exclude') + assert.strictEqual(scope.isDone(), true) done() }) ciVisibilityExporter._resolveCanUseCiVisProtocol(true) @@ -72,7 +76,7 @@ describe('CI Visibility Exporter', () => { .post('/api/v2/git/repository/search_commits') .reply(200, function () { const { meta: { repository_url: repositoryUrl } } = JSON.parse(this.req.requestBodyBuffers.toString()) - expect(repositoryUrl).to.equal('https://custom-git@datadog.com') + assert.strictEqual(repositoryUrl, 'https://custom-git@datadog.com') done() }) .post('/api/v2/git/repository/packfile') @@ -100,7 +104,7 @@ describe('CI Visibility Exporter', () => { ciVisibilityExporter._resolveCanUseCiVisProtocol(true) ciVisibilityExporter.getLibraryConfiguration({}, () => {}) ciVisibilityExporter._gitUploadPromise.then(() => { - expect(scope.isDone()).to.be.true + assert.strictEqual(scope.isDone(), true) done() }) }) @@ -112,9 +116,9 @@ describe('CI Visibility Exporter', () => { const ciVisibilityExporter = new CiVisibilityExporter({ port }) ciVisibilityExporter.getLibraryConfiguration({}, (err, libraryConfig) => { - expect(libraryConfig).to.eql({}) - expect(err).to.be.null - expect(scope.isDone()).not.to.be.true + assert.deepStrictEqual(libraryConfig, {}) + assert.strictEqual(err, null) + assert.notStrictEqual(scope.isDone(), true) done() }) }) @@ -147,8 +151,8 @@ describe('CI Visibility Exporter', () => { }) ciVisibilityExporter.getLibraryConfiguration({}, () => { - expect(scope.isDone()).to.be.true - expect(customConfig).to.eql({ + assert.strictEqual(scope.isDone(), true) + assert.deepStrictEqual(customConfig, { my_custom_config: 'my_custom_config_value' }) done() @@ -180,15 +184,15 @@ describe('CI Visibility Exporter', () => { tag: 'v1.0.0' } ciVisibilityExporter.getLibraryConfiguration(testConfiguration, (err, libraryConfig) => { - expect(err).to.be.null - expect(libraryConfig).to.contain({ + assert.strictEqual(err, null) + assertObjectContains(libraryConfig, { requireGit: false, isCodeCoverageEnabled: true, isItrEnabled: true, isSuitesSkippingEnabled: true }) - expect(scope.isDone()).to.be.true - expect(requestBody.data.attributes.branch).to.equal('v1.0.0') + assert.strictEqual(scope.isDone(), true) + assert.strictEqual(requestBody.data.attributes.branch, 'v1.0.0') done() }) ciVisibilityExporter._resolveCanUseCiVisProtocol(true) @@ -211,15 +215,15 @@ describe('CI Visibility Exporter', () => { const ciVisibilityExporter = new CiVisibilityExporter({ port, isIntelligentTestRunnerEnabled: true }) ciVisibilityExporter.getLibraryConfiguration({}, (err, libraryConfig) => { - expect(libraryConfig).to.contain({ + assertObjectContains(libraryConfig, { requireGit: false, isCodeCoverageEnabled: true, isItrEnabled: true, isSuitesSkippingEnabled: true, isEarlyFlakeDetectionEnabled: false }) - expect(err).not.to.exist - expect(scope.isDone()).to.be.true + assert.ok(err == null) + assert.strictEqual(scope.isDone(), true) done() }) ciVisibilityExporter._resolveCanUseCiVisProtocol(true) @@ -239,10 +243,10 @@ describe('CI Visibility Exporter', () => { })) const ciVisibilityExporter = new CiVisibilityExporter({ port, isIntelligentTestRunnerEnabled: true }) - expect(ciVisibilityExporter.shouldRequestSkippableSuites()).to.be.false + assert.strictEqual(ciVisibilityExporter.shouldRequestSkippableSuites(), false) ciVisibilityExporter.getLibraryConfiguration({}, () => { - expect(ciVisibilityExporter.shouldRequestSkippableSuites()).to.be.true + assert.strictEqual(ciVisibilityExporter.shouldRequestSkippableSuites(), true) done() }) ciVisibilityExporter._resolveCanUseCiVisProtocol(true) @@ -276,13 +280,13 @@ describe('CI Visibility Exporter', () => { port, isIntelligentTestRunnerEnabled: true }) ciVisibilityExporter._resolveCanUseCiVisProtocol(true) - expect(ciVisibilityExporter.shouldRequestLibraryConfiguration()).to.be.true + assert.strictEqual(ciVisibilityExporter.shouldRequestLibraryConfiguration(), true) ciVisibilityExporter.getLibraryConfiguration({}, (err, libraryConfig) => { - expect(scope.isDone()).to.be.true - expect(err).to.be.null + assert.strictEqual(scope.isDone(), true) + assert.strictEqual(err, null) // the second request returns require_git: false - expect(libraryConfig.requireGit).to.be.false - expect(hasUploadedGit).to.be.true + assert.strictEqual(libraryConfig.requireGit, false) + assert.strictEqual(hasUploadedGit, true) done() }) // Git upload finishes after a bit @@ -318,12 +322,12 @@ describe('CI Visibility Exporter', () => { port, isIntelligentTestRunnerEnabled: true }) ciVisibilityExporter._resolveCanUseCiVisProtocol(true) - expect(ciVisibilityExporter.shouldRequestLibraryConfiguration()).to.be.true + assert.strictEqual(ciVisibilityExporter.shouldRequestLibraryConfiguration(), true) ciVisibilityExporter.getLibraryConfiguration({}, (err, libraryConfig) => { - expect(scope.isDone()).to.be.true - expect(err).to.be.null + assert.strictEqual(scope.isDone(), true) + assert.strictEqual(err, null) // the second request returns require_git: false - expect(libraryConfig.requireGit).to.be.false + assert.strictEqual(libraryConfig.requireGit, false) done() }) ciVisibilityExporter._resolveGit() @@ -340,9 +344,9 @@ describe('CI Visibility Exporter', () => { const ciVisibilityExporter = new CiVisibilityExporter({ port }) ciVisibilityExporter.getSkippableSuites({}, (err, skippableSuites) => { - expect(err).to.be.null - expect(skippableSuites).to.eql([]) - expect(scope.isDone()).not.to.be.true + assert.strictEqual(err, null) + assert.deepStrictEqual(skippableSuites, []) + assert.notStrictEqual(scope.isDone(), true) done() }) }) @@ -359,9 +363,9 @@ describe('CI Visibility Exporter', () => { ciVisibilityExporter._resolveGit() ciVisibilityExporter.getSkippableSuites({}, (err, skippableSuites) => { - expect(err).to.be.null - expect(skippableSuites).to.eql([]) - expect(scope.isDone()).not.to.be.true + assert.strictEqual(err, null) + assert.deepStrictEqual(skippableSuites, []) + assert.notStrictEqual(scope.isDone(), true) done() }) }) @@ -405,8 +409,8 @@ describe('CI Visibility Exporter', () => { ciVisibilityExporter._resolveCanUseCiVisProtocol(true) ciVisibilityExporter.getSkippableSuites({}, () => { - expect(scope.isDone()).to.be.true - expect(customConfig).to.eql({ + assert.strictEqual(scope.isDone(), true) + assert.deepStrictEqual(customConfig, { my_custom_config_2: 'my_custom_config_value_2' }) done() @@ -446,9 +450,9 @@ describe('CI Visibility Exporter', () => { ciVisibilityExporter._resolveCanUseCiVisProtocol(true) ciVisibilityExporter.getSkippableSuites({}, (err, skippableSuites) => { - expect(err).to.be.null - expect(skippableSuites).to.eql(['ci-visibility/test/ci-visibility-test.js']) - expect(scope.isDone()).to.be.true + assert.strictEqual(err, null) + assert.deepStrictEqual(skippableSuites, ['ci-visibility/test/ci-visibility-test.js']) + assert.strictEqual(scope.isDone(), true) done() }) ciVisibilityExporter.sendGitMetadata() @@ -466,9 +470,9 @@ describe('CI Visibility Exporter', () => { ciVisibilityExporter._resolveCanUseCiVisProtocol(true) ciVisibilityExporter.getSkippableSuites({}, (err, skippableSuites) => { - expect(err.message).to.include('could not upload git metadata') - expect(skippableSuites).to.eql([]) - expect(scope.isDone()).not.to.be.true + assertObjectContains(err.message, 'could not upload git metadata') + assert.deepStrictEqual(skippableSuites, []) + assert.notStrictEqual(scope.isDone(), true) done() }) ciVisibilityExporter._resolveGit(new Error('could not upload git metadata')) @@ -516,10 +520,10 @@ describe('CI Visibility Exporter', () => { ciVisibilityExporter._isGzipCompatible = true ciVisibilityExporter.getSkippableSuites({}, (err, skippableSuites) => { - expect(err).to.be.null - expect(skippableSuites).to.eql(['ci-visibility/test/ci-visibility-test.js']) - expect(scope.isDone()).to.be.true - expect(requestHeaders['accept-encoding']).to.equal('gzip') + assert.strictEqual(err, null) + assert.deepStrictEqual(skippableSuites, ['ci-visibility/test/ci-visibility-test.js']) + assert.strictEqual(scope.isDone(), true) + assert.strictEqual(requestHeaders['accept-encoding'], 'gzip') done() }) ciVisibilityExporter.sendGitMetadata() @@ -563,10 +567,10 @@ describe('CI Visibility Exporter', () => { ciVisibilityExporter._isGzipCompatible = false ciVisibilityExporter.getSkippableSuites({}, (err, skippableSuites) => { - expect(err).to.be.null - expect(skippableSuites).to.eql(['ci-visibility/test/ci-visibility-test.js']) - expect(scope.isDone()).to.be.true - expect(requestHeaders['accept-encoding']).not.to.equal('gzip') + assert.strictEqual(err, null) + assert.deepStrictEqual(skippableSuites, ['ci-visibility/test/ci-visibility-test.js']) + assert.strictEqual(scope.isDone(), true) + assert.notStrictEqual(requestHeaders['accept-encoding'], 'gzip') done() }) ciVisibilityExporter.sendGitMetadata() @@ -581,8 +585,8 @@ describe('CI Visibility Exporter', () => { const ciVisibilityExporter = new CiVisibilityExporter({ port }) ciVisibilityExporter.export(trace) ciVisibilityExporter._export = sinon.spy() - expect(ciVisibilityExporter._traceBuffer).to.include(trace) - expect(ciVisibilityExporter._export).not.to.be.called + assertObjectContains(ciVisibilityExporter._traceBuffer, trace) + sinon.assert.notCalled(ciVisibilityExporter._export) }) }) context('is initialized', () => { @@ -598,7 +602,7 @@ describe('CI Visibility Exporter', () => { ciVisibilityExporter._writer = writer ciVisibilityExporter.export(trace) expect(ciVisibilityExporter._traceBuffer).not.to.include(trace) - expect(ciVisibilityExporter._writer.append).to.be.called + sinon.assert.called(ciVisibilityExporter._writer.append) }) }) context('is initialized and can not use CI Vis protocol', () => { @@ -616,7 +620,7 @@ describe('CI Visibility Exporter', () => { ciVisibilityExporter._writer = writer ciVisibilityExporter.export(trace) expect(ciVisibilityExporter._traceBuffer).not.to.include(trace) - expect(ciVisibilityExporter._writer.append).not.to.be.called + sinon.assert.notCalled(ciVisibilityExporter._writer.append) }) }) context('is initialized and can use CI Vis protocol', () => { @@ -635,7 +639,7 @@ describe('CI Visibility Exporter', () => { ciVisibilityExporter._canUseCiVisProtocol = true ciVisibilityExporter.export(trace) expect(ciVisibilityExporter._traceBuffer).not.to.include(trace) - expect(ciVisibilityExporter._writer.append).to.be.called + sinon.assert.called(ciVisibilityExporter._writer.append) }) }) }) @@ -647,8 +651,8 @@ describe('CI Visibility Exporter', () => { const ciVisibilityExporter = new CiVisibilityExporter({ port }) ciVisibilityExporter.exportCoverage(coverage) ciVisibilityExporter._export = sinon.spy() - expect(ciVisibilityExporter._coverageBuffer).to.include(coverage) - expect(ciVisibilityExporter._export).not.to.be.called + assertObjectContains(ciVisibilityExporter._coverageBuffer, coverage) + sinon.assert.notCalled(ciVisibilityExporter._export) }) }) context('is initialized but can not use CI Vis protocol', () => { @@ -664,7 +668,7 @@ describe('CI Visibility Exporter', () => { ciVisibilityExporter._coverageWriter = writer ciVisibilityExporter.exportCoverage(coverage) expect(ciVisibilityExporter._coverageBuffer).not.to.include(coverage) - expect(ciVisibilityExporter._coverageWriter.append).not.to.be.called + sinon.assert.notCalled(ciVisibilityExporter._coverageWriter.append) }) }) context('is initialized and can use CI Vis protocol', () => { @@ -686,7 +690,7 @@ describe('CI Visibility Exporter', () => { ciVisibilityExporter.exportCoverage(coverage) expect(ciVisibilityExporter._coverageBuffer).not.to.include(coverage) - expect(ciVisibilityExporter._coverageWriter.append).to.be.called + sinon.assert.called(ciVisibilityExporter._coverageWriter.append) }) }) }) @@ -706,9 +710,9 @@ describe('CI Visibility Exporter', () => { ciVisibilityExporter._libraryConfig = { isKnownTestsEnabled: false } ciVisibilityExporter.getKnownTests({}, (err, knownTests) => { - expect(err).to.be.null - expect(knownTests).to.eql(undefined) - expect(knownTestsScope.isDone()).not.to.be.true + assert.strictEqual(err, null) + assert.deepStrictEqual(knownTests, undefined) + assert.notStrictEqual(knownTestsScope.isDone(), true) done() }) }) @@ -726,8 +730,8 @@ describe('CI Visibility Exporter', () => { ciVisibilityExporter._libraryConfig = { isKnownTestsEnabled: true } ciVisibilityExporter.getKnownTests({}, (err) => { - expect(err).to.be.null - expect(scope.isDone()).not.to.be.true + assert.strictEqual(err, null) + assert.notStrictEqual(scope.isDone(), true) done() }) }) @@ -755,14 +759,14 @@ describe('CI Visibility Exporter', () => { ciVisibilityExporter._resolveCanUseCiVisProtocol(true) ciVisibilityExporter._libraryConfig = { isKnownTestsEnabled: true } ciVisibilityExporter.getKnownTests({}, (err, knownTests) => { - expect(err).to.be.null - expect(knownTests).to.eql({ + assert.strictEqual(err, null) + assert.deepStrictEqual(knownTests, { jest: { suite1: ['test1'], suite2: ['test2'] } }) - expect(scope.isDone()).to.be.true + assert.strictEqual(scope.isDone(), true) done() }) }) @@ -776,8 +780,8 @@ describe('CI Visibility Exporter', () => { ciVisibilityExporter._resolveCanUseCiVisProtocol(true) ciVisibilityExporter._libraryConfig = { isKnownTestsEnabled: true } ciVisibilityExporter.getKnownTests({}, (err) => { - expect(err).not.to.be.null - expect(scope.isDone()).to.be.true + assert.notStrictEqual(err, null) + assert.strictEqual(scope.isDone(), true) done() }) }) @@ -811,15 +815,15 @@ describe('CI Visibility Exporter', () => { ciVisibilityExporter._libraryConfig = { isKnownTestsEnabled: true } ciVisibilityExporter._isGzipCompatible = true ciVisibilityExporter.getKnownTests({}, (err, knownTests) => { - expect(err).to.be.null - expect(knownTests).to.eql({ + assert.strictEqual(err, null) + assert.deepStrictEqual(knownTests, { jest: { suite1: ['test1'], suite2: ['test2'] } }) - expect(scope.isDone()).to.be.true - expect(requestHeaders['accept-encoding']).to.equal('gzip') + assert.strictEqual(scope.isDone(), true) + assert.strictEqual(requestHeaders['accept-encoding'], 'gzip') done() }) }) @@ -852,15 +856,15 @@ describe('CI Visibility Exporter', () => { ciVisibilityExporter._isGzipCompatible = false ciVisibilityExporter.getKnownTests({}, (err, knownTests) => { - expect(err).to.be.null - expect(knownTests).to.eql({ + assert.strictEqual(err, null) + assert.deepStrictEqual(knownTests, { jest: { suite1: ['test1'], suite2: ['test2'] } }) - expect(scope.isDone()).to.be.true - expect(requestHeaders['accept-encoding']).not.to.equal('gzip') + assert.strictEqual(scope.isDone(), true) + assert.notStrictEqual(requestHeaders['accept-encoding'], 'gzip') done() }) }) @@ -874,7 +878,7 @@ describe('CI Visibility Exporter', () => { const ciVisibilityExporter = new CiVisibilityExporter({ port, isTestDynamicInstrumentationEnabled: true }) ciVisibilityExporter.exportDiLogs(log) ciVisibilityExporter._export = sinon.spy() - expect(ciVisibilityExporter._export).not.to.be.called + sinon.assert.notCalled(ciVisibilityExporter._export) }) }) @@ -891,7 +895,7 @@ describe('CI Visibility Exporter', () => { ciVisibilityExporter._logsWriter = writer ciVisibilityExporter._canForwardLogs = false ciVisibilityExporter.exportDiLogs(log) - expect(ciVisibilityExporter._logsWriter.append).not.to.be.called + sinon.assert.notCalled(ciVisibilityExporter._logsWriter.append) }) }) diff --git a/packages/dd-trace/test/ci-visibility/exporters/git/git_metadata.spec.js b/packages/dd-trace/test/ci-visibility/exporters/git/git_metadata.spec.js index dfdfa65fc01..bcb1d6c088d 100644 --- a/packages/dd-trace/test/ci-visibility/exporters/git/git_metadata.spec.js +++ b/packages/dd-trace/test/ci-visibility/exporters/git/git_metadata.spec.js @@ -1,6 +1,8 @@ 'use strict' -const { expect } = require('chai') +const assert = require('node:assert/strict') +const { assertObjectContains } = require('../../../../../../integration-tests/helpers') + const { describe, it, beforeEach, afterEach, before, after } = require('tap').mocha const sinon = require('sinon') const proxyquire = require('proxyquire').noPreserveCache() @@ -77,9 +79,9 @@ describe('git_metadata', () => { isShallowRepositoryStub.returns(true) gitMetadata.sendGitMetadata(new URL('https://api.test.com'), { isEvpProxy: false }, '', (err) => { - expect(unshallowRepositoryStub).not.to.have.been.called - expect(err).to.be.null - expect(scope.isDone()).to.be.true + sinon.assert.notCalled(unshallowRepositoryStub) + assert.strictEqual(err, null) + assert.strictEqual(scope.isDone(), true) done() }) }) @@ -95,9 +97,9 @@ describe('git_metadata', () => { isShallowRepositoryStub.returns(true) gitMetadata.sendGitMetadata(new URL('https://api.test.com'), { isEvpProxy: false }, '', (err) => { - expect(unshallowRepositoryStub).to.have.been.called - expect(err).to.be.null - expect(scope.isDone()).to.be.true + sinon.assert.called(unshallowRepositoryStub) + assert.strictEqual(err, null) + assert.strictEqual(scope.isDone(), true) done() }) }) @@ -114,9 +116,9 @@ describe('git_metadata', () => { isShallowRepositoryStub.returns(true) gitMetadata.sendGitMetadata(new URL('https://api.test.com'), { isEvpProxy: false }, '', (err) => { - expect(unshallowRepositoryStub).not.to.have.been.called - expect(err).to.be.null - expect(scope.isDone()).to.be.true + sinon.assert.notCalled(unshallowRepositoryStub) + assert.strictEqual(err, null) + assert.strictEqual(scope.isDone(), true) done() }) }) @@ -129,8 +131,8 @@ describe('git_metadata', () => { .reply(204) gitMetadata.sendGitMetadata(new URL('https://api.test.com'), { isEvpProxy: false }, '', (err) => { - expect(err).to.be.null - expect(scope.isDone()).to.be.true + assert.strictEqual(err, null) + assert.strictEqual(scope.isDone(), true) done() }) }) @@ -145,10 +147,10 @@ describe('git_metadata', () => { getCommitsRevListStub.returns([]) gitMetadata.sendGitMetadata(new URL('https://api.test.com'), { isEvpProxy: false }, '', (err) => { - expect(err).to.be.null + assert.strictEqual(err, null) // to check that it is not called - expect(scope.isDone()).to.be.false - expect(scope.pendingMocks()).to.contain('POST https://api.test.com:443/api/v2/git/repository/packfile') + assert.strictEqual(scope.isDone(), false) + assertObjectContains(scope.pendingMocks(), 'POST https://api.test.com:443/api/v2/git/repository/packfile') done() }) }) @@ -161,10 +163,10 @@ describe('git_metadata', () => { .reply(204) gitMetadata.sendGitMetadata(new URL('https://api.test.com'), { isEvpProxy: false }, '', (err) => { - expect(err.message).to.contain('Error fetching commits to exclude: Error from https://api.test.com/api/v2/git/repository/search_commits: 404 Not Found. Response from the endpoint: "Not found SHA"') + assertObjectContains(err.message, 'Error fetching commits to exclude: Error from https://api.test.com/api/v2/git/repository/search_commits: 404 Not Found. Response from the endpoint: "Not found SHA"') // to check that it is not called - expect(scope.isDone()).to.be.false - expect(scope.pendingMocks()).to.contain('POST https://api.test.com:443/api/v2/git/repository/packfile') + assert.strictEqual(scope.isDone(), false) + assertObjectContains(scope.pendingMocks(), 'POST https://api.test.com:443/api/v2/git/repository/packfile') done() }) }) @@ -177,10 +179,10 @@ describe('git_metadata', () => { .reply(204) gitMetadata.sendGitMetadata(new URL('https://api.test.com'), { isEvpProxy: false }, '', (err) => { - expect(err.message).to.contain("Can't parse commits to exclude response: Invalid commit type response") + assertObjectContains(err.message, "Can't parse commits to exclude response: Invalid commit type response") // to check that it is not called - expect(scope.isDone()).to.be.false - expect(scope.pendingMocks()).to.contain('POST https://api.test.com:443/api/v2/git/repository/packfile') + assert.strictEqual(scope.isDone(), false) + assertObjectContains(scope.pendingMocks(), 'POST https://api.test.com:443/api/v2/git/repository/packfile') done() }) }) @@ -193,10 +195,10 @@ describe('git_metadata', () => { .reply(204) gitMetadata.sendGitMetadata(new URL('https://api.test.com'), { isEvpProxy: false }, '', (err) => { - expect(err.message).to.contain("Can't parse commits to exclude response: Invalid commit format") + assertObjectContains(err.message, "Can't parse commits to exclude response: Invalid commit format") // to check that it is not called - expect(scope.isDone()).to.be.false - expect(scope.pendingMocks()).to.contain('POST https://api.test.com:443/api/v2/git/repository/packfile') + assert.strictEqual(scope.isDone(), false) + assertObjectContains(scope.pendingMocks(), 'POST https://api.test.com:443/api/v2/git/repository/packfile') done() }) }) @@ -209,8 +211,8 @@ describe('git_metadata', () => { .reply(502) gitMetadata.sendGitMetadata(new URL('https://api.test.com'), { isEvpProxy: false }, '', (err) => { - expect(err.message).to.contain('Could not upload packfiles: status code 502') - expect(scope.isDone()).to.be.true + assertObjectContains(err.message, 'Could not upload packfiles: status code 502') + assert.strictEqual(scope.isDone(), true) done() }) }) @@ -223,8 +225,8 @@ describe('git_metadata', () => { .reply(200, JSON.stringify({ data: [] })) gitMetadata.sendGitMetadata(new URL('https://api.test.com'), { isEvpProxy: false }, '', (err) => { - expect(err.message).to.contain('git rev-list failed') - expect(scope.isDone()).to.be.true + assertObjectContains(err.message, 'git rev-list failed') + assert.strictEqual(scope.isDone(), true) done() }) }) @@ -250,8 +252,8 @@ describe('git_metadata', () => { ]) gitMetadata.sendGitMetadata(new URL('https://api.test.com'), { isEvpProxy: false }, '', (err) => { - expect(err).to.be.null - expect(scope.isDone()).to.be.true + assert.strictEqual(err, null) + assert.strictEqual(scope.isDone(), true) done() }) }) @@ -264,7 +266,7 @@ describe('git_metadata', () => { 'test.com/repo/dummy' ] invalidUrls.forEach((invalidUrl) => { - expect(validateGitRepositoryUrl(invalidUrl), `${invalidUrl} is a valid URL`).to.be.false + assert.strictEqual(validateGitRepositoryUrl(invalidUrl), false) }) }) @@ -281,7 +283,7 @@ describe('git_metadata', () => { ] validUrls.forEach((validUrl) => { - expect(validateGitRepositoryUrl(validUrl), `${validUrl} is an invalid URL`).to.be.true + assert.strictEqual(validateGitRepositoryUrl(validUrl), true) }) }) }) @@ -297,7 +299,7 @@ describe('git_metadata', () => { const invalidSha7 = 'cb466452bfe18d4f6be2836c2a5551843013cf3812342239203182304928' const invalidShas = [invalidSha1, invalidSha2, invalidSha3, invalidSha4, invalidSha5, invalidSha6, invalidSha7] invalidShas.forEach((invalidSha) => { - expect(validateGitCommitSha(invalidSha)).to.be.false + assert.strictEqual(validateGitCommitSha(invalidSha), false) }) }) @@ -307,7 +309,7 @@ describe('git_metadata', () => { const validShas = [validSha1, validSha2] validShas.forEach((validSha) => { - expect(validateGitCommitSha(validSha)).to.be.true + assert.strictEqual(validateGitCommitSha(validSha), true) }) }) }) @@ -325,8 +327,8 @@ describe('git_metadata', () => { ]) gitMetadata.sendGitMetadata(new URL('https://api.test.com'), { isEvpProxy: false }, '', (err) => { - expect(err.message).to.contain('Could not read "not-there"') - expect(scope.isDone()).to.be.false + assertObjectContains(err.message, 'Could not read "not-there"') + assert.strictEqual(scope.isDone(), false) done() }) }) @@ -341,8 +343,8 @@ describe('git_metadata', () => { generatePackFilesForCommitsStub.returns([]) gitMetadata.sendGitMetadata(new URL('https://api.test.com'), { isEvpProxy: false }, '', (err) => { - expect(err.message).to.contain('Failed to generate packfiles') - expect(scope.isDone()).to.be.false + assertObjectContains(err.message, 'Failed to generate packfiles') + assert.strictEqual(scope.isDone(), false) done() }) }) @@ -359,8 +361,8 @@ describe('git_metadata', () => { .reply(204) gitMetadata.sendGitMetadata(new URL('https://api.test.com'), { isEvpProxy: false }, '', (err) => { - expect(err.message).to.contain('Git is not available') - expect(scope.isDone()).to.be.false + assertObjectContains(err.message, 'Git is not available') + assert.strictEqual(scope.isDone(), false) process.env.PATH = oldPath done() }) @@ -378,8 +380,8 @@ describe('git_metadata', () => { .reply(204) gitMetadata.sendGitMetadata(new URL('https://api.test.com'), { isEvpProxy: false }, '', (err) => { - expect(err).to.be.null - expect(scope.isDone()).to.be.true + assert.strictEqual(err, null) + assert.strictEqual(scope.isDone(), true) done() }) }) @@ -390,7 +392,7 @@ describe('git_metadata', () => { .reply(200, JSON.stringify({ data: [] })) .post('/evp_proxy/v2/api/v2/git/repository/packfile') .reply(204, function (uri, body) { - expect(this.req.headers['x-datadog-evp-subdomain']).to.equal('api') + assert.strictEqual(this.req.headers['x-datadog-evp-subdomain'], 'api') done() }) @@ -399,8 +401,8 @@ describe('git_metadata', () => { { isEvpProxy: true, evpProxyPrefix: '/evp_proxy/v2' }, '', (err) => { - expect(err).to.be.null - expect(scope.isDone()).to.be.true + assert.strictEqual(err, null) + assert.strictEqual(scope.isDone(), true) }) }) @@ -424,11 +426,11 @@ describe('git_metadata', () => { { isEvpProxy: true, evpProxyPrefix: '/evp_proxy/v2' }, 'https://custom-git@datadog.com', (err) => { - expect(err).to.be.null - expect(scope.isDone()).to.be.true + assert.strictEqual(err, null) + assert.strictEqual(scope.isDone(), true) requestPromise.then((repositoryUrl) => { - expect(getRepositoryUrlStub).not.to.have.been.called - expect(repositoryUrl).to.equal('https://custom-git@datadog.com') + sinon.assert.notCalled(getRepositoryUrlStub) + assert.strictEqual(repositoryUrl, 'https://custom-git@datadog.com') done() }) }) diff --git a/packages/dd-trace/test/datastreams/data_streams_checkpointer.spec.js b/packages/dd-trace/test/datastreams/data_streams_checkpointer.spec.js index c5adb9e042f..06a6e475427 100644 --- a/packages/dd-trace/test/datastreams/data_streams_checkpointer.spec.js +++ b/packages/dd-trace/test/datastreams/data_streams_checkpointer.spec.js @@ -1,6 +1,10 @@ 'use strict' +const assert = require('node:assert/strict') + const { expect } = require('chai') +const { assertObjectContains } = require('../../../../integration-tests/helpers') + const { describe, it, before, after } = require('tap').mocha const sinon = require('sinon') @@ -39,15 +43,15 @@ describe('data streams checkpointer manual api', () => { } } - expect(statsPointsReceived).to.equal(1) - expect(agent.dsmStatsExist(agent, expectedProducerHash, expectedEdgeTags)).to.equal(true) + assert.strictEqual(statsPointsReceived, 1) + assert.strictEqual(agent.dsmStatsExist(agent, expectedProducerHash, expectedEdgeTags), true) }, { timeoutMs: 5000 }).then(done, done) const headers = {} tracer.dataStreamsCheckpointer.setProduceCheckpoint('testProduce', 'test-queue', headers) - expect(DSM_CONTEXT_HEADER in headers).to.equal(true) + assert.strictEqual(DSM_CONTEXT_HEADER in headers, true) }) it('should set a checkpoint when calling setConsumeCheckpoint', function (done) { @@ -63,8 +67,8 @@ describe('data streams checkpointer manual api', () => { } } } - expect(statsPointsReceived).to.equal(2) - expect(agent.dsmStatsExist(agent, expectedConsumerHash, expectedEdgeTags)).to.equal(true) + assert.strictEqual(statsPointsReceived, 2) + assert.strictEqual(agent.dsmStatsExist(agent, expectedConsumerHash, expectedEdgeTags), true) }, { timeoutMs: 5000 }).then(done, done) const headers = { @@ -73,7 +77,7 @@ describe('data streams checkpointer manual api', () => { tracer.dataStreamsCheckpointer.setConsumeCheckpoint('testConsume', 'test-queue', headers) - expect(DSM_CONTEXT_HEADER in headers).to.equal(true) + assert.strictEqual(DSM_CONTEXT_HEADER in headers, true) }) it('should set manual checkpoint when setConsumeCheckpoint is called without additional parameters', function () { @@ -84,7 +88,7 @@ describe('data streams checkpointer manual api', () => { tracer.dataStreamsCheckpointer.setConsumeCheckpoint('kinesis', 'stream-123', headers) const calledTags = mockSetCheckpoint.getCall(0).args[0] - expect(calledTags).to.include('manual_checkpoint:true') + assertObjectContains(calledTags, 'manual_checkpoint:true') }) it('should set an automatic checkpoint when setConsumeCheckpoint is called with manualCheckpoint:false', function () { diff --git a/packages/dd-trace/test/datastreams/encoding.spec.js b/packages/dd-trace/test/datastreams/encoding.spec.js index 980cfc2538d..717fc2f85be 100644 --- a/packages/dd-trace/test/datastreams/encoding.spec.js +++ b/packages/dd-trace/test/datastreams/encoding.spec.js @@ -1,8 +1,6 @@ 'use strict' const assert = require('node:assert/strict') - -const { expect } = require('chai') const { describe, it } = require('tap').mocha require('../setup/core') @@ -16,7 +14,7 @@ describe('encoding', () => { const expectedEncoded = new Uint8Array([216, 150, 238, 193, 12]) const encoded = encodeVarint(n) assert.strictEqual(encoded.length, expectedEncoded.length) - expect(encoded.every((val, i) => val === expectedEncoded[i])).to.true + assert.strictEqual(encoded.every((val, i) => val === expectedEncoded[i]), true) const [decoded, bytes] = decodeVarint(encoded) assert.strictEqual(decoded, n) assert.strictEqual(bytes.length, 0) @@ -29,11 +27,11 @@ describe('encoding', () => { ]) const encoded = encodeVarint(n) assert.strictEqual(encoded.length, expectedEncoded.length) - expect(encoded.every((val, i) => val === expectedEncoded[i])).to.true + assert.strictEqual(encoded.every((val, i) => val === expectedEncoded[i]), true) const toDecode = [...encoded, ...encoded] const [decoded, bytes] = decodeVarint(toDecode) assert.strictEqual(decoded, n) - expect(bytes.every((val, i) => val === expectedEncoded[i])).to.true + assert.strictEqual(bytes.every((val, i) => val === expectedEncoded[i]), true) const [decoded2, bytes2] = decodeVarint(bytes) assert.strictEqual(decoded2, n) assert.strictEqual(bytes2.length, 0) @@ -42,7 +40,7 @@ describe('encoding', () => { it('encoding a number bigger than Max safe int fails.', () => { const n = Number.MAX_SAFE_INTEGER + 10 const encoded = encodeVarint(n) - expect(encoded).to.undefined + assert.strictEqual(encoded, undefined) }) }) }) diff --git a/packages/dd-trace/test/datastreams/processor.spec.js b/packages/dd-trace/test/datastreams/processor.spec.js index 7bda22dacd1..4225ea3ba54 100644 --- a/packages/dd-trace/test/datastreams/processor.spec.js +++ b/packages/dd-trace/test/datastreams/processor.spec.js @@ -93,7 +93,7 @@ describe('StatsBucket', () => { it('should add a new entry when no matching key is found', () => { const bucket = buckets.forCheckpoint(mockCheckpoint) const checkpoints = buckets.checkpoints - expect(bucket).to.be.an.instanceOf(StatsPoint) + assert.ok(bucket instanceof StatsPoint) assert.strictEqual(checkpoints.size, 1) const [key, value] = Array.from(checkpoints.entries())[0] assert.strictEqual(key.toString(), mockCheckpoint.hash.toString()) @@ -134,7 +134,7 @@ describe('StatsBucket', () => { it('should add a new entry when empty', () => { const bucket = backlogBuckets.forBacklog(mockBacklog) const backlogs = backlogBuckets.backlogs - expect(bucket).to.be.an.instanceOf(Backlog) + assert.ok(bucket instanceof Backlog) const [, value] = Array.from(backlogs.entries())[0] assert.ok(value instanceof Backlog) }) @@ -191,7 +191,7 @@ describe('TimeBuckets', () => { assert.strictEqual(buckets.size, 0) const bucket = buckets.forTime(12345) assert.strictEqual(buckets.size, 1) - expect(bucket).to.be.an.instanceOf(StatsBucket) + assert.ok(bucket instanceof StatsBucket) }) }) diff --git a/packages/dd-trace/test/debugger/devtools_client/json-buffer.spec.js b/packages/dd-trace/test/debugger/devtools_client/json-buffer.spec.js index 32f862bc7a6..1732e9ec2b0 100644 --- a/packages/dd-trace/test/debugger/devtools_client/json-buffer.spec.js +++ b/packages/dd-trace/test/debugger/devtools_client/json-buffer.spec.js @@ -2,7 +2,6 @@ const assert = require('node:assert/strict') -const { expect } = require('chai') const { describe, it } = require('mocha') require('../../setup/mocha') @@ -15,7 +14,7 @@ describe('JSONBuffer', () => { const onFlush = (json) => { const diff = Date.now() - start assert.strictEqual(json, '[{"message":1},{"message":2},{"message":3}]') - expect(diff).to.be.within(95, 110) + assert.ok(((diff) >= (95) && (diff) <= (110))) done() } diff --git a/packages/dd-trace/test/debugger/devtools_client/send.spec.js b/packages/dd-trace/test/debugger/devtools_client/send.spec.js index a223d8d34cd..b6c608ff77c 100644 --- a/packages/dd-trace/test/debugger/devtools_client/send.spec.js +++ b/packages/dd-trace/test/debugger/devtools_client/send.spec.js @@ -2,8 +2,6 @@ const assert = require('node:assert/strict') require('../../setup/mocha') - -const { expect } = require('chai') const { afterEach, beforeEach, describe, it } = require('mocha') const proxyquire = require('proxyquire') const sinon = require('sinon') @@ -95,16 +93,14 @@ describe('input message http requests', function () { const opts = getRequestOptions(request) assert.strictEqual(opts.method, 'POST') - expect(opts).to.have.property( - 'path', - '/debugger/v1/input?ddtags=' + + assert.ok('path' in opts); + assert.strictEqual(opts['path'], '/debugger/v1/input?ddtags=' + `env%3A${process.env.DD_ENV}%2C` + `version%3A${process.env.DD_VERSION}%2C` + `debugger_version%3A${version}%2C` + `host_name%3A${hostname}%2C` + `git.commit.sha%3A${commitSHA}%2C` + - `git.repository_url%3A${repositoryUrl}` - ) + `git.repository_url%3A${repositoryUrl}`) done() }) diff --git a/packages/dd-trace/test/debugger/devtools_client/snapshot/complex-types.spec.js b/packages/dd-trace/test/debugger/devtools_client/snapshot/complex-types.spec.js index bafd7e85724..ecfcb28d0b1 100644 --- a/packages/dd-trace/test/debugger/devtools_client/snapshot/complex-types.spec.js +++ b/packages/dd-trace/test/debugger/devtools_client/snapshot/complex-types.spec.js @@ -2,10 +2,9 @@ const assert = require('node:assert/strict') -const { expect } = require('chai') const { afterEach, beforeEach, describe, it } = require('mocha') -const { assertObjectContains } = require('../../../../../../integration-tests/helpers') +const { assertObjectContains } = require('../../../../../../integration-tests/helpers') require('../../../setup/mocha') const { @@ -53,7 +52,8 @@ describe('debugger -> devtools client -> snapshot.getLocalStateForCallFrame', fu // ... tested individually in the remaining it-blocks inside this describe-block // from closure scope - expect(state).to.have.deep.property('ref', { + assert.ok('ref' in state); +assert.deepStrictEqual(state['ref'], { type: 'Object', fields: { wmo1: { type: 'Object', fields: { a: { type: 'number', value: '1' } } }, @@ -63,7 +63,8 @@ describe('debugger -> devtools client -> snapshot.getLocalStateForCallFrame', fu wso3: { type: 'Object', fields: { a: { type: 'number', value: '3' } } } } }) - expect(state).to.have.deep.property('get', { + assert.ok('get' in state); +assert.deepStrictEqual(state['get'], { type: 'Function', fields: { length: { type: 'number', value: '0' }, @@ -73,7 +74,8 @@ describe('debugger -> devtools client -> snapshot.getLocalStateForCallFrame', fu }) it('object literal', function () { - expect(state).to.have.deep.property('oblit', { + assert.ok('oblit' in state); +assert.deepStrictEqual(state['oblit'], { type: 'Object', fields: { a: { type: 'number', value: '1' }, @@ -88,7 +90,8 @@ describe('debugger -> devtools client -> snapshot.getLocalStateForCallFrame', fu }) it('custom object from class', function () { - expect(state).to.have.deep.property('obnew', { + assert.ok('obnew' in state); +assert.deepStrictEqual(state['obnew'], { type: 'MyClass', fields: { foo: { type: 'number', value: '42' }, @@ -98,7 +101,8 @@ describe('debugger -> devtools client -> snapshot.getLocalStateForCallFrame', fu }) it('Array', function () { - expect(state).to.have.deep.property('arr', { + assert.ok('arr' in state); +assert.deepStrictEqual(state['arr'], { type: 'Array', elements: [ { type: 'number', value: '1' }, @@ -109,18 +113,21 @@ describe('debugger -> devtools client -> snapshot.getLocalStateForCallFrame', fu }) it('RegExp', function () { - expect(state).to.have.deep.property('regex', { type: 'RegExp', value: '/foo/' }) + assert.ok('regex' in state); +assert.deepStrictEqual(state['regex'], { type: 'RegExp', value: '/foo/' }) }) it('Date', function () { - expect(state).to.have.deep.property('date', { + assert.ok('date' in state); +assert.deepStrictEqual(state['date'], { type: 'Date', value: '2024-09-20T07:22:59Z' // missing milliseconds due to API limitation (should have been `998`) }) }) it('Map', function () { - expect(state).to.have.deep.property('map', { + assert.ok('map' in state); +assert.deepStrictEqual(state['map'], { type: 'Map', entries: [ [{ type: 'number', value: '1' }, { type: 'number', value: '2' }], @@ -130,7 +137,8 @@ describe('debugger -> devtools client -> snapshot.getLocalStateForCallFrame', fu }) it('Set', function () { - expect(state).to.have.deep.property('set', { + assert.ok('set' in state); +assert.deepStrictEqual(state['set'], { type: 'Set', elements: [ { @@ -148,10 +156,12 @@ describe('debugger -> devtools client -> snapshot.getLocalStateForCallFrame', fu it('WeakMap', function () { assert.ok(Object.hasOwn(state, 'wmap')) - expect(state.wmap).to.have.keys('type', 'entries') + assert.strictEqual(Object.keys(state.wmap).length, (['type', 'entries']).length) +assert.ok((['type', 'entries']).every(k => Object.hasOwn(state.wmap, k))) assert.ok(Array.isArray(state.wmap.entries)) state.wmap.entries = state.wmap.entries.sort((a, b) => a[1].value - b[1].value) - expect(state).to.have.deep.property('wmap', { + assert.ok('wmap' in state); +assert.deepStrictEqual(state['wmap'], { type: 'WeakMap', entries: [[ { type: 'Object', fields: { a: { type: 'number', value: '1' } } }, @@ -165,10 +175,12 @@ describe('debugger -> devtools client -> snapshot.getLocalStateForCallFrame', fu it('WeakSet', function () { assert.ok(Object.hasOwn(state, 'wset')) - expect(state.wset).to.have.keys('type', 'elements') + assert.strictEqual(Object.keys(state.wset).length, (['type', 'elements']).length) +assert.ok((['type', 'elements']).every(k => Object.hasOwn(state.wset, k))) assert.ok(Array.isArray(state.wset.elements)) state.wset.elements = state.wset.elements.sort((a, b) => a.fields.a.value - b.fields.a.value) - expect(state).to.have.deep.property('wset', { + assert.ok('wset' in state); +assert.deepStrictEqual(state['wset'], { type: 'WeakSet', elements: [ { type: 'Object', fields: { a: { type: 'number', value: '1' } } }, @@ -179,7 +191,8 @@ describe('debugger -> devtools client -> snapshot.getLocalStateForCallFrame', fu }) it('Generator', function () { - expect(state).to.have.deep.property('gen', { + assert.ok('gen' in state); +assert.deepStrictEqual(state['gen'], { type: 'generator', fields: { foo: { type: 'number', value: '42' } } }) @@ -187,19 +200,22 @@ describe('debugger -> devtools client -> snapshot.getLocalStateForCallFrame', fu it('Error', function () { assert.ok(Object.hasOwn(state, 'err')) - expect(state.err).to.have.keys('type', 'fields') + assert.strictEqual(Object.keys(state.err).length, (['type', 'fields']).length) +assert.ok((['type', 'fields']).every(k => Object.hasOwn(state.err, k))) assert.strictEqual(state.err.type, 'CustomError') assert.ok(typeof state.err.fields === 'object' && state.err.fields !== null) - expect(state.err.fields).to.have.keys('stack', 'message', 'foo') - expect(state.err.fields).to.deep.include({ + assert.strictEqual(Object.keys(state.err.fields).length, (['stack', 'message', 'foo']).length) +assert.ok((['stack', 'message', 'foo']).every(k => Object.hasOwn(state.err.fields, k))) + assertObjectContains(state.err.fields, { message: { type: 'string', value: 'boom!' }, foo: { type: 'number', value: '42' } }) - expect(state.err.fields.stack).to.have.keys('type', 'value', 'truncated', 'size') + assert.strictEqual(Object.keys(state.err.fields.stack).length, (['type', 'value', 'truncated', 'size']).length) +assert.ok((['type', 'value', 'truncated', 'size']).every(k => Object.hasOwn(state.err.fields.stack, k))) assert.strictEqual(typeof state.err.fields.stack.value, 'string') assert.match(state.err.fields.stack.value, /^Error: boom!/) assert.strictEqual(typeof state.err.fields.stack.size, 'number') - expect(state.err.fields.stack.size).to.above(255) + assert.ok(((state.err.fields.stack.size) > (255))) assertObjectContains(state.err.fields.stack, { type: 'string', truncated: true @@ -207,7 +223,8 @@ describe('debugger -> devtools client -> snapshot.getLocalStateForCallFrame', fu }) it('Function', function () { - expect(state).to.have.deep.property('fn', { + assert.ok('fn' in state); +assert.deepStrictEqual(state['fn'], { type: 'Function', fields: { foo: { @@ -221,7 +238,8 @@ describe('debugger -> devtools client -> snapshot.getLocalStateForCallFrame', fu }) it('Bound function', function () { - expect(state).to.have.deep.property('bfn', { + assert.ok('bfn' in state); +assert.deepStrictEqual(state['bfn'], { type: 'Function', fields: { length: { type: 'number', value: '0' }, @@ -231,7 +249,8 @@ describe('debugger -> devtools client -> snapshot.getLocalStateForCallFrame', fu }) it('Arrow function', function () { - expect(state).to.have.deep.property('afn', { + assert.ok('afn' in state); +assert.deepStrictEqual(state['afn'], { type: 'Function', fields: { length: { type: 'number', value: '0' }, @@ -241,15 +260,18 @@ describe('debugger -> devtools client -> snapshot.getLocalStateForCallFrame', fu }) it('Class', function () { - expect(state).to.have.deep.property('cls', { type: 'class MyClass' }) + assert.ok('cls' in state); +assert.deepStrictEqual(state['cls'], { type: 'class MyClass' }) }) it('Anonymous class', function () { - expect(state).to.have.deep.property('acls', { type: 'class' }) + assert.ok('acls' in state); +assert.deepStrictEqual(state['acls'], { type: 'class' }) }) it('Proxy for object literal', function () { - expect(state).to.have.deep.property('prox', { + assert.ok('prox' in state); +assert.deepStrictEqual(state['prox'], { type: NODE_20_PLUS ? 'Proxy(Object)' : 'Proxy', fields: { target: { type: 'boolean', value: 'true' } @@ -258,7 +280,8 @@ describe('debugger -> devtools client -> snapshot.getLocalStateForCallFrame', fu }) it('Proxy for custom class', function () { - expect(state).to.have.deep.property('custProx', { + assert.ok('custProx' in state); +assert.deepStrictEqual(state['custProx'], { type: NODE_20_PLUS ? 'Proxy(MyClass)' : 'Proxy', fields: { foo: { type: 'number', value: '42' } @@ -267,7 +290,8 @@ describe('debugger -> devtools client -> snapshot.getLocalStateForCallFrame', fu }) it('Promise: Pending', function () { - expect(state).to.have.deep.property('pPen', { + assert.ok('pPen' in state); +assert.deepStrictEqual(state['pPen'], { type: 'Promise', fields: { '[[PromiseState]]': { type: 'string', value: 'pending' }, @@ -277,7 +301,8 @@ describe('debugger -> devtools client -> snapshot.getLocalStateForCallFrame', fu }) it('Promise: Resolved', function () { - expect(state).to.have.deep.property('pRes', { + assert.ok('pRes' in state); +assert.deepStrictEqual(state['pRes'], { type: 'Promise', fields: { '[[PromiseState]]': { type: 'string', value: 'fulfilled' }, @@ -287,7 +312,8 @@ describe('debugger -> devtools client -> snapshot.getLocalStateForCallFrame', fu }) it('Promise: Rejected', function () { - expect(state).to.have.deep.property('pRej', { + assert.ok('pRej' in state); +assert.deepStrictEqual(state['pRej'], { type: 'Promise', fields: { '[[PromiseState]]': { type: 'string', value: 'rejected' }, @@ -297,7 +323,8 @@ describe('debugger -> devtools client -> snapshot.getLocalStateForCallFrame', fu }) it('TypedArray', function () { - expect(state).to.have.deep.property('tarr', { + assert.ok('tarr' in state); +assert.deepStrictEqual(state['tarr'], { type: 'Int8Array', elements: [ { type: 'number', value: '72' }, @@ -308,14 +335,16 @@ describe('debugger -> devtools client -> snapshot.getLocalStateForCallFrame', fu }) it('ArrayBuffer', function () { - expect(state).to.have.deep.property('ab', { + assert.ok('ab' in state); +assert.deepStrictEqual(state['ab'], { type: 'ArrayBuffer', value: 'HAL' }) }) it('SharedArrayBuffer', function () { - expect(state).to.have.deep.property('sab', { + assert.ok('sab' in state); +assert.deepStrictEqual(state['sab'], { type: 'SharedArrayBuffer', value: 'hello\x01\x02\x03world' }) @@ -326,13 +355,14 @@ describe('debugger -> devtools client -> snapshot.getLocalStateForCallFrame', fu assert.strictEqual(state.circular.type, 'Object') assert.ok(Object.hasOwn(state.circular, 'fields')) // For the circular field, just check that at least one of the expected properties are present - expect(state.circular.fields).to.deep.include({ + assertObjectContains(state.circular.fields, { regex: { type: 'RegExp', value: '/foo/' } }) }) it('non-enumerable property', function () { - expect(state).to.have.deep.property('hidden', { type: 'string', value: 'secret' }) + assert.ok('hidden' in state); +assert.deepStrictEqual(state['hidden'], { type: 'string', value: 'secret' }) }) }) }) diff --git a/packages/dd-trace/test/debugger/devtools_client/snapshot/max-collection-size.spec.js b/packages/dd-trace/test/debugger/devtools_client/snapshot/max-collection-size.spec.js index a3735a92d63..49171b25d1b 100644 --- a/packages/dd-trace/test/debugger/devtools_client/snapshot/max-collection-size.spec.js +++ b/packages/dd-trace/test/debugger/devtools_client/snapshot/max-collection-size.spec.js @@ -2,10 +2,9 @@ const assert = require('node:assert/strict') -const { expect } = require('chai') const { afterEach, beforeEach, describe, it } = require('mocha') -const { assertObjectContains } = require('../../../../../../integration-tests/helpers') +const { assertObjectContains } = require('../../../../../../integration-tests/helpers') require('../../../setup/mocha') const { getTargetCodePath, enable, teardown, assertOnBreakpoint, setAndTriggerBreakpoint } = require('./utils') @@ -55,11 +54,13 @@ describe('debugger -> devtools client -> snapshot.getLocalStateForCallFrame', fu }) it('should have expected number of elements in state', function () { - expect(state).to.have.keys(['LARGE_SIZE', 'arr', 'map', 'set', 'wmap', 'wset', 'typedArray']) + assert.strictEqual(Object.keys(state).length, ((Array.isArray(['LARGE_SIZE', 'arr', 'map', 'set', 'wmap', 'wset', 'typedArray']) ? ['LARGE_SIZE', 'arr', 'map', 'set', 'wmap', 'wset', 'typedArray'] : [['LARGE_SIZE', 'arr', 'map', 'set', 'wmap', 'wset', 'typedArray']])).length) +assert.ok(((Array.isArray(['LARGE_SIZE', 'arr', 'map', 'set', 'wmap', 'wset', 'typedArray']) ? ['LARGE_SIZE', 'arr', 'map', 'set', 'wmap', 'wset', 'typedArray'] : [['LARGE_SIZE', 'arr', 'map', 'set', 'wmap', 'wset', 'typedArray']])).every(k => Object.hasOwn(state, k))) }) it('Array', function () { - expect(state).to.have.deep.property('arr', { + assert.ok('arr' in state); +assert.deepStrictEqual(state['arr'], { type: 'Array', elements: expectedElements, notCapturedReason: 'collectionSize', @@ -68,7 +69,8 @@ describe('debugger -> devtools client -> snapshot.getLocalStateForCallFrame', fu }) it('Map', function () { - expect(state).to.have.deep.property('map', { + assert.ok('map' in state); +assert.deepStrictEqual(state['map'], { type: 'Map', entries: expectedEntries, notCapturedReason: 'collectionSize', @@ -77,7 +79,8 @@ describe('debugger -> devtools client -> snapshot.getLocalStateForCallFrame', fu }) it('Set', function () { - expect(state).to.have.deep.property('set', { + assert.ok('set' in state); +assert.deepStrictEqual(state['set'], { type: 'Set', elements: expectedElements, notCapturedReason: 'collectionSize', @@ -127,7 +130,8 @@ describe('debugger -> devtools client -> snapshot.getLocalStateForCallFrame', fu }) it('TypedArray', function () { - expect(state).to.have.deep.property('typedArray', { + assert.ok('typedArray' in state); +assert.deepStrictEqual(state['typedArray'], { type: 'Uint16Array', elements: expectedElements, notCapturedReason: 'collectionSize', diff --git a/packages/dd-trace/test/debugger/devtools_client/snapshot/max-field-count-scopes.spec.js b/packages/dd-trace/test/debugger/devtools_client/snapshot/max-field-count-scopes.spec.js index 3c7289605da..0234c43b415 100644 --- a/packages/dd-trace/test/debugger/devtools_client/snapshot/max-field-count-scopes.spec.js +++ b/packages/dd-trace/test/debugger/devtools_client/snapshot/max-field-count-scopes.spec.js @@ -1,8 +1,8 @@ 'use strict' -const { expect } = require('chai') -const { describe, it, beforeEach, afterEach } = require('mocha') +const assert = require('node:assert/strict') +const { afterEach, beforeEach, describe, it } = require('mocha') require('../../../setup/mocha') const { getTargetCodePath, enable, teardown, assertOnBreakpoint, setAndTriggerBreakpoint } = require('./utils') @@ -28,7 +28,8 @@ describe('debugger -> devtools client -> snapshot.getLocalStateForCallFrame', fu it('should capture expected snapshot', function () { // Expect the snapshot to have captured the first 3 fields from each scope - expect(state).to.have.keys(['a1', 'b1', 'c1', 'a2', 'b2', 'c2']) + assert.strictEqual(Object.keys(state).length, ((Array.isArray(['a1', 'b1', 'c1', 'a2', 'b2', 'c2']) ? ['a1', 'b1', 'c1', 'a2', 'b2', 'c2'] : [['a1', 'b1', 'c1', 'a2', 'b2', 'c2']])).length) +assert.ok(((Array.isArray(['a1', 'b1', 'c1', 'a2', 'b2', 'c2']) ? ['a1', 'b1', 'c1', 'a2', 'b2', 'c2'] : [['a1', 'b1', 'c1', 'a2', 'b2', 'c2']])).every(k => Object.hasOwn(state, k))) }) }) }) diff --git a/packages/dd-trace/test/debugger/devtools_client/snapshot/max-field-count.spec.js b/packages/dd-trace/test/debugger/devtools_client/snapshot/max-field-count.spec.js index 2b907bb6d96..4b007d4022a 100644 --- a/packages/dd-trace/test/debugger/devtools_client/snapshot/max-field-count.spec.js +++ b/packages/dd-trace/test/debugger/devtools_client/snapshot/max-field-count.spec.js @@ -1,8 +1,8 @@ 'use strict' -const { expect } = require('chai') -const { describe, it, beforeEach, afterEach } = require('mocha') +const assert = require('node:assert/strict') +const { afterEach, beforeEach, describe, it } = require('mocha') require('../../../setup/mocha') const { getTargetCodePath, enable, teardown, assertOnBreakpoint, setAndTriggerBreakpoint } = require('./utils') @@ -40,8 +40,10 @@ function generateTestCases (config) { }) it('should capture expected snapshot', function () { - expect(state).to.have.keys(['obj']) - expect(state).to.have.deep.property('obj', { + assert.strictEqual(Object.keys(state).length, ((Array.isArray(['obj']) ? ['obj'] : [['obj']])).length) +assert.ok(((Array.isArray(['obj']) ? ['obj'] : [['obj']])).every(k => Object.hasOwn(state, k))) + assert.ok('obj' in state); +assert.deepStrictEqual(state['obj'], { type: 'Object', fields: expectedFields, notCapturedReason: 'fieldCount', diff --git a/packages/dd-trace/test/debugger/devtools_client/snapshot/max-reference-depth.spec.js b/packages/dd-trace/test/debugger/devtools_client/snapshot/max-reference-depth.spec.js index c0bcd86852c..4ae378f0e00 100644 --- a/packages/dd-trace/test/debugger/devtools_client/snapshot/max-reference-depth.spec.js +++ b/packages/dd-trace/test/debugger/devtools_client/snapshot/max-reference-depth.spec.js @@ -2,7 +2,6 @@ const assert = require('node:assert/strict') -const { expect } = require('chai') const { afterEach, beforeEach, describe, it } = require('mocha') require('../../../setup/mocha') @@ -25,11 +24,13 @@ describe('debugger -> devtools client -> snapshot.getLocalStateForCallFrame', fu assert.ok(Object.hasOwn(state.myNestedObj, 'fields')) assert.strictEqual(Object.keys(state.myNestedObj).length, 2) - expect(state.myNestedObj.fields).to.have.deep.property('deepObj', { + assert.ok('deepObj' in state.myNestedObj.fields); +assert.deepStrictEqual(state.myNestedObj.fields['deepObj'], { type: 'Object', notCapturedReason: 'depth' }) - expect(state.myNestedObj.fields).to.have.deep.property('deepArr', { + assert.ok('deepArr' in state.myNestedObj.fields); +assert.deepStrictEqual(state.myNestedObj.fields['deepArr'], { type: 'Array', notCapturedReason: 'depth' }) }) @@ -46,7 +47,8 @@ describe('debugger -> devtools client -> snapshot.getLocalStateForCallFrame', fu assert.ok(Object.hasOwn(state.myNestedObj, 'fields')) assert.strictEqual(Object.entries(state.myNestedObj).length, 2) - expect(state.myNestedObj.fields).to.have.deep.property('deepObj', { + assert.ok('deepObj' in state.myNestedObj.fields); +assert.deepStrictEqual(state.myNestedObj.fields['deepObj'], { type: 'Object', fields: { foo: { @@ -68,7 +70,8 @@ describe('debugger -> devtools client -> snapshot.getLocalStateForCallFrame', fu } }) - expect(state.myNestedObj.fields).to.have.deep.property('deepArr', { + assert.ok('deepArr' in state.myNestedObj.fields); +assert.deepStrictEqual(state.myNestedObj.fields['deepArr'], { type: 'Array', elements: [{ type: 'Array', @@ -95,7 +98,8 @@ describe('debugger -> devtools client -> snapshot.getLocalStateForCallFrame', fu assert.ok(Object.hasOwn(state.myNestedObj, 'fields')) assert.strictEqual(Object.entries(state.myNestedObj).length, 2) - expect(state.myNestedObj.fields).to.have.deep.property('deepObj', { + assert.ok('deepObj' in state.myNestedObj.fields); +assert.deepStrictEqual(state.myNestedObj.fields['deepObj'], { type: 'Object', fields: { foo: { @@ -110,7 +114,8 @@ describe('debugger -> devtools client -> snapshot.getLocalStateForCallFrame', fu } }) - expect(state.myNestedObj.fields).to.have.deep.property('deepArr', { + assert.ok('deepArr' in state.myNestedObj.fields); +assert.deepStrictEqual(state.myNestedObj.fields['deepArr'], { type: 'Array', elements: [{ type: 'Array', diff --git a/packages/dd-trace/test/debugger/devtools_client/snapshot/primitives.spec.js b/packages/dd-trace/test/debugger/devtools_client/snapshot/primitives.spec.js index 63ed6a24030..6cacb6313ad 100644 --- a/packages/dd-trace/test/debugger/devtools_client/snapshot/primitives.spec.js +++ b/packages/dd-trace/test/debugger/devtools_client/snapshot/primitives.spec.js @@ -2,7 +2,6 @@ const assert = require('node:assert/strict') -const { expect } = require('chai') const { afterEach, beforeEach, describe, it } = require('mocha') require('../../../setup/mocha') @@ -19,13 +18,20 @@ describe('debugger -> devtools client -> snapshot.getLocalStateForCallFrame', fu it('should return expected object for primitives', function (done) { assertOnBreakpoint(done, (state) => { assert.strictEqual(Object.keys(state).length, 7) - expect(state).to.have.deep.property('undef', { type: 'undefined' }) - expect(state).to.have.deep.property('nil', { type: 'null', isNull: true }) - expect(state).to.have.deep.property('bool', { type: 'boolean', value: 'true' }) - expect(state).to.have.deep.property('num', { type: 'number', value: '42' }) - expect(state).to.have.deep.property('bigint', { type: 'bigint', value: '18014398509481982' }) - expect(state).to.have.deep.property('str', { type: 'string', value: 'foo' }) - expect(state).to.have.deep.property('sym', { type: 'symbol', value: 'Symbol(foo)' }) + assert.ok('undef' in state); +assert.deepStrictEqual(state['undef'], { type: 'undefined' }) + assert.ok('nil' in state); +assert.deepStrictEqual(state['nil'], { type: 'null', isNull: true }) + assert.ok('bool' in state); +assert.deepStrictEqual(state['bool'], { type: 'boolean', value: 'true' }) + assert.ok('num' in state); +assert.deepStrictEqual(state['num'], { type: 'number', value: '42' }) + assert.ok('bigint' in state); +assert.deepStrictEqual(state['bigint'], { type: 'bigint', value: '18014398509481982' }) + assert.ok('str' in state); +assert.deepStrictEqual(state['str'], { type: 'string', value: 'foo' }) + assert.ok('sym' in state); +assert.deepStrictEqual(state['sym'], { type: 'symbol', value: 'Symbol(foo)' }) }) setAndTriggerBreakpoint(target, 13) diff --git a/packages/dd-trace/test/debugger/devtools_client/snapshot/redaction.spec.js b/packages/dd-trace/test/debugger/devtools_client/snapshot/redaction.spec.js index cbe249d4728..ae0b0e35fdc 100644 --- a/packages/dd-trace/test/debugger/devtools_client/snapshot/redaction.spec.js +++ b/packages/dd-trace/test/debugger/devtools_client/snapshot/redaction.spec.js @@ -2,8 +2,6 @@ const assert = require('node:assert/strict') require('../../../setup/mocha') - -const { expect } = require('chai') const { getTargetCodePath, enable, teardown, assertOnBreakpoint, setAndTriggerBreakpoint } = require('./utils') const target = getTargetCodePath(__filename) @@ -18,38 +16,45 @@ describe('debugger -> devtools client -> snapshot.getLocalStateForCallFrame', fu // Non-default configuration is tested in the integration tests it('should replace PII in keys/properties/variables with expected notCapturedReason', function (done) { assertOnBreakpoint(done, (state) => { - expect(state).to.have.all.keys( - 'nonNormalizedSecretToken', 'foo', 'secret', 'Se_cret_$', 'weakMapKey', 'obj' - ) + assert.strictEqual(Object.keys(state).length, (['nonNormalizedSecretToken', 'foo', 'secret', 'Se_cret_$', 'weakMapKey', 'obj']).length) +assert.ok((['nonNormalizedSecretToken', 'foo', 'secret', 'Se_cret_$', 'weakMapKey', 'obj']).every(k => Object.hasOwn(state, k))) - expect(state).to.have.deep.property('foo', { type: 'string', value: 'bar' }) - expect(state).to.have.deep.property('secret', { type: 'string', notCapturedReason: 'redactedIdent' }) - expect(state).to.have.deep.property('Se_cret_$', { type: 'string', notCapturedReason: 'redactedIdent' }) - expect(state).to.have.deep.property('weakMapKey', { + assert.ok('foo' in state); +assert.deepStrictEqual(state['foo'], { type: 'string', value: 'bar' }) + assert.ok('secret' in state); +assert.deepStrictEqual(state['secret'], { type: 'string', notCapturedReason: 'redactedIdent' }) + assert.ok('Se_cret_$' in state); +assert.deepStrictEqual(state['Se_cret_$'], { type: 'string', notCapturedReason: 'redactedIdent' }) + assert.ok('weakMapKey' in state); +assert.deepStrictEqual(state['weakMapKey'], { type: 'Object', fields: { secret: { type: 'string', notCapturedReason: 'redactedIdent' } } }) - expect(state).to.have.deep.property('obj') + assert.ok('obj' in state) assert.strictEqual(state.obj.type, 'Object') const { fields } = state.obj - expect(fields).to.have.all.keys( - 'foo', 'secret', '@Se-cret_$_', 'nested', 'arr', 'map', 'weakmap', 'password', - 'Symbol(secret)', 'Symbol(@Se-cret_$_)' - ) + assert.strictEqual(Object.keys(fields).length, (['foo', 'secret', '@Se-cret_$_', 'nested', 'arr', 'map', 'weakmap', 'password', 'Symbol(secret)', 'Symbol(@Se-cret_$_)']).length) +assert.ok((['foo', 'secret', '@Se-cret_$_', 'nested', 'arr', 'map', 'weakmap', 'password', 'Symbol(secret)', 'Symbol(@Se-cret_$_)']).every(k => Object.hasOwn(fields, k))) - expect(fields).to.have.deep.property('foo', { type: 'string', value: 'bar' }) - expect(fields).to.have.deep.property('secret', { type: 'string', notCapturedReason: 'redactedIdent' }) - expect(fields).to.have.deep.property('@Se-cret_$_', { type: 'string', notCapturedReason: 'redactedIdent' }) - expect(fields).to.have.deep.property('nested', { + assert.ok('foo' in fields); +assert.deepStrictEqual(fields['foo'], { type: 'string', value: 'bar' }) + assert.ok('secret' in fields); +assert.deepStrictEqual(fields['secret'], { type: 'string', notCapturedReason: 'redactedIdent' }) + assert.ok('@Se-cret_$_' in fields); +assert.deepStrictEqual(fields['@Se-cret_$_'], { type: 'string', notCapturedReason: 'redactedIdent' }) + assert.ok('nested' in fields); +assert.deepStrictEqual(fields['nested'], { type: 'Object', fields: { secret: { type: 'string', notCapturedReason: 'redactedIdent' } } }) - expect(fields).to.have.deep.property('arr', { + assert.ok('arr' in fields); +assert.deepStrictEqual(fields['arr'], { type: 'Array', elements: [{ type: 'Object', fields: { secret: { type: 'string', notCapturedReason: 'redactedIdent' } } }] }) - expect(fields).to.have.deep.property('map', { + assert.ok('map' in fields); +assert.deepStrictEqual(fields['map'], { type: 'Map', entries: [ [ @@ -74,15 +79,18 @@ describe('debugger -> devtools client -> snapshot.getLocalStateForCallFrame', fu ] ] }) - expect(fields).to.have.deep.property('weakmap', { + assert.ok('weakmap' in fields); +assert.deepStrictEqual(fields['weakmap'], { type: 'WeakMap', entries: [[ { type: 'Object', fields: { secret: { type: 'string', notCapturedReason: 'redactedIdent' } } }, { type: 'number', value: '42' } ]] }) - expect(fields).to.have.deep.property('password', { type: 'string', notCapturedReason: 'redactedIdent' }) - expect(fields).to.have.deep.property('Symbol(secret)', { type: 'string', notCapturedReason: 'redactedIdent' }) + assert.ok('password' in fields); +assert.deepStrictEqual(fields['password'], { type: 'string', notCapturedReason: 'redactedIdent' }) + assert.ok('Symbol(secret)' in fields); +assert.deepStrictEqual(fields['Symbol(secret)'], { type: 'string', notCapturedReason: 'redactedIdent' }) }) setAndTriggerBreakpoint(target, BREAKPOINT_LINE_NUMBER) diff --git a/packages/dd-trace/test/debugger/devtools_client/snapshot/scopes.spec.js b/packages/dd-trace/test/debugger/devtools_client/snapshot/scopes.spec.js index 5f0ffde29b8..14e59ded9f8 100644 --- a/packages/dd-trace/test/debugger/devtools_client/snapshot/scopes.spec.js +++ b/packages/dd-trace/test/debugger/devtools_client/snapshot/scopes.spec.js @@ -2,7 +2,6 @@ const assert = require('node:assert/strict') -const { expect } = require('chai') const { afterEach, beforeEach, describe, it } = require('mocha') require('../../../setup/mocha') @@ -20,11 +19,16 @@ describe('debugger -> devtools client -> snapshot.getLocalStateForCallFrame', fu assertOnBreakpoint(done, (state) => { assert.strictEqual(Object.entries(state).length, 5) - expect(state).to.have.deep.property('a1', { type: 'number', value: '1' }) - expect(state).to.have.deep.property('a2', { type: 'number', value: '2' }) - expect(state).to.have.deep.property('total', { type: 'number', value: '0' }) - expect(state).to.have.deep.property('i', { type: 'number', value: '0' }) - expect(state).to.have.deep.property('inc', { type: 'number', value: '2' }) + assert.ok('a1' in state); +assert.deepStrictEqual(state['a1'], { type: 'number', value: '1' }) + assert.ok('a2' in state); +assert.deepStrictEqual(state['a2'], { type: 'number', value: '2' }) + assert.ok('total' in state); +assert.deepStrictEqual(state['total'], { type: 'number', value: '0' }) + assert.ok('i' in state); +assert.deepStrictEqual(state['i'], { type: 'number', value: '0' }) + assert.ok('inc' in state); +assert.deepStrictEqual(state['inc'], { type: 'number', value: '2' }) }) setAndTriggerBreakpoint(target, 13) diff --git a/packages/dd-trace/test/debugger/devtools_client/snapshot/time-budget.spec.js b/packages/dd-trace/test/debugger/devtools_client/snapshot/time-budget.spec.js index 3de3f1a75f9..59223278910 100644 --- a/packages/dd-trace/test/debugger/devtools_client/snapshot/time-budget.spec.js +++ b/packages/dd-trace/test/debugger/devtools_client/snapshot/time-budget.spec.js @@ -1,6 +1,6 @@ 'use strict' -const { assert } = require('chai') +const assert = require('node:assert/strict') const proxyquire = require('proxyquire') const { timeBudgetSym } = require('../../../../src/debugger/devtools_client/snapshot/symbols') @@ -38,7 +38,7 @@ describe('Debugger snapshot time budget', () => { }] const out = processRawState(raw, MAX_LENGTH) - assert.deepEqual(out.fn, { + assert.deepStrictEqual(out.fn, { type: 'Function', notCapturedReason: 'timeout' }) @@ -55,7 +55,7 @@ describe('Debugger snapshot time budget', () => { }] const out = processRawState(raw, MAX_LENGTH) - assert.deepEqual(out.obj, { + assert.deepStrictEqual(out.obj, { type: 'Object', notCapturedReason: 'timeout' }) @@ -73,7 +73,7 @@ describe('Debugger snapshot time budget', () => { }] const out = processRawState(raw, MAX_LENGTH) - assert.deepEqual(out.arr, { + assert.deepStrictEqual(out.arr, { type: 'Array', notCapturedReason: 'timeout' }) @@ -101,7 +101,7 @@ describe('Debugger snapshot time budget', () => { }] const out = processRawState(raw, MAX_LENGTH) - assert.deepEqual(out.map, { + assert.deepStrictEqual(out.map, { type: 'Map', notCapturedReason: 'timeout' }) @@ -129,7 +129,7 @@ describe('Debugger snapshot time budget', () => { }] const out = processRawState(raw, MAX_LENGTH) - assert.deepEqual(out.set, { + assert.deepStrictEqual(out.set, { type: 'Set', notCapturedReason: 'timeout' }) diff --git a/packages/dd-trace/test/debugger/devtools_client/source-maps.spec.js b/packages/dd-trace/test/debugger/devtools_client/source-maps.spec.js index 41f667a4e90..d726573f0ac 100644 --- a/packages/dd-trace/test/debugger/devtools_client/source-maps.spec.js +++ b/packages/dd-trace/test/debugger/devtools_client/source-maps.spec.js @@ -2,7 +2,6 @@ const assert = require('node:assert/strict') -const { expect } = require('chai') const { after, before, beforeEach, describe, it } = require('mocha') const proxyquire = require('proxyquire') const sinon = require('sinon') @@ -71,9 +70,9 @@ describe('source map utils', function () { }) it('should throw if inline source map is invalid', function () { - expect(() => { + assert.throws(() => { loadSourceMapSync(dir, inlineSourceMap.slice(0, -10)) - }).to.throw() + }) }) it('should return parsed source map', function () { diff --git a/packages/dd-trace/test/encode/0.5.spec.js b/packages/dd-trace/test/encode/0.5.spec.js index 09f27e75852..247ad422676 100644 --- a/packages/dd-trace/test/encode/0.5.spec.js +++ b/packages/dd-trace/test/encode/0.5.spec.js @@ -1,6 +1,8 @@ 'use strict' -const { expect } = require('chai') +const assert = require('node:assert/strict') +const { assertObjectContains } = require('../../../../integration-tests/helpers') + const { describe, it, beforeEach } = require('tap').mocha const msgpack = require('@msgpack/msgpack') const sinon = require('sinon') @@ -52,20 +54,20 @@ describe('encode 0.5', () => { const stringMap = decoded[0] const trace = decoded[1][0] - expect(trace).to.be.instanceof(Array) - expect(trace[0]).to.be.instanceof(Array) - expect(stringMap[trace[0][0]]).to.equal(data[0].service) - expect(stringMap[trace[0][1]]).to.equal(data[0].name) - expect(stringMap[trace[0][2]]).to.equal(data[0].resource) - expect(trace[0][3].toString(16)).to.equal(data[0].trace_id.toString()) - expect(trace[0][4].toString(16)).to.equal(data[0].span_id.toString()) - expect(trace[0][5].toString(16)).to.equal(data[0].parent_id.toString()) - expect(trace[0][6]).to.equal(BigInt(data[0].start)) - expect(trace[0][7]).to.equal(BigInt(data[0].duration)) - expect(trace[0][8]).to.equal(0) - expect(trace[0][9]).to.deep.equal({ [stringMap.indexOf('bar')]: stringMap.indexOf('baz') }) - expect(trace[0][10]).to.deep.equal({ [stringMap.indexOf('example')]: 1 }) - expect(stringMap[trace[0][11]]).to.equal('') // unset + assert.ok(trace instanceof Array) + assert.ok(trace[0] instanceof Array) + assert.strictEqual(stringMap[trace[0][0]], data[0].service) + assert.strictEqual(stringMap[trace[0][1]], data[0].name) + assert.strictEqual(stringMap[trace[0][2]], data[0].resource) + assert.strictEqual(trace[0][3].toString(16), data[0].trace_id.toString()) + assert.strictEqual(trace[0][4].toString(16), data[0].span_id.toString()) + assert.strictEqual(trace[0][5].toString(16), data[0].parent_id.toString()) + assert.strictEqual(trace[0][6], BigInt(data[0].start)) + assert.strictEqual(trace[0][7], BigInt(data[0].duration)) + assert.strictEqual(trace[0][8], 0) + assert.deepStrictEqual(trace[0][9], { [stringMap.indexOf('bar')]: stringMap.indexOf('baz') }) + assert.deepStrictEqual(trace[0][10], { [stringMap.indexOf('example')]: 1 }) + assert.strictEqual(stringMap[trace[0][11]], '') // unset }) it('should encode span events', () => { @@ -90,9 +92,9 @@ describe('encode 0.5', () => { const decoded = msgpack.decode(buffer, { useBigInt64: true }) const stringMap = decoded[0] const trace = decoded[1][0] - expect(stringMap).to.include('events') - expect(stringMap).to.include(encodedLink) - expect(trace[0][9]).to.include({ + assertObjectContains(stringMap, 'events') + assertObjectContains(stringMap, encodedLink) + assertObjectContains(trace[0][9], { [stringMap.indexOf('bar')]: stringMap.indexOf('baz'), [stringMap.indexOf('events')]: stringMap.indexOf(encodedLink) }) @@ -117,25 +119,25 @@ describe('encode 0.5', () => { const stringMap = decoded[0] const trace = decoded[1][0] - expect(trace).to.be.instanceof(Array) - expect(trace[0]).to.be.instanceof(Array) - expect(stringMap[trace[0][0]]).to.equal(data[0].service) - expect(stringMap[trace[0][1]]).to.equal(data[0].name) - expect(stringMap[trace[0][2]]).to.equal(data[0].resource) - expect(stringMap).to.include('_dd.span_links') - expect(stringMap).to.include(encodedLink) - expect(trace[0][3].toString(16)).to.equal(data[0].trace_id.toString()) - expect(trace[0][4].toString(16)).to.equal(data[0].span_id.toString()) - expect(trace[0][5].toString(16)).to.equal(data[0].parent_id.toString()) - expect(trace[0][6]).to.equal(BigInt(data[0].start)) - expect(trace[0][7]).to.equal(BigInt(data[0].duration)) - expect(trace[0][8]).to.equal(0) - expect(trace[0][9]).to.deep.equal({ + assert.ok(trace instanceof Array) + assert.ok(trace[0] instanceof Array) + assert.strictEqual(stringMap[trace[0][0]], data[0].service) + assert.strictEqual(stringMap[trace[0][1]], data[0].name) + assert.strictEqual(stringMap[trace[0][2]], data[0].resource) + assertObjectContains(stringMap, '_dd.span_links') + assertObjectContains(stringMap, encodedLink) + assert.strictEqual(trace[0][3].toString(16), data[0].trace_id.toString()) + assert.strictEqual(trace[0][4].toString(16), data[0].span_id.toString()) + assert.strictEqual(trace[0][5].toString(16), data[0].parent_id.toString()) + assert.strictEqual(trace[0][6], BigInt(data[0].start)) + assert.strictEqual(trace[0][7], BigInt(data[0].duration)) + assert.strictEqual(trace[0][8], 0) + assert.deepStrictEqual(trace[0][9], { [stringMap.indexOf('bar')]: stringMap.indexOf('baz'), [stringMap.indexOf('_dd.span_links')]: stringMap.indexOf(encodedLink) }) - expect(trace[0][10]).to.deep.equal({ [stringMap.indexOf('example')]: 1 }) - expect(stringMap[trace[0][11]]).to.equal('') // unset + assert.deepStrictEqual(trace[0][10], { [stringMap.indexOf('example')]: 1 }) + assert.strictEqual(stringMap[trace[0][11]], '') // unset }) it('should encode span link with just span and trace id', () => { @@ -151,25 +153,25 @@ describe('encode 0.5', () => { const stringMap = decoded[0] const trace = decoded[1][0] - expect(trace).to.be.instanceof(Array) - expect(trace[0]).to.be.instanceof(Array) - expect(stringMap[trace[0][0]]).to.equal(data[0].service) - expect(stringMap[trace[0][1]]).to.equal(data[0].name) - expect(stringMap[trace[0][2]]).to.equal(data[0].resource) - expect(stringMap).to.include('_dd.span_links') - expect(stringMap).to.include(encodedLink) - expect(trace[0][3].toString(16)).to.equal(data[0].trace_id.toString()) - expect(trace[0][4].toString(16)).to.equal(data[0].span_id.toString()) - expect(trace[0][5].toString(16)).to.equal(data[0].parent_id.toString()) - expect(trace[0][6]).to.equal(BigInt(data[0].start)) - expect(trace[0][7]).to.equal(BigInt(data[0].duration)) - expect(trace[0][8]).to.equal(0) - expect(trace[0][9]).to.deep.equal({ + assert.ok(trace instanceof Array) + assert.ok(trace[0] instanceof Array) + assert.strictEqual(stringMap[trace[0][0]], data[0].service) + assert.strictEqual(stringMap[trace[0][1]], data[0].name) + assert.strictEqual(stringMap[trace[0][2]], data[0].resource) + assertObjectContains(stringMap, '_dd.span_links') + assertObjectContains(stringMap, encodedLink) + assert.strictEqual(trace[0][3].toString(16), data[0].trace_id.toString()) + assert.strictEqual(trace[0][4].toString(16), data[0].span_id.toString()) + assert.strictEqual(trace[0][5].toString(16), data[0].parent_id.toString()) + assert.strictEqual(trace[0][6], BigInt(data[0].start)) + assert.strictEqual(trace[0][7], BigInt(data[0].duration)) + assert.strictEqual(trace[0][8], 0) + assert.deepStrictEqual(trace[0][9], { [stringMap.indexOf('bar')]: stringMap.indexOf('baz'), [stringMap.indexOf('_dd.span_links')]: stringMap.indexOf(encodedLink) }) - expect(trace[0][10]).to.deep.equal({ [stringMap.indexOf('example')]: 1 }) - expect(stringMap[trace[0][11]]).to.equal('') // unset + assert.deepStrictEqual(trace[0][10], { [stringMap.indexOf('example')]: 1 }) + assert.strictEqual(stringMap[trace[0][11]], '') // unset }) it('should truncate long IDs', () => { @@ -183,21 +185,21 @@ describe('encode 0.5', () => { const decoded = msgpack.decode(buffer, { useBigInt64: true }) const trace = decoded[1][0] - expect(trace[0][3].toString(16)).to.equal('1234abcd1234abcd') - expect(trace[0][4].toString(16)).to.equal('1234abcd1234abcd') - expect(trace[0][5].toString(16)).to.equal('1234abcd1234abcd') + assert.strictEqual(trace[0][3].toString(16), '1234abcd1234abcd') + assert.strictEqual(trace[0][4].toString(16), '1234abcd1234abcd') + assert.strictEqual(trace[0][5].toString(16), '1234abcd1234abcd') }) it('should report its count', () => { - expect(encoder.count()).to.equal(0) + assert.strictEqual(encoder.count(), 0) encoder.encode(data) - expect(encoder.count()).to.equal(1) + assert.strictEqual(encoder.count(), 1) encoder.encode(data) - expect(encoder.count()).to.equal(2) + assert.strictEqual(encoder.count(), 2) }) it('should flush when the payload size limit is reached', function () { @@ -208,7 +210,7 @@ describe('encode 0.5', () => { encoder.encode(data) - expect(writer.flush).to.have.been.called + sinon.assert.called(writer.flush) }) it('should reset after making a payload', () => { @@ -217,10 +219,10 @@ describe('encode 0.5', () => { const payload = encoder.makePayload() - expect(encoder.count()).to.equal(0) - expect(payload).to.have.length(12) - expect(payload[5]).to.equal(1) - expect(payload[11]).to.equal(0) + assert.strictEqual(encoder.count(), 0) + assert.strictEqual(payload.length, 12) + assert.strictEqual(payload[5], 1) + assert.strictEqual(payload[11], 0) }) it('should ignore meta_struct property', () => { @@ -233,20 +235,20 @@ describe('encode 0.5', () => { const stringMap = decoded[0] const trace = decoded[1][0] - expect(trace).to.be.instanceof(Array) - expect(trace[0]).to.be.instanceof(Array) - expect(stringMap[trace[0][0]]).to.equal(data[0].service) - expect(stringMap[trace[0][1]]).to.equal(data[0].name) - expect(stringMap[trace[0][2]]).to.equal(data[0].resource) - expect(trace[0][3].toString(16)).to.equal(data[0].trace_id.toString()) - expect(trace[0][4].toString(16)).to.equal(data[0].span_id.toString()) - expect(trace[0][5].toString(16)).to.equal(data[0].parent_id.toString()) - expect(trace[0][6]).to.equal(BigInt(data[0].start)) - expect(trace[0][7]).to.equal(BigInt(data[0].duration)) - expect(trace[0][8]).to.equal(0) - expect(trace[0][9]).to.deep.equal({ [stringMap.indexOf('bar')]: stringMap.indexOf('baz') }) - expect(trace[0][10]).to.deep.equal({ [stringMap.indexOf('example')]: 1 }) - expect(stringMap[trace[0][11]]).to.equal('') // unset - expect(trace[0][12]).to.be.undefined // Everything works the same as without meta_struct, and nothing else is added + assert.ok(trace instanceof Array) + assert.ok(trace[0] instanceof Array) + assert.strictEqual(stringMap[trace[0][0]], data[0].service) + assert.strictEqual(stringMap[trace[0][1]], data[0].name) + assert.strictEqual(stringMap[trace[0][2]], data[0].resource) + assert.strictEqual(trace[0][3].toString(16), data[0].trace_id.toString()) + assert.strictEqual(trace[0][4].toString(16), data[0].span_id.toString()) + assert.strictEqual(trace[0][5].toString(16), data[0].parent_id.toString()) + assert.strictEqual(trace[0][6], BigInt(data[0].start)) + assert.strictEqual(trace[0][7], BigInt(data[0].duration)) + assert.strictEqual(trace[0][8], 0) + assert.deepStrictEqual(trace[0][9], { [stringMap.indexOf('bar')]: stringMap.indexOf('baz') }) + assert.deepStrictEqual(trace[0][10], { [stringMap.indexOf('example')]: 1 }) + assert.strictEqual(stringMap[trace[0][11]], '') // unset + assert.strictEqual(trace[0][12], undefined) // Everything works the same as without meta_struct, and nothing else is added }) }) diff --git a/packages/dd-trace/test/encode/coverage-ci-visibility.spec.js b/packages/dd-trace/test/encode/coverage-ci-visibility.spec.js index b1e724e3001..a78098bc693 100644 --- a/packages/dd-trace/test/encode/coverage-ci-visibility.spec.js +++ b/packages/dd-trace/test/encode/coverage-ci-visibility.spec.js @@ -1,6 +1,8 @@ 'use strict' -const { expect } = require('chai') +const assert = require('node:assert/strict') +const { assertObjectContains } = require('../../../../integration-tests/helpers') + const { describe, it, beforeEach } = require('tap').mocha const msgpack = require('@msgpack/msgpack') const sinon = require('sinon') @@ -48,37 +50,37 @@ describe('coverage-ci-visibility', () => { const form = encoder.makePayload() - expect(form._data[1]).to.contain('Content-Disposition: form-data; name="coverage1"; filename="coverage1.msgpack"') - expect(form._data[2]).to.contain('Content-Type: application/msgpack') + assertObjectContains(form._data[1], 'Content-Disposition: form-data; name="coverage1"; filename="coverage1.msgpack"') + assertObjectContains(form._data[2], 'Content-Type: application/msgpack') const decodedCoverages = msgpack.decode(form._data[3]) - expect(decodedCoverages.version).to.equal(2) - expect(decodedCoverages.coverages).to.have.length(2) - expect(decodedCoverages.coverages[0]).to.contain({ test_session_id: 1, test_suite_id: 2 }) - expect(decodedCoverages.coverages[0].files[0]).to.eql({ filename: 'file.js' }) + assert.strictEqual(decodedCoverages.version, 2) + assert.strictEqual(decodedCoverages.coverages.length, 2) + assertObjectContains(decodedCoverages.coverages[0], { test_session_id: 1, test_suite_id: 2 }) + assert.deepStrictEqual(decodedCoverages.coverages[0].files[0], { filename: 'file.js' }) - expect(decodedCoverages.coverages[1]).to.contain({ test_session_id: 3, test_suite_id: 4 }) - expect(decodedCoverages.coverages[1].files[0]).to.eql({ filename: 'file2.js' }) + assertObjectContains(decodedCoverages.coverages[1], { test_session_id: 3, test_suite_id: 4 }) + assert.deepStrictEqual(decodedCoverages.coverages[1].files[0], { filename: 'file2.js' }) }) it('should report its count', () => { - expect(encoder.count()).to.equal(0) + assert.strictEqual(encoder.count(), 0) encoder.encode(formattedCoverage) - expect(encoder.count()).to.equal(1) + assert.strictEqual(encoder.count(), 1) encoder.encode(formattedCoverage) - expect(encoder.count()).to.equal(2) + assert.strictEqual(encoder.count(), 2) }) it('should reset after making a payload', () => { encoder.encode(formattedCoverage) encoder.makePayload() - expect(encoder.count()).to.equal(0) + assert.strictEqual(encoder.count(), 0) }) it('should be able to make multiple payloads', () => { @@ -86,16 +88,16 @@ describe('coverage-ci-visibility', () => { encoder.encode(formattedCoverage) form = encoder.makePayload() decodedCoverages = msgpack.decode(form._data[3]) - expect(decodedCoverages.version).to.equal(2) - expect(decodedCoverages.coverages).to.have.length(1) - expect(decodedCoverages.coverages[0]).to.contain({ test_session_id: 1, test_suite_id: 2 }) + assert.strictEqual(decodedCoverages.version, 2) + assert.strictEqual(decodedCoverages.coverages.length, 1) + assertObjectContains(decodedCoverages.coverages[0], { test_session_id: 1, test_suite_id: 2 }) encoder.encode(formattedCoverage2) form = encoder.makePayload() decodedCoverages = msgpack.decode(form._data[3]) - expect(decodedCoverages.version).to.equal(2) - expect(decodedCoverages.coverages).to.have.length(1) - expect(decodedCoverages.coverages[0]).to.contain({ test_session_id: 3, test_suite_id: 4 }) + assert.strictEqual(decodedCoverages.version, 2) + assert.strictEqual(decodedCoverages.coverages.length, 1) + assertObjectContains(decodedCoverages.coverages[0], { test_session_id: 3, test_suite_id: 4 }) }) it('should be able to encode test coverages', () => { @@ -103,14 +105,14 @@ describe('coverage-ci-visibility', () => { const form = encoder.makePayload() - expect(form._data[1]).to.contain('Content-Disposition: form-data; name="coverage1"; filename="coverage1.msgpack"') - expect(form._data[2]).to.contain('Content-Type: application/msgpack') + assertObjectContains(form._data[1], 'Content-Disposition: form-data; name="coverage1"; filename="coverage1.msgpack"') + assertObjectContains(form._data[2], 'Content-Type: application/msgpack') const decodedCoverages = msgpack.decode(form._data[3]) - expect(decodedCoverages.version).to.equal(2) - expect(decodedCoverages.coverages).to.have.length(1) - expect(decodedCoverages.coverages[0]).to.contain({ test_session_id: 5, test_suite_id: 6, span_id: 7 }) - expect(decodedCoverages.coverages[0].files[0]).to.eql({ filename: 'file3.js' }) + assert.strictEqual(decodedCoverages.version, 2) + assert.strictEqual(decodedCoverages.coverages.length, 1) + assertObjectContains(decodedCoverages.coverages[0], { test_session_id: 5, test_suite_id: 6, span_id: 7 }) + assert.deepStrictEqual(decodedCoverages.coverages[0].files[0], { filename: 'file3.js' }) }) }) diff --git a/packages/dd-trace/test/exporters/common/agent-info-exporter.spec.js b/packages/dd-trace/test/exporters/common/agent-info-exporter.spec.js index 62f219de746..c6330a56cc1 100644 --- a/packages/dd-trace/test/exporters/common/agent-info-exporter.spec.js +++ b/packages/dd-trace/test/exporters/common/agent-info-exporter.spec.js @@ -1,6 +1,10 @@ 'use strict' +const assert = require('node:assert/strict') + const { expect } = require('chai') +const { assertObjectContains } = require('../../../../../integration-tests/helpers') + const { describe, it } = require('tap').mocha const sinon = require('sinon') const nock = require('nock') @@ -27,11 +31,11 @@ describe('AgentInfoExporter', () => { })) const agentInfoExporter = new AgentInfoExporter({ port }) - expect(scope.isDone()).not.to.be.true + assert.notStrictEqual(scope.isDone(), true) agentInfoExporter.getAgentInfo((err, { endpoints }) => { - expect(err).to.be.null - expect(endpoints).to.include('/evp_proxy/v2') - expect(scope.isDone()).to.be.true + assert.strictEqual(err, null) + assertObjectContains(endpoints, '/evp_proxy/v2') + assert.strictEqual(scope.isDone(), true) done() }) }) @@ -47,10 +51,10 @@ describe('AgentInfoExporter', () => { agentInfoExporter.export(trace) - expect(agentInfoExporter.getUncodedTraces()).to.include(trace) + assertObjectContains(agentInfoExporter.getUncodedTraces(), trace) agentInfoExporter.getAgentInfo(() => { - expect(agentInfoExporter.getUncodedTraces()).to.include(trace) + assertObjectContains(agentInfoExporter.getUncodedTraces(), trace) done() }) }) @@ -69,11 +73,11 @@ describe('AgentInfoExporter', () => { agentInfoExporter._writer = writer agentInfoExporter._isInitialized = true agentInfoExporter.export(trace) - expect(writer.append).to.have.been.calledWith(trace) - expect(writer.flush).not.to.have.been.called + sinon.assert.calledWith(writer.append, trace) + sinon.assert.notCalled(writer.flush) expect(agentInfoExporter.getUncodedTraces()).not.to.include(trace) setTimeout(() => { - expect(writer.flush).to.have.been.called + sinon.assert.called(writer.flush) done() }, flushInterval) }) diff --git a/packages/dd-trace/test/external-logger/index.spec.js b/packages/dd-trace/test/external-logger/index.spec.js index cb600d5ea41..38821afd4cc 100644 --- a/packages/dd-trace/test/external-logger/index.spec.js +++ b/packages/dd-trace/test/external-logger/index.spec.js @@ -1,8 +1,6 @@ 'use strict' const assert = require('node:assert/strict') - -const { expect } = require('chai') const { describe, it, beforeEach, afterEach } = require('tap').mocha const sinon = require('sinon') const proxyquire = require('proxyquire') @@ -79,7 +77,7 @@ describe('External Logger', () => { assert.strictEqual(request[0].level, 'info') assert.strictEqual(request[0]['dd.trace_id'], '000001000') assert.strictEqual(request[0]['dd.span_id'], '9999991999') - expect(request[0].timestamp).to.be.greaterThanOrEqual(currentTime) + assert.ok(request[0].timestamp >= currentTime) assert.strictEqual(request[0].ddsource, 'logging_from_space') assert.strictEqual(request[0].ddtags, 'env:external_logger,version:1.2.3,service:external') } catch (e) { @@ -112,7 +110,7 @@ describe('External Logger', () => { externalLogger.enqueue({}) externalLogger.flush((err) => { - expect(err).to.be.an.instanceOf(Error) + assert.ok(err instanceof Error) assert.strictEqual(errorLog.getCall(0).args[0], 'failed to send 1 logs, received response code 400' ) @@ -127,7 +125,7 @@ describe('External Logger', () => { externalLogger.enqueue({}) externalLogger.flush((err) => { - expect(err).to.be.an.instanceOf(Error) + assert.ok(err instanceof Error) assert.strictEqual(errorLog.getCall(0).args[0], 'failed to send 1 log(s), with error missing API key' ) diff --git a/packages/dd-trace/test/git_metadata_tagger.spec.js b/packages/dd-trace/test/git_metadata_tagger.spec.js index eb92588e821..141d4121a06 100644 --- a/packages/dd-trace/test/git_metadata_tagger.spec.js +++ b/packages/dd-trace/test/git_metadata_tagger.spec.js @@ -1,8 +1,6 @@ 'use strict' const assert = require('node:assert/strict') - -const { expect } = require('chai') const { describe, it, beforeEach, afterEach } = require('tap').mocha require('./setup/core') @@ -56,8 +54,8 @@ describe('git metadata tagging', () => { assert.strictEqual(firstSpan.meta[SCI_REPOSITORY_URL], DUMMY_REPOSITORY_URL) const secondSpan = payload[0][1] - expect(secondSpan.meta[SCI_COMMIT_SHA]).not.to.exist - expect(secondSpan.meta[SCI_REPOSITORY_URL]).not.to.exist + assert.ok(secondSpan.meta[SCI_COMMIT_SHA] == null) + assert.ok(secondSpan.meta[SCI_REPOSITORY_URL] == null) }) }) }) diff --git a/packages/dd-trace/test/lambda/index.spec.js b/packages/dd-trace/test/lambda/index.spec.js index f4b4992509d..c252b1505ee 100644 --- a/packages/dd-trace/test/lambda/index.spec.js +++ b/packages/dd-trace/test/lambda/index.spec.js @@ -3,7 +3,6 @@ const assert = require('node:assert/strict') const path = require('node:path') -const { expect } = require('chai') const { afterEach, beforeEach, describe, it } = require('mocha') const agent = require('../plugins/agent') @@ -94,7 +93,7 @@ describe('lambda', () => { // Expect traces to be correct. const checkTraces = agent.assertSomeTraces((_traces) => { const traces = _traces[0] - expect(traces).lengthOf(1) + assert.strictEqual(traces.length, 1) traces.forEach((trace) => { assert.strictEqual(trace.error, 0) }) @@ -131,7 +130,7 @@ describe('lambda', () => { // Expect traces to be correct. const checkTraces = agent.assertSomeTraces((_traces) => { const traces = _traces[0] - expect(traces).lengthOf(1) + assert.strictEqual(traces.length, 1) traces.forEach((trace) => { assert.strictEqual(trace.error, 0) }) @@ -165,7 +164,7 @@ describe('lambda', () => { // Expect traces to be correct. const checkTraces = agent.assertSomeTraces((_traces) => { const traces = _traces[0] - expect(traces).lengthOf(1) + assert.strictEqual(traces.length, 1) traces.forEach((trace) => { assert.strictEqual(trace.error, 1) }) @@ -196,7 +195,7 @@ describe('lambda', () => { const checkTraces = agent.assertSomeTraces((_traces) => { const traces = _traces[0] - expect(traces).lengthOf(1) + assert.strictEqual(traces.length, 1) traces.forEach((trace) => { assert.strictEqual(trace.error, 0) }) diff --git a/packages/dd-trace/test/llmobs/sdk/index.spec.js b/packages/dd-trace/test/llmobs/sdk/index.spec.js index 2174388b214..a24cb03b76a 100644 --- a/packages/dd-trace/test/llmobs/sdk/index.spec.js +++ b/packages/dd-trace/test/llmobs/sdk/index.spec.js @@ -193,7 +193,7 @@ describe('sdk', () => { }) it('throws if the kind is invalid', () => { - expect(() => llmobs.trace({ kind: 'invalid' }, () => {})).to.throw() + assert.throws(() => llmobs.trace({ kind: 'invalid' }, () => {})) sinon.assert.notCalled(llmobs._tracer._processor.process) sinon.assert.notCalled(LLMObsSpanProcessor.prototype.format) @@ -201,7 +201,7 @@ describe('sdk', () => { // TODO: need span kind optional for this it.skip('throws if no name is provided', () => { - expect(() => llmobs.trace({ kind: 'workflow' }, () => {})).to.throw() + assert.throws(() => llmobs.trace({ kind: 'workflow' }, () => {})) sinon.assert.notCalled(llmobs._tracer._processor.process) sinon.assert.notCalled(LLMObsSpanProcessor.prototype.format) @@ -375,7 +375,7 @@ describe('sdk', () => { const fn = llmobs.wrap({ kind: 'workflow' }, (a) => { assert.strictEqual(a, 1) - expect(LLMObsTagger.tagMap.get(llmobs._active())).to.not.exist + assert.ok(LLMObsTagger.tagMap.get(llmobs._active()) == null) }) assert.doesNotThrow(() => fn(1)) @@ -387,7 +387,7 @@ describe('sdk', () => { }) it('throws if the kind is invalid', () => { - expect(() => llmobs.wrap({ kind: 'invalid' }, () => {})).to.throw() + assert.throws(() => llmobs.wrap({ kind: 'invalid' }, () => {})) }) it('wraps a function', () => { @@ -1212,7 +1212,8 @@ describe('sdk', () => { } }) - expect(LLMObsEvalMetricsWriter.prototype.append.getCall(0).args[0]).to.have.property('categorical_value', 'foo') + assert.ok('categorical_value' in LLMObsEvalMetricsWriter.prototype.append.getCall(0).args[0]); + assert.strictEqual(LLMObsEvalMetricsWriter.prototype.append.getCall(0).args[0]['categorical_value'], 'foo') }) it('defaults to the current time if no timestamp is provided', () => { @@ -1224,7 +1225,8 @@ describe('sdk', () => { value: 0.6 }) - expect(LLMObsEvalMetricsWriter.prototype.append.getCall(0).args[0]).to.have.property('timestamp_ms', 1234) + assert.ok('timestamp_ms' in LLMObsEvalMetricsWriter.prototype.append.getCall(0).args[0]); + assert.strictEqual(LLMObsEvalMetricsWriter.prototype.append.getCall(0).args[0]['timestamp_ms'], 1234) Date.now.restore() }) @@ -1238,7 +1240,7 @@ describe('sdk', () => { const evalMetric = LLMObsEvalMetricsWriter.prototype.append.getCall(0).args[0] - assert.deepEqual(evalMetric, { + assert.deepStrictEqual(evalMetric, { span_id: '5678', trace_id: '1234', label: 'has_toxicity', diff --git a/packages/dd-trace/test/llmobs/span_processor.spec.js b/packages/dd-trace/test/llmobs/span_processor.spec.js index 459a1a63090..cf343598297 100644 --- a/packages/dd-trace/test/llmobs/span_processor.spec.js +++ b/packages/dd-trace/test/llmobs/span_processor.spec.js @@ -1,12 +1,13 @@ 'use strict' -const { expect } = require('chai') -const { describe, it, beforeEach } = require('mocha') -const sinon = require('sinon') +const assert = require('node:assert/strict') + +const { beforeEach, describe, it } = require('mocha') const proxyquire = require('proxyquire') +const sinon = require('sinon') -// we will use this to populate the span-tags map const LLMObsTagger = require('../../src/llmobs/tagger') +const { assertObjectContains } = require('../../../../integration-tests/helpers') describe('span processor', () => { let LLMObsSpanProcessor @@ -38,13 +39,13 @@ describe('span processor', () => { it('should do nothing if llmobs is not enabled', () => { processor = new LLMObsSpanProcessor({ llmobs: { enabled: false } }) - expect(() => processor.process(span)).not.to.throw() + assert.doesNotThrow(() => processor.process(span)) }) it('should do nothing if the span is not an llm obs span', () => { span = { context: () => ({ _tags: {} }) } - expect(writer.append).to.not.have.been.called + sinon.assert.notCalled(writer.append) }) it('should format the span event for the writer', () => { @@ -74,7 +75,7 @@ describe('span processor', () => { processor.process(span) const payload = writer.append.getCall(0).firstArg - expect(payload).to.deep.equal({ + assert.deepStrictEqual(payload, { trace_id: '123', span_id: '456', parent_id: '1234', @@ -111,7 +112,7 @@ describe('span processor', () => { } }) - expect(writer.append).to.have.been.calledOnce + sinon.assert.calledOnce(writer.append) }) it('removes problematic fields from the metadata', () => { @@ -143,7 +144,7 @@ describe('span processor', () => { processor.process(span) const payload = writer.append.getCall(0).firstArg - expect(payload.meta.metadata).to.deep.equal({ + assert.deepStrictEqual(payload.meta.metadata, { bar: 'baz', bigint: 'Unserializable value', circular: 'Unserializable value', @@ -170,7 +171,7 @@ describe('span processor', () => { processor.process(span) const payload = writer.append.getCall(0).firstArg - expect(payload.meta.output.documents).to.deep.equal([{ + assert.deepStrictEqual(payload.meta.output.documents, [{ text: 'hello', name: 'myDoc', id: '1', @@ -197,7 +198,7 @@ describe('span processor', () => { processor.process(span) const payload = writer.append.getCall(0).firstArg - expect(payload.meta.input.documents).to.deep.equal([{ + assert.deepStrictEqual(payload.meta.input.documents, [{ text: 'hello', name: 'myDoc', id: '1', @@ -224,7 +225,7 @@ describe('span processor', () => { processor.process(span) const payload = writer.append.getCall(0).firstArg - expect(payload.meta.model_provider).to.equal('custom') + assert.strictEqual(payload.meta.model_provider, 'custom') }) it('sets an error appropriately', () => { @@ -249,12 +250,12 @@ describe('span processor', () => { processor.process(span) const payload = writer.append.getCall(0).firstArg - expect(payload.meta['error.message']).to.equal('error message') - expect(payload.meta['error.type']).to.equal('error type') - expect(payload.meta['error.stack']).to.equal('error stack') - expect(payload.status).to.equal('error') + assert.strictEqual(payload.meta['error.message'], 'error message') + assert.strictEqual(payload.meta['error.type'], 'error type') + assert.strictEqual(payload.meta['error.stack'], 'error stack') + assert.strictEqual(payload.status, 'error') - expect(payload.tags).to.include('error_type:error type') + assertObjectContains(payload.tags, 'error_type:error type') }) it('uses the error itself if the span does not have specific error fields', () => { @@ -277,12 +278,12 @@ describe('span processor', () => { processor.process(span) const payload = writer.append.getCall(0).firstArg - expect(payload.meta['error.message']).to.equal('error message') - expect(payload.meta['error.type']).to.equal('Error') - expect(payload.meta['error.stack']).to.exist - expect(payload.status).to.equal('error') + assert.strictEqual(payload.meta['error.message'], 'error message') + assert.strictEqual(payload.meta['error.type'], 'Error') + assert.ok(payload.meta['error.stack'] != null) + assert.strictEqual(payload.status, 'error') - expect(payload.tags).to.include('error_type:Error') + assertObjectContains(payload.tags, 'error_type:Error') }) it('uses the span name from the tag if provided', () => { @@ -305,7 +306,7 @@ describe('span processor', () => { processor.process(span) const payload = writer.append.getCall(0).firstArg - expect(payload.name).to.equal('mySpan') + assert.strictEqual(payload.name, 'mySpan') }) it('attaches session id if provided', () => { @@ -327,8 +328,8 @@ describe('span processor', () => { processor.process(span) const payload = writer.append.getCall(0).firstArg - expect(payload.session_id).to.equal('1234') - expect(payload.tags).to.include('session_id:1234') + assert.strictEqual(payload.session_id, '1234') + assertObjectContains(payload.tags, 'session_id:1234') }) it('sets span tags appropriately', () => { @@ -350,9 +351,9 @@ describe('span processor', () => { processor.process(span) const payload = writer.append.getCall(0).firstArg - expect(payload.tags).to.include('foo:bar') - expect(payload.tags).to.include('source:mySource') - expect(payload.tags).to.include('hostname:localhost') + assertObjectContains(payload.tags, 'foo:bar') + assertObjectContains(payload.tags, 'source:mySource') + assertObjectContains(payload.tags, 'hostname:localhost') }) }) }) diff --git a/packages/dd-trace/test/llmobs/tagger.spec.js b/packages/dd-trace/test/llmobs/tagger.spec.js index 7452a06f07f..818e531fd32 100644 --- a/packages/dd-trace/test/llmobs/tagger.spec.js +++ b/packages/dd-trace/test/llmobs/tagger.spec.js @@ -2,7 +2,6 @@ const assert = require('node:assert/strict') -const { expect } = require('chai') const { beforeEach, describe, it } = require('mocha') const proxyquire = require('proxyquire') const sinon = require('sinon') @@ -774,7 +773,7 @@ describe('tagger', () => { tagger._register(span) tagger.tagLLMIO(span, messages, undefined) - expect(Tagger.tagMap.get(span)).to.not.have.property('_ml_obs.meta.input.messages') + assert.ok(!('_ml_obs.meta.input.messages' in Tagger.tagMap.get(span))) sinon.assert.calledOnce(logger.warn) }) }) diff --git a/packages/dd-trace/test/llmobs/util.spec.js b/packages/dd-trace/test/llmobs/util.spec.js index fbb07b14732..ecb13186eca 100644 --- a/packages/dd-trace/test/llmobs/util.spec.js +++ b/packages/dd-trace/test/llmobs/util.spec.js @@ -2,7 +2,6 @@ const assert = require('node:assert/strict') -const { expect } = require('chai') const { before, describe, it } = require('mocha') const { encodeUnicode, @@ -45,25 +44,23 @@ describe('util', () => { describe('getFunctionArguments', () => { describe('functionality', () => { it('should return undefined for a function without arguments', () => { - expect(getFunctionArguments(() => {})).to.deep.equal(undefined) + assert.deepStrictEqual(getFunctionArguments(() => {}), undefined) }) it('should capture a single argument only by its value', () => { - expect(getFunctionArguments((arg) => {}, ['bar'])).to.deep.equal('bar') + assert.deepStrictEqual(getFunctionArguments((arg) => {}, ['bar']), 'bar') }) it('should capture multiple arguments by name', () => { - expect(getFunctionArguments((foo, bar) => {}, ['foo', 'bar'])).to.deep.equal({ foo: 'foo', bar: 'bar' }) + assert.deepStrictEqual(getFunctionArguments((foo, bar) => {}, ['foo', 'bar']), { foo: 'foo', bar: 'bar' }) }) it('should ignore arguments not passed in', () => { - expect(getFunctionArguments((foo, bar, baz) => {}, ['foo', 'bar'])).to.deep.equal({ foo: 'foo', bar: 'bar' }) + assert.deepStrictEqual(getFunctionArguments((foo, bar, baz) => {}, ['foo', 'bar']), { foo: 'foo', bar: 'bar' }) }) it('should capture spread arguments', () => { - expect( - getFunctionArguments((foo, bar, ...args) => {}, ['foo', 'bar', 1, 2, 3]) - ).to.deep.equal({ foo: 'foo', bar: 'bar', args: [1, 2, 3] }) + assert.deepStrictEqual(getFunctionArguments((foo, bar, ...args) => {}, ['foo', 'bar', 1, 2, 3]), { foo: 'foo', bar: 'bar', args: [1, 2, 3] }) }) }) diff --git a/packages/dd-trace/test/log.spec.js b/packages/dd-trace/test/log.spec.js index ae14d7a26f9..7253a0b1b4c 100644 --- a/packages/dd-trace/test/log.spec.js +++ b/packages/dd-trace/test/log.spec.js @@ -1,8 +1,6 @@ 'use strict' const assert = require('node:assert/strict') - -const { expect } = require('chai') const { describe, it, beforeEach, afterEach } = require('tap').mocha const sinon = require('sinon') const proxyquire = require('proxyquire') @@ -167,7 +165,8 @@ describe('log', () => { it('should call the logger in a noop context', () => { logger.debug = () => { - expect(storage('legacy').getStore()).to.have.property('noop', true) + assert.ok('noop' in storage('legacy').getStore()); + assert.strictEqual(storage('legacy').getStore()['noop'], true) } log.use(logger).debug('debug') @@ -458,8 +457,8 @@ describe('log', () => { sinon.assert.calledOnce(console.error) const consoleErrorArg = console.error.getCall(0).args[0] - expect(typeof consoleErrorArg).to.be.eq('object') - expect(consoleErrorArg.message).to.be.eq('message') + assert.strictEqual(typeof consoleErrorArg, 'object') + assert.strictEqual(consoleErrorArg.message, 'message') }) it('should only log once for a given code', () => { diff --git a/packages/dd-trace/test/openfeature/flagging_provider_timeout.spec.js b/packages/dd-trace/test/openfeature/flagging_provider_timeout.spec.js index a5a7167fb84..d5d25541b4f 100644 --- a/packages/dd-trace/test/openfeature/flagging_provider_timeout.spec.js +++ b/packages/dd-trace/test/openfeature/flagging_provider_timeout.spec.js @@ -1,10 +1,12 @@ 'use strict' -const { expect } = require('chai') -const { describe, it, beforeEach, afterEach } = require('mocha') -const sinon = require('sinon') -const proxyquire = require('proxyquire') +const assert = require('node:assert/strict') + const { ProviderEvents } = require('@openfeature/server-sdk') +const { afterEach, beforeEach, describe, it } = require('mocha') +const proxyquire = require('proxyquire') +const sinon = require('sinon') +const { assertObjectContains } = require('../../../../integration-tests/helpers') require('../setup/mocha') @@ -75,8 +77,8 @@ describe('FlaggingProvider Initialization Timeout', () => { }) // Verify initialization is in progress - expect(provider.initController).to.exist - expect(provider.initController.isInitializing()).to.be.true + assert.ok(provider.initController != null) + assert.strictEqual(provider.initController.isInitializing(), true) // Advance time by 30 seconds (default timeout) and run pending promises await clock.tickAsync(30000) @@ -85,7 +87,7 @@ describe('FlaggingProvider Initialization Timeout', () => { await initPromise.catch(() => {}) // Verify initialization is no longer in progress - expect(provider.initController.isInitializing()).to.be.false + assert.strictEqual(provider.initController.isInitializing(), false) }) it('should not timeout if configuration is set before 30 seconds', async () => { @@ -95,7 +97,7 @@ describe('FlaggingProvider Initialization Timeout', () => { const initPromise = provider.initialize() // Verify initialization is in progress - expect(provider.initController.isInitializing()).to.be.true + assert.strictEqual(provider.initController.isInitializing(), true) // Advance time by 20 seconds (before timeout) await clock.tickAsync(20000) @@ -118,8 +120,8 @@ describe('FlaggingProvider Initialization Timeout', () => { await initPromise // Verify initialization completed successfully - expect(provider.initController.isInitializing()).to.be.false - expect(provider.getConfiguration()).to.equal(ufc) + assert.strictEqual(provider.initController.isInitializing(), false) + assert.strictEqual(provider.getConfiguration(), ufc) }) it('should call setError with timeout message after 30 seconds', async () => { @@ -141,11 +143,11 @@ describe('FlaggingProvider Initialization Timeout', () => { await initPromise.catch(() => {}) // Verify setError was called with timeout error - expect(setErrorSpy).to.have.been.calledOnce + sinon.assert.calledOnce(setErrorSpy) const errorArg = setErrorSpy.firstCall.args[0] - expect(errorArg).to.be.instanceOf(Error) - expect(errorArg.message).to.include('Initialization timeout') - expect(errorArg.message).to.include('30000ms') + assert.ok(errorArg instanceof Error) + assertObjectContains(errorArg.message, 'Initialization timeout') + assertObjectContains(errorArg.message, '30000ms') }) it('should allow recovery if configuration is set after timeout', async () => { @@ -169,15 +171,15 @@ describe('FlaggingProvider Initialization Timeout', () => { await initPromise.catch(() => {}) // Configuration is still not set - expect(provider.getConfiguration()).to.be.undefined + assert.strictEqual(provider.getConfiguration(), undefined) // Now set configuration after timeout const ufc = { flags: { 'recovery-flag': {} } } provider._setConfiguration(ufc) // Should emit READY event to signal recovery - expect(readyEventSpy).to.have.been.calledOnce - expect(provider.getConfiguration()).to.equal(ufc) + sinon.assert.calledOnce(readyEventSpy) + assert.strictEqual(provider.getConfiguration(), ufc) }) describe('custom timeout configuration', () => { @@ -202,13 +204,13 @@ describe('FlaggingProvider Initialization Timeout', () => { }) // Verify initialization is in progress - expect(provider.initController.isInitializing()).to.be.true + assert.strictEqual(provider.initController.isInitializing(), true) // Advance time by 4.9 seconds (before custom timeout) await clock.tickAsync(4900) // Should still be initializing - expect(provider.initController.isInitializing()).to.be.true + assert.strictEqual(provider.initController.isInitializing(), true) // Advance by another 200ms to trigger the 5-second timeout await clock.tickAsync(200) @@ -217,7 +219,7 @@ describe('FlaggingProvider Initialization Timeout', () => { await initPromise.catch(() => {}) // Should now be timed out - expect(provider.initController.isInitializing()).to.be.false + assert.strictEqual(provider.initController.isInitializing(), false) }) it('should call setError with custom timeout value in message', async () => { @@ -249,11 +251,11 @@ describe('FlaggingProvider Initialization Timeout', () => { await initPromise.catch(() => {}) // Verify setError was called with custom timeout error - expect(setErrorSpy).to.have.been.calledOnce + sinon.assert.calledOnce(setErrorSpy) const errorArg = setErrorSpy.firstCall.args[0] - expect(errorArg).to.be.instanceOf(Error) - expect(errorArg.message).to.include('Initialization timeout') - expect(errorArg.message).to.include('10000ms') + assert.ok(errorArg instanceof Error) + assertObjectContains(errorArg.message, 'Initialization timeout') + assertObjectContains(errorArg.message, '10000ms') }) }) }) diff --git a/packages/dd-trace/test/openfeature/noop.spec.js b/packages/dd-trace/test/openfeature/noop.spec.js index 8ccf552b99f..7b7bd5f7e23 100644 --- a/packages/dd-trace/test/openfeature/noop.spec.js +++ b/packages/dd-trace/test/openfeature/noop.spec.js @@ -1,8 +1,6 @@ 'use strict' const assert = require('node:assert/strict') - -const { expect } = require('chai') const { describe, it, beforeEach } = require('tap').mocha require('../setup/core') @@ -138,10 +136,10 @@ describe('NoopFlaggingProvider', () => { const numberResult = noopProvider.resolveNumberEvaluation('test', 42, {}, {}) const objectResult = noopProvider.resolveObjectEvaluation('test', {}, {}, {}) - expect(booleanResult).to.be.a('promise') - expect(stringResult).to.be.a('promise') - expect(numberResult).to.be.a('promise') - expect(objectResult).to.be.a('promise') + assert.ok(booleanResult && typeof booleanResult.then === 'function') + assert.ok(stringResult && typeof stringResult.then === 'function') + assert.ok(numberResult && typeof numberResult.then === 'function') + assert.ok(objectResult && typeof objectResult.then === 'function') }) it('should resolve promises immediately', async () => { diff --git a/packages/dd-trace/test/opentelemetry/context_manager.spec.js b/packages/dd-trace/test/opentelemetry/context_manager.spec.js index 875aefaa782..e7d3bfaeda6 100644 --- a/packages/dd-trace/test/opentelemetry/context_manager.spec.js +++ b/packages/dd-trace/test/opentelemetry/context_manager.spec.js @@ -1,8 +1,6 @@ 'use strict' const assert = require('node:assert/strict') - -const { expect } = require('chai') const { describe, it, beforeEach } = require('tap').mocha const { context, propagation, trace, ROOT_CONTEXT } = require('@opentelemetry/api') const api = require('@opentelemetry/api') @@ -65,7 +63,7 @@ describe('OTel Context Manager', () => { it('should return root context', () => { const ctx = api.context.active() - expect(ctx).to.be.an.instanceof(ROOT_CONTEXT.constructor) + assert.ok(ctx instanceof ROOT_CONTEXT.constructor) }) it('should set active context', () => { @@ -107,7 +105,7 @@ describe('OTel Context Manager', () => { const ctx2 = ctx.setValue(key, 'context 2') assert.strictEqual(ctx.getValue(key), undefined) - expect(ctx).to.be.an.instanceof(ROOT_CONTEXT.constructor) + assert.ok(ctx instanceof ROOT_CONTEXT.constructor) assert.strictEqual(ctx2.getValue(key), 'context 2') const ret = api.context.with(ctx2, () => { @@ -165,11 +163,9 @@ describe('OTel Context Manager', () => { baggages = baggages.setEntry('key2', { value: 'otel2' }) contextWithUpdatedBaggages = propagation.setBaggage(api.context.active(), baggages) }) - expect(JSON.parse(ddSpan.getAllBaggageItems())).to.deep.equal({ key1: 'dd1' }) + assert.deepStrictEqual(JSON.parse(ddSpan.getAllBaggageItems()), { key1: 'dd1' }) api.context.with(contextWithUpdatedBaggages, () => { - expect(JSON.parse(ddSpan.getAllBaggageItems())).to.deep.equal( - { key1: 'otel1', key2: 'otel2' } - ) + assert.deepStrictEqual(JSON.parse(ddSpan.getAllBaggageItems()), { key1: 'otel1', key2: 'otel2' }) ddSpan.setBaggageItem('key2', 'dd2') assert.deepStrictEqual(propagation.getActiveBaggage().getAllEntries(), [['key1', { value: 'otel1' }], ['key2', { value: 'dd2' }]] @@ -187,13 +183,9 @@ describe('OTel Context Manager', () => { baggages = baggages.removeEntry('key1') contextWithUpdatedBaggages = propagation.setBaggage(api.context.active(), baggages) }) - expect(JSON.parse(ddSpan.getAllBaggageItems())).to.deep.equal( - { key1: 'dd1', key2: 'dd2' } - ) + assert.deepStrictEqual(JSON.parse(ddSpan.getAllBaggageItems()), { key1: 'dd1', key2: 'dd2' }) api.context.with(contextWithUpdatedBaggages, () => { - expect(JSON.parse(ddSpan.getAllBaggageItems())).to.deep.equal( - { key2: 'dd2' } - ) + assert.deepStrictEqual(JSON.parse(ddSpan.getAllBaggageItems()), { key2: 'dd2' }) ddSpan.removeBaggageItem('key2') assert.deepStrictEqual(propagation.getActiveBaggage().getAllEntries(), []) }) diff --git a/packages/dd-trace/test/opentelemetry/span.spec.js b/packages/dd-trace/test/opentelemetry/span.spec.js index afc4027c381..52bd9c4c885 100644 --- a/packages/dd-trace/test/opentelemetry/span.spec.js +++ b/packages/dd-trace/test/opentelemetry/span.spec.js @@ -248,7 +248,7 @@ describe('OTel Span', () => { const span = makeSpan('name') const spanContext = span.spanContext() - expect(spanContext).to.be.an.instanceOf(SpanContext) + assert.ok(spanContext instanceof SpanContext) assert.strictEqual(spanContext._ddContext, span._ddSpan.context()) }) @@ -468,7 +468,7 @@ describe('OTel Span', () => { const { _tags } = span._ddSpan.context() span.setStatus({ code: 2, message: 'error' }) - expect(_tags).to.not.have.property(ERROR_MESSAGE, 'error') + assert.ok(!(ERROR_MESSAGE in _tags) || _tags[ERROR_MESSAGE] !== 'error') }) it('should mark ended and expose recording state', () => { diff --git a/packages/dd-trace/test/opentelemetry/tracer.spec.js b/packages/dd-trace/test/opentelemetry/tracer.spec.js index 0a5037f95ef..f738fbb6562 100644 --- a/packages/dd-trace/test/opentelemetry/tracer.spec.js +++ b/packages/dd-trace/test/opentelemetry/tracer.spec.js @@ -1,8 +1,6 @@ 'use strict' const assert = require('node:assert/strict') - -const { expect } = require('chai') const { describe, it } = require('tap').mocha const sinon = require('sinon') const { performance } = require('perf_hooks') @@ -54,10 +52,10 @@ describe('OTel Tracer', () => { const otelTracer = new Tracer({}, {}, tracerProvider) const span = otelTracer.startSpan('name') - expect(span).to.be.an.instanceOf(Span) + assert.ok(span instanceof Span) const ddSpan = span._ddSpan - expect(ddSpan).to.be.an.instanceOf(DatadogSpan) + assert.ok(ddSpan instanceof DatadogSpan) assert.strictEqual(ddSpan._name, 'name') }) @@ -128,7 +126,7 @@ describe('OTel Tracer', () => { const otelTracer = new Tracer({}, {}, tracerProvider) otelTracer.startActiveSpan('name', (span) => { - expect(span).to.be.an.instanceOf(Span) + assert.ok(span instanceof Span) assert.strictEqual(span._ddSpan, tracer.scope().active()) }) }) @@ -182,7 +180,7 @@ describe('OTel Tracer', () => { const childContext = inner._ddSpan.context() assert.notStrictEqual(childContext.toTraceId(), parentContext.toTraceId()) - expect(childContext._parentId).to.not.eql(parentContext._spanId) + assert.notDeepStrictEqual(childContext._parentId, parentContext._spanId) }) }) diff --git a/packages/dd-trace/test/opentelemetry/tracer_provider.spec.js b/packages/dd-trace/test/opentelemetry/tracer_provider.spec.js index 08a8d8e18e7..5f7a92aa466 100644 --- a/packages/dd-trace/test/opentelemetry/tracer_provider.spec.js +++ b/packages/dd-trace/test/opentelemetry/tracer_provider.spec.js @@ -1,8 +1,6 @@ 'use strict' const assert = require('node:assert/strict') - -const { expect } = require('chai') const { describe, it } = require('tap').mocha const sinon = require('sinon') const { trace } = require('@opentelemetry/api') @@ -28,7 +26,7 @@ describe('OTel TracerProvider', () => { const provider = new TracerProvider() const tracer = provider.getTracer() - expect(tracer).to.be.an.instanceOf(Tracer) + assert.ok(tracer instanceof Tracer) assert.strictEqual(tracer, provider.getTracer()) }) @@ -46,7 +44,7 @@ describe('OTel TracerProvider', () => { // Initially is a NoopSpanProcessor assert.strictEqual(provider._processors.length, 0) - expect(provider.getActiveSpanProcessor()).to.be.an.instanceOf(NoopSpanProcessor) + assert.ok(provider.getActiveSpanProcessor() instanceof NoopSpanProcessor) // Swap out shutdown function to check if it's called const shutdown = sinon.stub() @@ -56,7 +54,7 @@ describe('OTel TracerProvider', () => { provider.addSpanProcessor(new NoopSpanProcessor()) sinon.assert.calledOnce(shutdown) assert.strictEqual(provider._processors.length, 1) - expect(provider.getActiveSpanProcessor()).to.be.an.instanceOf(MultiSpanProcessor) + assert.ok(provider.getActiveSpanProcessor() instanceof MultiSpanProcessor) }) it('should delegate shutdown to active span processor', () => { diff --git a/packages/dd-trace/test/opentracing/propagation/log.spec.js b/packages/dd-trace/test/opentracing/propagation/log.spec.js index be403425939..36cac9aa92f 100644 --- a/packages/dd-trace/test/opentracing/propagation/log.spec.js +++ b/packages/dd-trace/test/opentracing/propagation/log.spec.js @@ -1,8 +1,8 @@ 'use strict' const assert = require('node:assert/strict') +const { assertObjectContains } = require('../../../../../integration-tests/helpers') -const { expect } = require('chai') const { describe, it, beforeEach } = require('tap').mocha require('../../setup/core') @@ -52,7 +52,7 @@ describe('LogPropagator', () => { propagator.inject(null, carrier) - expect(carrier).to.deep.include({ + assertObjectContains(carrier, { dd: { service: 'test', env: 'dev', diff --git a/packages/dd-trace/test/opentracing/propagation/text_map.spec.js b/packages/dd-trace/test/opentracing/propagation/text_map.spec.js index 77063b99c94..6cbe77299ef 100644 --- a/packages/dd-trace/test/opentracing/propagation/text_map.spec.js +++ b/packages/dd-trace/test/opentracing/propagation/text_map.spec.js @@ -1,6 +1,10 @@ 'use strict' +const assert = require('node:assert/strict') + const { expect } = require('chai') +const { assertObjectContains } = require('../../../../../integration-tests/helpers') + const { describe, it, beforeEach } = require('tap').mocha const sinon = require('sinon') const proxyquire = require('proxyquire') @@ -97,10 +101,13 @@ describe('TextMapPropagator', () => { propagator.inject(spanContext, carrier) - expect(carrier).to.have.property('x-datadog-trace-id', '123') - expect(carrier).to.have.property('x-datadog-parent-id', '456') - expect(carrier).to.have.property('ot-baggage-foo', 'bar') - expect(carrier.baggage).to.be.undefined + assert.ok('x-datadog-trace-id' in carrier); + assert.strictEqual(carrier['x-datadog-trace-id'], '123') + assert.ok('x-datadog-parent-id' in carrier); + assert.strictEqual(carrier['x-datadog-parent-id'], '456') + assert.ok('ot-baggage-foo' in carrier); + assert.strictEqual(carrier['ot-baggage-foo'], 'bar') + assert.strictEqual(carrier.baggage, undefined) }) it('should handle non-string values', () => { @@ -115,11 +122,11 @@ describe('TextMapPropagator', () => { propagator.inject(spanContext, carrier) - expect(carrier['ot-baggage-number']).to.equal('1.23') - expect(carrier['ot-baggage-bool']).to.equal('true') - expect(carrier['ot-baggage-array']).to.equal('foo,bar') - expect(carrier['ot-baggage-object']).to.equal('[object Object]') - expect(carrier.baggage).to.be.undefined + assert.strictEqual(carrier['ot-baggage-number'], '1.23') + assert.strictEqual(carrier['ot-baggage-bool'], 'true') + assert.strictEqual(carrier['ot-baggage-array'], 'foo,bar') + assert.strictEqual(carrier['ot-baggage-object'], '[object Object]') + assert.strictEqual(carrier.baggage, undefined) }) it('should handle special characters in baggage', () => { @@ -127,7 +134,7 @@ describe('TextMapPropagator', () => { setBaggageItem('",;\\()/:<=>?@[]{}🐶é我', '",;\\🐶é我') propagator.inject(undefined, carrier) // eslint-disable-next-line @stylistic/max-len - expect(carrier.baggage).to.be.equal('%22%2C%3B%5C%28%29%2F%3A%3C%3D%3E%3F%40%5B%5D%7B%7D%F0%9F%90%B6%C3%A9%E6%88%91=%22%2C%3B%5C%F0%9F%90%B6%C3%A9%E6%88%91') + assert.strictEqual(carrier.baggage, '%22%2C%3B%5C%28%29%2F%3A%3C%3D%3E%3F%40%5B%5D%7B%7D%F0%9F%90%B6%C3%A9%E6%88%91=%22%2C%3B%5C%F0%9F%90%B6%C3%A9%E6%88%91') }) it('should drop excess baggage items when there are too many pairs', () => { @@ -136,7 +143,7 @@ describe('TextMapPropagator', () => { setBaggageItem(`key-${i}`, i) } propagator.inject(undefined, carrier) - expect(carrier.baggage.split(',').length).to.equal(config.baggageMaxItems) + assert.strictEqual(carrier.baggage.split(',').length, config.baggageMaxItems) }) it('should drop excess baggage items when the resulting baggage header contains many bytes', () => { @@ -145,7 +152,7 @@ describe('TextMapPropagator', () => { setBaggageItem('foo', Buffer.alloc(config.baggageMaxBytes).toString()) propagator.inject(undefined, carrier) - expect(carrier.baggage).to.equal('raccoon=chunky') + assert.strictEqual(carrier.baggage, 'raccoon=chunky') }) it('should inject an existing sampling priority', () => { @@ -158,7 +165,8 @@ describe('TextMapPropagator', () => { propagator.inject(spanContext, carrier) - expect(carrier).to.have.property('x-datadog-sampling-priority', '0') + assert.ok('x-datadog-sampling-priority' in carrier); + assert.strictEqual(carrier['x-datadog-sampling-priority'], '0') }) it('should inject the origin', () => { @@ -172,7 +180,8 @@ describe('TextMapPropagator', () => { propagator.inject(spanContext, carrier) - expect(carrier).to.have.property('x-datadog-origin', 'synthetics') + assert.ok('x-datadog-origin' in carrier); + assert.strictEqual(carrier['x-datadog-origin'], 'synthetics') }) it('should inject trace tags prefixed for propagation', () => { @@ -189,7 +198,8 @@ describe('TextMapPropagator', () => { propagator.inject(spanContext, carrier) - expect(carrier).to.have.property('x-datadog-tags', '_dd.p.foo=foo,_dd.p.baz=baz') + assert.ok('x-datadog-tags' in carrier); + assert.strictEqual(carrier['x-datadog-tags'], '_dd.p.foo=foo,_dd.p.baz=baz') }) it('should drop trace tags if too large', () => { @@ -204,7 +214,7 @@ describe('TextMapPropagator', () => { propagator.inject(spanContext, carrier) - expect(carrier).to.not.have.property('x-datadog-tags') + assert.ok(!('x-datadog-tags' in carrier)) }) it('should drop trace tags if value is invalid', () => { @@ -219,7 +229,7 @@ describe('TextMapPropagator', () => { propagator.inject(spanContext, carrier) - expect(carrier).to.not.have.property('x-datadog-tags') + assert.ok(!('x-datadog-tags' in carrier)) }) it('should drop trace tags if key is invalid', () => { @@ -234,7 +244,7 @@ describe('TextMapPropagator', () => { propagator.inject(spanContext, carrier) - expect(carrier).to.not.have.property('x-datadog-tags') + assert.ok(!('x-datadog-tags' in carrier)) }) it('should drop trace tags if disabled', () => { @@ -251,7 +261,7 @@ describe('TextMapPropagator', () => { propagator.inject(spanContext, carrier) - expect(carrier).to.not.have.property('x-datadog-tags') + assert.ok(!('x-datadog-tags' in carrier)) }) it('should inject the trace B3 headers', () => { @@ -269,11 +279,16 @@ describe('TextMapPropagator', () => { propagator.inject(spanContext, carrier) - expect(carrier).to.have.property('x-b3-traceid', '0000000000000123') - expect(carrier).to.have.property('x-b3-spanid', '0000000000000456') - expect(carrier).to.have.property('x-b3-parentspanid', '0000000000000789') - expect(carrier).to.have.property('x-b3-sampled', '1') - expect(carrier).to.have.property('x-b3-flags', '1') + assert.ok('x-b3-traceid' in carrier); + assert.strictEqual(carrier['x-b3-traceid'], '0000000000000123') + assert.ok('x-b3-spanid' in carrier); + assert.strictEqual(carrier['x-b3-spanid'], '0000000000000456') + assert.ok('x-b3-parentspanid' in carrier); + assert.strictEqual(carrier['x-b3-parentspanid'], '0000000000000789') + assert.ok('x-b3-sampled' in carrier); + assert.strictEqual(carrier['x-b3-sampled'], '1') + assert.ok('x-b3-flags' in carrier); + assert.strictEqual(carrier['x-b3-flags'], '1') }) it('should inject the 128-bit trace ID in B3 headers when available as tag', () => { @@ -291,7 +306,8 @@ describe('TextMapPropagator', () => { propagator.inject(spanContext, carrier) - expect(carrier).to.have.property('x-b3-traceid', '00000000000002340000000000000123') + assert.ok('x-b3-traceid' in carrier); + assert.strictEqual(carrier['x-b3-traceid'], '00000000000002340000000000000123') }) it('should inject the 128-bit trace ID in B3 headers when available as ID', () => { @@ -309,7 +325,8 @@ describe('TextMapPropagator', () => { propagator.inject(spanContext, carrier) - expect(carrier).to.have.property('x-b3-traceid', '00000000000002340000000000000123') + assert.ok('x-b3-traceid' in carrier); + assert.strictEqual(carrier['x-b3-traceid'], '00000000000002340000000000000123') }) it('should inject the traceparent header', () => { @@ -331,13 +348,12 @@ describe('TextMapPropagator', () => { config.tracePropagationStyle.inject = ['tracecontext'] propagator.inject(spanContext, carrier) - expect(spanContext._isRemote).to.equal(false) + assert.strictEqual(spanContext._isRemote, false) - expect(carrier).to.have.property('traceparent', '00-1111aaaa2222bbbb3333cccc4444dddd-5555eeee6666ffff-01') - expect(carrier).to.have.property( - 'tracestate', - 'dd=t.foo_bar_baz_:abc_!@#$%^&*()_+`-~;p:5555eeee6666ffff;s:2;o:foo_bar~;t.dm:-4,other=bleh' - ) + assert.ok('traceparent' in carrier); + assert.strictEqual(carrier['traceparent'], '00-1111aaaa2222bbbb3333cccc4444dddd-5555eeee6666ffff-01') + assert.ok('tracestate' in carrier); + assert.strictEqual(carrier['tracestate'], 'dd=t.foo_bar_baz_:abc_!@#$%^&*()_+`-~;p:5555eeee6666ffff;s:2;o:foo_bar~;t.dm:-4,other=bleh') }) it('should skip injection of B3 headers without the feature flag', () => { @@ -349,7 +365,7 @@ describe('TextMapPropagator', () => { propagator.inject(spanContext, carrier) - expect(carrier).to.not.have.property('x-b3-traceid') + assert.ok(!('x-b3-traceid' in carrier)) }) it('should skip injection of traceparent header without the feature flag', () => { @@ -363,7 +379,7 @@ describe('TextMapPropagator', () => { propagator.inject(spanContext, carrier) - expect(carrier).to.not.have.property('traceparent') + assert.ok(!('traceparent' in carrier)) }) it('should skip injection of datadog headers without the feature flag', () => { @@ -377,11 +393,11 @@ describe('TextMapPropagator', () => { propagator.inject(spanContext, carrier) - expect(carrier).to.not.have.property('x-datadog-trace-id') - expect(carrier).to.not.have.property('x-datadog-parent-id') - expect(carrier).to.not.have.property('x-datadog-sampling-priority') - expect(carrier).to.not.have.property('x-datadog-origin') - expect(carrier).to.not.have.property('x-datadog-tags') + assert.ok(!('x-datadog-trace-id' in carrier)) + assert.ok(!('x-datadog-parent-id' in carrier)) + assert.ok(!('x-datadog-sampling-priority' in carrier)) + assert.ok(!('x-datadog-origin' in carrier)) + assert.ok(!('x-datadog-tags' in carrier)) }) it('should publish spanContext and carrier', () => { @@ -397,8 +413,8 @@ describe('TextMapPropagator', () => { propagator.inject(spanContext, carrier) try { - expect(onSpanInject).to.be.calledOnce - expect(onSpanInject.firstCall.args[0]).to.be.deep.equal({ spanContext, carrier }) + sinon.assert.calledOnce(onSpanInject) + assert.deepStrictEqual(onSpanInject.firstCall.args[0], { spanContext, carrier }) } finally { injectCh.unsubscribe(onSpanInject) } @@ -418,9 +434,9 @@ describe('TextMapPropagator', () => { propagator.inject(undefined, carrier) - expect(tracerMetrics.count).to.have.been.calledWith('context_header_style.injected', ['header_style:baggage']) + sinon.assert.calledWith(tracerMetrics.count, 'context_header_style.injected', ['header_style:baggage']) expect(tracerMetrics.count().inc).to.have.been.called - expect(carrier.baggage).to.equal('test-key=test-value') + assert.strictEqual(carrier.baggage, 'test-key=test-value') }) it('should track truncation metric when baggage item count exceeds limit', () => { @@ -435,7 +451,7 @@ describe('TextMapPropagator', () => { propagator.inject(undefined, carrier) - expect(tracerMetrics.count).to.have.been.calledWith( + sinon.assert.calledWith(tracerMetrics.count, 'context_header.truncated', ['truncation_reason:baggage_item_count_exceeded'] ) @@ -455,7 +471,7 @@ describe('TextMapPropagator', () => { propagator.inject(undefined, carrier) - expect(tracerMetrics.count).to.have.been.calledWith( + sinon.assert.calledWith(tracerMetrics.count, 'context_header.truncated', ['truncation_reason:baggage_byte_count_exceeded'] ) @@ -472,12 +488,12 @@ describe('TextMapPropagator', () => { const carrier = textMap const spanContext = propagator.extract(carrier) - expect(spanContext.toTraceId()).to.equal(carrier['x-datadog-trace-id']) - expect(spanContext.toSpanId()).to.equal(carrier['x-datadog-parent-id']) - expect(spanContext._baggageItems.foo).to.equal(carrier['ot-baggage-foo']) - expect(spanContext._baggageItems).to.deep.equal({ foo: 'bar' }) - expect(getAllBaggageItems()).to.deep.equal({ foo: 'bar' }) - expect(spanContext._isRemote).to.equal(true) + assert.strictEqual(spanContext.toTraceId(), carrier['x-datadog-trace-id']) + assert.strictEqual(spanContext.toSpanId(), carrier['x-datadog-parent-id']) + assert.strictEqual(spanContext._baggageItems.foo, carrier['ot-baggage-foo']) + assert.deepStrictEqual(spanContext._baggageItems, { foo: 'bar' }) + assert.deepStrictEqual(getAllBaggageItems(), { foo: 'bar' }) + assert.strictEqual(spanContext._isRemote, true) }) it('should extract opentracing baggage when baggage is not a propagation style ', () => { @@ -491,12 +507,12 @@ describe('TextMapPropagator', () => { const carrier = textMap const spanContext = propagator.extract(carrier) - expect(spanContext.toTraceId()).to.equal(carrier['x-datadog-trace-id']) - expect(spanContext.toSpanId()).to.equal(carrier['x-datadog-parent-id']) - expect(spanContext._baggageItems.foo).to.equal(carrier['ot-baggage-foo']) - expect(spanContext._baggageItems).to.deep.equal({ foo: 'bar' }) - expect(getAllBaggageItems()).to.deep.equal({}) - expect(spanContext._isRemote).to.equal(true) + assert.strictEqual(spanContext.toTraceId(), carrier['x-datadog-trace-id']) + assert.strictEqual(spanContext.toSpanId(), carrier['x-datadog-parent-id']) + assert.strictEqual(spanContext._baggageItems.foo, carrier['ot-baggage-foo']) + assert.deepStrictEqual(spanContext._baggageItems, { foo: 'bar' }) + assert.deepStrictEqual(getAllBaggageItems(), {}) + assert.strictEqual(spanContext._isRemote, true) }) it('should extract otel baggage items with special characters', () => { @@ -508,8 +524,8 @@ describe('TextMapPropagator', () => { baggage: '%22%2C%3B%5C%28%29%2F%3A%3C%3D%3E%3F%40%5B%5D%7B%7D=%22%2C%3B%5C' } const spanContext = propagator.extract(carrier) - expect(spanContext._baggageItems).to.deep.equal({}) - expect(getAllBaggageItems()).to.deep.equal({ '",;\\()/:<=>?@[]{}': '",;\\' }) + assert.deepStrictEqual(spanContext._baggageItems, {}) + assert.deepStrictEqual(getAllBaggageItems(), { '",;\\()/:<=>?@[]{}': '",;\\' }) }) it('should not extract baggage when the header is malformed', () => { @@ -519,8 +535,8 @@ describe('TextMapPropagator', () => { baggage: 'no-equal-sign,foo=gets-dropped-because-previous-pair-is-malformed' } const spanContextA = propagator.extract(carrierA) - expect(spanContextA._baggageItems).to.deep.equal({}) - expect(getAllBaggageItems()).to.deep.equal({}) + assert.deepStrictEqual(spanContextA._baggageItems, {}) + assert.deepStrictEqual(getAllBaggageItems(), {}) const carrierB = { 'x-datadog-trace-id': '123', @@ -528,8 +544,8 @@ describe('TextMapPropagator', () => { baggage: 'foo=gets-dropped-because-subsequent-pair-is-malformed,=' } const spanContextB = propagator.extract(carrierB) - expect(spanContextB._baggageItems).to.deep.equal({}) - expect(getAllBaggageItems()).to.deep.equal({}) + assert.deepStrictEqual(spanContextB._baggageItems, {}) + assert.deepStrictEqual(getAllBaggageItems(), {}) const carrierC = { 'x-datadog-trace-id': '123', @@ -537,8 +553,8 @@ describe('TextMapPropagator', () => { baggage: '=no-key' } const spanContextC = propagator.extract(carrierC) - expect(spanContextC._baggageItems).to.deep.equal({}) - expect(getAllBaggageItems()).to.deep.equal({}) + assert.deepStrictEqual(spanContextC._baggageItems, {}) + assert.deepStrictEqual(getAllBaggageItems(), {}) const carrierD = { 'x-datadog-trace-id': '123', @@ -546,8 +562,8 @@ describe('TextMapPropagator', () => { baggage: 'no-value=' } const spanContextD = propagator.extract(carrierD) - expect(spanContextD._baggageItems).to.deep.equal({}) - expect(getAllBaggageItems()).to.deep.equal({}) + assert.deepStrictEqual(spanContextD._baggageItems, {}) + assert.deepStrictEqual(getAllBaggageItems(), {}) }) it('should add baggage items to span tags', () => { @@ -558,7 +574,7 @@ describe('TextMapPropagator', () => { baggage: 'user.id=capybara,session.id=987,account.id=789,nonDefaultKey=shouldBeIgnored' } const spanContextA = propagator.extract(carrier) - expect(spanContextA._trace.tags).to.deep.equal({ + assert.deepStrictEqual(spanContextA._trace.tags, { 'baggage.user.id': 'capybara', 'baggage.session.id': '987', 'baggage.account.id': '789' @@ -571,7 +587,7 @@ describe('TextMapPropagator', () => { baggage: 'user.id=capybara,sesSion.id=987,account.id=789' } const spanContextB = propagator.extract(carrier) - expect(spanContextB._trace.tags).to.deep.equal({ + assert.deepStrictEqual(spanContextB._trace.tags, { 'baggage.user.id': 'capybara', 'baggage.account.id': '789' }) @@ -582,7 +598,7 @@ describe('TextMapPropagator', () => { }) propagator = new TextMapPropagator(config) const spanContextC = propagator.extract(carrier) - expect(spanContextC._trace.tags).to.deep.equal({}) + assert.deepStrictEqual(spanContextC._trace.tags, {}) // should not add baggage when key list is empty config = getConfigFresh({ @@ -595,7 +611,7 @@ describe('TextMapPropagator', () => { baggage: 'customKey=beluga,randomKey=shouldBeIgnored' } const spanContextD = propagator.extract(carrier) - expect(spanContextD._trace.tags).to.deep.equal({ + assert.deepStrictEqual(spanContextD._trace.tags, { 'baggage.customKey': 'beluga' }) @@ -610,7 +626,7 @@ describe('TextMapPropagator', () => { baggage: 'customKey=beluga,randomKey=nothingIsIgnored' } const spanContextE = propagator.extract(carrier) - expect(spanContextE._trace.tags).to.deep.equal({ + assert.deepStrictEqual(spanContextE._trace.tags, { 'baggage.customKey': 'beluga', 'baggage.randomKey': 'nothingIsIgnored' }) @@ -624,9 +640,9 @@ describe('TextMapPropagator', () => { 'x-datadog-tags': '_dd.p.tid=1234567890abcdeX' } let spanContext = propagator.extract(carrier) - expect(spanContext.toTraceId()).to.equal(carrier['x-datadog-trace-id']) - expect(spanContext.toSpanId()).to.equal(carrier['x-datadog-parent-id']) - expect(spanContext._trace.tags).to.not.have.property('_dd.p.tid') + assert.strictEqual(spanContext.toTraceId(), carrier['x-datadog-trace-id']) + assert.strictEqual(spanContext.toSpanId(), carrier['x-datadog-parent-id']) + assert.ok(!('_dd.p.tid' in spanContext._trace.tags)) // tid too long carrier = { @@ -635,9 +651,9 @@ describe('TextMapPropagator', () => { 'x-datadog-tags': '_dd.p.tid=1234567890abcdef1' } spanContext = propagator.extract(carrier) - expect(spanContext.toTraceId()).to.equal(carrier['x-datadog-trace-id']) - expect(spanContext.toSpanId()).to.equal(carrier['x-datadog-parent-id']) - expect(spanContext._trace.tags).to.not.have.property('_dd.p.tid') + assert.strictEqual(spanContext.toTraceId(), carrier['x-datadog-trace-id']) + assert.strictEqual(spanContext.toSpanId(), carrier['x-datadog-parent-id']) + assert.ok(!('_dd.p.tid' in spanContext._trace.tags)) // tid too short carrier = { @@ -646,9 +662,9 @@ describe('TextMapPropagator', () => { 'x-datadog-tags': '_dd.p.tid=1234567890abcde' } spanContext = propagator.extract(carrier) - expect(spanContext.toTraceId()).to.equal(carrier['x-datadog-trace-id']) - expect(spanContext.toSpanId()).to.equal(carrier['x-datadog-parent-id']) - expect(spanContext._trace.tags).to.not.have.property('_dd.p.tid') + assert.strictEqual(spanContext.toTraceId(), carrier['x-datadog-trace-id']) + assert.strictEqual(spanContext.toSpanId(), carrier['x-datadog-parent-id']) + assert.ok(!('_dd.p.tid' in spanContext._trace.tags)) }) it('should extract baggage when it is the only propagation style', () => { @@ -663,9 +679,9 @@ describe('TextMapPropagator', () => { baggage: 'foo=bar' } const spanContext = propagator.extract(carrier) - expect(spanContext).to.equal(null) - expect(getBaggageItem('foo')).to.equal('bar') - expect(getAllBaggageItems()).to.deep.equal({ foo: 'bar' }) + assert.strictEqual(spanContext, null) + assert.strictEqual(getBaggageItem('foo'), 'bar') + assert.deepStrictEqual(getAllBaggageItems(), { foo: 'bar' }) }) it('should convert signed IDs to unsigned', () => { @@ -675,15 +691,15 @@ describe('TextMapPropagator', () => { const carrier = textMap const spanContext = propagator.extract(carrier) - expect(spanContext.toTraceId()).to.equal('18446744073709551493') // -123 casted to uint64 - expect(spanContext.toSpanId()).to.equal('18446744073709551160') // -456 casted to uint64 + assert.strictEqual(spanContext.toTraceId(), '18446744073709551493') // -123 casted to uint64 + assert.strictEqual(spanContext.toSpanId(), '18446744073709551160') // -456 casted to uint64 }) it('should return null if the carrier does not contain a trace', () => { const carrier = {} const spanContext = propagator.extract(carrier) - expect(spanContext).to.equal(null) + assert.strictEqual(spanContext, null) }) it('should extract a span context with a valid sampling priority', () => { @@ -691,7 +707,7 @@ describe('TextMapPropagator', () => { const carrier = textMap const spanContext = propagator.extract(carrier) - expect(spanContext._sampling.priority).to.equal(AUTO_REJECT) + assert.strictEqual(spanContext._sampling.priority, AUTO_REJECT) }) it('should extract the origin', () => { @@ -699,7 +715,8 @@ describe('TextMapPropagator', () => { const carrier = textMap const spanContext = propagator.extract(carrier) - expect(spanContext._trace).to.have.property('origin', 'synthetics') + assert.ok('origin' in spanContext._trace); + assert.strictEqual(spanContext._trace['origin'], 'synthetics') }) it('should extract trace tags', () => { @@ -708,7 +725,7 @@ describe('TextMapPropagator', () => { const carrier = textMap const spanContext = propagator.extract(carrier) - expect(spanContext._trace.tags).to.include({ + assertObjectContains(spanContext._trace.tags, { '_dd.p.foo': 'bar', '_dd.p.baz': 'qux' }) @@ -720,7 +737,7 @@ describe('TextMapPropagator', () => { const carrier = textMap const spanContext = propagator.extract(carrier) - expect(spanContext._trace.tags).to.not.have.property('_dd.p.foo') + assert.ok(!('_dd.p.foo' in spanContext._trace.tags)) }) it('should not extract invalid trace tags', () => { @@ -729,7 +746,7 @@ describe('TextMapPropagator', () => { const carrier = textMap const spanContext = propagator.extract(carrier) - expect(spanContext._trace.tags).to.not.have.property('_dd.p.foo') + assert.ok(!('_dd.p.foo' in spanContext._trace.tags)) }) it('should not extract trace tags with invalid values', () => { @@ -738,7 +755,7 @@ describe('TextMapPropagator', () => { const carrier = textMap const spanContext = propagator.extract(carrier) - expect(spanContext._trace.tags).to.not.have.property('_dd.p.foo') + assert.ok(!('_dd.p.foo' in spanContext._trace.tags)) }) it('should not extract trace tags with invalid keys', () => { @@ -747,7 +764,7 @@ describe('TextMapPropagator', () => { const carrier = textMap const spanContext = propagator.extract(carrier) - expect(spanContext._trace.tags).to.not.have.property('_ddupefoo') + assert.ok(!('_ddupefoo' in spanContext._trace.tags)) }) it('should not extract trace tags when disabled', () => { @@ -757,8 +774,8 @@ describe('TextMapPropagator', () => { const carrier = textMap const spanContext = propagator.extract(carrier) - expect(spanContext._trace.tags).to.not.have.property('_dd.p.foo') - expect(spanContext._trace.tags).to.not.have.property('_dd.p.baz') + assert.ok(!('_dd.p.foo' in spanContext._trace.tags)) + assert.ok(!('_dd.p.baz' in spanContext._trace.tags)) }) it('should extract from an aws-sqsd header', () => { @@ -768,7 +785,7 @@ describe('TextMapPropagator', () => { const spanContext = propagator.extract(carrier) - expect(spanContext).to.deep.equal(createContext({ + assert.deepStrictEqual(spanContext, createContext({ baggageItems: { foo: 'bar' } @@ -780,7 +797,7 @@ describe('TextMapPropagator', () => { config.tracePropagationStyle.extract = [] const spanContext = propagator.extract(carrier) - expect(spanContext).to.be.null + assert.strictEqual(spanContext, null) }) it('should support prioritization', () => { @@ -789,8 +806,8 @@ describe('TextMapPropagator', () => { // No traceparent yet, will skip ahead to datadog const second = propagator.extract(textMap) - expect(second.toTraceId()).to.equal(textMap['x-datadog-trace-id']) - expect(second.toSpanId()).to.equal(textMap['x-datadog-parent-id']) + assert.strictEqual(second.toTraceId(), textMap['x-datadog-trace-id']) + assert.strictEqual(second.toSpanId(), textMap['x-datadog-parent-id']) // Add a traceparent header and it will prioritize it const traceId = '1111aaaa2222bbbb3333cccc4444dddd' @@ -800,8 +817,8 @@ describe('TextMapPropagator', () => { const first = propagator.extract(textMap) - expect(first._traceId.toString(16)).to.equal(traceId) - expect(first._spanId.toString(16)).to.equal(spanId) + assert.strictEqual(first._traceId.toString(16), traceId) + assert.strictEqual(first._spanId.toString(16), spanId) }) it('should not crash with invalid traceparent', () => { @@ -818,7 +835,7 @@ describe('TextMapPropagator', () => { const carrier = textMap const spanContext = propagator.extract(carrier) - expect(spanContext._tracestate.get('other')).to.equal('bleh') + assert.strictEqual(spanContext._tracestate.get('other'), 'bleh') }) it('should extract the last datadog parent id from tracestate when p dd member is availible', () => { @@ -829,7 +846,8 @@ describe('TextMapPropagator', () => { const carrier = textMap const spanContext = propagator.extract(carrier) - expect(spanContext._trace.tags).to.have.property('_dd.parent_id', '2244eeee6666aaaa') + assert.ok('_dd.parent_id' in spanContext._trace.tags); + assert.strictEqual(spanContext._trace.tags['_dd.parent_id'], '2244eeee6666aaaa') }) it('should preserve trace header tid when tracestate contains an inconsistent tid', () => { @@ -840,8 +858,9 @@ describe('TextMapPropagator', () => { const carrier = textMap const spanContext = propagator.extract(carrier) - expect(spanContext._traceId.toString(16)).to.equal('640cfd8d00000000abcdefab12345678') - expect(spanContext._trace.tags).to.have.property('_dd.p.tid', '640cfd8d00000000') + assert.strictEqual(spanContext._traceId.toString(16), '640cfd8d00000000abcdefab12345678') + assert.ok('_dd.p.tid' in spanContext._trace.tags); + assert.strictEqual(spanContext._trace.tags['_dd.p.tid'], '640cfd8d00000000') }) it('should preserve trace header tid when tracestate contains a malformed tid', () => { @@ -852,8 +871,9 @@ describe('TextMapPropagator', () => { const carrier = textMap const spanContext = propagator.extract(carrier) - expect(spanContext._traceId.toString(16)).to.equal('640cfd8d00000000abcdefab12345678') - expect(spanContext._trace.tags).to.have.property('_dd.p.tid', '640cfd8d00000000') + assert.strictEqual(spanContext._traceId.toString(16), '640cfd8d00000000abcdefab12345678') + assert.ok('_dd.p.tid' in spanContext._trace.tags); + assert.strictEqual(spanContext._trace.tags['_dd.p.tid'], '640cfd8d00000000') }) it('should set the last datadog parent id to zero when p: is NOT in the tracestate', () => { @@ -863,7 +883,7 @@ describe('TextMapPropagator', () => { const carrier = textMap const spanContext = propagator.extract(carrier) - expect(spanContext._trace.tags).to.not.have.property('_dd.parent_id') + assert.ok(!('_dd.parent_id' in spanContext._trace.tags)) }) it('should not extract tracestate from tracecontext when trace IDs don\'t match', () => { @@ -874,7 +894,7 @@ describe('TextMapPropagator', () => { const carrier = textMap const spanContext = propagator.extract(carrier) - expect(spanContext._tracestate).to.be.undefined + assert.strictEqual(spanContext._tracestate, undefined) }) it('should not extract tracestate from tracecontext when configured to extract first', () => { @@ -886,7 +906,7 @@ describe('TextMapPropagator', () => { const carrier = textMap const spanContext = propagator.extract(carrier) - expect(spanContext._tracestate).to.be.undefined + assert.strictEqual(spanContext._tracestate, undefined) }) it('extracts span_id from tracecontext headers and stores datadog parent-id in trace_distributed_tags', () => { @@ -897,9 +917,10 @@ describe('TextMapPropagator', () => { const carrier = textMap const spanContext = propagator.extract(carrier) - expect(parseInt(spanContext._spanId.toString(), 16)).to.equal(73456) - expect(parseInt(spanContext._traceId.toString(), 16)).to.equal(61185) - expect(spanContext._trace.tags).to.have.property('_dd.parent_id', '000000000000000f') + assert.strictEqual(parseInt(spanContext._spanId.toString(), 16), 73456) + assert.strictEqual(parseInt(spanContext._traceId.toString(), 16), 61185) + assert.ok('_dd.parent_id' in spanContext._trace.tags); + assert.strictEqual(spanContext._trace.tags['_dd.parent_id'], '000000000000000f') }) it('extracts span_id from tracecontext headers and stores p value from tracestate in trace_distributed_tags', @@ -912,9 +933,10 @@ describe('TextMapPropagator', () => { const carrier = textMap const spanContext = propagator.extract(carrier) - expect(parseInt(spanContext._spanId.toString(), 16)).to.equal(73456) - expect(parseInt(spanContext._traceId.toString(), 16)).to.equal(61185) - expect(spanContext._trace.tags).to.have.property('_dd.parent_id', '0000000000000001') + assert.strictEqual(parseInt(spanContext._spanId.toString(), 16), 73456) + assert.strictEqual(parseInt(spanContext._traceId.toString(), 16), 61185) + assert.ok('_dd.parent_id' in spanContext._trace.tags); + assert.strictEqual(spanContext._trace.tags['_dd.parent_id'], '0000000000000001') }) it('should publish spanContext and carrier', () => { @@ -925,8 +947,8 @@ describe('TextMapPropagator', () => { const spanContext = propagator.extract(carrier) try { - expect(onSpanExtract).to.be.calledOnce - expect(onSpanExtract.firstCall.args[0]).to.be.deep.equal({ spanContext, carrier }) + sinon.assert.calledOnce(onSpanExtract) + assert.deepStrictEqual(onSpanExtract.firstCall.args[0], { spanContext, carrier }) } finally { extractCh.unsubscribe(onSpanExtract) } @@ -951,9 +973,9 @@ describe('TextMapPropagator', () => { propagator.extract(carrier) - expect(tracerMetrics.count).to.have.been.calledWith('context_header_style.extracted', ['header_style:baggage']) + sinon.assert.calledWith(tracerMetrics.count, 'context_header_style.extracted', ['header_style:baggage']) expect(tracerMetrics.count().inc).to.have.been.called - expect(getBaggageItem('test-key')).to.equal('test-value') + assert.strictEqual(getBaggageItem('test-key'), 'test-value') }) it('should track malformed metric when baggage has empty key', () => { @@ -965,9 +987,9 @@ describe('TextMapPropagator', () => { propagator.extract(carrier) - expect(tracerMetrics.count).to.have.been.calledWith('context_header_style.malformed', ['header_style:baggage']) + sinon.assert.calledWith(tracerMetrics.count, 'context_header_style.malformed', ['header_style:baggage']) expect(tracerMetrics.count().inc).to.have.been.called - expect(getAllBaggageItems()).to.deep.equal({}) + assert.deepStrictEqual(getAllBaggageItems(), {}) }) }) @@ -981,11 +1003,11 @@ describe('TextMapPropagator', () => { const first = propagator.extract(textMap) - expect(first._links.length).to.equal(1) - expect(first._links[0].context.toTraceId()).to.equal(textMap['x-datadog-trace-id']) - expect(first._links[0].context.toSpanId()).to.equal(textMap['x-datadog-parent-id']) - expect(first._links[0].attributes.reason).to.equal('terminated_context') - expect(first._links[0].attributes.context_headers).to.equal('datadog') + assert.strictEqual(first._links.length, 1) + assert.strictEqual(first._links[0].context.toTraceId(), textMap['x-datadog-trace-id']) + assert.strictEqual(first._links[0].context.toSpanId(), textMap['x-datadog-parent-id']) + assert.strictEqual(first._links[0].attributes.reason, 'terminated_context') + assert.strictEqual(first._links[0].attributes.context_headers, 'datadog') }) it('should log extraction', () => { @@ -993,8 +1015,8 @@ describe('TextMapPropagator', () => { propagator.extract(carrier) - expect(log.debug).to.have.been.called - expect(log.debug.firstCall.args[0]()).to.equal([ + sinon.assert.called(log.debug) + assert.strictEqual(log.debug.firstCall.args[0](), [ 'Extract from carrier (datadog, tracecontext, baggage):', '{"x-datadog-trace-id":"123","x-datadog-parent-id":"456"}.' ].join(' ')) @@ -1016,7 +1038,7 @@ describe('TextMapPropagator', () => { const carrier = textMap const spanContext = propagator.extract(carrier) - expect(spanContext).to.deep.equal(createContext({ + assert.deepStrictEqual(spanContext, createContext({ traceId: id('123', 16), spanId: id('456', 16), sampling: { @@ -1032,10 +1054,10 @@ describe('TextMapPropagator', () => { const spanContext = propagator.extract(carrier) const idExpr = /^[0-9a-f]{16}$/ - expect(spanContext._traceId).to.match(idExpr) - expect(spanContext._traceId.toString()).to.not.equal('0000000000000000') - expect(spanContext._spanId).to.be.null - expect(spanContext._sampling.priority).to.equal(AUTO_REJECT) + assert.match(spanContext._traceId, idExpr) + assert.notStrictEqual(spanContext._traceId.toString(), '0000000000000000') + assert.strictEqual(spanContext._spanId, null) + assert.strictEqual(spanContext._sampling.priority, AUTO_REJECT) }) it('should support sampled traces', () => { @@ -1045,10 +1067,10 @@ describe('TextMapPropagator', () => { const spanContext = propagator.extract(carrier) const idExpr = /^[0-9a-f]{16}$/ - expect(spanContext._traceId).to.match(idExpr) - expect(spanContext._traceId.toString()).to.not.equal('0000000000000000') - expect(spanContext._spanId).to.be.null - expect(spanContext._sampling.priority).to.equal(AUTO_KEEP) + assert.match(spanContext._traceId, idExpr) + assert.notStrictEqual(spanContext._traceId.toString(), '0000000000000000') + assert.strictEqual(spanContext._spanId, null) + assert.strictEqual(spanContext._sampling.priority, AUTO_KEEP) }) it('should support the debug flag', () => { @@ -1058,10 +1080,10 @@ describe('TextMapPropagator', () => { const spanContext = propagator.extract(carrier) const idExpr = /^[0-9a-f]{16}$/ - expect(spanContext._traceId).to.match(idExpr) - expect(spanContext._traceId.toString()).to.not.equal('0000000000000000') - expect(spanContext._spanId).to.be.null - expect(spanContext._sampling.priority).to.equal(USER_KEEP) + assert.match(spanContext._traceId, idExpr) + assert.notStrictEqual(spanContext._traceId.toString(), '0000000000000000') + assert.strictEqual(spanContext._spanId, null) + assert.strictEqual(spanContext._sampling.priority, USER_KEEP) }) it('should skip extraction without the feature flag', () => { @@ -1073,7 +1095,7 @@ describe('TextMapPropagator', () => { const carrier = textMap const spanContext = propagator.extract(carrier) - expect(spanContext).to.be.null + assert.strictEqual(spanContext, null) }) it('should log extraction', () => { @@ -1082,8 +1104,8 @@ describe('TextMapPropagator', () => { propagator.extract(textMap) - expect(log.debug).to.have.been.called - expect(log.debug.firstCall.args[0]()).to.equal([ + sinon.assert.called(log.debug) + assert.strictEqual(log.debug.firstCall.args[0](), [ 'Extract from carrier (b3multi):', '{"x-b3-traceid":"0000000000000123","x-b3-spanid":"0000000000000456"}.' ].join(' ')) @@ -1104,7 +1126,7 @@ describe('TextMapPropagator', () => { const carrier = textMap const spanContext = propagator.extract(carrier) - expect(spanContext).to.deep.equal(createContext({ + assert.deepStrictEqual(spanContext, createContext({ traceId: id('123', 16), spanId: id('456', 16) })) @@ -1116,7 +1138,7 @@ describe('TextMapPropagator', () => { const carrier = textMap const spanContext = propagator.extract(carrier) - expect(spanContext).to.deep.equal(createContext({ + assert.deepStrictEqual(spanContext, createContext({ traceId: id('123', 16), spanId: id('456', 16), sampling: { @@ -1131,7 +1153,7 @@ describe('TextMapPropagator', () => { const carrier = textMap const spanContext = propagator.extract(carrier) - expect(spanContext).to.deep.equal(createContext({ + assert.deepStrictEqual(spanContext, createContext({ traceId: id('123', 16), spanId: id('456', 16), sampling: { @@ -1147,10 +1169,10 @@ describe('TextMapPropagator', () => { const spanContext = propagator.extract(carrier) const idExpr = /^[0-9a-f]{16}$/ - expect(spanContext._traceId).to.match(idExpr) - expect(spanContext._traceId.toString()).to.not.equal('0000000000000000') - expect(spanContext._spanId).to.be.null - expect(spanContext._sampling.priority).to.equal(AUTO_REJECT) + assert.match(spanContext._traceId, idExpr) + assert.notStrictEqual(spanContext._traceId.toString(), '0000000000000000') + assert.strictEqual(spanContext._spanId, null) + assert.strictEqual(spanContext._sampling.priority, AUTO_REJECT) }) it('should support sampled traces', () => { @@ -1160,10 +1182,10 @@ describe('TextMapPropagator', () => { const spanContext = propagator.extract(carrier) const idExpr = /^[0-9a-f]{16}$/ - expect(spanContext._traceId).to.match(idExpr) - expect(spanContext._traceId.toString()).to.not.equal('0000000000000000') - expect(spanContext._spanId).to.be.null - expect(spanContext._sampling.priority).to.equal(AUTO_KEEP) + assert.match(spanContext._traceId, idExpr) + assert.notStrictEqual(spanContext._traceId.toString(), '0000000000000000') + assert.strictEqual(spanContext._spanId, null) + assert.strictEqual(spanContext._sampling.priority, AUTO_KEEP) }) it('should support the debug flag', () => { @@ -1173,10 +1195,10 @@ describe('TextMapPropagator', () => { const spanContext = propagator.extract(carrier) const idExpr = /^[0-9a-f]{16}$/ - expect(spanContext._traceId).to.match(idExpr) - expect(spanContext._traceId.toString()).to.not.equal('0000000000000000') - expect(spanContext._spanId).to.be.null - expect(spanContext._sampling.priority).to.equal(USER_KEEP) + assert.match(spanContext._traceId, idExpr) + assert.notStrictEqual(spanContext._traceId.toString(), '0000000000000000') + assert.strictEqual(spanContext._spanId, null) + assert.strictEqual(spanContext._sampling.priority, USER_KEEP) }) it('should skip extraction without the feature flag', () => { @@ -1187,7 +1209,7 @@ describe('TextMapPropagator', () => { const carrier = textMap const spanContext = propagator.extract(carrier) - expect(spanContext).to.be.null + assert.strictEqual(spanContext, null) }) it('should support 128-bit trace IDs', () => { @@ -1198,7 +1220,7 @@ describe('TextMapPropagator', () => { const carrier = textMap const spanContext = propagator.extract(carrier) - expect(spanContext).to.deep.equal(createContext({ + assert.deepStrictEqual(spanContext, createContext({ traceId: id('00000000000002340000000000000123', 16), spanId: id('456', 16), trace: { @@ -1217,7 +1239,7 @@ describe('TextMapPropagator', () => { const carrier = textMap const spanContext = propagator.extract(carrier) - expect(spanContext).to.deep.equal(createContext({ + assert.deepStrictEqual(spanContext, createContext({ traceId: id('00000000000000000000000000000123', 16), spanId: id('456', 16) })) @@ -1228,10 +1250,8 @@ describe('TextMapPropagator', () => { propagator.extract(textMap) - expect(log.debug).to.have.been.called - expect(log.debug.firstCall.args[0]()).to.equal( - `Extract from carrier (b3 single header): {"b3":"${textMap.b3}"}.` - ) + sinon.assert.called(log.debug) + assert.strictEqual(log.debug.firstCall.args[0](), `Extract from carrier (b3 single header): {"b3":"${textMap.b3}"}.`) }) }) @@ -1247,7 +1267,7 @@ describe('TextMapPropagator', () => { const carrier = textMap const spanContext = propagator.extract(carrier) - expect(spanContext).to.be.null + assert.strictEqual(spanContext, null) }) it('should extract the header', () => { @@ -1257,15 +1277,13 @@ describe('TextMapPropagator', () => { const carrier = textMap const spanContext = propagator.extract(carrier) - expect(spanContext._traceId.toString(16)).to.equal('1111aaaa2222bbbb3333cccc4444dddd') - expect(spanContext._spanId.toString(16)).to.equal('5555eeee6666ffff') - expect(spanContext._sampling.priority).to.equal(USER_KEEP) - expect(spanContext._trace.origin).to.equal('foo') - expect(spanContext._trace.tags).to.have.property( - '_dd.p.foo_bar_baz_', - 'abc_!@#$%^&*()_+`-=' - ) - expect(spanContext._trace.tags['_dd.p.dm']).to.eql('-4') + assert.strictEqual(spanContext._traceId.toString(16), '1111aaaa2222bbbb3333cccc4444dddd') + assert.strictEqual(spanContext._spanId.toString(16), '5555eeee6666ffff') + assert.strictEqual(spanContext._sampling.priority, USER_KEEP) + assert.strictEqual(spanContext._trace.origin, 'foo') + assert.ok('_dd.p.foo_bar_baz_' in spanContext._trace.tags); + assert.strictEqual(spanContext._trace.tags['_dd.p.foo_bar_baz_'], 'abc_!@#$%^&*()_+`-=') + assert.deepStrictEqual(spanContext._trace.tags['_dd.p.dm'], '-4') }) it('should extract a 128-bit trace ID', () => { @@ -1275,8 +1293,9 @@ describe('TextMapPropagator', () => { const carrier = textMap const spanContext = propagator.extract(carrier) - expect(spanContext._traceId.toString(16)).to.equal('1111aaaa2222bbbb3333cccc4444dddd') - expect(spanContext._trace.tags).to.have.property('_dd.p.tid', '1111aaaa2222bbbb') + assert.strictEqual(spanContext._traceId.toString(16), '1111aaaa2222bbbb3333cccc4444dddd') + assert.ok('_dd.p.tid' in spanContext._trace.tags); + assert.strictEqual(spanContext._trace.tags['_dd.p.tid'], '1111aaaa2222bbbb') }) it('should skip extracting upper bits for 64-bit trace IDs', () => { @@ -1287,8 +1306,8 @@ describe('TextMapPropagator', () => { const carrier = textMap const spanContext = propagator.extract(carrier) - expect(spanContext._traceId.toString(16)).to.equal('00000000000000003333cccc4444dddd') - expect(spanContext._trace.tags).to.not.have.property('_dd.p.tid') + assert.strictEqual(spanContext._traceId.toString(16), '00000000000000003333cccc4444dddd') + assert.ok(!('_dd.p.tid' in spanContext._trace.tags)) }) it('should propagate the version', () => { @@ -1301,9 +1320,9 @@ describe('TextMapPropagator', () => { propagator.inject(spanContext, carrier) - expect(carrier.traceparent).to.match(/^01/) - expect(carrier['x-datadog-tags']).to.include('_dd.p.dm=-4') - expect(spanContext._trace.tags['_dd.p.dm']).to.eql('-4') + assert.match(carrier.traceparent, /^01/) + assertObjectContains(carrier['x-datadog-tags'], '_dd.p.dm=-4') + assert.deepStrictEqual(spanContext._trace.tags['_dd.p.dm'], '-4') }) it('should propagate other vendors', () => { @@ -1316,7 +1335,7 @@ describe('TextMapPropagator', () => { propagator.inject(spanContext, carrier) - expect(carrier.tracestate).to.include('other=bleh') + assertObjectContains(carrier.tracestate, 'other=bleh') }) it('should propagate last datadog id', () => { @@ -1327,11 +1346,11 @@ describe('TextMapPropagator', () => { const carrier = {} const spanContext = propagator.extract(textMap) // Ensure the span context is marked as remote (i.e. not generated by the current process) - expect(spanContext._isRemote).to.equal(true) + assert.strictEqual(spanContext._isRemote, true) propagator.inject(spanContext, carrier) - expect(carrier.tracestate).to.include('p:4444eeee6666aaaa') + assertObjectContains(carrier.tracestate, 'p:4444eeee6666aaaa') }) it('should fix _dd.p.dm if invalid (non-hyphenated) input is received', () => { @@ -1344,8 +1363,8 @@ describe('TextMapPropagator', () => { propagator.inject(spanContext, carrier) - expect(carrier['x-datadog-tags']).to.include('_dd.p.dm=-4') - expect(spanContext._trace.tags['_dd.p.dm']).to.eql('-4') + assertObjectContains(carrier['x-datadog-tags'], '_dd.p.dm=-4') + assert.deepStrictEqual(spanContext._trace.tags['_dd.p.dm'], '-4') }) it('should maintain hyphen prefix when a default mechanism of 0 is received', () => { @@ -1358,8 +1377,8 @@ describe('TextMapPropagator', () => { propagator.inject(spanContext, carrier) - expect(carrier['x-datadog-tags']).to.include('_dd.p.dm=-0') - expect(spanContext._trace.tags['_dd.p.dm']).to.eql('-0') + assertObjectContains(carrier['x-datadog-tags'], '_dd.p.dm=-0') + assert.deepStrictEqual(spanContext._trace.tags['_dd.p.dm'], '-0') }) it('should log extraction', () => { @@ -1370,8 +1389,8 @@ describe('TextMapPropagator', () => { propagator.extract(textMap) - expect(log.debug).to.have.been.called - expect(log.debug.firstCall.args[0]()).to.equal([ + sinon.assert.called(log.debug) + assert.strictEqual(log.debug.firstCall.args[0](), [ 'Extract from carrier (tracecontext):', `{"traceparent":"${traceparent}","tracestate":"${tracestate}"}.` ].join(' ')) @@ -1405,7 +1424,7 @@ describe('TextMapPropagator', () => { const extractedContext = propagator.extract(textMap) // No span links should occur when we return from extract - expect(extractedContext._links.length).to.equal(0) + assert.strictEqual(extractedContext._links.length, 0) }) it('should set span link to extracted trace when Trace_Propagation_Behavior_Extract is set to restart', () => { @@ -1419,11 +1438,11 @@ describe('TextMapPropagator', () => { const extractedContext = propagator.extract(textMap) // Expect to see span links related to the extracted span - expect(extractedContext._links.length).to.equal(1) - expect(extractedContext._links[0].context.toTraceId(true)).to.equal(traceId) - expect(extractedContext._links[0].context.toSpanId(true)).to.equal(spanId) - expect(extractedContext._links[0].attributes.reason).to.equal('propagation_behavior_extract') - expect(extractedContext._links[0].attributes.context_headers).to.equal('tracecontext') + assert.strictEqual(extractedContext._links.length, 1) + assert.strictEqual(extractedContext._links[0].context.toTraceId(true), traceId) + assert.strictEqual(extractedContext._links[0].context.toSpanId(true), spanId) + assert.strictEqual(extractedContext._links[0].attributes.reason, 'propagation_behavior_extract') + assert.strictEqual(extractedContext._links[0].attributes.context_headers, 'tracecontext') }) it('should not extract baggage when Trace_Propagation_Behavior_Extract is set to ignore', () => { @@ -1442,7 +1461,7 @@ describe('TextMapPropagator', () => { propagator = new TextMapPropagator(config) propagator.extract(textMap) - expect(getAllBaggageItems()).to.deep.equal({}) + assert.deepStrictEqual(getAllBaggageItems(), {}) }) }) }) diff --git a/packages/dd-trace/test/opentracing/propagation/tracestate.spec.js b/packages/dd-trace/test/opentracing/propagation/tracestate.spec.js index 8b2f9a1e97c..e72281fbfd1 100644 --- a/packages/dd-trace/test/opentracing/propagation/tracestate.spec.js +++ b/packages/dd-trace/test/opentracing/propagation/tracestate.spec.js @@ -1,8 +1,6 @@ 'use strict' const assert = require('node:assert/strict') - -const { expect } = require('chai') const { describe, it, beforeEach } = require('tap').mocha require('../../setup/core') @@ -16,7 +14,7 @@ describe('TraceState', () => { it('should convert from header', () => { const ts = TraceState.fromString('other=bleh,dd=s:2;o:foo;t.dm:-4') - expect(ts).to.be.an.instanceOf(Map) + assert.ok(ts instanceof Map) assert.strictEqual(ts.get('other'), 'bleh') assert.strictEqual(ts.get('dd'), 's:2;o:foo;t.dm:-4') }) @@ -39,7 +37,7 @@ describe('TraceState', () => { ts.forVendor('dd', (state) => { called = true - expect(state).to.be.an.instanceOf(Map) + assert.ok(state instanceof Map) assert.strictEqual(state.get('s'), '2') assert.strictEqual(state.get('o'), 'foo:bar') assert.strictEqual(state.get('t.dm'), '-4') diff --git a/packages/dd-trace/test/opentracing/span.spec.js b/packages/dd-trace/test/opentracing/span.spec.js index ad490ab76df..1ac27d89f82 100644 --- a/packages/dd-trace/test/opentracing/span.spec.js +++ b/packages/dd-trace/test/opentracing/span.spec.js @@ -2,9 +2,7 @@ const assert = require('node:assert/strict') -const { expect } = require('chai') const { assertObjectContains } = require('../../../../integration-tests/helpers') - const { describe, it, beforeEach, afterEach } = require('tap').mocha const sinon = require('sinon') const { channel } = require('dc-polyfill') @@ -217,8 +215,9 @@ describe('Span', () => { span = new Span(tracer, processor, prioritySampler, { operationName: 'operation', parent }) span.setBaggageItem('foo', 'bar') - expect(span.context()._baggageItems).to.have.property('foo', 'bar') - expect(parent._baggageItems).to.not.have.property('foo', 'bar') + assert.ok('foo' in span.context()._baggageItems); + assert.strictEqual(span.context()._baggageItems['foo'], 'bar') + assert.ok(!('foo' in parent._baggageItems) || parent._baggageItems['foo'] !== 'bar') }) it('should pass baggage items to future causal spans', () => { @@ -236,7 +235,8 @@ describe('Span', () => { span = new Span(tracer, processor, prioritySampler, { operationName: 'operation', parent }) - expect(span.context()._baggageItems).to.have.property('foo', 'bar') + assert.ok('foo' in span.context()._baggageItems); + assert.strictEqual(span.context()._baggageItems['foo'], 'bar') }) }) diff --git a/packages/dd-trace/test/opentracing/tracer.spec.js b/packages/dd-trace/test/opentracing/tracer.spec.js index 8b42695a1e6..2fe1602a2e4 100644 --- a/packages/dd-trace/test/opentracing/tracer.spec.js +++ b/packages/dd-trace/test/opentracing/tracer.spec.js @@ -1,8 +1,6 @@ 'use strict' const assert = require('node:assert/strict') - -const { expect } = require('chai') const { describe, it, beforeEach } = require('tap').mocha const sinon = require('sinon') const opentracing = require('opentracing') @@ -368,7 +366,7 @@ describe('Tracer', () => { it('should handle errors', () => { tracer = new Tracer(config) - expect(() => tracer.inject({})).not.to.throw() + assert.doesNotThrow(() => tracer.inject({})) sinon.assert.calledOnce(log.error) }) @@ -426,7 +424,7 @@ describe('Tracer', () => { it('should handle errors', () => { tracer = new Tracer(config) - expect(() => tracer.extract()).not.to.throw() + assert.doesNotThrow(() => tracer.extract()) }) }) }) diff --git a/packages/dd-trace/test/plugin_manager.spec.js b/packages/dd-trace/test/plugin_manager.spec.js index 027ad218707..c6993529a13 100644 --- a/packages/dd-trace/test/plugin_manager.spec.js +++ b/packages/dd-trace/test/plugin_manager.spec.js @@ -1,8 +1,6 @@ 'use strict' const assert = require('node:assert/strict') - -const { expect } = require('chai') const { describe, it, beforeEach, afterEach } = require('tap').mocha const sinon = require('sinon') const { channel } = require('dc-polyfill') @@ -274,7 +272,7 @@ describe('Plugin Manager', () => { it('should not instantiate plugins', () => { pm.configure() pm.configurePlugin('two') - expect(instantiated).to.be.empty + assert.strictEqual(instantiated.length, 0) sinon.assert.notCalled(Two.prototype.configure) }) }) diff --git a/packages/dd-trace/test/plugins/log_plugin.spec.js b/packages/dd-trace/test/plugins/log_plugin.spec.js index d0ad1286f6c..ccdaa79d76d 100644 --- a/packages/dd-trace/test/plugins/log_plugin.spec.js +++ b/packages/dd-trace/test/plugins/log_plugin.spec.js @@ -1,8 +1,8 @@ 'use strict' const assert = require('node:assert/strict') +const { assertObjectContains } = require('../../../../integration-tests/helpers') -const { expect } = require('chai') const { describe, it } = require('tap').mocha const { channel } = require('dc-polyfill') @@ -59,7 +59,7 @@ describe('LogPlugin', () => { testLogChannel.publish(data) const { message } = data - expect(message.dd).to.contain(config) + assertObjectContains(message.dd, config) // Should have trace/span data when none is active assert.strictEqual(message.dd.trace_id, span.context().toTraceId(true)) diff --git a/packages/dd-trace/test/plugins/outbound.spec.js b/packages/dd-trace/test/plugins/outbound.spec.js index a8b69b3e5f9..a19332feae4 100644 --- a/packages/dd-trace/test/plugins/outbound.spec.js +++ b/packages/dd-trace/test/plugins/outbound.spec.js @@ -1,8 +1,8 @@ 'use strict' const assert = require('node:assert/strict') +const { assertObjectContains } = require('../../../../integration-tests/helpers') -const { expect } = require('chai') const { describe, it, beforeEach, afterEach, before } = require('tap').mocha const sinon = require('sinon') @@ -47,14 +47,14 @@ describe('OuboundPlugin', () => { instance.tagPeerService({ context: () => { return { _tags: {} } }, addTags: () => {} }) sinon.assert.called(getPeerServiceStub) - expect(getRemapStub).to.not.be.called + sinon.assert.notCalled(getRemapStub) }) it('should do nothing when disabled', () => { computePeerServiceStub.value({ spanComputePeerService: false }) instance.tagPeerService({ context: () => { return { _tags: {} } }, addTags: () => {} }) - expect(getPeerServiceStub).to.not.be.called - expect(getRemapStub).to.not.be.called + sinon.assert.notCalled(getPeerServiceStub) + sinon.assert.notCalled(getRemapStub) }) }) @@ -209,7 +209,7 @@ describe('OuboundPlugin', () => { assert.strictEqual(args.length, 1) const tags = parseTags(args[0]) - expect(tags).to.nested.include({ '_dd.code_origin.type': 'exit' }) + assertObjectContains(tags, { '_dd.code_origin.type': 'exit' }) assert.ok(Array.isArray(tags._dd.code_origin.frames)) assert.ok(tags._dd.code_origin.frames.length > 0) diff --git a/packages/dd-trace/test/plugins/plugin-structure.spec.js b/packages/dd-trace/test/plugins/plugin-structure.spec.js index e31416ef9ce..7f7de8377f6 100644 --- a/packages/dd-trace/test/plugins/plugin-structure.spec.js +++ b/packages/dd-trace/test/plugins/plugin-structure.spec.js @@ -1,8 +1,6 @@ 'use strict' const assert = require('node:assert/strict') - -const { expect } = require('chai') const { describe, it, before } = require('tap').mocha const fs = require('node:fs') const path = require('node:path') @@ -98,7 +96,7 @@ describe('Plugin Structure Validation', () => { } }) - expect(missingInstrumentations).to.be.empty + assert.strictEqual(missingInstrumentations.length, 0) }) it('should have all plugins accounted for with a hook', () => { diff --git a/packages/dd-trace/test/plugins/tracing.spec.js b/packages/dd-trace/test/plugins/tracing.spec.js index 950f5fc8d2b..af03a4e52e5 100644 --- a/packages/dd-trace/test/plugins/tracing.spec.js +++ b/packages/dd-trace/test/plugins/tracing.spec.js @@ -1,8 +1,6 @@ 'use strict' const assert = require('node:assert/strict') - -const { expect } = require('chai') const { describe, it, before, after } = require('tap').mocha const sinon = require('sinon') const { channel } = require('dc-polyfill') @@ -120,7 +118,7 @@ describe('common Plugin behaviour', () => { done, 'commonPlugin', {}, span => { assert.strictEqual(span.service, 'test') - expect(span.meta).to.not.have.property('_dd.base_service', 'test') + assert.ok(!('_dd.base_service' in span.meta) || span.meta['_dd.base_service'] !== 'test') } ) }) diff --git a/packages/dd-trace/test/plugins/util/ip_extractor.spec.js b/packages/dd-trace/test/plugins/util/ip_extractor.spec.js index 241e9654eff..1ca2b02ff07 100644 --- a/packages/dd-trace/test/plugins/util/ip_extractor.spec.js +++ b/packages/dd-trace/test/plugins/util/ip_extractor.spec.js @@ -1,8 +1,6 @@ 'use strict' const assert = require('node:assert/strict') - -const { expect } = require('chai') const { describe, it, before, after } = require('tap').mocha const axios = require('axios') const http = require('node:http') @@ -195,7 +193,7 @@ describe('ip extractor', () => { controller = function (req) { const ip = extractIp({}, req) try { - expect(['::1', '127.0.0.1']).to.include(ip) + assert.ok(['::1', '127.0.0.1'].includes(ip)) done() } catch (e) { done(e) @@ -221,7 +219,7 @@ describe('ip extractor', () => { controller = function (req) { const ip = extractIp({}, req) try { - expect(['::1', '127.0.0.1']).to.include(ip) + assert.ok(['::1', '127.0.0.1'].includes(ip)) done() } catch (e) { done(e) diff --git a/packages/dd-trace/test/plugins/util/llm.spec.js b/packages/dd-trace/test/plugins/util/llm.spec.js index 068209b43b4..eb71dbb3817 100644 --- a/packages/dd-trace/test/plugins/util/llm.spec.js +++ b/packages/dd-trace/test/plugins/util/llm.spec.js @@ -1,8 +1,6 @@ 'use strict' const assert = require('node:assert/strict') - -const { expect } = require('chai') const { describe, it, beforeEach } = require('tap').mocha require('../../setup/core') @@ -37,7 +35,7 @@ describe('llm utils', () => { }) it('should always sample prompt completion', () => { - expect(utils.isPromptCompletionSampled(new SpanContext({ traceId: id() }))).to.be.true + assert.strictEqual(utils.isPromptCompletionSampled(new SpanContext({ traceId: id() })), true) }) }) @@ -58,11 +56,11 @@ describe('llm utils', () => { describe('with sampling rate 0.6', () => { it('should not sample prompt completion', () => { - expect(utils.isPromptCompletionSampled(new SpanContext({ traceId: id('8081965455359722133', 10) }))).to.be.false + assert.strictEqual(utils.isPromptCompletionSampled(new SpanContext({ traceId: id('8081965455359722133', 10) })), false) }) it('should sample prompt completion', () => { - expect(utils.isPromptCompletionSampled(new SpanContext({ traceId: id('5533085789307409170', 10) }))).to.be.true + assert.strictEqual(utils.isPromptCompletionSampled(new SpanContext({ traceId: id('5533085789307409170', 10) })), true) }) }) }) diff --git a/packages/dd-trace/test/plugins/util/test-environment.spec.js b/packages/dd-trace/test/plugins/util/test-environment.spec.js index 8e199a67a09..fc900e5fcc7 100644 --- a/packages/dd-trace/test/plugins/util/test-environment.spec.js +++ b/packages/dd-trace/test/plugins/util/test-environment.spec.js @@ -1,8 +1,6 @@ 'use strict' const assert = require('node:assert/strict') - -const { expect } = require('chai') const { assertObjectContains } = require('../../../../../integration-tests/helpers') const { describe, it } = require('tap').mocha @@ -99,14 +97,14 @@ describe('test environment data', () => { ...restOfExpectedTags } = expectedSpanTags - expect(restOfTags, testCaseName ? `${testCaseName} has failed.` : undefined).to.contain(restOfExpectedTags) + assertObjectContains(restOfTags, restOfExpectedTags) // `CI_ENV_VARS` key contains a dictionary, so we do a `eql` comparison if (envVars && expectedEnvVars) { assert.deepStrictEqual(JSON.parse(envVars), JSON.parse(expectedEnvVars)) } // `CI_NODE_LABELS` key contains an array, so we do a `to.have.same.members` comparison if (nodeLabels && expectedNodeLabels) { - expect(JSON.parse(nodeLabels)).to.have.same.members(JSON.parse(expectedNodeLabels)) + assertObjectContains(JSON.parse(nodeLabels), JSON.parse(expectedNodeLabels)) } }) }) diff --git a/packages/dd-trace/test/plugins/util/test.spec.js b/packages/dd-trace/test/plugins/util/test.spec.js index 0e18848f216..5d33dfa8352 100644 --- a/packages/dd-trace/test/plugins/util/test.spec.js +++ b/packages/dd-trace/test/plugins/util/test.spec.js @@ -1,8 +1,6 @@ 'use strict' const assert = require('node:assert/strict') - -const { expect } = require('chai') const { describe, it, beforeEach, context } = require('tap').mocha const path = require('node:path') const istanbul = require('istanbul-lib-coverage') @@ -239,9 +237,7 @@ describe('metadata validation', () => { const invalidMetadata5 = { [GIT_REPOSITORY_URL]: '', [CI_PIPELINE_URL]: '', [GIT_COMMIT_SHA]: '' } const invalidMetadatas = [invalidMetadata1, invalidMetadata2, invalidMetadata3, invalidMetadata4, invalidMetadata5] invalidMetadatas.forEach((invalidMetadata) => { - expect( - JSON.stringify(removeInvalidMetadata(invalidMetadata)), `${JSON.stringify(invalidMetadata)} is valid` - ).to.equal(JSON.stringify({})) + assert.strictEqual(JSON.stringify(removeInvalidMetadata(invalidMetadata)), JSON.stringify({})) }) }) @@ -263,7 +259,7 @@ describe('metadata validation', () => { } const validMetadatas = [validMetadata1, validMetadata2, validMetadata3] validMetadatas.forEach((validMetadata) => { - expect(JSON.stringify(removeInvalidMetadata(validMetadata))).to.be.equal(JSON.stringify(validMetadata)) + assert.strictEqual(JSON.stringify(removeInvalidMetadata(validMetadata)), JSON.stringify(validMetadata)) }) }) }) diff --git a/packages/dd-trace/test/plugins/util/web.spec.js b/packages/dd-trace/test/plugins/util/web.spec.js index f77d78c0ba8..a9475aad3be 100644 --- a/packages/dd-trace/test/plugins/util/web.spec.js +++ b/packages/dd-trace/test/plugins/util/web.spec.js @@ -2,9 +2,7 @@ const assert = require('node:assert/strict') -const { expect } = require('chai') const { assertObjectContains } = require('../../../../../integration-tests/helpers') - const { describe, it, beforeEach } = require('tap').mocha const sinon = require('sinon') @@ -135,7 +133,8 @@ describe('plugins/util/web', () => { queryStringObfuscation: 'a*' }) - expect(config).to.have.deep.property('queryStringObfuscation', /a*/gi) + assert.ok('queryStringObfuscation' in config); +assert.deepStrictEqual(config['queryStringObfuscation'], /a*/gi) }) it('should default to true when passed a bad regex', () => { @@ -304,7 +303,7 @@ describe('plugins/util/web', () => { res.end() - expect(tags).to.include({ + assertObjectContains(tags, { [`${HTTP_REQUEST_HEADERS}.host`]: 'localhost', 'http.req': 'incoming', [`${HTTP_RESPONSE_HEADERS}.server`]: 'test', @@ -334,7 +333,8 @@ describe('plugins/util/web', () => { config.service = 'test2' web.instrument(tracer, config, req, res, 'test.request') - expect(span.context()._tags).to.have.property('service.name', 'test2') + assert.ok('service.name' in span.context()._tags); + assert.strictEqual(span.context()._tags['service.name'], 'test2') }) }) @@ -359,7 +359,7 @@ describe('plugins/util/web', () => { res.end() - expect(tags).to.include({ + assertObjectContains(tags, { [`${HTTP_REQUEST_HEADERS}.date`]: 'now' }) }) diff --git a/packages/dd-trace/test/priority_sampler.spec.js b/packages/dd-trace/test/priority_sampler.spec.js index d5ed3994bda..6add282d70e 100644 --- a/packages/dd-trace/test/priority_sampler.spec.js +++ b/packages/dd-trace/test/priority_sampler.spec.js @@ -511,9 +511,9 @@ describe('PrioritySampler', () => { prioritySampler.setPriority(span, USER_KEEP, SAMPLING_MECHANISM_APPSEC) - expect(context._sampling.priority).to.undefined - expect(context._sampling.mechanism).to.undefined - expect(context._trace.tags[DECISION_MAKER_KEY]).to.undefined + assert.strictEqual(context._sampling.priority, undefined) + assert.strictEqual(context._sampling.mechanism, undefined) + assert.strictEqual(context._trace.tags[DECISION_MAKER_KEY], undefined) }) }) diff --git a/packages/dd-trace/test/profiling/config.spec.js b/packages/dd-trace/test/profiling/config.spec.js index b38eb329c8e..98d75126013 100644 --- a/packages/dd-trace/test/profiling/config.spec.js +++ b/packages/dd-trace/test/profiling/config.spec.js @@ -2,9 +2,7 @@ const assert = require('node:assert/strict') -const { expect } = require('chai') const { assertObjectContains } = require('../../../../integration-tests/helpers') - const { describe, it, beforeEach, afterEach } = require('tap').mocha const os = require('node:os') const path = require('node:path') @@ -54,12 +52,12 @@ describe('config', () => { host: os.hostname() }) - expect(config.logger).to.be.an.instanceof(ConsoleLogger) - expect(config.exporters[0]).to.be.an.instanceof(AgentExporter) - expect(config.profilers[0]).to.be.an.instanceof(SpaceProfiler) - expect(config.profilers[1]).to.be.an.instanceof(WallProfiler) + assert.ok(config.logger instanceof ConsoleLogger) + assert.ok(config.exporters[0] instanceof AgentExporter) + assert.ok(config.profilers[0] instanceof SpaceProfiler) + assert.ok(config.profilers[1] instanceof WallProfiler) assert.strictEqual(config.profilers[1].codeHotspotsEnabled(), samplingContextsAvailable) - expect(config.v8ProfilerBugWorkaroundEnabled).true + assert.strictEqual(config.v8ProfilerBugWorkaroundEnabled, true) assert.strictEqual(config.cpuProfilingEnabled, samplingContextsAvailable) assert.strictEqual(config.uploadCompression.method, 'gzip') assert.strictEqual(config.uploadCompression.level, undefined) @@ -88,16 +86,16 @@ describe('config', () => { assert.strictEqual(config.flushInterval, 65 * 1000) assert.ok(Array.isArray(config.exporters)) assert.strictEqual(config.exporters.length, 2) - expect(config.exporters[0]).to.be.an.instanceof(AgentExporter) + assert.ok(config.exporters[0] instanceof AgentExporter) assert.strictEqual(config.exporters[0]._url.toString(), options.url) - expect(config.exporters[1]).to.be.an.instanceof(FileExporter) + assert.ok(config.exporters[1] instanceof FileExporter) assert.ok(Array.isArray(config.profilers)) assert.strictEqual(config.profilers.length, 2 + (samplingContextsAvailable ? 1 : 0)) - expect(config.profilers[0]).to.be.an.instanceOf(SpaceProfiler) - expect(config.profilers[1]).to.be.an.instanceOf(WallProfiler) - expect(config.profilers[1].codeHotspotsEnabled()).false + assert.ok(config.profilers[0] instanceof SpaceProfiler) + assert.ok(config.profilers[1] instanceof WallProfiler) + assert.strictEqual(config.profilers[1].codeHotspotsEnabled(), false) if (samplingContextsAvailable) { - expect(config.profilers[2]).to.be.an.instanceOf(EventsProfiler) + assert.ok(config.profilers[2] instanceof EventsProfiler) } }) @@ -155,12 +153,12 @@ describe('config', () => { assert.ok(Array.isArray(config.profilers)) assert.strictEqual(config.profilers.length, 1 + (samplingContextsAvailable ? 1 : 0)) - expect(config.profilers[0]).to.be.an.instanceOf(WallProfiler) + assert.ok(config.profilers[0] instanceof WallProfiler) assert.strictEqual(config.profilers[0].codeHotspotsEnabled(), samplingContextsAvailable) if (samplingContextsAvailable) { - expect(config.profilers[1]).to.be.an.instanceOf(EventsProfiler) + assert.ok(config.profilers[1] instanceof EventsProfiler) } - expect(config.v8ProfilerBugWorkaroundEnabled).false + assert.strictEqual(config.v8ProfilerBugWorkaroundEnabled, false) assert.strictEqual(config.cpuProfilingEnabled, samplingContextsAvailable) }) @@ -178,7 +176,7 @@ describe('config', () => { assert.ok(Array.isArray(config.profilers)) assert.strictEqual(config.profilers.length, 1) - expect(config.profilers[0]).to.be.an.instanceOf(SpaceProfiler) + assert.ok(config.profilers[0] instanceof SpaceProfiler) }) it('should ensure space profiler is ordered first with DD_PROFILING_HEAP_ENABLED', () => { @@ -194,8 +192,8 @@ describe('config', () => { assert.ok(Array.isArray(config.profilers)) assert.strictEqual(config.profilers.length, 2 + (samplingContextsAvailable ? 1 : 0)) - expect(config.profilers[0]).to.be.an.instanceOf(SpaceProfiler) - expect(config.profilers[1]).to.be.an.instanceOf(WallProfiler) + assert.ok(config.profilers[0] instanceof SpaceProfiler) + assert.ok(config.profilers[1] instanceof WallProfiler) }) it('should ensure space profiler order is preserved when explicitly set with DD_PROFILING_PROFILERS', () => { @@ -211,8 +209,8 @@ describe('config', () => { assert.ok(Array.isArray(config.profilers)) assert.strictEqual(config.profilers.length, 2 + (samplingContextsAvailable ? 1 : 0)) - expect(config.profilers[0]).to.be.an.instanceOf(WallProfiler) - expect(config.profilers[1]).to.be.an.instanceOf(SpaceProfiler) + assert.ok(config.profilers[0] instanceof WallProfiler) + assert.ok(config.profilers[1] instanceof SpaceProfiler) }) it('should be able to read some env vars', () => { @@ -252,9 +250,9 @@ describe('config', () => { assert.ok(Array.isArray(config.profilers)) assert.strictEqual(config.profilers.length, 1 + (samplingContextsAvailable ? 1 : 0)) - expect(config.profilers[0]).to.be.an.instanceOf(WallProfiler) + assert.ok(config.profilers[0] instanceof WallProfiler) if (samplingContextsAvailable) { - expect(config.profilers[1]).to.be.an.instanceOf(EventsProfiler) + assert.ok(config.profilers[1] instanceof EventsProfiler) } }) @@ -278,10 +276,10 @@ describe('config', () => { assert.ok(Array.isArray(config.profilers)) assert.strictEqual(config.profilers.length, 2) - expect(config.profilers[0]).to.be.an.instanceOf(WallProfiler) - expect(config.profilers[0].codeHotspotsEnabled()).false - expect(config.profilers[0].endpointCollectionEnabled()).false - expect(config.profilers[1]).to.be.an.instanceOf(EventsProfiler) + assert.ok(config.profilers[0] instanceof WallProfiler) + assert.strictEqual(config.profilers[0].codeHotspotsEnabled(), false) + assert.strictEqual(config.profilers[0].endpointCollectionEnabled(), false) + assert.ok(config.profilers[1] instanceof EventsProfiler) }) it('should prioritize non-experimental env variables and warn about experimental ones', () => { @@ -312,10 +310,10 @@ describe('config', () => { assert.ok(Array.isArray(config.profilers)) assert.strictEqual(config.profilers.length, 2) - expect(config.profilers[0]).to.be.an.instanceOf(WallProfiler) - expect(config.profilers[0].codeHotspotsEnabled()).false - expect(config.profilers[0].endpointCollectionEnabled()).false - expect(config.profilers[1]).to.be.an.instanceOf(EventsProfiler) + assert.ok(config.profilers[0] instanceof WallProfiler) + assert.strictEqual(config.profilers[0].codeHotspotsEnabled(), false) + assert.strictEqual(config.profilers[0].endpointCollectionEnabled(), false) + assert.ok(config.profilers[1] instanceof EventsProfiler) }) function optionOnlyWorksWithGivenCondition (property, name, condition) { @@ -365,7 +363,7 @@ describe('config', () => { const config = new Config({ tags }) - expect(config.tags).to.include(tags) + assertObjectContains(config.tags, tags) }) it('should prioritize options over tags', () => { diff --git a/packages/dd-trace/test/profiling/profiler.spec.js b/packages/dd-trace/test/profiling/profiler.spec.js index 7e4fd0c04cf..cdd3d0a069d 100644 --- a/packages/dd-trace/test/profiling/profiler.spec.js +++ b/packages/dd-trace/test/profiling/profiler.spec.js @@ -323,7 +323,7 @@ describe('profiler', function () { await waitForExport() const { start: start2, end: end2 } = exporter.export.args[0][0] - expect(start2).to.be.greaterThanOrEqual(end) + assert.ok(start2 >= end) expect(start2).to.be.a('date') expect(end2).to.be.a('date') assert.strictEqual(end2 - start2, 65000) diff --git a/packages/dd-trace/test/profiling/profilers/space.spec.js b/packages/dd-trace/test/profiling/profilers/space.spec.js index 5a17c92e1cb..863e2ba077b 100644 --- a/packages/dd-trace/test/profiling/profilers/space.spec.js +++ b/packages/dd-trace/test/profiling/profilers/space.spec.js @@ -1,8 +1,6 @@ 'use strict' const assert = require('node:assert/strict') - -const { expect } = require('chai') const { describe, it, beforeEach } = require('tap').mocha const proxyquire = require('proxyquire') const sinon = require('sinon') @@ -65,7 +63,7 @@ describe('profilers/native/space', () => { const profiler = new NativeSpaceProfiler() const info = profiler.getInfo() - expect(Object.keys(info)).to.be.empty + assert.strictEqual(Object.keys(info).length, 0) }) it('should collect profiles from the pprof space profiler', () => { diff --git a/packages/dd-trace/test/remote_config/manager.spec.js b/packages/dd-trace/test/remote_config/manager.spec.js index a7fecba15d5..1daf60eed7b 100644 --- a/packages/dd-trace/test/remote_config/manager.spec.js +++ b/packages/dd-trace/test/remote_config/manager.spec.js @@ -125,7 +125,7 @@ describe('RemoteConfigManager', () => { cached_target_files: [] }) - expect(rc.appliedConfigs).to.be.an.instanceOf(Map) + assert.ok(rc.appliedConfigs instanceof Map) }) it('should add git metadata to tags if present', () => { @@ -208,7 +208,7 @@ describe('RemoteConfigManager', () => { rc.removeProductHandler('ASM_DD') sinon.assert.called(rc.scheduler.stop) - expect(rc.state.client.products).to.be.empty + assert.strictEqual(rc.state.client.products.length, 0) }) }) @@ -289,7 +289,7 @@ describe('RemoteConfigManager', () => { sinon.assert.calledOnce(rc.parseConfig) sinon.assert.calledOnce(log.error) assert.strictEqual(rc.state.client.state.has_error, false) - expect(rc.state.client.state.error).to.be.empty + assert.strictEqual(rc.state.client.state.error.length, 0) cb() }) }) @@ -695,7 +695,7 @@ describe('RemoteConfigManager', () => { rc.dispatch([rc.appliedConfigs.get('datadog/42/ASM_FEATURES/confId/config')], 'unapply') sinon.assert.calledOnceWithExactly(handler, 'unapply', { asm: { enabled: true } }, 'asm_data') - expect(rc.appliedConfigs).to.be.empty + assert.strictEqual(rc.appliedConfigs.length, 0) }) }) }) diff --git a/packages/dd-trace/test/sampler.spec.js b/packages/dd-trace/test/sampler.spec.js index 768b1cfa143..4bf6425012a 100644 --- a/packages/dd-trace/test/sampler.spec.js +++ b/packages/dd-trace/test/sampler.spec.js @@ -1,8 +1,6 @@ 'use strict' const assert = require('node:assert/strict') - -const { expect } = require('chai') const { describe, it, beforeEach, afterEach } = require('tap').mocha const sinon = require('sinon') @@ -55,20 +53,20 @@ describe('Sampler', () => { it('should always sample when rate is 1', () => { sampler = new Sampler(1) - expect(sampler.isSampled(new SpanContext({ traceId: id() }))).to.be.true + assert.strictEqual(sampler.isSampled(new SpanContext({ traceId: id() })), true) }) it('should never sample when rate is 0', () => { sampler = new Sampler(0) - expect(sampler.isSampled(new SpanContext({ traceId: id() }))).to.be.false + assert.strictEqual(sampler.isSampled(new SpanContext({ traceId: id() })), false) }) it('should sample according to the rate', () => { sampler = new Sampler(0.1234) - expect(sampler.isSampled(new SpanContext({ traceId: id('8135292307740797052', 10) }))).to.be.true - expect(sampler.isSampled(new SpanContext({ traceId: id('2263640730249415707', 10) }))).to.be.false + assert.strictEqual(sampler.isSampled(new SpanContext({ traceId: id('8135292307740797052', 10) })), true) + assert.strictEqual(sampler.isSampled(new SpanContext({ traceId: id('2263640730249415707', 10) })), false) }) it('should sample according to different rates', () => { @@ -106,7 +104,7 @@ describe('Sampler', () => { idsAndRates.forEach(([id, rate, expected]) => { const sampler = new Sampler(rate) - expect(sampler.isSampled(new SpanContext({ traceId: id }))).to.equal(expected) + assert.strictEqual(sampler.isSampled(new SpanContext({ traceId: id })), expected) }) }) }) diff --git a/packages/dd-trace/test/sampling_rule.spec.js b/packages/dd-trace/test/sampling_rule.spec.js index 4b3a4f74109..f5a977646c4 100644 --- a/packages/dd-trace/test/sampling_rule.spec.js +++ b/packages/dd-trace/test/sampling_rule.spec.js @@ -1,8 +1,6 @@ 'use strict' const assert = require('node:assert/strict') - -const { expect } = require('chai') const { describe, it, beforeEach, afterEach } = require('tap').mocha const sinon = require('sinon') @@ -358,7 +356,7 @@ describe('sampling rule', () => { maxPerSecond: 1 }) - expect(rule.sample(new SpanContext({ traceId: id() }))).to.equal(true) + assert.strictEqual(rule.sample(new SpanContext({ traceId: id() })), true) }) it('should not sample on non-allowed sample rate', () => { @@ -369,7 +367,7 @@ describe('sampling rule', () => { maxPerSecond: 1 }) - expect(rule.sample(new SpanContext({ traceId: id('6148299799767393280', 10) }))).to.equal(false) + assert.strictEqual(rule.sample(new SpanContext({ traceId: id('6148299799767393280', 10) })), false) }) }) @@ -419,7 +417,7 @@ describe('sampling rule', () => { }) for (let i = 0; i < 1e3; i++) { - expect(rule.sample(new SpanContext({ traceId: id() }))).to.equal(true) + assert.strictEqual(rule.sample(new SpanContext({ traceId: id() })), true) } }) @@ -435,10 +433,10 @@ describe('sampling rule', () => { now: new Date(), toFake: ['Date', 'setTimeout', 'clearTimeout', 'setInterval', 'clearInterval', 'hrtime'] }) - expect(rule.sample(new SpanContext({ traceId: id() }))).to.equal(true) - expect(rule.sample(new SpanContext({ traceId: id() }))).to.equal(false) + assert.strictEqual(rule.sample(new SpanContext({ traceId: id() })), true) + assert.strictEqual(rule.sample(new SpanContext({ traceId: id() })), false) clock.tick(1000) - expect(rule.sample(new SpanContext({ traceId: id() }))).to.equal(true) + assert.strictEqual(rule.sample(new SpanContext({ traceId: id() })), true) }) }) }) diff --git a/packages/dd-trace/test/scope.spec.js b/packages/dd-trace/test/scope.spec.js index 525d0cd4d33..e497cab04e0 100644 --- a/packages/dd-trace/test/scope.spec.js +++ b/packages/dd-trace/test/scope.spec.js @@ -1,8 +1,6 @@ 'use strict' const assert = require('node:assert/strict') - -const { expect } = require('chai') const { describe, it, beforeEach } = require('tap').mocha const sinon = require('sinon') const { Span } = require('opentracing') @@ -28,7 +26,7 @@ describe('Scope', () => { describe('activate()', () => { it('should return the value returned by the callback', () => { - expect(scope.activate(span, () => 'test')).to.equal('test') + assert.strictEqual(scope.activate(span, () => 'test'), 'test') }) it('should preserve the surrounding scope', () => { @@ -40,7 +38,7 @@ describe('Scope', () => { }) it('should support an invalid callback', () => { - expect(() => { scope.activate(span, 'invalid') }).to.not.throw(Error) + assert.doesNotThrow(() => { scope.activate(span, 'invalid') }, Error) }) it('should activate the span on the current scope', () => { diff --git a/packages/dd-trace/test/span_format.spec.js b/packages/dd-trace/test/span_format.spec.js index bc197651053..ae31580bf8b 100644 --- a/packages/dd-trace/test/span_format.spec.js +++ b/packages/dd-trace/test/span_format.spec.js @@ -3,8 +3,8 @@ const assert = require('node:assert/strict') const { expect } = require('chai') -const { assertObjectContains } = require('../../../integration-tests/helpers') +const { assertObjectContains } = require('../../../integration-tests/helpers') const { describe, it, beforeEach } = require('tap').mocha const sinon = require('sinon') @@ -206,11 +206,7 @@ describe('spanFormat', () => { trace = spanFormat(span) - expect(trace.metrics).to.not.have.keys( - SAMPLING_AGENT_DECISION, - SAMPLING_LIMIT_DECISION, - SAMPLING_RULE_DECISION - ) + assert.ok(!(([SAMPLING_AGENT_DECISION, SAMPLING_LIMIT_DECISION, SAMPLING_RULE_DECISION]).some(k => Object.hasOwn(trace.metrics, k)))) }) it('should always add single span ingestion tags from options if present', () => { @@ -230,11 +226,7 @@ describe('spanFormat', () => { it('should not add single span ingestion tags if options not present', () => { trace = spanFormat(span) - expect(trace.metrics).to.not.have.keys( - SPAN_SAMPLING_MECHANISM, - SPAN_SAMPLING_MAX_PER_SECOND, - SPAN_SAMPLING_RULE_RATE - ) + assert.ok(!(([SPAN_SAMPLING_MECHANISM, SPAN_SAMPLING_MAX_PER_SECOND, SPAN_SAMPLING_RULE_RATE]).some(k => Object.hasOwn(trace.metrics, k)))) }) it('should format span links', () => { diff --git a/packages/dd-trace/test/span_processor.spec.js b/packages/dd-trace/test/span_processor.spec.js index 1f09ea9b269..47544990a55 100644 --- a/packages/dd-trace/test/span_processor.spec.js +++ b/packages/dd-trace/test/span_processor.spec.js @@ -1,8 +1,6 @@ 'use strict' const assert = require('node:assert/strict') - -const { expect } = require('chai') const { describe, it, beforeEach } = require('tap').mocha const sinon = require('sinon') const proxyquire = require('proxyquire') @@ -77,7 +75,7 @@ describe('SpanProcessor', () => { it('should generate sampling priority when sampling manually', () => { processor.sample(finishedSpan) - expect(prioritySampler.sample).to.have.been.calledWith(finishedSpan.context()) + sinon.assert.calledWith(prioritySampler.sample, finishedSpan.context()) }) it('should erase the trace once finished', () => { @@ -86,9 +84,12 @@ describe('SpanProcessor', () => { processor.process(finishedSpan) - expect(trace).to.have.deep.property('started', []) - expect(trace).to.have.deep.property('finished', []) - expect(finishedSpan.context()).to.have.deep.property('_tags', {}) + assert.ok('started' in trace); +assert.deepStrictEqual(trace['started'], []) + assert.ok('finished' in trace); +assert.deepStrictEqual(trace['finished'], []) + assert.ok('_tags' in finishedSpan.context()); +assert.deepStrictEqual(finishedSpan.context()['_tags'], {}) }) it('should skip traces with unfinished spans', () => { @@ -119,8 +120,10 @@ describe('SpanProcessor', () => { { formatted: true } ]) - expect(trace).to.have.deep.property('started', [activeSpan]) - expect(trace).to.have.deep.property('finished', []) + assert.ok('started' in trace); +assert.deepStrictEqual(trace['started'], [activeSpan]) + assert.ok('finished' in trace); +assert.deepStrictEqual(trace['finished'], []) }) it('should configure span sampler correctly', () => { @@ -159,9 +162,12 @@ describe('SpanProcessor', () => { processor.process(finishedSpan) - expect(trace).to.have.deep.property('started', []) - expect(trace).to.have.deep.property('finished', []) - expect(finishedSpan.context()).to.have.deep.property('_tags', {}) + assert.ok('started' in trace); +assert.deepStrictEqual(trace['started'], []) + assert.ok('finished' in trace); +assert.deepStrictEqual(trace['finished'], []) + assert.ok('_tags' in finishedSpan.context()); +assert.deepStrictEqual(finishedSpan.context()['_tags'], {}) sinon.assert.notCalled(exporter.export) }) @@ -172,8 +178,10 @@ describe('SpanProcessor', () => { trace.finished = [finishedSpan] processor.process(activeSpan) - expect(trace).to.have.deep.property('started', [activeSpan]) - expect(trace).to.have.deep.property('finished', []) + assert.ok('started' in trace); +assert.deepStrictEqual(trace['started'], [activeSpan]) + assert.ok('finished' in trace); +assert.deepStrictEqual(trace['finished'], []) assert.strictEqual(spanFormat.callCount, 1) sinon.assert.calledWith(spanFormat, finishedSpan, true) }) diff --git a/packages/dd-trace/test/standalone/index.spec.js b/packages/dd-trace/test/standalone/index.spec.js index ad89e2df14b..da88bab4da1 100644 --- a/packages/dd-trace/test/standalone/index.spec.js +++ b/packages/dd-trace/test/standalone/index.spec.js @@ -1,6 +1,6 @@ 'use strict' -const { assert } = require('chai') +const assert = require('node:assert/strict') const { describe, it, beforeEach, afterEach } = require('tap').mocha const sinon = require('sinon') const proxyquire = require('proxyquire') @@ -114,13 +114,13 @@ describe('Disabled APM Tracing or Standalone', () => { it('should not return a prioritySampler when standalone ASM is disabled', () => { const prioritySampler = standalone.configure({ apmTracingEnabled: true }) - assert.isUndefined(prioritySampler) + assert.strictEqual(prioritySampler, undefined) }) it('should return a TraceSourcePrioritySampler when standalone ASM is enabled', () => { const prioritySampler = standalone.configure(config) - assert.instanceOf(prioritySampler, TraceSourcePrioritySampler) + assert.ok(prioritySampler instanceof TraceSourcePrioritySampler) }) }) @@ -133,7 +133,7 @@ describe('Disabled APM Tracing or Standalone', () => { operationName: 'operation' }) - assert.notProperty(span.context()._tags, APM_TRACING_ENABLED_KEY) + assert.ok(!Object.hasOwn(span.context()._tags, APM_TRACING_ENABLED_KEY)) }) it('should add _dd.apm.enabled tag when standalone is enabled', () => { @@ -143,7 +143,7 @@ describe('Disabled APM Tracing or Standalone', () => { operationName: 'operation' }) - assert.property(span.context()._tags, APM_TRACING_ENABLED_KEY) + assert.ok(Object.hasOwn(span.context()._tags, APM_TRACING_ENABLED_KEY)) }) it('should not add _dd.apm.enabled tag in child spans with local parent', () => { @@ -153,14 +153,14 @@ describe('Disabled APM Tracing or Standalone', () => { operationName: 'operation' }) - assert.propertyVal(parent.context()._tags, APM_TRACING_ENABLED_KEY, 0) + assert.strictEqual(parent.context()._tags[APM_TRACING_ENABLED_KEY], 0) const child = new DatadogSpan(tracer, processor, prioritySampler, { operationName: 'operation', parent }) - assert.notProperty(child.context()._tags, APM_TRACING_ENABLED_KEY) + assert.ok(!Object.hasOwn(child.context()._tags, APM_TRACING_ENABLED_KEY)) }) it('should add _dd.apm.enabled tag in child spans with remote parent', () => { @@ -177,7 +177,7 @@ describe('Disabled APM Tracing or Standalone', () => { parent }) - assert.propertyVal(child.context()._tags, APM_TRACING_ENABLED_KEY, 0) + assert.strictEqual(child.context()._tags[APM_TRACING_ENABLED_KEY], 0) }) }) @@ -194,7 +194,7 @@ describe('Disabled APM Tracing or Standalone', () => { const propagator = new TextMapPropagator(config) const spanContext = propagator.extract(carrier) - assert.isUndefined(spanContext._sampling.priority) + assert.strictEqual(spanContext._sampling.priority, undefined) }) it('should not reset dm if _dd.p.ts not present', () => { @@ -210,7 +210,7 @@ describe('Disabled APM Tracing or Standalone', () => { const propagator = new TextMapPropagator(config) const spanContext = propagator.extract(carrier) - assert.propertyVal(spanContext._trace.tags, DECISION_MAKER_KEY, '-4') + assert.strictEqual(spanContext._trace.tags[DECISION_MAKER_KEY], '-4') }) it('should keep priority if _dd.p.ts is present', () => { @@ -227,7 +227,7 @@ describe('Disabled APM Tracing or Standalone', () => { const spanContext = propagator.extract(carrier) assert.strictEqual(spanContext._sampling.priority, USER_KEEP) - assert.propertyVal(spanContext._trace.tags, DECISION_MAKER_KEY, '-5') + assert.strictEqual(spanContext._trace.tags[DECISION_MAKER_KEY], '-5') }) it('should set USER_KEEP priority if _dd.p.ts=02 is present', () => { @@ -280,12 +280,12 @@ describe('Disabled APM Tracing or Standalone', () => { const propagator = new TextMapPropagator(config) propagator.inject(span._spanContext, carrier) - assert.notProperty(carrier, 'x-datadog-trace-id') - assert.notProperty(carrier, 'x-datadog-parent-id') - assert.notProperty(carrier, 'x-datadog-sampling-priority') + assert.ok(!Object.hasOwn(carrier, 'x-datadog-trace-id')) + assert.ok(!Object.hasOwn(carrier, 'x-datadog-parent-id')) + assert.ok(!Object.hasOwn(carrier, 'x-datadog-sampling-priority')) - assert.notProperty(carrier, 'x-b3-traceid') - assert.notProperty(carrier, 'x-b3-spanid') + assert.ok(!Object.hasOwn(carrier, 'x-b3-traceid')) + assert.ok(!Object.hasOwn(carrier, 'x-b3-spanid')) }) it('should keep priority if apm tracing is disabled and there is an appsec event', () => { @@ -306,10 +306,10 @@ describe('Disabled APM Tracing or Standalone', () => { const propagator = new TextMapPropagator(config) propagator.inject(span._spanContext, carrier) - assert.property(carrier, 'x-datadog-trace-id') - assert.property(carrier, 'x-datadog-parent-id') - assert.property(carrier, 'x-datadog-sampling-priority') - assert.propertyVal(carrier, 'x-datadog-tags', '_dd.p.ts=02') + assert.ok(Object.hasOwn(carrier, 'x-datadog-trace-id')) + assert.ok(Object.hasOwn(carrier, 'x-datadog-parent-id')) + assert.ok(Object.hasOwn(carrier, 'x-datadog-sampling-priority')) + assert.strictEqual(carrier['x-datadog-tags'], '_dd.p.ts=02') }) it('should not reset priority if standalone disabled', () => { @@ -329,12 +329,12 @@ describe('Disabled APM Tracing or Standalone', () => { const propagator = new TextMapPropagator(config) propagator.inject(span._spanContext, carrier) - assert.property(carrier, 'x-datadog-trace-id') - assert.property(carrier, 'x-datadog-parent-id') - assert.property(carrier, 'x-datadog-sampling-priority') + assert.ok(Object.hasOwn(carrier, 'x-datadog-trace-id')) + assert.ok(Object.hasOwn(carrier, 'x-datadog-parent-id')) + assert.ok(Object.hasOwn(carrier, 'x-datadog-sampling-priority')) - assert.property(carrier, 'x-b3-traceid') - assert.property(carrier, 'x-b3-spanid') + assert.ok(Object.hasOwn(carrier, 'x-b3-traceid')) + assert.ok(Object.hasOwn(carrier, 'x-b3-spanid')) }) it('should clear tracestate datadog info', () => { @@ -358,8 +358,8 @@ describe('Disabled APM Tracing or Standalone', () => { const propagator = new TextMapPropagator(config) propagator.inject(span._spanContext, carrier) - assert.propertyVal(carrier, 'tracestate', 'other=id:0xC0FFEE') - assert.notProperty(carrier, 'traceparent') + assert.strictEqual(carrier['tracestate'], 'other=id:0xC0FFEE') + assert.ok(!Object.hasOwn(carrier, 'traceparent')) }) }) }) diff --git a/packages/dd-trace/test/standalone/product.spec.js b/packages/dd-trace/test/standalone/product.spec.js index 06b521c6cc0..2f812473716 100644 --- a/packages/dd-trace/test/standalone/product.spec.js +++ b/packages/dd-trace/test/standalone/product.spec.js @@ -1,6 +1,6 @@ 'use strict' -const { assert } = require('chai') +const assert = require('node:assert/strict') const { describe, it, beforeEach, afterEach } = require('tap').mocha const sinon = require('sinon') const proxyquire = require('proxyquire') @@ -31,20 +31,20 @@ describe('Disabled APM Tracing or Standalone - Product', () => { describe('getProductRateLimiter', () => { it('should return a drop all traces rateLimiter by default', () => { const rateLimiter = getProductRateLimiter({}) - assert.propertyVal(rateLimiter, 'limit', 0) - assert.propertyVal(rateLimiter, 'interval', 'second') + assert.strictEqual(rateLimiter['limit'], 0) + assert.strictEqual(rateLimiter['interval'], 'second') }) it('should return a 1req/min rateLimiter when appsec is enabled', () => { const rateLimiter = getProductRateLimiter({ appsec: { enabled: true } }) - assert.propertyVal(rateLimiter, 'limit', 1) - assert.propertyVal(rateLimiter, 'interval', 'minute') + assert.strictEqual(rateLimiter['limit'], 1) + assert.strictEqual(rateLimiter['interval'], 'minute') }) it('should return a 1req/min rateLimiter when iast is enabled', () => { const rateLimiter = getProductRateLimiter({ iast: { enabled: true } }) - assert.propertyVal(rateLimiter, 'limit', 1) - assert.propertyVal(rateLimiter, 'interval', 'minute') + assert.strictEqual(rateLimiter['limit'], 1) + assert.strictEqual(rateLimiter['interval'], 'minute') }) }) }) diff --git a/packages/dd-trace/test/standalone/tracesource.spec.js b/packages/dd-trace/test/standalone/tracesource.spec.js index 5ca122cdf56..8132f23ca66 100644 --- a/packages/dd-trace/test/standalone/tracesource.spec.js +++ b/packages/dd-trace/test/standalone/tracesource.spec.js @@ -1,6 +1,6 @@ 'use strict' -const { assert } = require('chai') +const assert = require('node:assert/strict') const { describe, it, beforeEach } = require('tap').mocha require('../setup/core') @@ -18,33 +18,33 @@ describe('Disabled APM Tracing or Standalone - Tracesource propagation tag', () describe('addTraceSourceTag', () => { it('should not fail', () => { - assert.notProperty(addTraceSourceTag(tags), TRACE_SOURCE_PROPAGATION_KEY) + assert.ok(!Object.hasOwn(addTraceSourceTag(tags), TRACE_SOURCE_PROPAGATION_KEY)) }) it('should not modify original tag value', () => { tags[TRACE_SOURCE_PROPAGATION_KEY] = '04' - assert.propertyVal(addTraceSourceTag(tags), TRACE_SOURCE_PROPAGATION_KEY, '04') + assert.strictEqual(addTraceSourceTag(tags)[TRACE_SOURCE_PROPAGATION_KEY], '04') }) it('should add product', () => { - assert.propertyVal(addTraceSourceTag(tags, ASM), TRACE_SOURCE_PROPAGATION_KEY, '02') + assert.strictEqual(addTraceSourceTag(tags, ASM)[TRACE_SOURCE_PROPAGATION_KEY], '02') }) it('should not modify existing product', () => { tags[TRACE_SOURCE_PROPAGATION_KEY] = '02' - assert.propertyVal(addTraceSourceTag(tags, ASM), TRACE_SOURCE_PROPAGATION_KEY, '02') + assert.strictEqual(addTraceSourceTag(tags, ASM)[TRACE_SOURCE_PROPAGATION_KEY], '02') }) it('should add new product to existing product', () => { tags[TRACE_SOURCE_PROPAGATION_KEY] = '04' - assert.propertyVal(addTraceSourceTag(tags, ASM), TRACE_SOURCE_PROPAGATION_KEY, '06') + assert.strictEqual(addTraceSourceTag(tags, ASM)[TRACE_SOURCE_PROPAGATION_KEY], '06') }) it('should handle 32 bits tag values', () => { const FUTURE_PRODUCT_TAG = ((1 << 31) >>> 0).toString(16) // 80000000 tags[TRACE_SOURCE_PROPAGATION_KEY] = FUTURE_PRODUCT_TAG - assert.propertyVal(addTraceSourceTag(tags, ASM), TRACE_SOURCE_PROPAGATION_KEY, '80000002') + assert.strictEqual(addTraceSourceTag(tags, ASM)[TRACE_SOURCE_PROPAGATION_KEY], '80000002') }) }) }) diff --git a/packages/dd-trace/test/standalone/tracesource_priority_sampler.spec.js b/packages/dd-trace/test/standalone/tracesource_priority_sampler.spec.js index 3c316e0a94f..4e56cdad06f 100644 --- a/packages/dd-trace/test/standalone/tracesource_priority_sampler.spec.js +++ b/packages/dd-trace/test/standalone/tracesource_priority_sampler.spec.js @@ -1,6 +1,6 @@ 'use strict' -const { assert } = require('chai') +const assert = require('node:assert/strict') const { describe, it, beforeEach } = require('tap').mocha const sinon = require('sinon') const proxyquire = require('proxyquire') @@ -55,7 +55,7 @@ describe('Disabled APM Tracing or Standalone - TraceSourcePrioritySampler', () = }) it('should return undefined if manual.keep or _dd.p.ts are not present', () => { - assert.isUndefined(prioritySampler._getPriorityFromTags(tags, context)) + assert.strictEqual(prioritySampler._getPriorityFromTags(tags, context), undefined) }) }) diff --git a/packages/dd-trace/test/tagger.spec.js b/packages/dd-trace/test/tagger.spec.js index 990b2761213..2db165a43e3 100644 --- a/packages/dd-trace/test/tagger.spec.js +++ b/packages/dd-trace/test/tagger.spec.js @@ -1,8 +1,6 @@ 'use strict' const assert = require('node:assert/strict') - -const { expect } = require('chai') const { describe, it, beforeEach } = require('tap').mocha const constants = require('../src/constants') @@ -71,11 +69,11 @@ describe('tagger', () => { }) it('should handle missing key/value pairs', () => { - expect(() => tagger.add(carrier)).not.to.throw() + assert.doesNotThrow(() => tagger.add(carrier)) }) it('should handle missing carrier', () => { - expect(() => tagger.add()).not.to.throw() + assert.doesNotThrow(() => tagger.add()) }) it('should set trace error', () => { diff --git a/packages/dd-trace/test/telemetry/endpoints.spec.js b/packages/dd-trace/test/telemetry/endpoints.spec.js index 1a769148d1c..d62cb6468fe 100644 --- a/packages/dd-trace/test/telemetry/endpoints.spec.js +++ b/packages/dd-trace/test/telemetry/endpoints.spec.js @@ -1,6 +1,8 @@ 'use strict' -const { expect } = require('chai') +const assert = require('node:assert/strict') +const { assertObjectContains } = require('../../../../integration-tests/helpers') + const { describe, it, beforeEach, afterEach } = require('tap').mocha const sinon = require('sinon') const proxyquire = require('proxyquire') @@ -32,14 +34,14 @@ describe('endpoints telemetry', () => { const config = { appsec: { apiSecurity: { endpointCollectionEnabled: true } } } endpoints.start(config) - expect(subscribe).to.have.been.calledThrice + sinon.assert.calledThrice(subscribe) }) it('should not subscribe', () => { const config = { appsec: { apiSecurity: { endpointCollectionEnabled: false } } } endpoints.start(config) - expect(subscribe).to.not.have.been.called + sinon.assert.notCalled(subscribe) }) }) @@ -98,9 +100,9 @@ describe('endpoints telemetry', () => { scheduledCallbacks.forEach(cb => cb()) - expect(sendData).to.have.been.calledOnce + sinon.assert.calledOnce(sendData) const payload = sendData.firstCall.args[4] - expect(payload.endpoints).to.have.deep.members([ + assertObjectContains(payload.endpoints, [ { type: 'REST', method: 'GET', @@ -132,12 +134,13 @@ describe('endpoints telemetry', () => { fastifyRouteCh.publish({ routeOptions: { method: 'POST', path: '/two' } }) scheduledCallbacks.forEach(cb => cb()) - expect(sendData.callCount).to.equal(2) + assert.strictEqual(sendData.callCount, 2) const firstPayload = sendData.firstCall.args[4] const secondPayload = sendData.secondCall.args[4] - expect(firstPayload).to.have.property('is_first', true) - expect(Boolean(secondPayload.is_first)).to.equal(false) + assert.ok('is_first' in firstPayload); + assert.strictEqual(firstPayload['is_first'], true) + assert.strictEqual(Boolean(secondPayload.is_first), false) }) it('should send large amount of endpoints in small batches', () => { @@ -148,12 +151,12 @@ describe('endpoints telemetry', () => { scheduledCallbacks.forEach(cb => cb()) scheduledCallbacks.forEach(cb => cb()) - expect(sendData.callCount).to.equal(2) + assert.strictEqual(sendData.callCount, 2) const firstPayload = sendData.firstCall.args[4] const secondPayload = sendData.secondCall.args[4] - expect(firstPayload.endpoints).to.have.length(100) - expect(secondPayload.endpoints).to.have.length(50) + assert.strictEqual(firstPayload.endpoints.length, 100) + assert.strictEqual(secondPayload.endpoints.length, 50) }) it('should record express route and add HEAD for GET', () => { @@ -161,11 +164,11 @@ describe('endpoints telemetry', () => { scheduledCallbacks.forEach(cb => cb()) - expect(sendData).to.have.been.calledOnce + sinon.assert.calledOnce(sendData) const payload = sendData.firstCall.args[4] const resources = payload.endpoints.map(e => e.resource_name) - expect(resources).to.include('GET /test') - expect(resources).to.include('HEAD /test') + assertObjectContains(resources, 'GET /test') + assertObjectContains(resources, 'HEAD /test') }) it('should record express wildcard and ignore subsequent specific methods for same path', () => { @@ -175,10 +178,10 @@ describe('endpoints telemetry', () => { scheduledCallbacks.forEach(cb => cb()) - expect(sendData).to.have.been.calledOnce + sinon.assert.calledOnce(sendData) const payload = sendData.firstCall.args[4] const resources = payload.endpoints.map(e => e.resource_name) - expect(resources).to.deep.equal(['* /all']) + assert.deepStrictEqual(resources, ['* /all']) }) it('should handle router routes the same way as express routes', () => { @@ -186,11 +189,11 @@ describe('endpoints telemetry', () => { scheduledCallbacks.forEach(cb => cb()) - expect(sendData).to.have.been.calledOnce + sinon.assert.calledOnce(sendData) const payload = sendData.firstCall.args[4] const resources = payload.endpoints.map(e => e.resource_name) - expect(resources).to.include('GET /router-test') - expect(resources).to.include('HEAD /router-test') + assertObjectContains(resources, 'GET /router-test') + assertObjectContains(resources, 'HEAD /router-test') }) describe('on failed request', () => { @@ -210,9 +213,9 @@ describe('endpoints telemetry', () => { scheduledCallbacks.forEach(cb => cb()) - expect(getRetryData).to.have.been.calledOnce - expect(capturedRequestType).to.equal('app-endpoints') - expect(updateRetryData).to.have.been.calledOnce + sinon.assert.calledOnce(getRetryData) + assert.strictEqual(capturedRequestType, 'app-endpoints') + sinon.assert.calledOnce(updateRetryData) }) it('should create batch request when retry data exists', () => { @@ -220,8 +223,8 @@ describe('endpoints telemetry', () => { scheduledCallbacks.forEach(cb => cb()) - expect(getRetryData).to.have.been.calledOnce - expect(capturedRequestType).to.equal('app-endpoints') + sinon.assert.calledOnce(getRetryData) + assert.strictEqual(capturedRequestType, 'app-endpoints') getRetryData.returns({ reqType: 'app-endpoints', @@ -230,9 +233,9 @@ describe('endpoints telemetry', () => { fastifyRouteCh.publish({ routeOptions: { method: 'POST', path: '/second' } }) scheduledCallbacks.forEach(cb => cb()) - expect(getRetryData).to.have.been.calledTwice - expect(capturedRequestType).to.equal('message-batch') - expect(updateRetryData).to.have.been.calledTwice + sinon.assert.calledTwice(getRetryData) + assert.strictEqual(capturedRequestType, 'message-batch') + sinon.assert.calledTwice(updateRetryData) }) }) }) diff --git a/packages/dd-trace/test/telemetry/index.spec.js b/packages/dd-trace/test/telemetry/index.spec.js index 2932fa50efe..dfd3222d5e8 100644 --- a/packages/dd-trace/test/telemetry/index.spec.js +++ b/packages/dd-trace/test/telemetry/index.spec.js @@ -3,8 +3,8 @@ const assert = require('node:assert/strict') const { expect } = require('chai') -const { assertObjectContains } = require('../../../../integration-tests/helpers') +const { assertObjectContains } = require('../../../../integration-tests/helpers') const { describe, it, beforeEach, afterEach, before, after } = require('tap').mocha const sinon = require('sinon') const proxyquire = require('proxyquire').noPreserveCache() @@ -860,7 +860,7 @@ describe('Telemetry retry', () => { clock.tick(86400000) assert.strictEqual(extendedHeartbeatRequest, 'app-extended-heartbeat') expect(extendedHeartbeatPayload).to.haveOwnProperty('integrations') - expect(extendedHeartbeatPayload.integrations).to.deep.include({ + assertObjectContains(extendedHeartbeatPayload.integrations, { integrations: [ { name: 'foo2', enabled: true, auto_enabled: true }, { name: 'bar2', enabled: false, auto_enabled: true } @@ -1036,7 +1036,7 @@ async function testSeq (seqId, reqType, validatePayload) { architecture: os.arch() } } - expect(req.body).to.deep.include({ + assertObjectContains(req.body, { api_version: 'v2', naming_schema_version: '', request_type: reqType, @@ -1052,7 +1052,7 @@ async function testSeq (seqId, reqType, validatePayload) { }, host }) - expect([1, 0, -1].includes(Math.floor(Date.now() / 1000) - req.body.tracer_time)).to.be.true + assert.strictEqual([1, 0, -1].includes(Math.floor(Date.now() / 1000) - req.body.tracer_time), true) validatePayload(req.body.payload) } diff --git a/packages/dd-trace/test/telemetry/logs/index.spec.js b/packages/dd-trace/test/telemetry/logs/index.spec.js index 00a99dcd67f..4f2f40a7aa5 100644 --- a/packages/dd-trace/test/telemetry/logs/index.spec.js +++ b/packages/dd-trace/test/telemetry/logs/index.spec.js @@ -108,7 +108,7 @@ describe('telemetry logs', () => { it('should be not called with DEBUG level', () => { telemetryLog.publish({ message: 'message', level: 'DEBUG' }) - expect(logCollectorAdd).to.not.be.called + sinon.assert.notCalled(logCollectorAdd) }) it('should be called with WARN level', () => { @@ -134,13 +134,13 @@ describe('telemetry logs', () => { it('should not be called with no defined level', () => { telemetryLog.publish({ message: 'message' }) - expect(logCollectorAdd).to.not.be.called + sinon.assert.notCalled(logCollectorAdd) }) it('should not be called with incorrect level', () => { telemetryLog.publish({ message: 'message', level: 'INFO' }) - expect(logCollectorAdd).to.not.be.called + sinon.assert.notCalled(logCollectorAdd) }) describe('datadog:log:error', () => { @@ -171,19 +171,19 @@ describe('telemetry logs', () => { it('should not be called when an invalid object is published to datadog:log:error', () => { errorLog.publish({ invalid: 'field', sendViaTelemetry: true }) - expect(logCollectorAdd).not.to.be.called + sinon.assert.notCalled(logCollectorAdd) }) it('should not be called when an object without message and stack is published to datadog:log:error', () => { errorLog.publish(Log.parse(() => new Error('error'))) - expect(logCollectorAdd).not.to.be.called + sinon.assert.notCalled(logCollectorAdd) }) it('should not be called when an error contains sendViaTelemetry:false', () => { errorLog.publish({ message: 'custom error message', sendViaTelemetry: false }) - expect(logCollectorAdd).not.to.be.called + sinon.assert.notCalled(logCollectorAdd) }) }) }) @@ -227,8 +227,8 @@ describe('telemetry logs', () => { logs.send(defaultConfig, application, host) - expect(logCollectorDrain).to.not.be.called - expect(sendData).to.not.be.called + sinon.assert.notCalled(logCollectorDrain) + sinon.assert.notCalled(sendData) }) }) }) diff --git a/packages/dd-trace/test/telemetry/logs/log-collector.spec.js b/packages/dd-trace/test/telemetry/logs/log-collector.spec.js index b51fbcfaec0..42a5e33867d 100644 --- a/packages/dd-trace/test/telemetry/logs/log-collector.spec.js +++ b/packages/dd-trace/test/telemetry/logs/log-collector.spec.js @@ -1,8 +1,6 @@ 'use strict' const assert = require('node:assert/strict') - -const { expect } = require('chai') const { describe, it, afterEach } = require('tap').mocha require('../../setup/core') @@ -183,7 +181,7 @@ describe('telemetry log collector', () => { const logs = logCollector.drain() assert.strictEqual(logs.length, 4) - expect(logs[3]).to.deep.eq({ message: 'Omitted 2 entries due to overflowing', level: 'ERROR' }) + assert.deepStrictEqual(logs[3], { message: 'Omitted 2 entries due to overflowing', level: 'ERROR' }) }) it('duplicated errors should send incremented count values', () => { diff --git a/packages/dd-trace/test/telemetry/metrics.spec.js b/packages/dd-trace/test/telemetry/metrics.spec.js index c1d1a0360c8..6bf7e38bc73 100644 --- a/packages/dd-trace/test/telemetry/metrics.spec.js +++ b/packages/dd-trace/test/telemetry/metrics.spec.js @@ -192,22 +192,22 @@ describe('metrics', () => { it('should get count metric', () => { const ns = new metrics.Namespace('name') - expect(ns.count('name')).to.be.instanceOf(metrics.CountMetric) + assert.ok(ns.count('name') instanceof metrics.CountMetric) }) it('should get distribution metric', () => { const ns = new metrics.Namespace('name') - expect(ns.distribution('name')).to.be.instanceOf(metrics.DistributionMetric) + assert.ok(ns.distribution('name') instanceof metrics.DistributionMetric) }) it('should get gauge metric', () => { const ns = new metrics.Namespace('name') - expect(ns.gauge('name')).to.be.instanceOf(metrics.GaugeMetric) + assert.ok(ns.gauge('name') instanceof metrics.GaugeMetric) }) it('should get rate metric', () => { const ns = new metrics.Namespace('name') - expect(ns.rate('name')).to.be.instanceOf(metrics.RateMetric) + assert.ok(ns.rate('name') instanceof metrics.RateMetric) }) it('should have unique metrics per unique tag set', () => { diff --git a/packages/dd-trace/test/tracer.spec.js b/packages/dd-trace/test/tracer.spec.js index 2e3a721cc1b..c14d7b9afcc 100644 --- a/packages/dd-trace/test/tracer.spec.js +++ b/packages/dd-trace/test/tracer.spec.js @@ -1,8 +1,6 @@ 'use strict' const assert = require('node:assert/strict') - -const { expect } = require('chai') const { assertObjectContains } = require('../../../integration-tests/helpers') const { describe, it, beforeEach, afterEach } = require('tap').mocha @@ -72,7 +70,7 @@ describe('Tracer', () => { tracer.trace('name', options, span => { assert.ok(span instanceof Span) - expect(span.context()._tags).to.include(options.tags) + assertObjectContains(span.context()._tags, options.tags) assertObjectContains(span.context()._tags, { [SERVICE_NAME]: 'service', [RESOURCE_NAME]: 'resource', diff --git a/packages/dd-trace/test/util.spec.js b/packages/dd-trace/test/util.spec.js index fdd80b4e8db..cef6dcfd196 100644 --- a/packages/dd-trace/test/util.spec.js +++ b/packages/dd-trace/test/util.spec.js @@ -1,8 +1,6 @@ 'use strict' const assert = require('node:assert/strict') - -const { expect } = require('chai') const { describe, it } = require('tap').mocha require('./setup/core') @@ -44,22 +42,22 @@ describe('util', () => { it('isTrue works', () => { TRUES.forEach((v) => { assert.strictEqual(isTrue(v), true) - expect(isTrue(String(v))).to.equal(true) + assert.strictEqual(isTrue(String(v)), true) }) FALSES.forEach((v) => { assert.strictEqual(isTrue(v), false) - expect(isTrue(String(v))).to.equal(false) + assert.strictEqual(isTrue(String(v)), false) }) }) it('isFalse works', () => { FALSES.forEach((v) => { assert.strictEqual(isFalse(v), true) - expect(isFalse(String(v))).to.equal(true) + assert.strictEqual(isFalse(String(v)), true) }) TRUES.forEach((v) => { assert.strictEqual(isFalse(v), false) - expect(isFalse(String(v))).to.equal(false) + assert.strictEqual(isFalse(String(v)), false) }) }) diff --git a/scripts/codemods/chai-to-assert.js b/scripts/codemods/chai-to-assert.js index bf4861f66c9..3ddbd807994 100644 --- a/scripts/codemods/chai-to-assert.js +++ b/scripts/codemods/chai-to-assert.js @@ -115,7 +115,13 @@ function rebuildImportsSortedByType (code) { if (node.length) pieces.push(node.map(x => x.line).join('\n')) if (npm.length) pieces.push(npm.map(x => x.line).join('\n')) if (rel.length) pieces.push(rel.map(x => x.line).join('\n')) - const rebuilt = pieces.join('\n\n') + let rebuilt = pieces.join('\n\n') + // Preserve the original number of lines in the import block to avoid removing blank lines + const originalLineCount = lines.length + const rebuiltLineCount = rebuilt.length ? rebuilt.split('\n').length : 0 + if (rebuiltLineCount < originalLineCount) { + rebuilt += '\n'.repeat(originalLineCount - rebuiltLineCount) + } return code.slice(0, start) + rebuilt + code.slice(end) } @@ -229,14 +235,7 @@ function ensureAssertObjectContainsImport (code, file) { return importLine + code } -/** - * Escape a JS expression to a regex at runtime. - * Produces: new RegExp((EXPR).replace(/[.*+?^${}()|[\]\\]/g, '\\$&')) - */ -function wrapAsEscapedRegex (expr) { - return 'new RegExp((' + expr + ')' + - ".replace(/[.*+?^${}()|[\\]\\]/g, '\\$&'))" -} +// wrapAsEscapedRegex removed – literals now use .includes checks // -------- Helpers to format long assert lines (wrap args if >120 chars) -------- function splitTopLevelArgs (s) { @@ -307,6 +306,28 @@ function buildAccessor (objExpr, keyLiteral) { return `${objExpr}[${k}]` } +// Build nested accessor for dot-separated string paths like 'a.b.c'. +// Only supports simple string literals with identifier segments. Otherwise, returns null. +function buildNestedAccessor (objExpr, pathLiteral) { + const p = (pathLiteral || '').trim() + const isQuoted = (p.startsWith('"') && p.endsWith('"')) || (p.startsWith("'") && p.endsWith("'")) + if (!isQuoted) return null + const inner = p.slice(1, -1) + if (!inner) return null + const parts = inner.split('.') + let out = objExpr + for (const raw of parts) { + const part = raw.trim() + if (!part) return null + if (/^[A-Za-z_][A-Za-z0-9_]*$/.test(part)) { + out += '.' + part + } else { + out += "['" + part.replace(/'/g, "\\'") + "']" + } + } + return out +} + // Detect files using expect from Playwright and skip transforming them function usesPlaywrightExpect (code) { // import { expect } from '@playwright/test' @@ -427,7 +448,6 @@ function transform (code, file) { const hasNodeAssertImportBefore = /\bconst\s+assert\s*=\s*require\(['"](node:)?assert(?:\/strict)?['"]\)/.test(code) || /^\s*import\s+(?:\*\s+as\s+)?assert\s+from\s*['"](node:)?assert(?:\/strict)?['"]/m.test(code) || /^\s*import\s*\{\s*strict\s+as\s+assert\s*\}\s*from\s*['"](node:)?assert['"]/m.test(code) - const hasAssertVariableBefore = /\b(?:const|let|var)\s+assert\s*=/.test(code) || /\bconst\s*\{[^}]*\bassert\b[^}]*\}\s*=\s*require\(\s*['"]chai['"]\s*\)/.test(code) || /\bimport\s*\{[^}]*\bassert\b[^}]*\}\s*from\s*['"]chai['"]/.test(code) // 0) Do not alter chai/sinon-chai imports or chai.use lines here; we only add assert when used. @@ -439,9 +459,14 @@ function transform (code, file) { 'await assert.rejects($1, $2)') out = out.replace(/await\s+expect\(([^)]+)\)\.to\.be\.rejected(?!With)/g, 'await assert.rejects($1)') + // return expect(p).to.be.rejected[With(...)] + out = out.replace(/return\s+expect\(([^)]+)\)\.to\.be\.rejectedWith\(([^)]+)\)/g, + 'return assert.rejects($1, $2)') + out = out.replace(/return\s+expect\(([^)]+)\)\.to\.be\.rejected(?!With)/g, + 'return assert.rejects($1)') // 3) NaN - out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.be\.NaN/g, 'assert.strictEqual($1, NaN)') + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.be\.NaN/g, 'assert.ok(Number.isNaN($1))') // 6) Basic equality out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.deep\.(?:equal|eql)\(([^)]+)\)/g, 'assert.deepStrictEqual($1, $2)') @@ -450,10 +475,19 @@ function transform (code, file) { out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.eq\(([^)]+)\)/g, 'assert.strictEqual($1, $2)') out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.eql\(([^)]+)\)/g, 'assert.deepStrictEqual($1, $2)') out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.(?:be\.)?(?:equal|equals)\(([^)]+)\)/g, 'assert.strictEqual($1, $2)') + // .to.be.eq(...) + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.be\.eq\(([^)]+)\)/g, 'assert.strictEqual($1, $2)') // function-call aware equal/equals (balanced one-level parentheses) out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.not\.(?:be\.)?(?:equal|equals)\(([^)]+)\)/g, 'assert.notStrictEqual($1, $2)') out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.(?:to\.not|not\.to)\.(?:be\.)?(?:equal|equals)\(([^)]+)\)/g, 'assert.notStrictEqual($1, $2)') out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.(?:to\.not|not\.to)\.deep\.(?:equal|eql)\(([^)]+)\)/g, 'assert.notDeepStrictEqual($1, $2)') + // Direct method forms without 'to.' chain: equal/equals/eq/eql + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.(?:equal|equals)\(([^)]+)\)/g, 'assert.strictEqual($1, $2)') + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.eq\(([^)]+)\)/g, 'assert.strictEqual($1, $2)') + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.eql\(([^)]+)\)/g, 'assert.deepStrictEqual($1, $2)') + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.not\.(?:equal|equals)\(([^)]+)\)/g, 'assert.notStrictEqual($1, $2)') + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.not\.eq\(([^)]+)\)/g, 'assert.notStrictEqual($1, $2)') + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.not\.eql\(([^)]+)\)/g, 'assert.notDeepStrictEqual($1, $2)') // toBe / not.toBe (used in some chai setups too) out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.toBe\(([^)]+)\)/g, 'assert.strictEqual($1, $2)') out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.not\.toBe\(([^)]+)\)/g, 'assert.notStrictEqual($1, $2)') @@ -464,16 +498,40 @@ function transform (code, file) { // 4) Truthiness & types out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.be\.true/g, 'assert.strictEqual($1, true)') out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.be\.false/g, 'assert.strictEqual($1, false)') + // negative true/false + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.(?:to\.not|not\.to)\.be\.true\b/g, 'assert.notStrictEqual($1, true)') + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.(?:to\.not|not\.to)\.be\.false\b/g, 'assert.notStrictEqual($1, false)') + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.be\.not\.true\b/g, 'assert.notStrictEqual($1, true)') + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.be\.not\.false\b/g, 'assert.notStrictEqual($1, false)') + // with message argument: .to.be.true(msg) / .to.be.false(msg) + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.be\.true\([^)]*\)/g, 'assert.strictEqual($1, true)') + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.be\.false\([^)]*\)/g, 'assert.strictEqual($1, false)') out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.be\.ok/g, 'assert.ok($1)') + // negative ok + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.(?:to\.not|not\.to)\.be\.ok\b/g, 'assert.ok(!$1)') + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.be\.not\.ok\b/g, 'assert.ok(!$1)') // .to.not.undefined (property form) out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.not\.undefined\b/g, 'assert.notStrictEqual($1, undefined)') out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.be\.undefined/g, 'assert.strictEqual($1, undefined)') + // with message: .to.be.undefined(msg) + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.be\.undefined\([^)]*\)/g, 'assert.strictEqual($1, undefined)') out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.be\.null/g, 'assert.strictEqual($1, null)') + // with message: .to.be.null(msg) + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.be\.null\([^)]*\)/g, 'assert.strictEqual($1, null)') // negatives: to.not / not.to out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.(?:to\.not|not\.to)\.be\.undefined/g, 'assert.notStrictEqual($1, undefined)') out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.(?:to\.not|not\.to)\.be\.null/g, 'assert.notStrictEqual($1, null)') + // tolerant 'to.be.not.null/undefined' + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.be\.not\.null\b/g, 'assert.notStrictEqual($1, null)') + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.be\.not\.undefined\b/g, 'assert.notStrictEqual($1, undefined)') out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.exist/g, 'assert.ok($1 != null)') out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.not\.exist/g, 'assert.ok($1 == null)') + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.not\.to\.exist/g, 'assert.ok($1 == null)') + // with message: .to.exist(msg) / .to.not.exist(msg) / .not.to.exist(msg) + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.exist\([^)]*\)/g, 'assert.ok($1 != null)') + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.not\.exist\([^)]*\)/g, 'assert.ok($1 == null)') + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.not\.to\.exist\([^)]*\)/g, 'assert.ok($1 == null)') + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.not\.to\.exist/g, 'assert.ok($1 == null)') out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.be\.(?:an|a)\(['"]array['"]\)/g, 'assert.ok(Array.isArray($1))') out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.be\.(?:an|a)\(['"]object['"]\)/g, "assert.ok(typeof $1 === 'object' && $1 !== null)") out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.be\.(?:an|a)\(['"]string['"]\)/g, "assert.strictEqual(typeof $1, 'string')") @@ -481,6 +539,9 @@ function transform (code, file) { out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.be\.(?:an|a)\(['"]boolean['"]\)/g, "assert.strictEqual(typeof $1, 'boolean')") out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.be\.(?:an|a)\(['"]bigint['"]\)/g, "assert.strictEqual(typeof $1, 'bigint')") out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.be\.(?:an|a)\(['"]function['"]\)/g, "assert.strictEqual(typeof $1, 'function')") + // 'promise' and 'error' types + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.be\.(?:an|a)\(['"]promise['"]\)/g, "assert.ok($1 && typeof $1.then === 'function')") + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.be\.(?:an|a)\(['"]error['"]\)/g, 'assert.ok($1 instanceof Error)') out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.be\.(?:an|a)\(['"]array['"]\)\.and\.have\.length\(([^)]+)\)/g, '(assert.ok(Array.isArray($1)), assert.strictEqual($1.length, $2))') // instanceOf (Array special case first) @@ -488,23 +549,25 @@ function transform (code, file) { out = out.replace(/expect\(([^)]+)\)\.to\.not\.be\.(?:instanceOf|instanceof)\(\s*Array\s*\)/g, 'assert.ok(!Array.isArray($1))') out = out.replace(/expect\(([^)]+)\)\.to\.be\.(?:instanceOf|instanceof)\(([^)]+)\)/g, 'assert.ok($1 instanceof $2)') out = out.replace(/expect\(([^)]+)\)\.to\.not\.be\.(?:instanceOf|instanceof)\(([^)]+)\)/g, 'assert.ok(!($1 instanceof $2))') + // instanceOf with article: .to.be.an.instanceOf(...) + out = out.replace(/expect\(([^)]+)\)\.to\.be\.(?:an|a)\.(?:instanceOf|instanceof)\(([^)]+)\)/g, 'assert.ok($1 instanceof $2)') // 8) Regex - out = out.replace(/expect\(([^)]+)\)\.to\.match\(([^)]+)\)/g, 'assert.match($1, $2)') - out = out.replace(/expect\(([^)]+)\)\.to\.not\.match\(([^)]+)\)/g, 'assert.doesNotMatch($1, $2)') + out = out.replace(/expect\(([^)]+)\)\.to\.match\(((?:[^()]|\([^()]*\))+?)\)/g, 'assert.match($1, $2)') + out = out.replace(/expect\(([^)]+)\)\.to\.not\.match\(((?:[^()]|\([^()]*\))+?)\)/g, 'assert.doesNotMatch($1, $2)') // function-call aware regex - out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.match\(([^)]+)\)/g, 'assert.match($1, $2)') - out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.not\.match\(([^)]+)\)/g, 'assert.doesNotMatch($1, $2)') + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.match\(((?:[^()]|\([^()]*\))+?)\)/g, 'assert.match($1, $2)') + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.not\.match\(((?:[^()]|\([^()]*\))+?)\)/g, 'assert.doesNotMatch($1, $2)') // 8.1) contain/include string literal or .contain alias → assert.match(haystack, escaped(needle)) out = out.replace(/expect\(([^)]+)\)\.to\.(?:contain|include)\(\s*(['"][^'"]+['"])\s*\)/g, - (m, haystack, lit) => `assert.match(${haystack}, ${wrapAsEscapedRegex(lit)})`) + (m, haystack, lit) => `assert.ok(${haystack}.includes(${lit}))`) out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.(?:contain|include)\(\s*(['"][^'"]+['"])\s*\)/g, - (m, haystack, lit) => `assert.match(${haystack}, ${wrapAsEscapedRegex(lit)})`) + (m, haystack, lit) => `assert.ok(${haystack}.includes(${lit}))`) out = out.replace(/expect\(([^)]+)\)\.to\.contain\(\s*(['"][^'"]+['"])\s*\)/g, - (m, haystack, lit) => `assert.match(${haystack}, ${wrapAsEscapedRegex(lit)})`) + (m, haystack, lit) => `assert.ok(${haystack}.includes(${lit}))`) out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.contain\(\s*(['"][^'"]+['"])\s*\)/g, - (m, haystack, lit) => `assert.match(${haystack}, ${wrapAsEscapedRegex(lit)})`) + (m, haystack, lit) => `assert.ok(${haystack}.includes(${lit}))`) // 8.2) include/contain with object literal → assertObjectContains (allowed everywhere) out = out.replace(/expect\(([^)]+)\)\.to\.(?:contain|include)\(\s*(\{[^}]*\})\s*\)/g, 'assertObjectContains($1, $2)') @@ -515,23 +578,41 @@ function transform (code, file) { // 8.3) deep.include with object literal → assertObjectContains out = out.replace(/expect\(([^)]+)\)\.to\.deep\.include\(\s*(\{[^}]*\})\s*\)/g, 'assertObjectContains($1, $2)') out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.deep\.include\(\s*(\{[^}]*\})\s*\)/g, 'assertObjectContains($1, $2)') + // 8.4) include/contain with template literal needles + out = out.replace(/expect\(([^)]+)\)\.to\.(?:contain|include)\(\s*(`[^`]*`)\s*\)/g, + (m, haystack, tpl) => `assert.ok(${haystack}.includes(${tpl}))`) + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.(?:contain|include)\(\s*(`[^`]*`)\s*\)/g, + (m, haystack, tpl) => `assert.ok(${haystack}.includes(${tpl}))`) + // 8.5) generic include/contain with expression needles (strings/arrays) – conservative generic form + out = out.replace(/expect\(([^)]+)\)\.to\.(?:contain|include)\(\s*((?:[^()]|\([^()]*\))+?)\s*\)/g, + 'assert.ok($1.includes($2))') + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.(?:contain|include)\(\s*((?:[^()]|\([^()]*\))+?)\s*\)/g, + 'assert.ok($1.includes($2))') // Skip generic include/contain for safety otherwise // 10) property // expect(obj).to.have.property('k').that.deep.equal(v) → deepStrictEqual(accessor, v) - out = out.replace(/expect\(([^)]+)\)\.to\.have\.property\((['"][^'"]+['"])\)\.that\.deep\.equal\(([^)]+)\)/g, + out = out.replace(/expect\(([^)]+)\)\.to\.have\.property\((['"][^'"]+['"])\)\.that\.deep\.equal\(((?:[^()]|\([^()]*\))+?)\)/g, (m, obj, key, val) => `assert.deepStrictEqual(${buildAccessor(obj, key)}, ${val})`) - out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.have\.property\((['"][^'"]+['"])\)\.that\.deep\.equal\(([^)]+)\)/g, + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.have\.property\((['"][^'"]+['"])\)\.that\.deep\.equal\(((?:[^()]|\([^()]*\))+?)\)/g, (m, obj, key, val) => `assert.deepStrictEqual(${buildAccessor(obj, key)}, ${val})`) // expect(obj).to.have.property('k').that.equal(v) → strictEqual(accessor, v) - out = out.replace(/expect\(([^)]+)\)\.to\.have\.property\((['"][^'"]+['"])\)\.that\.equal\(([^)]+)\)/g, + out = out.replace(/expect\(([^)]+)\)\.to\.have\.property\((['"][^'"]+['"])\)\.that\.equal\(((?:[^()]|\([^()]*\))+?)\)/g, (m, obj, key, val) => `assert.strictEqual(${buildAccessor(obj, key)}, ${val})`) - out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.have\.property\((['"][^'"]+['"])\)\.that\.equal\(([^)]+)\)/g, + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.have\.property\((['"][^'"]+['"])\)\.that\.equal\(((?:[^()]|\([^()]*\))+?)\)/g, (m, obj, key, val) => `assert.strictEqual(${buildAccessor(obj, key)}, ${val})`) // expect(obj).to.have.property('k').that.match(/re/) → match(accessor, /re/) - out = out.replace(/expect\(([^)]+)\)\.to\.have\.property\((['"][^'"]+['"])\)\.that\.match\(([^)]+)\)/g, + out = out.replace(/expect\(([^)]+)\)\.to\.have\.property\((['"][^'"]+['"])\)\.that\.match\(((?:[^()]|\([^()]*\))+?)\)/g, (m, obj, key, re) => `assert.match(${buildAccessor(obj, key)}, ${re})`) - out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.have\.property\((['"][^'"]+['"])\)\.that\.match\(([^)]+)\)/g, + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.have\.property\((['"][^'"]+['"])\)\.that\.match\(((?:[^()]|\([^()]*\))+?)\)/g, + (m, obj, key, re) => `assert.match(${buildAccessor(obj, key)}, ${re})`) + // Multi-line tolerant and chain-filler tolerant variants for property('k') chains: + // allow (that|which|and|with|to|be|have) between links, and tolerate newlines/whitespace + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\s*\.\s*to\s*\.\s*have\s*\.\s*property\(\s*(['"][^'"]+['"])\s*\)(?:\s*\.\s*(?:that|which|and|with|to|be|have)\s*)*\.\s*deep\s*\.\s*(?:equal|eql)\(([^)]+)\)/gs, + (m, obj, key, val) => `assert.deepStrictEqual(${buildAccessor(obj, key)}, ${val})`) + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\s*\.\s*to\s*\.\s*have\s*\.\s*property\(\s*(['"][^'"]+['"])\s*\)(?:\s*\.\s*(?:that|which|and|with|to|be|have)\s*)*\.\s*(?:equal|equals)\(([^)]+)\)/gs, + (m, obj, key, val) => `assert.strictEqual(${buildAccessor(obj, key)}, ${val})`) + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\s*\.\s*to\s*\.\s*have\s*\.\s*property\(\s*(['"][^'"]+['"])\s*\)(?:\s*\.\s*(?:that|which|and|with|to|be|have)\s*)*\.\s*match\(([^)]+)\)/gs, (m, obj, key, re) => `assert.match(${buildAccessor(obj, key)}, ${re})`) // // Handle leftover chains after hasOwn conversion // out = out.replace(/assert\.ok\(Object\.hasOwn\(([^,]+),\s*(['"][^'"]+['"])\)\)\.that\.deep\.equal\(([^)]+)\)/g, @@ -541,11 +622,25 @@ function transform (code, file) { // out = out.replace(/assert\.ok\(Object\.hasOwn\(([^,]+),\s*(['"][^'"]+['"])\)\)\.that\.match\(([^)]+)\)/g, // (m, obj, key, re) => `assert.match(${buildAccessor(obj, key)}, ${re})`) // expect(obj).to.have.property('k', v) → assert.strictEqual(accessor, v) - out = out.replace(/expect\(([^)]+)\)\.to\.have\.property\((['"][^'"]+['"]),\s*([^)]+)\)/g, + out = out.replace(/expect\(([^)]+)\)\.to\.have\.property\((['"][^'"]+['"]),\s*((?:[^()]|\([^()]*\))+?)\)/g, (m, obj, key, val) => `assert.strictEqual(${buildAccessor(obj, key)}, ${val})`) + // expect(obj).to.not.have.property('k', v) → assert.notStrictEqual(accessor, v) + out = out.replace(/expect\(([^)]+)\)\.to\.not\.have\.property\(\s*(['"][^'"]+['"])\s*,\s*([^)]+)\)/g, + (m, obj, key, val) => `assert.notStrictEqual(${buildAccessor(obj, key)}, ${val})`) + out = out.replace(/expect\(([^)]+)\)\.not\.to\.have\.property\(\s*(['"][^'"]+['"])\s*,\s*([^)]+)\)/g, + (m, obj, key, val) => `assert.notStrictEqual(${buildAccessor(obj, key)}, ${val})`) // variable key: expect(obj).to.have.property(KEY, v) - out = out.replace(/expect\(([^)]+)\)\.to\.have\.property\(([^,'")]+),\s*([^)]+)\)/g, 'assert.strictEqual($1[$2], $3)') - out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.have\.property\(([^,'")]+),\s*([^)]+)\)/g, 'assert.strictEqual($1[$2], $3)') + out = out.replace(/expect\(([^)]+)\)\.to\.have\.property\(([^,'")]+),\s*((?:[^()]|\([^()]*\))+?)\)/g, 'assert.strictEqual($1[$2], $3)') + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.have\.property\(([^,'")]+),\s*((?:[^()]|\([^()]*\))+?)\)/g, 'assert.strictEqual($1[$2], $3)') + // variable key negative: expect(obj).to.not.have.property(KEY, v) + out = out.replace(/expect\(([^)]+)\)\.to\.not\.have\.property\(([^,'")]+),\s*([^)]+)\)/g, 'assert.notStrictEqual($1[$2], $3)') + out = out.replace(/expect\(([^)]+)\)\.not\.to\.have\.property\(([^,'")]+),\s*([^)]+)\)/g, 'assert.notStrictEqual($1[$2], $3)') + // negative two-arg: expect(obj).to.not.have.property('k', v) + out = out.replace(/expect\(([^)]+)\)\.(?:to\.not|not\.to)\.have\.property\(\s*(['"][^'"]+['"])\s*,\s*([^)]+)\)/g, + (m, obj, key, val) => `assert.ok(!Object.hasOwn(${obj}, ${key}) || ${buildAccessor(obj, key)} !== ${val})`) + // negative two-arg with variable key + out = out.replace(/expect\(([^)]+)\)\.(?:to\.not|not\.to)\.have\.property\(\s*([^,'")]+)\s*,\s*([^)]+)\)/g, + 'assert.ok(!Object.hasOwn($1, $2) || $1[$2] !== $3)') // expect(obj).to.have.property('k') → assert.ok(Object.hasOwn(obj, 'k')) (preserve key quoting rules) out = out.replace(/expect\(([^)]+)\)\.to\.have\.property\(([^,)]+)\)/g, 'assert.ok(Object.hasOwn($1, $2))') @@ -570,6 +665,9 @@ function transform (code, file) { 'assert.strictEqual($1.length, $2)') out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.(?:have\.)?lengthOf\(([^)]+)\)/g, 'assert.strictEqual($1.length, $2)') + // bare .lengthOf(n) + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.lengthOf\(([^)]+)\)/g, + 'assert.strictEqual($1.length, $2)') // length alias (chai): .length(n) out = out.replace(/expect\(([^)]+)\)\.to\.(?:have\.)?length\(([^)]+)\)/g, 'assert.strictEqual($1.length, $2)') @@ -588,9 +686,203 @@ function transform (code, file) { // property(...).that.length(Of)?(n) out = out.replace(/expect\(([^)]+)\)\.to\.have\.property\((['"][^'"]+['"])\)\.that\.(?:have\.)?length(?:Of)?\(([^)]+)\)/g, (m, obj, key, val) => `assert.strictEqual(${buildAccessor(obj, key)}.length, ${val})`) + // property(...).with.length(Of)?(n) + out = out.replace(/expect\(([^)]+)\)\.to\.have\.property\((['"][^'"]+['"])\)\.with\.(?:have\.)?length(?:Of)?\(([^)]+)\)/g, + (m, obj, key, val) => `assert.strictEqual(${buildAccessor(obj, key)}.length, ${val})`) + // property(...).(that|which|and|with|to|be|have)*.with.length(Of)?(n) – tolerant + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\s*\.\s*to\s*\.\s*have\s*\.\s*property\(\s*(['"][^'"]+['"])\s*\)(?:\s*\.\s*(?:that|which|and|with|to|be|have)\s*)*\.\s*with\s*\.\s*(?:have\s*\.\s*)?length(?:Of)?\(([^)]+)\)/gs, + (m, obj, key, val) => `assert.strictEqual(${buildAccessor(obj, key)}.length, ${val})`) + + // Nested property: presence/value/deep.equal (string literal path only) + out = out.replace(/expect\(([^)]+)\)\.to\.have\.nested\.property\(\s*(['"][^'"]+['"])\s*\)/g, + (m, obj, path) => { + const acc = buildNestedAccessor(obj, path) + return acc ? `assert.ok(${acc} !== undefined)` : m + }) + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.have\.nested\.property\(\s*(['"][^'"]+['"])\s*\)/g, + (m, obj, path) => { + const acc = buildNestedAccessor(obj, path) + return acc ? `assert.ok(${acc} !== undefined)` : m + }) + out = out.replace(/expect\(([^)]+)\)\.to\.have\.nested\.property\(\s*(['"][^'"]+['"])\s*,\s*([^)]+)\)/g, + (m, obj, path, val) => { + const acc = buildNestedAccessor(obj, path) + return acc ? `assert.strictEqual(${acc}, ${val})` : m + }) + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.have\.nested\.property\(\s*(['"][^'"]+['"])\s*,\s*([^)]+)\)/g, + (m, obj, path, val) => { + const acc = buildNestedAccessor(obj, path) + return acc ? `assert.strictEqual(${acc}, ${val})` : m + }) + out = out.replace(/expect\(([^)]+)\)\.to\.have\.nested\.property\(\s*(['"][^'"]+['"])\s*\)\.that\.deep\.equal\(([^)]+)\)/g, + (m, obj, path, val) => { + const acc = buildNestedAccessor(obj, path) + return acc ? `assert.deepStrictEqual(${acc}, ${val})` : m + }) + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.have\.nested\.property\(\s*(['"][^'"]+['"])\s*\)\.that\.deep\.equal\(([^)]+)\)/g, + (m, obj, path, val) => { + const acc = buildNestedAccessor(obj, path) + return acc ? `assert.deepStrictEqual(${acc}, ${val})` : m + }) + + // 15.51) expect(...).to.have.nested.deep.property(...) – treat like nested.property for string literal paths + out = out.replace(/expect\(([^)]+)\)\.to\.have\.nested\.deep\.property\(\s*(['"][^'"]+['"])\s*\)/g, + (m, obj, path) => { + const acc = buildNestedAccessor(obj, path) + return acc ? `assert.ok(${acc} !== undefined)` : m + }) + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.have\.nested\.deep\.property\(\s*(['"][^'"]+['"])\s*\)/g, + (m, obj, path) => { + const acc = buildNestedAccessor(obj, path) + return acc ? `assert.ok(${acc} !== undefined)` : m + }) + out = out.replace(/expect\(([^)]+)\)\.to\.have\.nested\.deep\.property\(\s*(['"][^'"]+['"])\s*,\s*([^)]+)\)/g, + (m, obj, path, val) => { + const acc = buildNestedAccessor(obj, path) + return acc ? `assert.strictEqual(${acc}, ${val})` : m + }) + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.have\.nested\.deep\.property\(\s*(['"][^'"]+['"])\s*,\s*([^)]+)\)/g, + (m, obj, path, val) => { + const acc = buildNestedAccessor(obj, path) + return acc ? `assert.strictEqual(${acc}, ${val})` : m + }) + out = out.replace(/expect\(([^)]+)\)\.to\.have\.nested\.deep\.property\(\s*(['"][^'"]+['"])\s*\)\.that\.deep\.equal\(([^)]+)\)/g, + (m, obj, path, val) => { + const acc = buildNestedAccessor(obj, path) + return acc ? `assert.deepStrictEqual(${acc}, ${val})` : m + }) + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.have\.nested\.deep\.property\(\s*(['"][^'"]+['"])\s*\)\.that\.deep\.equal\(([^)]+)\)/g, + (m, obj, path, val) => { + const acc = buildNestedAccessor(obj, path) + return acc ? `assert.deepStrictEqual(${acc}, ${val})` : m + }) + + // deep.property(...) – string literal paths + out = out.replace(/expect\(([^)]+)\)\.to\.have\.deep\.property\(\s*(['"][^'"]+['"])\s*\)/g, + (m, obj, path) => { + const acc = buildNestedAccessor(obj, path) + return acc ? `assert.ok(${acc} !== undefined)` : m + }) + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.have\.deep\.property\(\s*(['"][^'"]+['"])\s*\)/g, + (m, obj, path) => { + const acc = buildNestedAccessor(obj, path) + return acc ? `assert.ok(${acc} !== undefined)` : m + }) + out = out.replace(/expect\(([^)]+)\)\.to\.have\.deep\.property\(\s*(['"][^'"]+['"])\s*,\s*((?:[^()]|\([^()]*\))+?)\)/g, + (m, obj, path, val) => { + const acc = buildNestedAccessor(obj, path) + return acc ? `assert.deepStrictEqual(${acc}, ${val})` : m + }) + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.have\.deep\.property\(\s*(['"][^'"]+['"])\s*,\s*((?:[^()]|\([^()]*\))+?)\)/g, + (m, obj, path, val) => { + const acc = buildNestedAccessor(obj, path) + return acc ? `assert.deepStrictEqual(${acc}, ${val})` : m + }) + out = out.replace(/expect\(([^)]+)\)\.to\.have\.deep\.property\(\s*(['"][^'"]+['"])\s*\)\.that\.deep\.equal\(([^)]+)\)/g, + (m, obj, path, val) => { + const acc = buildNestedAccessor(obj, path) + return acc ? `assert.deepStrictEqual(${acc}, ${val})` : m + }) + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.have\.deep\.property\(\s*(['"][^'"]+['"])\s*\)\.that\.deep\.equal\(([^)]+)\)/g, + (m, obj, path, val) => { + const acc = buildNestedAccessor(obj, path) + return acc ? `assert.deepStrictEqual(${acc}, ${val})` : m + }) + // Keys / all.keys + out = out.replace( + /expect\(([^)]+)\)\.to\.have\.(?:all\.)?keys\(([^)]+)\)/g, + (m, obj, args) => ( + 'assert.deepStrictEqual(' + + 'Object.keys(' + obj + ').slice().sort(), ' + + '((Array.isArray(' + args + ') ? ' + args + ' : [' + args + ']).slice().sort()))' + ) + ) + out = out.replace( + /expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.have\.(?:all\.)?keys\(([^)]+)\)/g, + (m, obj, args) => ( + 'assert.deepStrictEqual(' + + 'Object.keys(' + obj + ').slice().sort(), ' + + '((Array.isArray(' + args + ') ? ' + args + ' : [' + args + ']).slice().sort()))' + ) + ) + // any.keys (at least one key present) + out = out.replace( + /expect\(([^)]+)\)\.to\.have\.any\.keys\(([^)]+)\)/g, + (m, obj, args) => + 'assert.ok(((Array.isArray(' + args + ') ? ' + args + ' : [' + args + ']))' + + '.some(k => Object.hasOwn(' + obj + ', k)))' + ) + out = out.replace( + /expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.have\.any\.keys\(([^)]+)\)/g, + (m, obj, args) => + 'assert.ok(((Array.isArray(' + args + ') ? ' + args + ' : [' + args + ']))' + + '.some(k => Object.hasOwn(' + obj + ', k)))' + ) + // negative any.keys (none of keys present) + out = out.replace( + /expect\(([^)]+)\)\.(?:to\.not|not\.to)\.have\.any\.keys\(([^)]+)\)/g, + (m, obj, args) => + 'assert.ok(!((Array.isArray(' + args + ') ? ' + args + ' : [' + args + ']))' + + '.some(k => Object.hasOwn(' + obj + ', k)))' + ) + out = out.replace( + /expect\(((?:[^()]|\([^()]*\))+?)\)\.(?:to\.not|not\.to)\.have\.any\.keys\(([^)]+)\)/g, + (m, obj, args) => + 'assert.ok(!((Array.isArray(' + args + ') ? ' + args + ' : [' + args + ']))' + + '.some(k => Object.hasOwn(' + obj + ', k)))' + ) + + // include.members / have.members + out = out.replace( + /expect\(([^)]+)\)\.to\.(?:include|have)\.members\(([^)]+)\)/g, + (m, obj, args) => ( + 'assert.ok(((Array.isArray(' + args + ') ? ' + args + ' : [' + args + ']))' + + '.every(v => ' + obj + '.includes(v)))' + ) + ) + out = out.replace( + /expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.(?:include|have)\.members\(([^)]+)\)/g, + (m, obj, args) => ( + 'assert.ok(((Array.isArray(' + args + ') ? ' + args + ' : [' + args + ']))' + + '.every(v => ' + obj + '.includes(v)))' + ) + ) + out = out.replace( + /expect\(([^)]+)\)\.(?:to\.not|not\.to)\.include\.members\(([^)]+)\)/g, + (m, obj, args) => ( + 'assert.ok(!((Array.isArray(' + args + ') ? ' + args + ' : [' + args + ']))' + + '.every(v => ' + obj + '.includes(v)))' + ) + ) + out = out.replace( + /expect\(((?:[^()]|\([^()]*\))+?)\)\.(?:to\.not|not\.to)\.include\.members\(([^)]+)\)/g, + (m, obj, args) => ( + 'assert.ok(!((Array.isArray(' + args + ') ? ' + args + ' : [' + args + ']))' + + '.every(v => ' + obj + '.includes(v)))' + ) + ) + out = out.replace( + /expect\(([^)]+)\)\.to\.have\.members\(([^)]+)\)/g, + (m, obj, args) => ( + 'assert.deepStrictEqual(([...' + obj + ']).slice().sort(), ' + + '((Array.isArray(' + args + ') ? ' + args + ' : [' + args + ']).slice().sort()))' + ) + ) + out = out.replace( + /expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.have\.members\(([^)]+)\)/g, + (m, obj, args) => ( + 'assert.deepStrictEqual(([...' + obj + ']).slice().sort(), ' + + '((Array.isArray(' + args + ') ? ' + args + ' : [' + args + ']).slice().sort()))' + ) + ) + + // Empty / Not empty + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.be\.empty\b/g, 'assert.strictEqual($1.length, 0)') + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.(?:to\.not|not\.to)\.be\.empty\b/g, 'assert.ok($1.length > 0)') // 12) Comparisons out = out.replace(/expect\(([^)]+)\)\.to\.be\.above\(([^)]+)\)/g, 'assert.ok($1 > $2)') + out = out.replace(/expect\(([^)]+)\)\.to\.above\(([^)]+)\)/g, 'assert.ok($1 > $2)') out = out.replace(/expect\(([^)]+)\)\.to\.be\.at\.least\(([^)]+)\)/g, 'assert.ok($1 >= $2)') out = out.replace(/expect\(([^)]+)\)\.to\.be\.below\(([^)]+)\)/g, 'assert.ok($1 < $2)') out = out.replace(/expect\(([^)]+)\)\.to\.be\.at\.most\(([^)]+)\)/g, 'assert.ok($1 <= $2)') @@ -602,8 +894,17 @@ function transform (code, file) { out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.be\.(?:gte)\(([^)]+)\)/g, 'assert.ok($1 >= $2)') out = out.replace(/expect\(([^)]+)\)\.to\.be\.(?:lte)\(([^)]+)\)/g, 'assert.ok($1 <= $2)') out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\.to\.be\.(?:lte)\(([^)]+)\)/g, 'assert.ok($1 <= $2)') + // greaterThanOrEqual / lessThanOrEqual + out = out.replace(/expect\(([^)]+)\)\.to\.be\.greaterThanOrEqual\(([^)]+)\)/g, 'assert.ok($1 >= $2)') + out = out.replace(/expect\(([^)]+)\)\.to\.be\.lessThanOrEqual\(([^)]+)\)/g, 'assert.ok($1 <= $2)') out = out.replace(/expect\(([^)]+)\)\.to\.be\.closeTo\(([^,]+),\s*([^)]+)\)/g, 'assert.ok(Math.abs(($1) - ($2)) <= ($3))') + // within + out = out.replace(/expect\(([^)]+)\)\.to\.be\.within\(([^,]+),\s*([^)]+)\)/g, + 'assert.ok(($1) >= ($2) && ($1) <= ($3))') + // oneOf + out = out.replace(/expect\(([^)]+)\)\.to\.be\.oneOf\(\s*(\[[^\]]*\])\s*\)/g, + 'assert.ok($2.includes($1))') // 12) Throws out = out.replace(/expect\(([^)]+)\)\.to\.throw\(\s*\)/g, 'assert.throws($1)') @@ -629,6 +930,8 @@ function transform (code, file) { out = out.replace(/expect\(([^)]+)\)\.(?:to\.not|not\.to)\.have\.been\.called\b/g, 'sinon.assert.notCalled($1)') // also support: to.be.called out = out.replace(/expect\(([^)]+)\)\.to\.be\.called\b/g, 'sinon.assert.called($1)') + // negative to.be.called + out = out.replace(/expect\(([^)]+)\)\.(?:to\.not|not\.to)\.be\.called\b/g, 'sinon.assert.notCalled($1)') out = out.replace(/expect\(([^)]+)\)\.to\.have\.been\.calledWithExactly\(([^)]+)\)/g, 'sinon.assert.calledWithExactly($1, $2)') out = out.replace(/expect\(([^)]+)\)\.to\.have\.been\.calledWithMatch\(([^)]+)\)/g, @@ -645,12 +948,101 @@ function transform (code, file) { // negative calledWith variants out = out.replace(/expect\(([^)]+)\)\.to\.not\.have\.been\.calledWith\(([^)]+)\)/g, 'sinon.assert.neverCalledWith($1, $2)') out = out.replace(/expect\(([^)]+)\)\.not\.to\.have\.been\.calledWith\(([^)]+)\)/g, 'sinon.assert.neverCalledWith($1, $2)') + out = out.replace(/expect\(([^)]+)\)\.to\.have\.not\.been\.calledWith\(([^)]+)\)/g, 'sinon.assert.neverCalledWith($1, $2)') out = out.replace(/expect\(([^)]+)\)\.to\.not\.have\.been\.calledWithMatch\(([^)]+)\)/g, 'sinon.assert.neverCalledWithMatch($1, $2)') out = out.replace(/expect\(([^)]+)\)\.not\.to\.have\.been\.calledWithMatch\(([^)]+)\)/g, 'sinon.assert.neverCalledWithMatch($1, $2)') - // 15) chai.assert style minimal mapping + // 15) chai.assert and chai { assert } helper mappings + // chai.assert.* direct calls out = out.replace(/chai\.assert\.deepEqual\(([^)]+)\)/g, 'assert.deepStrictEqual($1)') out = out.replace(/chai\.assert\.equal\(([^)]+)\)/g, 'assert.strictEqual($1)') + // Equality + out = out.replace(/\bassert\.equal\(\s*((?:[^()]|\([^()]*\))+?)\s*,\s*((?:[^()]|\([^()]*\))+?)\s*\)/g, 'assert.strictEqual($1, $2)') + out = out.replace(/\bassert\.notEqual\(\s*((?:[^()]|\([^()]*\))+?)\s*,\s*((?:[^()]|\([^()]*\))+?)\s*\)/g, 'assert.notStrictEqual($1, $2)') + out = out.replace(/\bassert\.deepEqual\(\s*((?:[^()]|\([^()]*\))+?)\s*,\s*((?:[^()]|\([^()]*\))+?)\s*\)/g, 'assert.deepStrictEqual($1, $2)') + out = out.replace(/\bassert\.notDeepEqual\(\s*((?:[^()]|\([^()]*\))+?)\s*,\s*((?:[^()]|\([^()]*\))+?)\s*\)/g, 'assert.notDeepStrictEqual($1, $2)') + // Truthiness and types + out = out.replace(/\bassert\.isTrue\(\s*((?:[^()]|\([^()]*\))+?)\s*\)/g, 'assert.strictEqual($1, true)') + out = out.replace(/\bassert\.isFalse\(\s*((?:[^()]|\([^()]*\))+?)\s*\)/g, 'assert.strictEqual($1, false)') + out = out.replace(/\bassert\.isOk\(\s*((?:[^()]|\([^()]*\))+?)\s*\)/g, 'assert.ok($1)') + out = out.replace(/\bassert\.isNotOk\(\s*((?:[^()]|\([^()]*\))+?)\s*\)/g, 'assert.ok(!$1)') + out = out.replace(/\bassert\.isUndefined\(\s*((?:[^()]|\([^()]*\))+?)\s*\)/g, 'assert.strictEqual($1, undefined)') + out = out.replace(/\bassert\.isDefined\(\s*((?:[^()]|\([^()]*\))+?)\s*\)/g, 'assert.notStrictEqual($1, undefined)') + out = out.replace(/\bassert\.isNull\(\s*((?:[^()]|\([^()]*\))+?)\s*\)/g, 'assert.strictEqual($1, null)') + out = out.replace(/\bassert\.isNotNull\(\s*((?:[^()]|\([^()]*\))+?)\s*\)/g, 'assert.notStrictEqual($1, null)') + out = out.replace(/\bassert\.isArray\(\s*((?:[^()]|\([^()]*\))+?)\s*\)/g, 'assert.ok(Array.isArray($1))') + out = out.replace(/\bassert\.isObject\(\s*((?:[^()]|\([^()]*\))+?)\s*\)/g, "assert.ok(typeof $1 === 'object' && $1 !== null)") + out = out.replace(/\bassert\.isString\(\s*((?:[^()]|\([^()]*\))+?)\s*\)/g, "assert.strictEqual(typeof $1, 'string')") + out = out.replace(/\bassert\.isNumber\(\s*((?:[^()]|\([^()]*\))+?)\s*\)/g, "assert.strictEqual(typeof $1, 'number')") + out = out.replace(/\bassert\.isBoolean\(\s*((?:[^()]|\([^()]*\))+?)\s*\)/g, "assert.strictEqual(typeof $1, 'boolean')") + out = out.replace(/\bassert\.isBigInt\(\s*((?:[^()]|\([^()]*\))+?)\s*\)/g, "assert.strictEqual(typeof $1, 'bigint')") + out = out.replace(/\bassert\.isFunction\(\s*((?:[^()]|\([^()]*\))+?)\s*\)/g, "assert.strictEqual(typeof $1, 'function')") + // exists / notExists + out = out.replace(/\bassert\.exists\(\s*((?:[^()]|\([^()]*\))+?)\s*(?:,\s*[^)]*)?\)/g, 'assert.ok($1 != null)') + out = out.replace(/\bassert\.notExists\(\s*((?:[^()]|\([^()]*\))+?)\s*(?:,\s*[^)]*)?\)/g, 'assert.ok($1 == null)') + // typeOf with special handling for 'array' + out = out.replace(/\bassert\.typeOf\(\s*((?:[^()]|\([^()]*\))+?)\s*,\s*(['"][^'"]+['"])\s*(?:,\s*[^)]*)?\)/g, + (m, value, typeLit) => { + return (typeLit === "'array'" || typeLit === '"array"') + ? 'assert.ok(Array.isArray(' + value + '))' + : 'assert.strictEqual(typeof ' + value + ', ' + typeLit + ')' + }) + // hasAllKeys (exact key set equality) + out = out.replace(/\bassert\.hasAllKeys\(\s*((?:[^()]|\([^()]*\))+?)\s*,\s*((?:[^()]|\([^()]*\))+?)\s*(?:,\s*[^)]*)?\)/g, + (m, obj, keys) => ( + 'assert.deepStrictEqual(' + + 'Object.keys(' + obj + ').slice().sort(), ' + + '((Array.isArray(' + keys + ') ? ' + keys + ' : [' + keys + ']).slice().sort()))' + )) + // numeric comparisons (below/above/atLeast/atMost) + out = out.replace(/\bassert\.isBelow\(\s*((?:[^()]|\([^()]*\))+?)\s*,\s*((?:[^()]|\([^()]*\))+?)\s*(?:,\s*[^)]*)?\)/g, 'assert.ok($1 < $2)') + out = out.replace(/\bassert\.isAbove\(\s*((?:[^()]|\([^()]*\))+?)\s*,\s*((?:[^()]|\([^()]*\))+?)\s*(?:,\s*[^)]*)?\)/g, 'assert.ok($1 > $2)') + out = out.replace(/\bassert\.isAtLeast\(\s*((?:[^()]|\([^()]*\))+?)\s*,\s*((?:[^()]|\([^()]*\))+?)\s*(?:,\s*[^)]*)?\)/g, 'assert.ok($1 >= $2)') + out = out.replace(/\bassert\.isAtMost\(\s*((?:[^()]|\([^()]*\))+?)\s*,\s*((?:[^()]|\([^()]*\))+?)\s*(?:,\s*[^)]*)?\)/g, 'assert.ok($1 <= $2)') + // synonyms without "is" + out = out.replace(/\bassert\.below\(\s*((?:[^()]|\([^()]*\))+?)\s*,\s*((?:[^()]|\([^()]*\))+?)\s*(?:,\s*[^)]*)?\)/g, 'assert.ok($1 < $2)') + out = out.replace(/\bassert\.above\(\s*((?:[^()]|\([^()]*\))+?)\s*,\s*((?:[^()]|\([^()]*\))+?)\s*(?:,\s*[^)]*)?\)/g, 'assert.ok($1 > $2)') + out = out.replace(/\bassert\.atLeast\(\s*((?:[^()]|\([^()]*\))+?)\s*,\s*((?:[^()]|\([^()]*\))+?)\s*(?:,\s*[^)]*)?\)/g, 'assert.ok($1 >= $2)') + out = out.replace(/\bassert\.atMost\(\s*((?:[^()]|\([^()]*\))+?)\s*,\s*((?:[^()]|\([^()]*\))+?)\s*(?:,\s*[^)]*)?\)/g, 'assert.ok($1 <= $2)') + // instanceOf (and common misspelling istanceOf) + out = out.replace(/\bassert\.instanceOf\(\s*((?:[^()]|\([^()]*\))+?)\s*,\s*((?:[^()]|\([^()]*\))+?)\s*(?:,\s*[^)]*)?\)/g, 'assert.ok($1 instanceof $2)') + out = out.replace(/\bassert\.notInstanceOf\(\s*((?:[^()]|\([^()]*\))+?)\s*,\s*((?:[^()]|\([^()]*\))+?)\s*(?:,\s*[^)]*)?\)/g, 'assert.ok(!($1 instanceof $2))') + out = out.replace(/\bassert\.istanceOf\(\s*((?:[^()]|\([^()]*\))+?)\s*,\s*((?:[^()]|\([^()]*\))+?)\s*(?:,\s*[^)]*)?\)/g, 'assert.ok($1 instanceof $2)') + // InstanceOf + out = out.replace(/\bassert\.instanceOf\(\s*((?:[^()]|\([^()]*\))+?)\s*,\s*((?:[^()]|\([^()]*\))+?)\s*(?:,\s*[^)]*)?\)/g, 'assert.ok($1 instanceof $2)') + out = out.replace(/\bassert\.notInstanceOf\(\s*((?:[^()]|\([^()]*\))+?)\s*,\s*((?:[^()]|\([^()]*\))+?)\s*(?:,\s*[^)]*)?\)/g, 'assert.ok(!($1 instanceof $2))') + // Length helpers + out = out.replace(/\bassert\.lengthOf\(\s*((?:[^()]|\([^()]*\))+?)\s*,\s*((?:[^()]|\([^()]*\))+?)\s*\)/g, 'assert.strictEqual($1.length, $2)') + out = out.replace(/\bassert\.notLengthOf\(\s*((?:[^()]|\([^()]*\))+?)\s*,\s*((?:[^()]|\([^()]*\))+?)\s*\)/g, 'assert.notStrictEqual($1.length, $2)') + // Property helpers + out = out.replace(/\bassert\.property\(\s*((?:[^()]|\([^()]*\))+?)\s*,\s*((?:[^()]|\([^()]*\))+?)\s*(?:,[^)]+)?\)/g, 'assert.ok(Object.hasOwn($1, $2))') + out = out.replace(/\bassert\.notProperty\(\s*((?:[^()]|\([^()]*\))+?)\s*,\s*((?:[^()]|\([^()]*\))+?)\s*(?:,[^)]+)?\)/g, 'assert.ok(!Object.hasOwn($1, $2))') + out = out.replace(/\bassert\.propertyVal\(\s*((?:[^()]|\([^()]*\))+?)\s*,\s*((?:[^()]|\([^()]*\))+?)\s*,\s*((?:[^()]|\([^()]*\))+?)\s*\)/g, 'assert.strictEqual($1[$2], $3)') + out = out.replace(/\bassert\.notPropertyVal\(\s*((?:[^()]|\([^()]*\))+?)\s*,\s*((?:[^()]|\([^()]*\))+?)\s*,\s*((?:[^()]|\([^()]*\))+?)\s*\)/g, 'assert.notStrictEqual($1[$2], $3)') + // Include helpers (string/array) + out = out.replace(/\bassert\.include\(\s*((?:[^()]|\([^()]*\))+?)\s*,\s*((?:[^()]|\([^()]*\))+?)\s*\)/g, 'assert.ok($1.includes($2))') + out = out.replace(/\bassert\.notInclude\(\s*((?:[^()]|\([^()]*\))+?)\s*,\s*((?:[^()]|\([^()]*\))+?)\s*\)/g, 'assert.ok(!$1.includes($2))') + // sameMembers (order-insensitive shallow) + out = out.replace(/\bassert\.sameMembers\(\s*((?:[^()]|\([^()]*\))+?)\s*,\s*((?:[^()]|\([^()]*\))+?)\s*(?:,\s*[^)]*)?\)/g, + (m, arr, expected) => ( + 'assert.deepStrictEqual(([...' + arr + ']).slice().sort(), ' + + '((Array.isArray(' + expected + ') ? ' + expected + ' : [' + expected + ']).slice().sort()))' + )) + // sameDeepMembers (order-insensitive deep) via stable JSON string sort + out = out.replace(/\bassert\.sameDeepMembers\(\s*((?:[^()]|\([^()]*\))+?)\s*,\s*((?:[^()]|\([^()]*\))+?)\s*(?:,\s*[^)]*)?\)/g, + (m, arr, expected) => ( + 'assert.deepStrictEqual(' + + '([... ' + arr + ']).slice().sort((a, b) => JSON.stringify(a).localeCompare(JSON.stringify(b))), ' + + '((Array.isArray(' + expected + ') ? ' + expected + ' : [' + expected + ']).slice().' + + 'sort((a, b) => JSON.stringify(a).localeCompare(JSON.stringify(b)))))' + )) + // Deep include (object literal) → assertObjectContains + out = out.replace(/\bassert\.deepInclude\(\s*((?:[^()]|\([^()]*\))+?)\s*,\s*(\{[^}]*\})\s*\)/g, 'assertObjectContains($1, $2)') + // Match/NotMatch + out = out.replace(/\bassert\.notMatch\(\s*((?:[^()]|\([^()]*\))+?)\s*,\s*((?:[^()]|\([^()]*\))+?)\s*\)/g, 'assert.doesNotMatch($1, $2)') + // Empty / NotEmpty (arrays/strings usage in repo) + out = out.replace(/\bassert\.isEmpty\(\s*((?:[^()]|\([^()]*\))+?)\s*\)/g, 'assert.strictEqual($1.length, 0)') + out = out.replace(/\bassert\.isNotEmpty\(\s*((?:[^()]|\([^()]*\))+?)\s*\)/g, 'assert.ok($1.length > 0)') // 16) Insert Node assert only when safe. Otherwise, skip touching this file. const afterNonChaiAssertCount = (out.match(/(^|[^.\w$])assert\./g) || []).length @@ -662,14 +1054,6 @@ function transform (code, file) { let insertedNodeAssert = false if (needsNodeAssertImport) { - if (hasAssertVariableBefore && !hasNodeAssertImportBefore) { - if (beforeNonChaiAssertCount > 0 && !didReplaceAssert) { - return code - } - if (beforeNonChaiAssertCount > 0) { - return code - } - } out = ensureAssertImport(out) insertedNodeAssert = true } @@ -704,18 +1088,72 @@ function transform (code, file) { out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\s*\.\s*to\s*\.\s*exist\b/gs, 'assert.ok($1 != null)') out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\s*\.\s*to\s*\.\s*not\s*\.\s*exist\b/gs, 'assert.ok($1 == null)') out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\s*\.\s*to\s*\.\s*be\s*\.\s*(?:an|a)\(\s*['"]array['"]\s*\)/gs, 'assert.ok(Array.isArray($1))') - out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\s*\.\s*to\s*\.\s*be\s*\.\s*(?:an|a)\(\s*['"]object['"]\s*\)/gs, "(assert.strictEqual(typeof $1, 'object'), assert.notStrictEqual($1, null))") + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\s*\.\s*to\s*\.\s*be\s*\.\s*(?:an|a)\(\s*['"]object['"]\s*\)/gs, "assert.ok(typeof $1 === 'object' && $1 !== null)") // Regex matching out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\s*\.\s*to\s*\.\s*match\(([^)]+)\)/gs, 'assert.match($1, $2)') out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\s*\.\s*to\s*\.\s*not\s*\.\s*match\(([^)]+)\)/gs, 'assert.doesNotMatch($1, $2)') // Include/contain object literal out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\s*\.\s*to\s*\.\s*(?:contain|include)\(\s*(\{[^}]*\})\s*\)/gs, 'assertObjectContains($1, $2)') out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\s*\.\s*to\s*\.\s*deep\s*\.\s*include\(\s*(\{[^}]*\})\s*\)/gs, 'assertObjectContains($1, $2)') + // Include/contain literal → .includes + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\s*\.\s*to(?:\s*\.\s*(?:be|have))*\s*\.\s*(?:contain|include)\(\s*(['"][^'"]+['"])\s*\)/gs, + 'assert.ok($1.includes($2))') // Throws out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\s*\.\s*to\s*\.\s*throw\(\s*\)/gs, 'assert.throws($1)') out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\s*\.\s*to\s*\.\s*throw\(([^)]+)\)/gs, 'assert.throws($1, $2)') out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\s*\.\s*to\s*\.\s*not\s*\.\s*throw\(\s*\)/gs, 'assert.doesNotThrow($1)') + // property presence (tolerant) – literal/variable key, single-arg form + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\s*\.\s*to\s*\.\s*have\s*\.\s*property\(\s*([^,)]+)\s*\)/gs, + 'assert.ok(Object.hasOwn($1, $2))') + + // Chained property(...).with.length + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\s*\.\s*to\s*\.\s*have\s*\.\s*property\(\s*(['"][^'"]+['"])\s*\)\s*\.\s*with\s*\.\s*(?:have\s*\.\s*)?length(?:Of)?\(([^)]+)\)/gs, + (m, obj, key, val) => `assert.strictEqual(${buildAccessor(obj, key)}.length, ${val})`) + // Nested property (presence/value/deep.equal) - string literal paths only + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\s*\.\s*to\s*\.\s*have\s*\.\s*nested\s*\.\s*property\(\s*(['"][^'"]+['"])\s*\)/gs, + (m, obj, path) => { + const acc = buildNestedAccessor(obj, path) + return acc ? `assert.ok(${acc} !== undefined)` : m + }) + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\s*\.\s*to\s*\.\s*have\s*\.\s*nested\s*\.\s*property\(\s*(['"][^'"]+['"])\s*,\s*([^)]+)\)/gs, + (m, obj, path, val) => { + const acc = buildNestedAccessor(obj, path) + return acc ? `assert.strictEqual(${acc}, ${val})` : m + }) + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\s*\.\s*to\s*\.\s*have\s*\.\s*nested\s*\.\s*property\(\s*(['"][^'"]+['"])\s*\)\s*\.\s*that\s*\.\s*deep\s*\.\s*equal\(([^)]+)\)/gs, + (m, obj, path, val) => { + const acc = buildNestedAccessor(obj, path) + return acc ? `assert.deepStrictEqual(${acc}, ${val})` : m + }) + // Keys / all.keys + out = out.replace( + /expect\(((?:[^()]|\([^()]*\))+?)\)\s*\.\s*to\s*\.\s*have\s*\.\s*(?:all\s*\.\s*)?keys\(([^)]+)\)/gs, + (m, obj, args) => ( + 'assert.deepStrictEqual(Object.keys(' + obj + ').slice().sort(), ' + + '((Array.isArray(' + args + ') ? ' + args + ' : [' + args + ']).slice().sort()))' + ) + ) + // include.members / have.members (+ negative) + out = out.replace( + /expect\(((?:[^()]|\([^()]*\))+?)\)\s*\.\s*to\s*\.\s*(?:include|have)\s*\.\s*members\(([^)]+)\)/gs, + (m, obj, args) => ( + 'assert.ok(((Array.isArray(' + args + ') ? ' + args + ' : [' + args + ']))' + + '.every(v => ' + obj + '.includes(v)))' + ) + ) + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\s*\.\s*(?:to\s*\.\s*not|not\s*\.\s*to)\s*\.\s*include\s*\.\s*members\(([^)]+)\)/gs, + (m, obj, args) => `assert.ok(!((Array.isArray(${args}) ? ${args} : [${args}])).every(v => ${obj}.includes(v)))`) + out = out.replace( + /expect\(((?:[^()]|\([^()]*\))+?)\)\s*\.\s*to\s*\.\s*have\s*\.\s*members\(([^)]+)\)/gs, + (m, obj, args) => ( + 'assert.deepStrictEqual(([...' + obj + ']).slice().sort(), ' + + '((Array.isArray(' + args + ') ? ' + args + ' : [' + args + ']).slice().sort()))' + ) + ) + // Empty / Not empty + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\s*\.\s*to\s*\.\s*be\s*\.\s*empty\b/gs, 'assert.strictEqual($1.length, 0)') + out = out.replace(/expect\(((?:[^()]|\([^()]*\))+?)\)\s*\.\s*(?:to\s*\.\s*not|not\s*\.\s*to)\s*\.\s*be\s*\.\s*empty\b/gs, 'assert.ok($1.length > 0)') // 20) On full replacement, remove chai assert import and chai expect if unused const expectStillUsed = /(?:^|[^\w$])expect\s*(\(|\.)/.test(out) const chaiAssertCallsRemain = /\bchai\.assert\./.test(out) @@ -782,11 +1220,25 @@ function isBrowserCypress (file) { } function main () { - const patterns = [ - 'packages/**/test/**/*.js', - 'integration-tests/**/*.js' - ] - const files = patterns.flatMap((pat) => glob.sync(path.join(ROOT, pat), { nodir: true })) + const targetArg = process.argv[2] + let files = [] + if (targetArg) { + const targetPath = path.isAbsolute(targetArg) ? targetArg : path.join(ROOT, targetArg) + const stat = fs.existsSync(targetPath) ? fs.statSync(targetPath) : null + if (stat && stat.isFile()) { + files = [targetPath] + } else if (stat && stat.isDirectory()) { + files = glob.sync(path.join(targetPath, '**/*.js'), { nodir: true }) + } else { + files = glob.sync(path.join(ROOT, targetArg), { nodir: true }) + } + } else { + const patterns = [ + 'packages/**/test/**/*.js', + 'integration-tests/**/*.js' + ] + files = patterns.flatMap((pat) => glob.sync(path.join(ROOT, pat), { nodir: true })) + } let changed = 0 const reverted = [] const ignored = [] @@ -812,9 +1264,10 @@ function main () { after = after.replace(/^(\s*import\s*\{[^}]*)(\s*from\s*["']chai["'][^\n]*\n)/mg, (m, head, tail) => head.trimEnd() + ' } ' + tail) - // Syntax validation: revert on failure; skip for ESM + // Syntax validation: revert on failure; skip for ESM or when explicitly disabled const isLikelyESM = /^\s*(?:import|export)\s/m.test(after) - if (!isLikelyESM) { + const skipSyntax = process.env.CHAI_TO_ASSERT_SKIP_SYNTAX === '1' + if (!isLikelyESM && !skipSyntax) { try { // eslint-disable-next-line no-new-func Function(after) From 82b41bb85845602d5cf92602cc5f5f3d81c2cda7 Mon Sep 17 00:00:00 2001 From: Ruben Bridgewater Date: Mon, 24 Nov 2025 13:10:51 +0900 Subject: [PATCH 4/5] test: linting issues auto fixed --- integration-tests/appsec/graphql.spec.js | 8 +- .../appsec/standalone-asm.spec.js | 6 +- .../non-dependency-mock-test-2.js | 4 - .../jest-plugin-tests/jest-test.js | 1 - .../subproject/subproject-test.js | 2 - .../ci-visibility/test-api-manual.spec.js | 2 +- integration-tests/cucumber/cucumber.spec.js | 20 +-- integration-tests/jest/jest.spec.js | 26 ++-- integration-tests/mocha/mocha.spec.js | 16 +-- integration-tests/startup.spec.js | 24 ++-- integration-tests/vitest/vitest.spec.js | 2 +- .../test/mysql2.spec.js | 32 ++--- .../datadog-instrumentations/test/pg.spec.js | 14 +-- .../test/integration-test/client.spec.js | 2 +- .../test/integration-test/client.spec.js | 2 +- .../test/integration-test/client.spec.js | 2 +- .../test/integration-test/client.spec.js | 2 +- .../test/integration-test/client.spec.js | 2 +- .../test/integration-test/client.spec.js | 2 +- .../test/integration-test/client.spec.js | 2 +- .../integration-test/http-test/client.spec.js | 4 +- .../test/integration-test/client.spec.js | 2 +- .../test/integration-test/client.spec.js | 2 +- .../test/index.spec.js | 12 +- .../test/scrub-cmd-params.spec.js | 30 ++--- .../test/integration-test/client.spec.js | 2 +- .../test/integration-test/client.spec.js | 2 +- .../test/integration-test/client.spec.js | 2 +- .../test/integration-test/client.spec.js | 2 +- .../test/index.spec.js | 8 +- .../test/integration-test/client.spec.js | 2 +- .../test/integration-test/client.spec.js | 10 +- .../test/integration-test/client.spec.js | 6 +- .../test/integration-test/client.spec.js | 2 +- .../test/integration-test/client.spec.js | 2 +- .../test/integration-test/client.spec.js | 2 +- .../test/esm-test/esm.spec.js | 4 +- .../datadog-plugin-graphql/test/index.spec.js | 4 +- .../test/integration-test/client.spec.js | 2 +- .../test/integration-test/client.spec.js | 2 +- .../datadog-plugin-grpc/test/server.spec.js | 4 +- .../test/integration-test/client.spec.js | 4 +- .../test/integration-test/client.spec.js | 6 +- .../test/integration-test/client.spec.js | 2 +- .../test/integration-test/client.spec.js | 2 +- .../test/integration-test/client.spec.js | 2 +- .../datadog-plugin-koa/test/index.spec.js | 8 +- .../test/integration-test/client.spec.js | 2 +- .../test/integration-test/client.spec.js | 2 +- .../test/integration-test/client.spec.js | 2 +- .../test/integration-test/client.spec.js | 2 +- .../test/integration-test/client.spec.js | 2 +- .../test/integration-test/client.spec.js | 2 +- .../test/integration-test/client.spec.js | 2 +- .../test/integration-test/client.spec.js | 4 +- .../test/integration-test/client.spec.js | 2 +- .../test/integration-test/client.spec.js | 2 +- .../test/integration-test/client.spec.js | 2 +- .../test/integration-test/client.spec.js | 2 +- .../datadog-plugin-openai/test/index.spec.js | 40 +++--- .../test/integration-test/client.spec.js | 2 +- .../test/index.spec.js | 4 +- .../test/integration-test/client.spec.js | 2 +- .../test/integration-test/client.spec.js | 2 +- .../test/integration-test/client.spec.js | 2 +- .../datadog-plugin-pino/test/index.spec.js | 44 +++---- .../test/integration-test/client.spec.js | 2 +- .../test/integration-test/client.spec.js | 2 +- .../datadog-plugin-rhea/test/index.spec.js | 16 +-- .../test/integration-test/client.spec.js | 2 +- .../test/integration-test/client.spec.js | 2 +- .../datadog-plugin-sharedb/test/index.spec.js | 4 +- .../test/integration-test/client.spec.js | 2 +- .../test/integration-test/client.spec.js | 2 +- .../datadog-plugin-winston/test/index.spec.js | 8 +- .../appsec/iast/overhead-controller.spec.js | 44 +++---- .../taint-tracking-impl.spec.js | 18 +-- .../taint-tracking-operations.spec.js | 6 +- .../test/appsec/rasp/fs-plugin.spec.js | 18 +-- .../dd-trace/test/appsec/rule_manager.spec.js | 1 - .../sdk/track_event-integration.spec.js | 2 +- .../test/appsec/telemetry/waf.spec.js | 20 +-- .../debugger/devtools_client/send.spec.js | 4 +- .../snapshot/complex-types.spec.js | 114 +++++++++--------- .../snapshot/max-collection-size.spec.js | 20 +-- .../snapshot/max-field-count-scopes.spec.js | 2 +- .../snapshot/max-field-count.spec.js | 6 +- .../snapshot/max-reference-depth.spec.js | 24 ++-- .../snapshot/primitives.spec.js | 28 ++--- .../snapshot/redaction.spec.js | 56 ++++----- .../devtools_client/snapshot/scopes.spec.js | 20 +-- .../dd-trace/test/llmobs/sdk/index.spec.js | 8 +- packages/dd-trace/test/log.spec.js | 4 +- .../opentracing/propagation/text_map.spec.js | 96 +++++++-------- .../dd-trace/test/opentracing/span.spec.js | 10 +- .../plugins/util/test-environment.spec.js | 2 +- .../dd-trace/test/plugins/util/web.spec.js | 8 +- packages/dd-trace/test/span_processor.spec.js | 40 +++--- .../dd-trace/test/standalone/index.spec.js | 2 +- .../dd-trace/test/standalone/product.spec.js | 12 +- .../dd-trace/test/telemetry/endpoints.spec.js | 4 +- 101 files changed, 512 insertions(+), 520 deletions(-) diff --git a/integration-tests/appsec/graphql.spec.js b/integration-tests/appsec/graphql.spec.js index 6b7900e94c1..1b040f2e972 100644 --- a/integration-tests/appsec/graphql.spec.js +++ b/integration-tests/appsec/graphql.spec.js @@ -38,11 +38,11 @@ describe('graphql', () => { it('should not report any attack', async () => { const agentPromise = agent.assertMessageReceived(({ headers, payload }) => { - assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.strictEqual(headers.host, `127.0.0.1:${agent.port}`) assert.ok(Array.isArray(payload)) assert.strictEqual(payload.length, 2) // Apollo server 5 is using Node.js http server instead of express - assert.strictEqual(payload[1][0]['name'], 'web.request') + assert.strictEqual(payload[1][0].name, 'web.request') assert.strictEqual(payload[1][0].metrics['_dd.appsec.enabled'], 1) assert.ok(Object.hasOwn(payload[1][0].metrics, '_dd.appsec.waf.duration')) assert.ok(!Object.hasOwn(payload[1][0].meta, '_dd.appsec.event')) @@ -100,11 +100,11 @@ describe('graphql', () => { } const agentPromise = agent.assertMessageReceived(({ headers, payload }) => { - assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.strictEqual(headers.host, `127.0.0.1:${agent.port}`) assert.ok(Array.isArray(payload)) assert.strictEqual(payload.length, 2) // Apollo server 5 is using Node.js http server instead of express - assert.strictEqual(payload[1][0]['name'], 'web.request') + assert.strictEqual(payload[1][0].name, 'web.request') assert.strictEqual(payload[1][0].metrics['_dd.appsec.enabled'], 1) assert.ok(Object.hasOwn(payload[1][0].metrics, '_dd.appsec.waf.duration')) assert.strictEqual(payload[1][0].meta['appsec.event'], 'true') diff --git a/integration-tests/appsec/standalone-asm.spec.js b/integration-tests/appsec/standalone-asm.spec.js index 382b796a6db..973c2b06ee1 100644 --- a/integration-tests/appsec/standalone-asm.spec.js +++ b/integration-tests/appsec/standalone-asm.spec.js @@ -26,14 +26,14 @@ describe('Standalone ASM', () => { function assertKeep ({ meta, metrics }) { assert.strictEqual(meta['_dd.p.ts'], '02') - assert.strictEqual(metrics['_sampling_priority_v1'], USER_KEEP) + assert.strictEqual(metrics._sampling_priority_v1, USER_KEEP) assert.strictEqual(metrics['_dd.apm.enabled'], 0) } function assertDrop ({ meta, metrics }) { assert.ok(!Object.hasOwn(meta, '_dd.p.ts')) - assert.strictEqual(metrics['_sampling_priority_v1'], AUTO_REJECT) + assert.strictEqual(metrics._sampling_priority_v1, AUTO_REJECT) assert.strictEqual(metrics['_dd.apm.enabled'], 0) } @@ -99,7 +99,7 @@ describe('Standalone ASM', () => { assert.ok(!Object.hasOwn(meta, 'manual.keep')) assert.ok(!Object.hasOwn(meta, '_dd.p.ts')) - assert.strictEqual(metrics['_sampling_priority_v1'], AUTO_KEEP) + assert.strictEqual(metrics._sampling_priority_v1, AUTO_KEEP) assert.strictEqual(metrics['_dd.apm.enabled'], 0) } }, 70000, 2) diff --git a/integration-tests/ci-visibility/jest-package-mock/non-dependency-mock-test-2.js b/integration-tests/ci-visibility/jest-package-mock/non-dependency-mock-test-2.js index 5df557962c0..1a0bea5139f 100644 --- a/integration-tests/ci-visibility/jest-package-mock/non-dependency-mock-test-2.js +++ b/integration-tests/ci-visibility/jest-package-mock/non-dependency-mock-test-2.js @@ -2,10 +2,6 @@ const assert = require('node:assert/strict') - - - - const hello = jest.requireActual('some-package') test('hello function returns correct greeting', () => { diff --git a/integration-tests/ci-visibility/jest-plugin-tests/jest-test.js b/integration-tests/ci-visibility/jest-plugin-tests/jest-test.js index 32a5f86d876..c2db2e0bfe8 100644 --- a/integration-tests/ci-visibility/jest-plugin-tests/jest-test.js +++ b/integration-tests/ci-visibility/jest-plugin-tests/jest-test.js @@ -5,7 +5,6 @@ const assert = require('node:assert/strict') const tracer = require('dd-trace') - const ENDPOINT_URL = process.env.DD_CIVISIBILITY_AGENTLESS_URL || `http://127.0.0.1:${process.env.DD_TRACE_AGENT_PORT}` diff --git a/integration-tests/ci-visibility/subproject/subproject-test.js b/integration-tests/ci-visibility/subproject/subproject-test.js index 23a0dbb92eb..545ab81d8db 100644 --- a/integration-tests/ci-visibility/subproject/subproject-test.js +++ b/integration-tests/ci-visibility/subproject/subproject-test.js @@ -4,8 +4,6 @@ const assert = require('node:assert/strict') const dependency = require('./dependency') - - describe('subproject-test', () => { it('can run', () => { assert.strictEqual(dependency(1, 2), 3) diff --git a/integration-tests/ci-visibility/test-api-manual.spec.js b/integration-tests/ci-visibility/test-api-manual.spec.js index 4329b3cba54..609a7e23d57 100644 --- a/integration-tests/ci-visibility/test-api-manual.spec.js +++ b/integration-tests/ci-visibility/test-api-manual.spec.js @@ -56,7 +56,7 @@ describe('test-api-manual', () => { assert.strictEqual(passedTest.content.meta['test.custom.tag'], 'custom.value') const customSpan = events.find(event => event.type === 'span') - assert.strictEqual(customSpan.content['resource'], 'custom.span') + assert.strictEqual(customSpan.content.resource, 'custom.span') }).catch(done) childProcess = exec( diff --git a/integration-tests/cucumber/cucumber.spec.js b/integration-tests/cucumber/cucumber.spec.js index e246e5b4675..97287c9d851 100644 --- a/integration-tests/cucumber/cucumber.spec.js +++ b/integration-tests/cucumber/cucumber.spec.js @@ -191,8 +191,8 @@ describe(`cucumber@${version} commonJS`, () => { testSpans.forEach(testSpan => { const testName = testSpan.meta[TEST_NAME] - assert.strictEqual(testSpan.meta['language'], 'javascript') - assert.strictEqual(testSpan.meta['service'], 'cucumber-test-service') + assert.strictEqual(testSpan.meta.language, 'javascript') + assert.strictEqual(testSpan.meta.service, 'cucumber-test-service') const { status } = testInfoByTestName[testName] assert.strictEqual(testSpan.meta[TEST_STATUS], status, `Expected status for ${testName} to be ${status}`) @@ -254,7 +254,7 @@ describe(`cucumber@${version} commonJS`, () => { assert.strictEqual(stepSpan.meta['step.status'], stepStatus, `Test ${testName} should have step ${name} with status ${stepStatus}`) assert.strictEqual(stepSpan.meta[COMPONENT], 'cucumber') - assert.notStrictEqual(stepSpan['type'], 'test') + assert.notStrictEqual(stepSpan.type, 'test') }) }) }) @@ -502,9 +502,9 @@ describe(`cucumber@${version} commonJS`, () => { assert.ok(!Object.hasOwn(codeCovRequest.headers, 'dd-api-key')) } - assert.strictEqual(coveragePayload['name'], 'coverage1') - assert.strictEqual(coveragePayload['filename'], 'coverage1.msgpack') - assert.strictEqual(coveragePayload['type'], 'application/msgpack') + assert.strictEqual(coveragePayload.name, 'coverage1') + assert.strictEqual(coveragePayload.filename, 'coverage1.msgpack') + assert.strictEqual(coveragePayload.type, 'application/msgpack') assert.ok(coveragePayload.content.includes({ version: 2 })) @@ -624,9 +624,9 @@ describe(`cucumber@${version} commonJS`, () => { assert.ok(!Object.hasOwn(coverageRequest.headers, 'dd-api-key')) assert.ok(!Object.hasOwn(eventsRequest.headers, 'dd-api-key')) } - assert.strictEqual(coveragePayload['name'], 'coverage1') - assert.strictEqual(coveragePayload['filename'], 'coverage1.msgpack') - assert.strictEqual(coveragePayload['type'], 'application/msgpack') + assert.strictEqual(coveragePayload.name, 'coverage1') + assert.strictEqual(coveragePayload.filename, 'coverage1.msgpack') + assert.strictEqual(coveragePayload.type, 'application/msgpack') const eventTypes = eventsRequest.payload.events.map(event => event.type) @@ -1961,7 +1961,7 @@ describe(`cucumber@${version} commonJS`, () => { assert.strictEqual(retriedTest.meta[DI_ERROR_DEBUG_INFO_CAPTURED], 'true') assert.strictEqual(retriedTest.meta[`${DI_DEBUG_ERROR_PREFIX}.0.${DI_DEBUG_ERROR_FILE_SUFFIX}`] - .endsWith('ci-visibility/features-di/support/sum.js'), true) + .endsWith('ci-visibility/features-di/support/sum.js'), true) assert.strictEqual(retriedTest.metrics[`${DI_DEBUG_ERROR_PREFIX}.0.${DI_DEBUG_ERROR_LINE_SUFFIX}`], 6) const snapshotIdKey = `${DI_DEBUG_ERROR_PREFIX}.0.${DI_DEBUG_ERROR_SNAPSHOT_ID_SUFFIX}` diff --git a/integration-tests/jest/jest.spec.js b/integration-tests/jest/jest.spec.js index f5830ff5a81..c9a511223d9 100644 --- a/integration-tests/jest/jest.spec.js +++ b/integration-tests/jest/jest.spec.js @@ -239,8 +239,8 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { assert.ok(test != null) - assert.strictEqual(test.meta['language'], 'javascript') - assert.strictEqual(test.meta['service'], 'plugin-tests') + assert.strictEqual(test.meta.language, 'javascript') + assert.strictEqual(test.meta.service, 'plugin-tests') assert.strictEqual(test.meta[ORIGIN_KEY], CI_APP_ORIGIN) assert.strictEqual(test.meta[TEST_FRAMEWORK], 'jest') assert.strictEqual(test.meta[TEST_NAME], name) @@ -316,7 +316,7 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { ) assert.ok(testSpan != null) - assert.strictEqual(testSpan.meta['language'], 'javascript') + assert.strictEqual(testSpan.meta.language, 'javascript') assert.strictEqual(testSpan.meta[ORIGIN_KEY], CI_APP_ORIGIN) assert.strictEqual(testSpan.meta[TEST_FRAMEWORK], 'jest') assert.strictEqual(testSpan.meta[TEST_NAME], name) @@ -369,7 +369,7 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { ) assert.ok(testSpan != null) - assert.strictEqual(testSpan.meta['language'], 'javascript') + assert.strictEqual(testSpan.meta.language, 'javascript') assert.strictEqual(testSpan.meta[ORIGIN_KEY], CI_APP_ORIGIN) assert.strictEqual(testSpan.meta[TEST_FRAMEWORK], 'jest') assert.strictEqual(testSpan.meta[TEST_NAME], name) @@ -897,7 +897,7 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { assert.strictEqual(retriedTest.meta[DI_ERROR_DEBUG_INFO_CAPTURED], 'true') assert.strictEqual(retriedTest.meta[`${DI_DEBUG_ERROR_PREFIX}.0.${DI_DEBUG_ERROR_FILE_SUFFIX}`] - .endsWith('ci-visibility/dynamic-instrumentation/dependency.js'), true) + .endsWith('ci-visibility/dynamic-instrumentation/dependency.js'), true) assert.strictEqual(retriedTest.metrics[`${DI_DEBUG_ERROR_PREFIX}.0.${DI_DEBUG_ERROR_LINE_SUFFIX}`], 6) const snapshotIdKey = `${DI_DEBUG_ERROR_PREFIX}.0.${DI_DEBUG_ERROR_SNAPSHOT_ID_SUFFIX}` @@ -1395,9 +1395,9 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { const [coveragePayload] = codeCovRequest.payload assert.strictEqual(codeCovRequest.headers['dd-api-key'], '1') - assert.strictEqual(coveragePayload['name'], 'coverage1') - assert.strictEqual(coveragePayload['filename'], 'coverage1.msgpack') - assert.strictEqual(coveragePayload['type'], 'application/msgpack') + assert.strictEqual(coveragePayload.name, 'coverage1') + assert.strictEqual(coveragePayload.filename, 'coverage1.msgpack') + assert.strictEqual(coveragePayload.type, 'application/msgpack') assert.ok(coveragePayload.content.includes({ version: 2 })) @@ -1498,9 +1498,9 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { assert.strictEqual(skippableRequest.headers['dd-api-key'], '1') const [coveragePayload] = coverageRequest.payload assert.strictEqual(coverageRequest.headers['dd-api-key'], '1') - assert.strictEqual(coveragePayload['name'], 'coverage1') - assert.strictEqual(coveragePayload['filename'], 'coverage1.msgpack') - assert.strictEqual(coveragePayload['type'], 'application/msgpack') + assert.strictEqual(coveragePayload.name, 'coverage1') + assert.strictEqual(coveragePayload.filename, 'coverage1.msgpack') + assert.strictEqual(coveragePayload.type, 'application/msgpack') assert.strictEqual(eventsRequest.headers['dd-api-key'], '1') const eventTypes = eventsRequest.payload.events.map(event => event.type) @@ -3481,7 +3481,7 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { assert.strictEqual(retriedTest.meta[DI_ERROR_DEBUG_INFO_CAPTURED], 'true') assert.strictEqual(retriedTest.meta[`${DI_DEBUG_ERROR_PREFIX}.0.${DI_DEBUG_ERROR_FILE_SUFFIX}`] - .endsWith('ci-visibility/dynamic-instrumentation/dependency.js'), true) + .endsWith('ci-visibility/dynamic-instrumentation/dependency.js'), true) assert.strictEqual(retriedTest.metrics[`${DI_DEBUG_ERROR_PREFIX}.0.${DI_DEBUG_ERROR_LINE_SUFFIX}`], 6) const snapshotIdKey = `${DI_DEBUG_ERROR_PREFIX}.0.${DI_DEBUG_ERROR_SNAPSHOT_ID_SUFFIX}` @@ -3565,7 +3565,7 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { assert.strictEqual(retriedTest.meta[DI_ERROR_DEBUG_INFO_CAPTURED], 'true') assert.strictEqual(retriedTest.meta[`${DI_DEBUG_ERROR_PREFIX}.0.${DI_DEBUG_ERROR_FILE_SUFFIX}`] - .endsWith('ci-visibility/dynamic-instrumentation/dependency.js'), true) + .endsWith('ci-visibility/dynamic-instrumentation/dependency.js'), true) assert.strictEqual(retriedTest.metrics[`${DI_DEBUG_ERROR_PREFIX}.0.${DI_DEBUG_ERROR_LINE_SUFFIX}`], 6) const snapshotIdKey = `${DI_DEBUG_ERROR_PREFIX}.0.${DI_DEBUG_ERROR_SNAPSHOT_ID_SUFFIX}` diff --git a/integration-tests/mocha/mocha.spec.js b/integration-tests/mocha/mocha.spec.js index 4b3b28e6300..75f37a38c35 100644 --- a/integration-tests/mocha/mocha.spec.js +++ b/integration-tests/mocha/mocha.spec.js @@ -309,7 +309,7 @@ describe(`mocha@${MOCHA_VERSION}`, function () { assert.strictEqual(tests.length, 1) const [test] = tests assert.strictEqual(test.meta[COMPONENT], 'mocha') - assert.strictEqual(test.meta['language'], 'javascript') + assert.strictEqual(test.meta.language, 'javascript') assert.strictEqual(test.meta[TEST_NAME], 'mocha-test-fail can fail') assert.strictEqual(test.meta[TEST_STATUS], 'fail') assert.strictEqual(test.meta[TEST_TYPE], 'test') @@ -1485,9 +1485,9 @@ describe(`mocha@${MOCHA_VERSION}`, function () { const [coveragePayload] = codeCovRequest.payload assert.strictEqual(codeCovRequest.headers['dd-api-key'], '1') - assert.strictEqual(coveragePayload['name'], 'coverage1') - assert.strictEqual(coveragePayload['filename'], 'coverage1.msgpack') - assert.strictEqual(coveragePayload['type'], 'application/msgpack') + assert.strictEqual(coveragePayload.name, 'coverage1') + assert.strictEqual(coveragePayload.filename, 'coverage1.msgpack') + assert.strictEqual(coveragePayload.type, 'application/msgpack') assert.ok(coveragePayload.content.includes({ version: 2 })) @@ -1592,9 +1592,9 @@ describe(`mocha@${MOCHA_VERSION}`, function () { assert.strictEqual(skippableRequest.headers['dd-api-key'], '1') const [coveragePayload] = coverageRequest.payload assert.strictEqual(coverageRequest.headers['dd-api-key'], '1') - assert.strictEqual(coveragePayload['name'], 'coverage1') - assert.strictEqual(coveragePayload['filename'], 'coverage1.msgpack') - assert.strictEqual(coveragePayload['type'], 'application/msgpack') + assert.strictEqual(coveragePayload.name, 'coverage1') + assert.strictEqual(coveragePayload.filename, 'coverage1.msgpack') + assert.strictEqual(coveragePayload.type, 'application/msgpack') assert.strictEqual(eventsRequest.headers['dd-api-key'], '1') const eventTypes = eventsRequest.payload.events.map(event => event.type) @@ -3260,7 +3260,7 @@ describe(`mocha@${MOCHA_VERSION}`, function () { assert.strictEqual(retriedTest.meta[DI_ERROR_DEBUG_INFO_CAPTURED], 'true') assert.strictEqual(retriedTest.meta[`${DI_DEBUG_ERROR_PREFIX}.0.${DI_DEBUG_ERROR_FILE_SUFFIX}`] - .endsWith('ci-visibility/dynamic-instrumentation/dependency.js'), true) + .endsWith('ci-visibility/dynamic-instrumentation/dependency.js'), true) assert.strictEqual(retriedTest.metrics[`${DI_DEBUG_ERROR_PREFIX}.0.${DI_DEBUG_ERROR_LINE_SUFFIX}`], 6) const snapshotIdKey = `${DI_DEBUG_ERROR_PREFIX}.0.${DI_DEBUG_ERROR_SNAPSHOT_ID_SUFFIX}` diff --git a/integration-tests/startup.spec.js b/integration-tests/startup.spec.js index 8fa8c98febd..6f472cca6b6 100644 --- a/integration-tests/startup.spec.js +++ b/integration-tests/startup.spec.js @@ -65,12 +65,12 @@ execArgvs.forEach(({ execArgv, skip }) => { } }) return curlAndAssertMessage(agent, proc, ({ headers, payload }) => { - assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.strictEqual(headers.host, `127.0.0.1:${agent.port}`) assert.ok(Array.isArray(payload)) assert.strictEqual(payload.length, 1) assert.ok(Array.isArray(payload[0])) assert.strictEqual(payload[0].length, 1) - assert.strictEqual(payload[0][0]['name'], 'web.request') + assert.strictEqual(payload[0][0].name, 'web.request') }) }) @@ -116,12 +116,12 @@ execArgvs.forEach(({ execArgv, skip }) => { } }) return curlAndAssertMessage(agent, proc, ({ headers, payload }) => { - assert.strictEqual(headers['host'], `localhost:${agent.port}`) + assert.strictEqual(headers.host, `localhost:${agent.port}`) assert.ok(Array.isArray(payload)) assert.strictEqual(payload.length, 1) assert.ok(Array.isArray(payload[0])) assert.strictEqual(payload[0].length, 1) - assert.strictEqual(payload[0][0]['name'], 'web.request') + assert.strictEqual(payload[0][0].name, 'web.request') }) }) }) @@ -145,12 +145,12 @@ execArgvs.forEach(({ execArgv, skip }) => { } }) return curlAndAssertMessage(agent, proc, ({ headers, payload }) => { - assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.strictEqual(headers.host, `127.0.0.1:${agent.port}`) assert.ok(Array.isArray(payload)) assert.strictEqual(payload.length, 1) assert.ok(Array.isArray(payload[0])) assert.strictEqual(payload[0].length, 1) - assert.strictEqual(payload[0][0]['name'], 'web.request') + assert.strictEqual(payload[0][0].name, 'web.request') }) }) @@ -163,12 +163,12 @@ execArgvs.forEach(({ execArgv, skip }) => { } }) return curlAndAssertMessage(agent, proc, ({ headers, payload }) => { - assert.strictEqual(headers['host'], `localhost:${agent.port}`) + assert.strictEqual(headers.host, `localhost:${agent.port}`) assert.ok(Array.isArray(payload)) assert.strictEqual(payload.length, 1) assert.ok(Array.isArray(payload[0])) assert.strictEqual(payload[0].length, 1) - assert.strictEqual(payload[0][0]['name'], 'web.request') + assert.strictEqual(payload[0][0].name, 'web.request') }) }) }) @@ -191,12 +191,12 @@ execArgvs.forEach(({ execArgv, skip }) => { execArgv }) return curlAndAssertMessage(agent, proc, ({ headers, payload }) => { - assert.strictEqual(headers['host'], '127.0.0.1:8126') + assert.strictEqual(headers.host, '127.0.0.1:8126') assert.ok(Array.isArray(payload)) assert.strictEqual(payload.length, 1) assert.ok(Array.isArray(payload[0])) assert.strictEqual(payload[0].length, 1) - assert.strictEqual(payload[0][0]['name'], 'web.request') + assert.strictEqual(payload[0][0].name, 'web.request') }) }) @@ -209,12 +209,12 @@ execArgvs.forEach(({ execArgv, skip }) => { } }) return curlAndAssertMessage(agent, proc, ({ headers, payload }) => { - assert.strictEqual(headers['host'], '127.0.0.1:8126') + assert.strictEqual(headers.host, '127.0.0.1:8126') assert.ok(Array.isArray(payload)) assert.strictEqual(payload.length, 1) assert.ok(Array.isArray(payload[0])) assert.strictEqual(payload[0].length, 1) - assert.strictEqual(payload[0][0]['name'], 'web.request') + assert.strictEqual(payload[0][0].name, 'web.request') }) }) }) diff --git a/integration-tests/vitest/vitest.spec.js b/integration-tests/vitest/vitest.spec.js index efb338f80a3..e3a872b4927 100644 --- a/integration-tests/vitest/vitest.spec.js +++ b/integration-tests/vitest/vitest.spec.js @@ -1266,7 +1266,7 @@ versions.forEach((version) => { assert.strictEqual(retriedTest.meta[DI_ERROR_DEBUG_INFO_CAPTURED], 'true') assert.strictEqual(retriedTest.meta[`${DI_DEBUG_ERROR_PREFIX}.0.${DI_DEBUG_ERROR_FILE_SUFFIX}`] - .endsWith('ci-visibility/vitest-tests/bad-sum.mjs'), true) + .endsWith('ci-visibility/vitest-tests/bad-sum.mjs'), true) assert.strictEqual(retriedTest.metrics[`${DI_DEBUG_ERROR_PREFIX}.0.${DI_DEBUG_ERROR_LINE_SUFFIX}`], 4) const snapshotIdKey = `${DI_DEBUG_ERROR_PREFIX}.0.${DI_DEBUG_ERROR_SNAPSHOT_ID_SUFFIX}` diff --git a/packages/datadog-instrumentations/test/mysql2.spec.js b/packages/datadog-instrumentations/test/mysql2.spec.js index 8c91f403a8b..ff72168933a 100644 --- a/packages/datadog-instrumentations/test/mysql2.spec.js +++ b/packages/datadog-instrumentations/test/mysql2.spec.js @@ -76,7 +76,7 @@ describe('mysql2 instrumentation', () => { it('should abort the query on abortController.abort()', (done) => { startCh.subscribe(abort) const query = connection.query(sql, (err) => { - assert.strictEqual(err['message'], 'Test') + assert.strictEqual(err.message, 'Test') sinon.assert.notCalled(apmQueryStart) if (!shouldEmitEndAfterQueryAbort) done() @@ -112,7 +112,7 @@ describe('mysql2 instrumentation', () => { const query = connection.query(sql) query.on('error', (err) => { - assert.strictEqual(err['message'], 'Test') + assert.strictEqual(err.message, 'Test') sinon.assert.notCalled(apmQueryStart) if (!shouldEmitEndAfterQueryAbort) done() }) @@ -151,7 +151,7 @@ describe('mysql2 instrumentation', () => { it('should abort the query on abortController.abort()', (done) => { startCh.subscribe(abort) const query = mysql2.Connection.createQuery(sql, (err) => { - assert.strictEqual(err['message'], 'Test') + assert.strictEqual(err.message, 'Test') sinon.assert.notCalled(apmQueryStart) if (!shouldEmitEndAfterQueryAbort) done() @@ -192,7 +192,7 @@ describe('mysql2 instrumentation', () => { const query = mysql2.Connection.createQuery(sql, null, null, {}) query.on('error', (err) => { - assert.strictEqual(err['message'], 'Test') + assert.strictEqual(err.message, 'Test') sinon.assert.notCalled(apmQueryStart) if (!shouldEmitEndAfterQueryAbort) done() @@ -239,7 +239,7 @@ describe('mysql2 instrumentation', () => { const options = { sql } const commandExecute = connection.execute(options, (err) => { - assert.strictEqual(err['message'], 'Test') + assert.strictEqual(err.message, 'Test') sinon.assert.notCalled(apmQueryStart) done() @@ -278,7 +278,7 @@ describe('mysql2 instrumentation', () => { startCh.subscribe(abort) connection.execute(sql, (err) => { - assert.strictEqual(err['message'], 'Test') + assert.strictEqual(err.message, 'Test') sinon.assert.notCalled(apmQueryStart) done() }) @@ -322,7 +322,7 @@ describe('mysql2 instrumentation', () => { it('should abort the query on abortController.abort()', (done) => { startCh.subscribe(abort) const query = pool.query({ sql }, (err) => { - assert.strictEqual(err['message'], 'Test') + assert.strictEqual(err.message, 'Test') sinon.assert.notCalled(apmQueryStart) if (!shouldEmitEndAfterQueryAbort) done() @@ -357,7 +357,7 @@ describe('mysql2 instrumentation', () => { startCh.subscribe(abort) const query = pool.query({ sql }) query.on('error', err => { - assert.strictEqual(err['message'], 'Test') + assert.strictEqual(err.message, 'Test') sinon.assert.notCalled(apmQueryStart) if (!shouldEmitEndAfterQueryAbort) done() }) @@ -393,7 +393,7 @@ describe('mysql2 instrumentation', () => { it('should abort the query on abortController.abort()', (done) => { startCh.subscribe(abort) const query = pool.query(sql, (err) => { - assert.strictEqual(err['message'], 'Test') + assert.strictEqual(err.message, 'Test') sinon.assert.notCalled(apmQueryStart) if (!shouldEmitEndAfterQueryAbort) done() @@ -428,7 +428,7 @@ describe('mysql2 instrumentation', () => { startCh.subscribe(abort) const query = pool.query(sql) query.on('error', err => { - assert.strictEqual(err['message'], 'Test') + assert.strictEqual(err.message, 'Test') sinon.assert.notCalled(apmQueryStart) if (!shouldEmitEndAfterQueryAbort) done() }) @@ -467,7 +467,7 @@ describe('mysql2 instrumentation', () => { it('should abort the query on abortController.abort()', (done) => { startCh.subscribe(abort) pool.execute({ sql }, (err) => { - assert.strictEqual(err['message'], 'Test') + assert.strictEqual(err.message, 'Test') setTimeout(() => { sinon.assert.notCalled(apmQueryStart) @@ -503,7 +503,7 @@ describe('mysql2 instrumentation', () => { it('should abort the query on abortController.abort()', (done) => { startCh.subscribe(abort) pool.execute(sql, (err) => { - assert.strictEqual(err['message'], 'Test') + assert.strictEqual(err.message, 'Test') setTimeout(() => { sinon.assert.notCalled(apmQueryStart) @@ -568,7 +568,7 @@ describe('mysql2 instrumentation', () => { startCh.subscribe(abort) const namespace = poolCluster.of() namespace.query(sql, (err) => { - assert.strictEqual(err['message'], 'Test') + assert.strictEqual(err.message, 'Test') setTimeout(() => { sinon.assert.notCalled(apmQueryStart) @@ -605,7 +605,7 @@ describe('mysql2 instrumentation', () => { startCh.subscribe(abort) const namespace = poolCluster.of() namespace.query({ sql }, (err) => { - assert.strictEqual(err['message'], 'Test') + assert.strictEqual(err.message, 'Test') setTimeout(() => { sinon.assert.notCalled(apmQueryStart) @@ -645,7 +645,7 @@ describe('mysql2 instrumentation', () => { const namespace = poolCluster.of() namespace.execute(sql, (err) => { - assert.strictEqual(err['message'], 'Test') + assert.strictEqual(err.message, 'Test') setTimeout(() => { sinon.assert.notCalled(apmQueryStart) @@ -683,7 +683,7 @@ describe('mysql2 instrumentation', () => { const namespace = poolCluster.of() namespace.execute({ sql }, (err) => { - assert.strictEqual(err['message'], 'Test') + assert.strictEqual(err.message, 'Test') setTimeout(() => { sinon.assert.notCalled(apmQueryStart) diff --git a/packages/datadog-instrumentations/test/pg.spec.js b/packages/datadog-instrumentations/test/pg.spec.js index 1fd1d00ed19..802f4c8b2ec 100644 --- a/packages/datadog-instrumentations/test/pg.spec.js +++ b/packages/datadog-instrumentations/test/pg.spec.js @@ -73,7 +73,7 @@ describe('pg instrumentation', () => { queryClientStartChannel.subscribe(abortQuery) client.query('SELECT 1', (err) => { - assert.strictEqual(err['message'], 'Test') + assert.strictEqual(err.message, 'Test') done() }) }) @@ -90,7 +90,7 @@ describe('pg instrumentation', () => { try { await client.query('SELECT 1') } catch (err) { - assert.strictEqual(err['message'], 'Test') + assert.strictEqual(err.message, 'Test') return } @@ -119,7 +119,7 @@ describe('pg instrumentation', () => { client.query(query) query.on('error', err => { - assert.strictEqual(err['message'], 'Test') + assert.strictEqual(err.message, 'Test') done() }) @@ -144,7 +144,7 @@ describe('pg instrumentation', () => { const query = new Query('SELECT 1') query.callback = err => { - assert.strictEqual(err['message'], 'Test') + assert.strictEqual(err.message, 'Test') done() } @@ -167,7 +167,7 @@ describe('pg instrumentation', () => { const query = new Query('SELECT 1') client.query(query, err => { - assert.strictEqual(err['message'], 'Test') + assert.strictEqual(err.message, 'Test') done() }) }) @@ -211,7 +211,7 @@ describe('pg instrumentation', () => { queryPoolStartChannel.subscribe(abortQuery) pool.query('SELECT 1', (err) => { - assert.strictEqual(err['message'], 'Test') + assert.strictEqual(err.message, 'Test') done() }) }) @@ -228,7 +228,7 @@ describe('pg instrumentation', () => { try { await pool.query('SELECT 1') } catch (err) { - assert.strictEqual(err['message'], 'Test') + assert.strictEqual(err.message, 'Test') return } diff --git a/packages/datadog-plugin-ai/test/integration-test/client.spec.js b/packages/datadog-plugin-ai/test/integration-test/client.spec.js index ead28467b63..ab89d1da692 100644 --- a/packages/datadog-plugin-ai/test/integration-test/client.spec.js +++ b/packages/datadog-plugin-ai/test/integration-test/client.spec.js @@ -42,7 +42,7 @@ describe('esm', () => { it('is instrumented', async () => { const res = agent.assertMessageReceived(({ headers, payload }) => { - assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.strictEqual(headers.host, `127.0.0.1:${agent.port}`) assert.ok(Array.isArray(payload)) // special check for ai spans diff --git a/packages/datadog-plugin-amqp10/test/integration-test/client.spec.js b/packages/datadog-plugin-amqp10/test/integration-test/client.spec.js index bcbea83d9cf..ccb23b23efd 100644 --- a/packages/datadog-plugin-amqp10/test/integration-test/client.spec.js +++ b/packages/datadog-plugin-amqp10/test/integration-test/client.spec.js @@ -29,7 +29,7 @@ describe('esm', () => { it('is instrumented', async () => { const res = agent.assertMessageReceived(({ headers, payload }) => { - assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.strictEqual(headers.host, `127.0.0.1:${agent.port}`) assert.ok(Array.isArray(payload)) assert.strictEqual(checkSpansForServiceName(payload, 'amqp.send'), true) }) diff --git a/packages/datadog-plugin-amqplib/test/integration-test/client.spec.js b/packages/datadog-plugin-amqplib/test/integration-test/client.spec.js index 94bb52405b1..ec0cb79118a 100644 --- a/packages/datadog-plugin-amqplib/test/integration-test/client.spec.js +++ b/packages/datadog-plugin-amqplib/test/integration-test/client.spec.js @@ -37,7 +37,7 @@ describe('esm', () => { for (const variant of varySandbox.VARIANTS) { it(`is instrumented loaded with ${variant}`, async () => { const res = agent.assertMessageReceived(({ headers, payload }) => { - assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.strictEqual(headers.host, `127.0.0.1:${agent.port}`) assert.ok(Array.isArray(payload)) assert.strictEqual(checkSpansForServiceName(payload, 'amqp.command'), true) }) diff --git a/packages/datadog-plugin-anthropic/test/integration-test/client.spec.js b/packages/datadog-plugin-anthropic/test/integration-test/client.spec.js index 6e68d26d3ca..060c4f6c7ae 100644 --- a/packages/datadog-plugin-anthropic/test/integration-test/client.spec.js +++ b/packages/datadog-plugin-anthropic/test/integration-test/client.spec.js @@ -34,7 +34,7 @@ describe('esm', () => { it('is instrumented', async () => { const res = agent.assertMessageReceived(({ headers, payload }) => { - assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.strictEqual(headers.host, `127.0.0.1:${agent.port}`) assert.ok(Array.isArray(payload)) assert.strictEqual(checkSpansForServiceName(payload, 'anthropic.request'), true) }) diff --git a/packages/datadog-plugin-aws-sdk/test/integration-test/client.spec.js b/packages/datadog-plugin-aws-sdk/test/integration-test/client.spec.js index 43dca8ada08..20d4fd3d5ae 100644 --- a/packages/datadog-plugin-aws-sdk/test/integration-test/client.spec.js +++ b/packages/datadog-plugin-aws-sdk/test/integration-test/client.spec.js @@ -29,7 +29,7 @@ describe('esm', () => { it('is instrumented', async () => { const res = agent.assertMessageReceived(({ headers, payload }) => { - assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.strictEqual(headers.host, `127.0.0.1:${agent.port}`) assert.ok(Array.isArray(payload)) assert.strictEqual(checkSpansForServiceName(payload, 'aws.request'), true) }) diff --git a/packages/datadog-plugin-axios/test/integration-test/client.spec.js b/packages/datadog-plugin-axios/test/integration-test/client.spec.js index 21b235ce7f3..b23af4f0aa9 100644 --- a/packages/datadog-plugin-axios/test/integration-test/client.spec.js +++ b/packages/datadog-plugin-axios/test/integration-test/client.spec.js @@ -28,7 +28,7 @@ describe('esm', () => { context('axios', () => { it('is instrumented', async () => { const res = agent.assertMessageReceived(({ headers, payload }) => { - assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.strictEqual(headers.host, `127.0.0.1:${agent.port}`) assert.ok(Array.isArray(payload)) assert.strictEqual(checkSpansForServiceName(payload, 'http.request'), true) }) diff --git a/packages/datadog-plugin-azure-event-hubs/test/integration-test/client.spec.js b/packages/datadog-plugin-azure-event-hubs/test/integration-test/client.spec.js index 340b3152b06..732dfe93c66 100644 --- a/packages/datadog-plugin-azure-event-hubs/test/integration-test/client.spec.js +++ b/packages/datadog-plugin-azure-event-hubs/test/integration-test/client.spec.js @@ -35,7 +35,7 @@ describe.skip('esm', () => { it('is instrumented', async () => { const res = agent.assertMessageReceived(({ headers, payload }) => { - assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.strictEqual(headers.host, `127.0.0.1:${agent.port}`) assert.ok(Array.isArray(payload)) assert.strictEqual(checkSpansForServiceName(payload, 'azure.eventhubs.send'), true) }) diff --git a/packages/datadog-plugin-azure-functions/test/integration-test/http-test/client.spec.js b/packages/datadog-plugin-azure-functions/test/integration-test/http-test/client.spec.js index 21356733584..8d7ee02899b 100644 --- a/packages/datadog-plugin-azure-functions/test/integration-test/http-test/client.spec.js +++ b/packages/datadog-plugin-azure-functions/test/integration-test/http-test/client.spec.js @@ -48,12 +48,12 @@ describe('esm', () => { proc = await spawnPluginIntegrationTestProc(sandboxCwd(), 'func', ['start'], agent.port, undefined, envArgs) return curlAndAssertMessage(agent, 'http://127.0.0.1:7071/api/httptest', ({ headers, payload }) => { - assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.strictEqual(headers.host, `127.0.0.1:${agent.port}`) assert.ok(Array.isArray(payload)) assert.strictEqual(payload.length, 1) assert.ok(Array.isArray(payload[0])) assert.strictEqual(payload[0].length, 1) - assert.strictEqual(payload[0][0]['name'], 'azure.functions.invoke') + assert.strictEqual(payload[0][0].name, 'azure.functions.invoke') }) }).timeout(60_000) diff --git a/packages/datadog-plugin-azure-service-bus/test/integration-test/client.spec.js b/packages/datadog-plugin-azure-service-bus/test/integration-test/client.spec.js index de517d2b785..b11f370c444 100644 --- a/packages/datadog-plugin-azure-service-bus/test/integration-test/client.spec.js +++ b/packages/datadog-plugin-azure-service-bus/test/integration-test/client.spec.js @@ -31,7 +31,7 @@ describe('esm', () => { it('is instrumented', async () => { const res = agent.assertMessageReceived(({ headers, payload }) => { - assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.strictEqual(headers.host, `127.0.0.1:${agent.port}`) assert.ok(Array.isArray(payload)) }) diff --git a/packages/datadog-plugin-cassandra-driver/test/integration-test/client.spec.js b/packages/datadog-plugin-cassandra-driver/test/integration-test/client.spec.js index de7c3474b2d..c90a4715707 100644 --- a/packages/datadog-plugin-cassandra-driver/test/integration-test/client.spec.js +++ b/packages/datadog-plugin-cassandra-driver/test/integration-test/client.spec.js @@ -37,7 +37,7 @@ describe('esm', () => { for (const variant of varySandbox.VARIANTS) { it(`is instrumented loaded with ${variant}`, async () => { const res = agent.assertMessageReceived(({ headers, payload }) => { - assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.strictEqual(headers.host, `127.0.0.1:${agent.port}`) assert.ok(Array.isArray(payload)) assert.strictEqual(checkSpansForServiceName(payload, 'cassandra.query'), true) }) diff --git a/packages/datadog-plugin-child_process/test/index.spec.js b/packages/datadog-plugin-child_process/test/index.spec.js index 2450ff341c6..403c5b362b7 100644 --- a/packages/datadog-plugin-child_process/test/index.spec.js +++ b/packages/datadog-plugin-child_process/test/index.spec.js @@ -55,7 +55,7 @@ describe('Child process plugin', () => { shellPlugin.start({ command: 'ls -l' }) - sinon.assert.calledOnceWithExactly(tracerStub.startSpan, + sinon.assert.calledOnceWithExactly(tracerStub.startSpan, 'command_execution', { startTime: undefined, @@ -79,7 +79,7 @@ describe('Child process plugin', () => { shellPlugin.start({ command: 'ls -l', shell: true }) - sinon.assert.calledOnceWithExactly(tracerStub.startSpan, + sinon.assert.calledOnceWithExactly(tracerStub.startSpan, 'command_execution', { startTime: undefined, @@ -105,7 +105,7 @@ describe('Child process plugin', () => { shellPlugin.start({ command }) - sinon.assert.calledOnceWithExactly(tracerStub.startSpan, + sinon.assert.calledOnceWithExactly(tracerStub.startSpan, 'command_execution', { startTime: undefined, @@ -132,7 +132,7 @@ describe('Child process plugin', () => { shellPlugin.start({ command, shell: true }) - sinon.assert.calledOnceWithExactly(tracerStub.startSpan, + sinon.assert.calledOnceWithExactly(tracerStub.startSpan, 'command_execution', { startTime: undefined, @@ -160,7 +160,7 @@ describe('Child process plugin', () => { shellPlugin.start({ command }) - sinon.assert.calledOnceWithExactly(tracerStub.startSpan, + sinon.assert.calledOnceWithExactly(tracerStub.startSpan, 'command_execution', { startTime: undefined, @@ -188,7 +188,7 @@ describe('Child process plugin', () => { shellPlugin.start({ command, shell: true }) - sinon.assert.calledOnceWithExactly(tracerStub.startSpan, + sinon.assert.calledOnceWithExactly(tracerStub.startSpan, 'command_execution', { startTime: undefined, diff --git a/packages/datadog-plugin-child_process/test/scrub-cmd-params.spec.js b/packages/datadog-plugin-child_process/test/scrub-cmd-params.spec.js index 639990e0561..b11f11de942 100644 --- a/packages/datadog-plugin-child_process/test/scrub-cmd-params.spec.js +++ b/packages/datadog-plugin-child_process/test/scrub-cmd-params.spec.js @@ -48,21 +48,21 @@ describe('scrub cmds', () => { assert.deepStrictEqual(scrubCmdParams('md5 -s pony'), ['md5', '?', '?']) assert.deepStrictEqual(scrubCmdParams('cat passwords.txt | while read line; do; md5 -s $line; done'), [ - 'cat', - 'passwords.txt', - '|', - 'while', - 'read', - 'line', - ';', - 'do', - ';', - 'md5', - '?', - '?', - ';', - 'done' - ]) + 'cat', + 'passwords.txt', + '|', + 'while', + 'read', + 'line', + ';', + 'do', + ';', + 'md5', + '?', + '?', + ';', + 'done' + ]) }) it('should scrub shell expressions', () => { diff --git a/packages/datadog-plugin-confluentinc-kafka-javascript/test/integration-test/client.spec.js b/packages/datadog-plugin-confluentinc-kafka-javascript/test/integration-test/client.spec.js index 5a9ecfcf1bb..b42f02978cd 100644 --- a/packages/datadog-plugin-confluentinc-kafka-javascript/test/integration-test/client.spec.js +++ b/packages/datadog-plugin-confluentinc-kafka-javascript/test/integration-test/client.spec.js @@ -29,7 +29,7 @@ describe('esm', () => { it('is instrumented', async () => { const res = agent.assertMessageReceived(({ headers, payload }) => { - assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.strictEqual(headers.host, `127.0.0.1:${agent.port}`) assert.ok(Array.isArray(payload)) assert.strictEqual(checkSpansForServiceName(payload, 'kafka.produce'), true) }) diff --git a/packages/datadog-plugin-connect/test/integration-test/client.spec.js b/packages/datadog-plugin-connect/test/integration-test/client.spec.js index 6e9eea7aa30..2dc0166fa7b 100644 --- a/packages/datadog-plugin-connect/test/integration-test/client.spec.js +++ b/packages/datadog-plugin-connect/test/integration-test/client.spec.js @@ -39,7 +39,7 @@ describe('esm', () => { proc = await spawnPluginIntegrationTestProc(sandboxCwd(), variants[variant], agent.port) return curlAndAssertMessage(agent, proc, ({ headers, payload }) => { - assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.strictEqual(headers.host, `127.0.0.1:${agent.port}`) assert.ok(Array.isArray(payload)) assert.strictEqual(checkSpansForServiceName(payload, 'connect.request'), true) }) diff --git a/packages/datadog-plugin-couchbase/test/integration-test/client.spec.js b/packages/datadog-plugin-couchbase/test/integration-test/client.spec.js index 9ad470df3f4..c1c1117b780 100644 --- a/packages/datadog-plugin-couchbase/test/integration-test/client.spec.js +++ b/packages/datadog-plugin-couchbase/test/integration-test/client.spec.js @@ -30,7 +30,7 @@ describe('esm', () => { it('is instrumented', async () => { const res = agent.assertMessageReceived(({ headers, payload }) => { - assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.strictEqual(headers.host, `127.0.0.1:${agent.port}`) assert.ok(Array.isArray(payload)) assert.strictEqual(checkSpansForServiceName(payload, 'couchbase.upsert'), true) }) diff --git a/packages/datadog-plugin-dns/test/integration-test/client.spec.js b/packages/datadog-plugin-dns/test/integration-test/client.spec.js index fe794560831..d71c56c47aa 100644 --- a/packages/datadog-plugin-dns/test/integration-test/client.spec.js +++ b/packages/datadog-plugin-dns/test/integration-test/client.spec.js @@ -35,7 +35,7 @@ describe('esm', () => { for (const variant of varySandbox.VARIANTS) { it(`is instrumented loaded with ${variant}`, async () => { const res = agent.assertMessageReceived(({ headers, payload }) => { - assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.strictEqual(headers.host, `127.0.0.1:${agent.port}`) assert.ok(Array.isArray(payload)) assert.strictEqual(checkSpansForServiceName(payload, 'dns.lookup'), true) assert.strictEqual(payload[0][0].resource, 'fakedomain.faketld') diff --git a/packages/datadog-plugin-elasticsearch/test/index.spec.js b/packages/datadog-plugin-elasticsearch/test/index.spec.js index a867dc8bed0..3852086de33 100644 --- a/packages/datadog-plugin-elasticsearch/test/index.spec.js +++ b/packages/datadog-plugin-elasticsearch/test/index.spec.js @@ -94,8 +94,8 @@ describe('Plugin', () => { assert.strictEqual(traces[0][0].meta['elasticsearch.body'], '{"query":{"match_all":{}}}') assert.strictEqual(traces[0][0].meta['elasticsearch.params'], '{"sort":"name","size":100}') } else { - assert.ok('elasticsearch.body' in traces[0][0].meta); - assert.strictEqual(traces[0][0].meta['elasticsearch.body'], '{"query":{"match_all":{}},"sort":"name","size":100}') + assert.ok('elasticsearch.body' in traces[0][0].meta) + assert.strictEqual(traces[0][0].meta['elasticsearch.body'], '{"query":{"match_all":{}},"sort":"name","size":100}') } }) .then(done) @@ -123,8 +123,8 @@ describe('Plugin', () => { assert.strictEqual(traces[0][0].meta['span.kind'], 'client') assert.strictEqual(traces[0][0].meta['elasticsearch.method'], 'POST') assert.strictEqual(traces[0][0].meta['elasticsearch.url'], '/_msearch') - assert.ok('elasticsearch.body' in traces[0][0].meta); - assert.strictEqual(traces[0][0].meta['elasticsearch.body'], '[{"index":"docs"},{"query":{"match_all":{}}},{"index":"docs2"},{"query":{"match_all":{}}}]') + assert.ok('elasticsearch.body' in traces[0][0].meta) + assert.strictEqual(traces[0][0].meta['elasticsearch.body'], '[{"index":"docs"},{"query":{"match_all":{}}},{"index":"docs2"},{"query":{"match_all":{}}}]') }) .then(done) .catch(done) diff --git a/packages/datadog-plugin-elasticsearch/test/integration-test/client.spec.js b/packages/datadog-plugin-elasticsearch/test/integration-test/client.spec.js index 467bd282963..9722e89a3c8 100644 --- a/packages/datadog-plugin-elasticsearch/test/integration-test/client.spec.js +++ b/packages/datadog-plugin-elasticsearch/test/integration-test/client.spec.js @@ -36,7 +36,7 @@ describe('esm', () => { for (const variant of varySandbox.VARIANTS) { it(`is instrumented loaded with ${variant}`, async () => { const res = agent.assertMessageReceived(({ headers, payload }) => { - assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.strictEqual(headers.host, `127.0.0.1:${agent.port}`) assert.ok(Array.isArray(payload)) assert.strictEqual(checkSpansForServiceName(payload, 'elasticsearch.query'), true) }) diff --git a/packages/datadog-plugin-express/test/integration-test/client.spec.js b/packages/datadog-plugin-express/test/integration-test/client.spec.js index 683733cee7d..94b862c2e16 100644 --- a/packages/datadog-plugin-express/test/integration-test/client.spec.js +++ b/packages/datadog-plugin-express/test/integration-test/client.spec.js @@ -44,13 +44,13 @@ describe('esm', () => { : 'router' return curlAndAssertMessage(agent, proc, ({ headers, payload }) => { - assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.strictEqual(headers.host, `127.0.0.1:${agent.port}`) assert.ok(Array.isArray(payload)) assert.strictEqual(payload.length, 1) assert.ok(Array.isArray(payload[0])) assert.strictEqual(payload[0].length, numberOfSpans) - assert.strictEqual(payload[0][0]['name'], 'express.request') - assert.strictEqual(payload[0][1]['name'], `${whichMiddleware}.middleware`) + assert.strictEqual(payload[0][0].name, 'express.request') + assert.strictEqual(payload[0][1].name, `${whichMiddleware}.middleware`) }) }).timeout(50000) }) @@ -69,12 +69,12 @@ describe('esm', () => { const numberOfSpans = 1 return curlAndAssertMessage(agent, proc, ({ headers, payload }) => { - assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.strictEqual(headers.host, `127.0.0.1:${agent.port}`) assert.ok(Array.isArray(payload)) assert.strictEqual(payload.length, 1) assert.ok(Array.isArray(payload[0])) assert.strictEqual(payload[0].length, numberOfSpans) - assert.strictEqual(payload[0][0]['name'], 'express.request') + assert.strictEqual(payload[0][0].name, 'express.request') }) }).timeout(50000) }) diff --git a/packages/datadog-plugin-fastify/test/integration-test/client.spec.js b/packages/datadog-plugin-fastify/test/integration-test/client.spec.js index c1e3e4b3eb5..1fc95ca22d0 100644 --- a/packages/datadog-plugin-fastify/test/integration-test/client.spec.js +++ b/packages/datadog-plugin-fastify/test/integration-test/client.spec.js @@ -35,7 +35,7 @@ describe('esm', () => { proc = await spawnPluginIntegrationTestProc(__dirname, 'server.mjs', agent.port, env) return curlAndAssertMessage(agent, proc, ({ headers, payload }) => { - assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.strictEqual(headers.host, `127.0.0.1:${agent.port}`) assert.ok(Array.isArray(payload)) assert.strictEqual(checkSpansForServiceName(payload, 'fastify.request'), true) }) @@ -45,7 +45,7 @@ describe('esm', () => { proc = await spawnPluginIntegrationTestProc(__dirname, 'server1.mjs', agent.port, env) return curlAndAssertMessage(agent, proc, ({ headers, payload }) => { - assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.strictEqual(headers.host, `127.0.0.1:${agent.port}`) assert.ok(Array.isArray(payload)) assert.strictEqual(checkSpansForServiceName(payload, 'fastify.request'), true) }) @@ -55,7 +55,7 @@ describe('esm', () => { proc = await spawnPluginIntegrationTestProc(__dirname, 'server2.mjs', agent.port, env) return curlAndAssertMessage(agent, proc, ({ headers, payload }) => { - assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.strictEqual(headers.host, `127.0.0.1:${agent.port}`) assert.ok(Array.isArray(payload)) assert.strictEqual(checkSpansForServiceName(payload, 'fastify.request'), true) }) diff --git a/packages/datadog-plugin-fetch/test/integration-test/client.spec.js b/packages/datadog-plugin-fetch/test/integration-test/client.spec.js index 095b711eecf..ea32c88004b 100644 --- a/packages/datadog-plugin-fetch/test/integration-test/client.spec.js +++ b/packages/datadog-plugin-fetch/test/integration-test/client.spec.js @@ -29,7 +29,7 @@ describe('esm', () => { context('fetch', () => { it('is instrumented', async () => { const res = agent.assertMessageReceived(({ headers, payload }) => { - assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.strictEqual(headers.host, `127.0.0.1:${agent.port}`) assert.ok(Array.isArray(payload)) const isFetch = payload.some((span) => span.some((nestedSpan) => nestedSpan.meta.component === 'fetch')) assert.strictEqual(isFetch, true) diff --git a/packages/datadog-plugin-google-cloud-pubsub/test/integration-test/client.spec.js b/packages/datadog-plugin-google-cloud-pubsub/test/integration-test/client.spec.js index 2b84c9eb5d5..e14e690f1a9 100644 --- a/packages/datadog-plugin-google-cloud-pubsub/test/integration-test/client.spec.js +++ b/packages/datadog-plugin-google-cloud-pubsub/test/integration-test/client.spec.js @@ -29,7 +29,7 @@ describe('esm', () => { it('is instrumented', async () => { const res = agent.assertMessageReceived(({ headers, payload }) => { - assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.strictEqual(headers.host, `127.0.0.1:${agent.port}`) assert.ok(Array.isArray(payload)) assert.strictEqual(checkSpansForServiceName(payload, 'pubsub.request'), true) }) diff --git a/packages/datadog-plugin-google-cloud-vertexai/test/integration-test/client.spec.js b/packages/datadog-plugin-google-cloud-vertexai/test/integration-test/client.spec.js index cacb17f84dc..da6ff54d906 100644 --- a/packages/datadog-plugin-google-cloud-vertexai/test/integration-test/client.spec.js +++ b/packages/datadog-plugin-google-cloud-vertexai/test/integration-test/client.spec.js @@ -33,7 +33,7 @@ describe('esm', () => { it('is instrumented', async () => { const res = agent.assertMessageReceived(({ headers, payload }) => { - assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.strictEqual(headers.host, `127.0.0.1:${agent.port}`) assert.ok(Array.isArray(payload)) assert.strictEqual(checkSpansForServiceName(payload, 'vertexai.request'), true) }) diff --git a/packages/datadog-plugin-graphql/test/esm-test/esm.spec.js b/packages/datadog-plugin-graphql/test/esm-test/esm.spec.js index 127c6a43cbd..dc3dafcc8de 100644 --- a/packages/datadog-plugin-graphql/test/esm-test/esm.spec.js +++ b/packages/datadog-plugin-graphql/test/esm-test/esm.spec.js @@ -33,7 +33,7 @@ describe('Plugin (ESM)', () => { it('should instrument GraphQL execution with ESM', async () => { const res = agent.assertMessageReceived(({ headers, payload }) => { - assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.strictEqual(headers.host, `127.0.0.1:${agent.port}`) assert.ok(Array.isArray(payload)) assert.strictEqual(checkSpansForServiceName(payload, 'graphql.execute'), true) }) @@ -72,7 +72,7 @@ describe('Plugin (ESM)', () => { if (coercedVersion && semver.gte(coercedVersion, '15.0.0')) { it('should instrument GraphQL Yoga execution with ESM', async () => { const res = agent.assertMessageReceived(({ headers, payload }) => { - assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.strictEqual(headers.host, `127.0.0.1:${agent.port}`) assert.ok(Array.isArray(payload)) assert.strictEqual(checkSpansForServiceName(payload, 'graphql.execute'), true) }) diff --git a/packages/datadog-plugin-graphql/test/index.spec.js b/packages/datadog-plugin-graphql/test/index.spec.js index 9f6062d4bf2..759f106dad8 100644 --- a/packages/datadog-plugin-graphql/test/index.spec.js +++ b/packages/datadog-plugin-graphql/test/index.spec.js @@ -1508,8 +1508,8 @@ describe('Plugin', () => { try { assert.notStrictEqual(span, null) - assert.ok('_name' in span.context()); - assert.strictEqual(span.context()['_name'], expectedSchema.server.opName) + assert.ok('_name' in span.context()) + assert.strictEqual(span.context()._name, expectedSchema.server.opName) done() } catch (e) { done(e) diff --git a/packages/datadog-plugin-graphql/test/integration-test/client.spec.js b/packages/datadog-plugin-graphql/test/integration-test/client.spec.js index 291eb800f7e..9a6ffcabf18 100644 --- a/packages/datadog-plugin-graphql/test/integration-test/client.spec.js +++ b/packages/datadog-plugin-graphql/test/integration-test/client.spec.js @@ -29,7 +29,7 @@ describe('esm', () => { it('is instrumented', async () => { const res = agent.assertMessageReceived(({ headers, payload }) => { - assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.strictEqual(headers.host, `127.0.0.1:${agent.port}`) assert.ok(Array.isArray(payload)) assert.strictEqual(checkSpansForServiceName(payload, 'graphql.parse'), true) }) diff --git a/packages/datadog-plugin-grpc/test/integration-test/client.spec.js b/packages/datadog-plugin-grpc/test/integration-test/client.spec.js index ee94c5811b1..81202693cd6 100644 --- a/packages/datadog-plugin-grpc/test/integration-test/client.spec.js +++ b/packages/datadog-plugin-grpc/test/integration-test/client.spec.js @@ -31,7 +31,7 @@ describe('esm', () => { it('is instrumented', async () => { const res = agent.assertMessageReceived(({ headers, payload }) => { - assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.strictEqual(headers.host, `127.0.0.1:${agent.port}`) assert.ok(Array.isArray(payload)) assert.strictEqual(checkSpansForServiceName(payload, 'grpc.client'), true) }) diff --git a/packages/datadog-plugin-grpc/test/server.spec.js b/packages/datadog-plugin-grpc/test/server.spec.js index 1921af05727..ec17b0601a8 100644 --- a/packages/datadog-plugin-grpc/test/server.spec.js +++ b/packages/datadog-plugin-grpc/test/server.spec.js @@ -490,8 +490,8 @@ describe('Plugin', () => { callback(null, {}) try { - assert.ok('foo' in call.metadata.getMap()); - assert.strictEqual(call.metadata.getMap()['foo'], 'bar') + assert.ok('foo' in call.metadata.getMap()) + assert.strictEqual(call.metadata.getMap().foo, 'bar') done() } catch (e) { done(e) diff --git a/packages/datadog-plugin-http/test/integration-test/client.spec.js b/packages/datadog-plugin-http/test/integration-test/client.spec.js index 35bd1b714aa..6d53998c554 100644 --- a/packages/datadog-plugin-http/test/integration-test/client.spec.js +++ b/packages/datadog-plugin-http/test/integration-test/client.spec.js @@ -30,12 +30,12 @@ describe('esm', () => { proc = await spawnPluginIntegrationTestProc(sandboxCwd(), 'server.mjs', agent.port) return curlAndAssertMessage(agent, proc, ({ headers, payload }) => { - assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.strictEqual(headers.host, `127.0.0.1:${agent.port}`) assert.ok(Array.isArray(payload)) assert.strictEqual(payload.length, 1) assert.ok(Array.isArray(payload[0])) assert.strictEqual(payload[0].length, 1) - assert.strictEqual(payload[0][0]['name'], 'web.request') + assert.strictEqual(payload[0][0].name, 'web.request') }) }).timeout(20000) }) diff --git a/packages/datadog-plugin-http2/test/integration-test/client.spec.js b/packages/datadog-plugin-http2/test/integration-test/client.spec.js index 150b5bff9d9..0b41aef9303 100644 --- a/packages/datadog-plugin-http2/test/integration-test/client.spec.js +++ b/packages/datadog-plugin-http2/test/integration-test/client.spec.js @@ -37,13 +37,13 @@ describe('esm', () => { it(`is instrumented loaded with ${variant}`, async () => { proc = await spawnPluginIntegrationTestProc(sandboxCwd(), variants[variant], agent.port) const resultPromise = agent.assertMessageReceived(({ headers, payload }) => { - assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.strictEqual(headers.host, `127.0.0.1:${agent.port}`) assert.ok(Array.isArray(payload)) assert.strictEqual(payload.length, 1) assert.ok(Array.isArray(payload[0])) assert.strictEqual(payload[0].length, 1) - assert.strictEqual(payload[0][0]['name'], 'web.request') - assert.strictEqual(payload[0][0].meta['component'], 'http2') + assert.strictEqual(payload[0][0].name, 'web.request') + assert.strictEqual(payload[0][0].meta.component, 'http2') }) await curl(proc) return resultPromise diff --git a/packages/datadog-plugin-ioredis/test/integration-test/client.spec.js b/packages/datadog-plugin-ioredis/test/integration-test/client.spec.js index abe4c76e95f..22d61933548 100644 --- a/packages/datadog-plugin-ioredis/test/integration-test/client.spec.js +++ b/packages/datadog-plugin-ioredis/test/integration-test/client.spec.js @@ -35,7 +35,7 @@ describe('esm', () => { for (const variant of varySandbox.VARIANTS) { it(`is instrumented loaded with ${variant}`, async () => { const res = agent.assertMessageReceived(({ headers, payload }) => { - assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.strictEqual(headers.host, `127.0.0.1:${agent.port}`) assert.ok(Array.isArray(payload)) assert.strictEqual(checkSpansForServiceName(payload, 'redis.command'), true) }) diff --git a/packages/datadog-plugin-iovalkey/test/integration-test/client.spec.js b/packages/datadog-plugin-iovalkey/test/integration-test/client.spec.js index 5a214d2a9a0..2d3d690b634 100644 --- a/packages/datadog-plugin-iovalkey/test/integration-test/client.spec.js +++ b/packages/datadog-plugin-iovalkey/test/integration-test/client.spec.js @@ -29,7 +29,7 @@ describe('esm', () => { it('is instrumented', async () => { const res = agent.assertMessageReceived(({ headers, payload }) => { - assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.strictEqual(headers.host, `127.0.0.1:${agent.port}`) assert.ok(Array.isArray(payload)) assert.strictEqual(checkSpansForServiceName(payload, 'valkey.command'), true) }) diff --git a/packages/datadog-plugin-kafkajs/test/integration-test/client.spec.js b/packages/datadog-plugin-kafkajs/test/integration-test/client.spec.js index 4470aae6a2e..414af65f963 100644 --- a/packages/datadog-plugin-kafkajs/test/integration-test/client.spec.js +++ b/packages/datadog-plugin-kafkajs/test/integration-test/client.spec.js @@ -29,7 +29,7 @@ describe('esm', () => { it('is instrumented', async () => { const res = agent.assertMessageReceived(({ headers, payload }) => { - assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.strictEqual(headers.host, `127.0.0.1:${agent.port}`) assert.ok(Array.isArray(payload)) assert.strictEqual(checkSpansForServiceName(payload, 'kafka.produce'), true) }) diff --git a/packages/datadog-plugin-koa/test/index.spec.js b/packages/datadog-plugin-koa/test/index.spec.js index 892f1c32e08..157a8d4ffad 100644 --- a/packages/datadog-plugin-koa/test/index.spec.js +++ b/packages/datadog-plugin-koa/test/index.spec.js @@ -520,8 +520,8 @@ describe('Plugin', () => { const spans = sort(traces[0]) assert.strictEqual(spans[0].resource, 'GET /forums/:fid/discussions/:did/posts/:pid') - assert.ok('http.url' in spans[0].meta); - assert.strictEqual(spans[0].meta['http.url'], `http://localhost:${port}/forums/123/discussions/456/posts/789`) + assert.ok('http.url' in spans[0].meta) + assert.strictEqual(spans[0].meta['http.url'], `http://localhost:${port}/forums/123/discussions/456/posts/789`) }) .then(done) .catch(done) @@ -557,8 +557,8 @@ describe('Plugin', () => { const spans = sort(traces[0]) assert.strictEqual(spans[0].resource, 'GET /first/child') - assert.ok('http.url' in spans[0].meta); - assert.strictEqual(spans[0].meta['http.url'], `http://localhost:${port}/first/child`) + assert.ok('http.url' in spans[0].meta) + assert.strictEqual(spans[0].meta['http.url'], `http://localhost:${port}/first/child`) }) .then(done) .catch(done) diff --git a/packages/datadog-plugin-koa/test/integration-test/client.spec.js b/packages/datadog-plugin-koa/test/integration-test/client.spec.js index 41286fd8f24..8a1d99a3435 100644 --- a/packages/datadog-plugin-koa/test/integration-test/client.spec.js +++ b/packages/datadog-plugin-koa/test/integration-test/client.spec.js @@ -32,7 +32,7 @@ describe('esm', () => { proc = await spawnPluginIntegrationTestProc(sandboxCwd(), 'server.mjs', agent.port) return curlAndAssertMessage(agent, proc, ({ headers, payload }) => { - assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.strictEqual(headers.host, `127.0.0.1:${agent.port}`) assert.ok(Array.isArray(payload)) assert.strictEqual(checkSpansForServiceName(payload, 'koa.request'), true) }) diff --git a/packages/datadog-plugin-langchain/test/integration-test/client.spec.js b/packages/datadog-plugin-langchain/test/integration-test/client.spec.js index 18707d16955..d40dd2224a8 100644 --- a/packages/datadog-plugin-langchain/test/integration-test/client.spec.js +++ b/packages/datadog-plugin-langchain/test/integration-test/client.spec.js @@ -34,7 +34,7 @@ describe('esm', () => { it('is instrumented', async () => { const res = agent.assertMessageReceived(({ headers, payload }) => { - assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.strictEqual(headers.host, `127.0.0.1:${agent.port}`) assert.ok(Array.isArray(payload)) assert.strictEqual(checkSpansForServiceName(payload, 'langchain.request'), true) }) diff --git a/packages/datadog-plugin-limitd-client/test/integration-test/client.spec.js b/packages/datadog-plugin-limitd-client/test/integration-test/client.spec.js index 13e59731211..8cf16cb57d4 100644 --- a/packages/datadog-plugin-limitd-client/test/integration-test/client.spec.js +++ b/packages/datadog-plugin-limitd-client/test/integration-test/client.spec.js @@ -35,7 +35,7 @@ describe('esm', () => { for (const variant of varySandbox.VARIANTS) { it(`is instrumented loaded with ${variant}`, async () => { const res = agent.assertMessageReceived(({ headers, payload }) => { - assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.strictEqual(headers.host, `127.0.0.1:${agent.port}`) assert.ok(Array.isArray(payload)) // not asserting for a limitd-client trace, // just asserting that we're not completely breaking when loading limitd-client with esm diff --git a/packages/datadog-plugin-mariadb/test/integration-test/client.spec.js b/packages/datadog-plugin-mariadb/test/integration-test/client.spec.js index e73f9cca684..ae4bae994e1 100644 --- a/packages/datadog-plugin-mariadb/test/integration-test/client.spec.js +++ b/packages/datadog-plugin-mariadb/test/integration-test/client.spec.js @@ -30,7 +30,7 @@ describe('esm', () => { it('is instrumented', async () => { const res = agent.assertMessageReceived(({ headers, payload }) => { - assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.strictEqual(headers.host, `127.0.0.1:${agent.port}`) assert.ok(Array.isArray(payload)) assert.strictEqual(checkSpansForServiceName(payload, 'mariadb.query'), true) }) diff --git a/packages/datadog-plugin-memcached/test/integration-test/client.spec.js b/packages/datadog-plugin-memcached/test/integration-test/client.spec.js index 3eb8985d089..b0db3cede08 100644 --- a/packages/datadog-plugin-memcached/test/integration-test/client.spec.js +++ b/packages/datadog-plugin-memcached/test/integration-test/client.spec.js @@ -29,7 +29,7 @@ describe('esm', () => { it('is instrumented', async () => { const res = agent.assertMessageReceived(({ headers, payload }) => { - assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.strictEqual(headers.host, `127.0.0.1:${agent.port}`) assert.ok(Array.isArray(payload)) assert.strictEqual(checkSpansForServiceName(payload, 'memcached.command'), true) }) diff --git a/packages/datadog-plugin-microgateway-core/test/integration-test/client.spec.js b/packages/datadog-plugin-microgateway-core/test/integration-test/client.spec.js index 4db1442ec38..2a978f046f4 100644 --- a/packages/datadog-plugin-microgateway-core/test/integration-test/client.spec.js +++ b/packages/datadog-plugin-microgateway-core/test/integration-test/client.spec.js @@ -33,7 +33,7 @@ describe('esm', () => { proc = await spawnPluginIntegrationTestProc(sandboxCwd(), 'server.mjs', agent.port) return curlAndAssertMessage(agent, proc, ({ headers, payload }) => { - assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.strictEqual(headers.host, `127.0.0.1:${agent.port}`) assert.ok(Array.isArray(payload)) assert.strictEqual(checkSpansForServiceName(payload, 'microgateway.request'), true) }) diff --git a/packages/datadog-plugin-moleculer/test/integration-test/client.spec.js b/packages/datadog-plugin-moleculer/test/integration-test/client.spec.js index 44a50884c3e..8314dbc0a6b 100644 --- a/packages/datadog-plugin-moleculer/test/integration-test/client.spec.js +++ b/packages/datadog-plugin-moleculer/test/integration-test/client.spec.js @@ -30,7 +30,7 @@ describe('esm', () => { it('is instrumented', async () => { const res = agent.assertMessageReceived(({ headers, payload }) => { - assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.strictEqual(headers.host, `127.0.0.1:${agent.port}`) assert.ok(Array.isArray(payload)) assert.strictEqual(checkSpansForServiceName(payload, 'moleculer.action'), true) }) diff --git a/packages/datadog-plugin-mongodb-core/test/integration-test/client.spec.js b/packages/datadog-plugin-mongodb-core/test/integration-test/client.spec.js index 26b07127277..49a3236874a 100644 --- a/packages/datadog-plugin-mongodb-core/test/integration-test/client.spec.js +++ b/packages/datadog-plugin-mongodb-core/test/integration-test/client.spec.js @@ -36,7 +36,7 @@ describe('esm', () => { for (const variant of varySandbox.VARIANTS) { it(`is instrumented loaded with ${variant}`, async () => { const res = agent.assertMessageReceived(({ headers, payload }) => { - assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.strictEqual(headers.host, `127.0.0.1:${agent.port}`) assert.ok(Array.isArray(payload)) assert.strictEqual(checkSpansForServiceName(payload, 'mongodb.query'), true) }) @@ -69,7 +69,7 @@ describe('esm', () => { for (const variant of varySandbox.VARIANTS) { it(`is instrumented loaded with ${variant}`, async () => { const res = agent.assertMessageReceived(({ headers, payload }) => { - assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.strictEqual(headers.host, `127.0.0.1:${agent.port}`) assert.ok(Array.isArray(payload)) assert.strictEqual(checkSpansForServiceName(payload, 'mongodb.query'), true) }) diff --git a/packages/datadog-plugin-mongoose/test/integration-test/client.spec.js b/packages/datadog-plugin-mongoose/test/integration-test/client.spec.js index 223124011b9..3b17b7c811e 100644 --- a/packages/datadog-plugin-mongoose/test/integration-test/client.spec.js +++ b/packages/datadog-plugin-mongoose/test/integration-test/client.spec.js @@ -35,7 +35,7 @@ describe('esm', () => { for (const variant of varySandbox.VARIANTS) { it(`is instrumented loaded with ${variant}`, async () => { const res = agent.assertMessageReceived(({ headers, payload }) => { - assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.strictEqual(headers.host, `127.0.0.1:${agent.port}`) assert.ok(Array.isArray(payload)) assert.strictEqual(checkSpansForServiceName(payload, 'mongodb.query'), true) }) diff --git a/packages/datadog-plugin-mysql/test/integration-test/client.spec.js b/packages/datadog-plugin-mysql/test/integration-test/client.spec.js index 03e8b539449..902f900b848 100644 --- a/packages/datadog-plugin-mysql/test/integration-test/client.spec.js +++ b/packages/datadog-plugin-mysql/test/integration-test/client.spec.js @@ -36,7 +36,7 @@ describe('esm', () => { for (const variant of varySandbox.VARIANTS) { it(`is instrumented loaded with ${variant}`, async () => { const res = agent.assertMessageReceived(({ headers, payload }) => { - assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.strictEqual(headers.host, `127.0.0.1:${agent.port}`) assert.ok(Array.isArray(payload)) assert.strictEqual(checkSpansForServiceName(payload, 'mysql.query'), true) }) diff --git a/packages/datadog-plugin-mysql2/test/integration-test/client.spec.js b/packages/datadog-plugin-mysql2/test/integration-test/client.spec.js index b1ffa891036..8672e2fd572 100644 --- a/packages/datadog-plugin-mysql2/test/integration-test/client.spec.js +++ b/packages/datadog-plugin-mysql2/test/integration-test/client.spec.js @@ -29,7 +29,7 @@ describe('esm', () => { it('is instrumented', async () => { const res = agent.assertMessageReceived(({ headers, payload }) => { - assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.strictEqual(headers.host, `127.0.0.1:${agent.port}`) assert.ok(Array.isArray(payload)) assert.strictEqual(checkSpansForServiceName(payload, 'mysql.query'), true) }) diff --git a/packages/datadog-plugin-net/test/integration-test/client.spec.js b/packages/datadog-plugin-net/test/integration-test/client.spec.js index 79a3c522791..b8e3b9c3ff6 100644 --- a/packages/datadog-plugin-net/test/integration-test/client.spec.js +++ b/packages/datadog-plugin-net/test/integration-test/client.spec.js @@ -35,7 +35,7 @@ describe('esm', () => { for (const variant of varySandbox.VARIANTS) { it(`is instrumented loaded with ${variant}`, async () => { const res = agent.assertMessageReceived(({ headers, payload }) => { - assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.strictEqual(headers.host, `127.0.0.1:${agent.port}`) assert.ok(Array.isArray(payload)) assert.strictEqual(checkSpansForServiceName(payload, 'tcp.connect'), true) const metaContainsNet = payload.some((span) => span.some((nestedSpan) => nestedSpan.meta.component === 'net')) diff --git a/packages/datadog-plugin-openai/test/index.spec.js b/packages/datadog-plugin-openai/test/index.spec.js index 479d90224e5..522edff7568 100644 --- a/packages/datadog-plugin-openai/test/index.spec.js +++ b/packages/datadog-plugin-openai/test/index.spec.js @@ -236,8 +236,8 @@ describe('Plugin', () => { } assert.strictEqual(traces[0][0].error, 0) assert.strictEqual(traces[0][0].meta['openai.request.method'], 'POST') - assert.ok('openai.request.endpoint' in traces[0][0].meta); - assert.strictEqual(traces[0][0].meta['openai.request.endpoint'], '/vcr/openai/completions') + assert.ok('openai.request.endpoint' in traces[0][0].meta) + assert.strictEqual(traces[0][0].meta['openai.request.endpoint'], '/vcr/openai/completions') assert.strictEqual(traces[0][0].meta.component, 'openai') assert.strictEqual(traces[0][0].meta['_dd.integration'], 'openai') @@ -501,8 +501,8 @@ describe('Plugin', () => { assert.strictEqual(traces[0][0].meta['openai.request.endpoint'], '/v1/models/*') assert.strictEqual(traces[0][0].metrics['openai.response.deleted'], 1) - assert.ok('openai.response.id' in traces[0][0].meta); - assert.strictEqual(traces[0][0].meta['openai.response.id'], 'ft:gpt-4.1-mini-2025-04-14:datadog-staging::BkaILRSh') + assert.ok('openai.response.id' in traces[0][0].meta) + assert.strictEqual(traces[0][0].meta['openai.response.id'], 'ft:gpt-4.1-mini-2025-04-14:datadog-staging::BkaILRSh') }) if (semver.satisfies(realVersion, '>=4.0.0')) { @@ -715,8 +715,8 @@ describe('Plugin', () => { } assert.strictEqual(traces[0][0].error, 0) assert.strictEqual(traces[0][0].meta['openai.request.method'], 'POST') - assert.ok('openai.request.endpoint' in traces[0][0].meta); - assert.strictEqual(traces[0][0].meta['openai.request.endpoint'], '/vcr/openai/fine_tuning/jobs') + assert.ok('openai.request.endpoint' in traces[0][0].meta) + assert.strictEqual(traces[0][0].meta['openai.request.endpoint'], '/vcr/openai/fine_tuning/jobs') assert.strictEqual(traces[0][0].meta['openai.request.model'], 'gpt-4.1-mini-2025-04-14') assert.match(traces[0][0].meta['openai.response.id'], /^ftjob-/) @@ -836,8 +836,8 @@ describe('Plugin', () => { } assert.strictEqual(traces[0][0].error, 0) assert.strictEqual(traces[0][0].meta['openai.request.method'], 'GET') - assert.ok('openai.request.endpoint' in traces[0][0].meta); - assert.strictEqual(traces[0][0].meta['openai.request.endpoint'], '/vcr/openai/fine_tuning/jobs') + assert.ok('openai.request.endpoint' in traces[0][0].meta) + assert.strictEqual(traces[0][0].meta['openai.request.endpoint'], '/vcr/openai/fine_tuning/jobs') assert.ok(Object.hasOwn(traces[0][0].metrics, 'openai.response.count')) }) @@ -904,8 +904,8 @@ describe('Plugin', () => { } assert.strictEqual(traces[0][0].error, 0) assert.strictEqual(traces[0][0].meta['openai.request.method'], 'POST') - assert.ok('openai.request.endpoint' in traces[0][0].meta); - assert.strictEqual(traces[0][0].meta['openai.request.endpoint'], '/vcr/openai/images/generations') + assert.ok('openai.request.endpoint' in traces[0][0].meta) + assert.strictEqual(traces[0][0].meta['openai.request.endpoint'], '/vcr/openai/images/generations') assert.strictEqual(traces[0][0].meta['openai.request.model'], 'dall-e-3') }) @@ -965,8 +965,8 @@ describe('Plugin', () => { } assert.strictEqual(traces[0][0].error, 0) assert.strictEqual(traces[0][0].meta['openai.request.method'], 'POST') - assert.ok('openai.request.endpoint' in traces[0][0].meta); - assert.strictEqual(traces[0][0].meta['openai.request.endpoint'], '/vcr/openai/images/edits') + assert.ok('openai.request.endpoint' in traces[0][0].meta) + assert.strictEqual(traces[0][0].meta['openai.request.endpoint'], '/vcr/openai/images/edits') // TODO(sabrenner): fix in a follow-up (super simple - img.name) }) @@ -1008,8 +1008,8 @@ describe('Plugin', () => { } assert.strictEqual(traces[0][0].error, 0) assert.strictEqual(traces[0][0].meta['openai.request.method'], 'POST') - assert.ok('openai.request.endpoint' in traces[0][0].meta); - assert.strictEqual(traces[0][0].meta['openai.request.endpoint'], '/vcr/openai/images/variations') + assert.ok('openai.request.endpoint' in traces[0][0].meta) + assert.strictEqual(traces[0][0].meta['openai.request.endpoint'], '/vcr/openai/images/variations') }) if (semver.satisfies(realVersion, '>=4.0.0')) { @@ -1052,8 +1052,8 @@ describe('Plugin', () => { } assert.strictEqual(traces[0][0].error, 0) - assert.ok('openai.request.endpoint' in traces[0][0].meta); - assert.strictEqual(traces[0][0].meta['openai.request.endpoint'], '/vcr/openai/audio/transcriptions') + assert.ok('openai.request.endpoint' in traces[0][0].meta) + assert.strictEqual(traces[0][0].meta['openai.request.endpoint'], '/vcr/openai/audio/transcriptions') assert.strictEqual(traces[0][0].meta['openai.request.method'], 'POST') assert.strictEqual(traces[0][0].meta['openai.request.model'], 'gpt-4o-mini-transcribe') }) @@ -1094,8 +1094,8 @@ describe('Plugin', () => { } assert.strictEqual(traces[0][0].error, 0) - assert.ok('openai.request.endpoint' in traces[0][0].meta); - assert.strictEqual(traces[0][0].meta['openai.request.endpoint'], '/vcr/openai/audio/translations') + assert.ok('openai.request.endpoint' in traces[0][0].meta) + assert.strictEqual(traces[0][0].meta['openai.request.endpoint'], '/vcr/openai/audio/translations') assert.strictEqual(traces[0][0].meta['openai.request.method'], 'POST') assert.strictEqual(traces[0][0].meta['openai.request.model'], 'whisper-1') }) @@ -1146,8 +1146,8 @@ describe('Plugin', () => { assert.strictEqual(traces[0][0].error, 0) assert.strictEqual(traces[0][0].meta['openai.request.method'], 'POST') - assert.ok('openai.request.endpoint' in traces[0][0].meta); - assert.strictEqual(traces[0][0].meta['openai.request.endpoint'], '/vcr/openai/chat/completions') + assert.ok('openai.request.endpoint' in traces[0][0].meta) + assert.strictEqual(traces[0][0].meta['openai.request.endpoint'], '/vcr/openai/chat/completions') assert.strictEqual(traces[0][0].meta['openai.request.model'], 'gpt-3.5-turbo') assert.ok(Object.hasOwn(traces[0][0].meta, 'openai.response.model')) diff --git a/packages/datadog-plugin-openai/test/integration-test/client.spec.js b/packages/datadog-plugin-openai/test/integration-test/client.spec.js index 6fd6ab0b3a1..98136c6b1f4 100644 --- a/packages/datadog-plugin-openai/test/integration-test/client.spec.js +++ b/packages/datadog-plugin-openai/test/integration-test/client.spec.js @@ -40,7 +40,7 @@ describe('esm', () => { it('is instrumented', async () => { const res = agent.assertMessageReceived(({ headers, payload }) => { - assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.strictEqual(headers.host, `127.0.0.1:${agent.port}`) assert.ok(Array.isArray(payload)) assert.strictEqual( checkSpansForServiceName(payload, 'openai.request'), diff --git a/packages/datadog-plugin-opensearch/test/index.spec.js b/packages/datadog-plugin-opensearch/test/index.spec.js index 30fc5df742e..327a90f244c 100644 --- a/packages/datadog-plugin-opensearch/test/index.spec.js +++ b/packages/datadog-plugin-opensearch/test/index.spec.js @@ -97,8 +97,8 @@ describe('Plugin', () => { assert.strictEqual(traces[0][0].meta['span.kind'], 'client') assert.strictEqual(traces[0][0].meta['opensearch.method'], 'POST') assert.strictEqual(traces[0][0].meta['opensearch.url'], '/_msearch') - assert.ok('opensearch.body' in traces[0][0].meta); - assert.strictEqual(traces[0][0].meta['opensearch.body'], '[{"index":"docs"},{"query":{"match_all":{}}},{"index":"docs2"},{"query":{"match_all":{}}}]') + assert.ok('opensearch.body' in traces[0][0].meta) + assert.strictEqual(traces[0][0].meta['opensearch.body'], '[{"index":"docs"},{"query":{"match_all":{}}},{"index":"docs2"},{"query":{"match_all":{}}}]') assert.strictEqual(traces[0][0].meta['opensearch.params'], '{"size":100}') assert.strictEqual(traces[0][0].meta.component, 'opensearch') assert.strictEqual(traces[0][0].meta['_dd.integration'], 'opensearch') diff --git a/packages/datadog-plugin-opensearch/test/integration-test/client.spec.js b/packages/datadog-plugin-opensearch/test/integration-test/client.spec.js index faf9d6d71f9..381d7312dea 100644 --- a/packages/datadog-plugin-opensearch/test/integration-test/client.spec.js +++ b/packages/datadog-plugin-opensearch/test/integration-test/client.spec.js @@ -29,7 +29,7 @@ describe('esm', () => { it('is instrumented', async () => { const res = agent.assertMessageReceived(({ headers, payload }) => { - assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.strictEqual(headers.host, `127.0.0.1:${agent.port}`) assert.ok(Array.isArray(payload)) assert.strictEqual(checkSpansForServiceName(payload, 'opensearch.query'), true) }) diff --git a/packages/datadog-plugin-oracledb/test/integration-test/client.spec.js b/packages/datadog-plugin-oracledb/test/integration-test/client.spec.js index b8b1ce90138..483a57d6a5d 100644 --- a/packages/datadog-plugin-oracledb/test/integration-test/client.spec.js +++ b/packages/datadog-plugin-oracledb/test/integration-test/client.spec.js @@ -29,7 +29,7 @@ describe('esm', () => { it('is instrumented', async () => { const res = agent.assertMessageReceived(({ headers, payload }) => { - assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.strictEqual(headers.host, `127.0.0.1:${agent.port}`) assert.ok(Array.isArray(payload)) assert.strictEqual(checkSpansForServiceName(payload, 'oracle.query'), true) }) diff --git a/packages/datadog-plugin-pg/test/integration-test/client.spec.js b/packages/datadog-plugin-pg/test/integration-test/client.spec.js index a14bda65ec2..ab101858d9b 100644 --- a/packages/datadog-plugin-pg/test/integration-test/client.spec.js +++ b/packages/datadog-plugin-pg/test/integration-test/client.spec.js @@ -46,7 +46,7 @@ describe('esm', () => { for (const variant of varySandbox.VARIANTS) { it(`is instrumented loaded with ${variant}`, async () => { const res = agent.assertMessageReceived(({ headers, payload }) => { - assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.strictEqual(headers.host, `127.0.0.1:${agent.port}`) assert.ok(Array.isArray(payload)) assert.strictEqual(checkSpansForServiceName(payload, 'pg.query'), true) }) diff --git a/packages/datadog-plugin-pino/test/index.spec.js b/packages/datadog-plugin-pino/test/index.spec.js index d1d2da7972f..c054f269a6f 100644 --- a/packages/datadog-plugin-pino/test/index.spec.js +++ b/packages/datadog-plugin-pino/test/index.spec.js @@ -72,8 +72,8 @@ describe('Plugin', () => { const record = JSON.parse(stream.write.firstCall.args[0].toString()) assert.ok('dd' in record) - assert.ok('msg' in record); -assert.deepStrictEqual(record['msg'], 'message') + assert.ok('msg' in record) + assert.deepStrictEqual(record.msg, 'message') }) }) @@ -122,8 +122,8 @@ assert.deepStrictEqual(record['msg'], 'message') span_id: span.context().toSpanId() }) - assert.ok('msg' in record); -assert.deepStrictEqual(record['msg'], 'message') + assert.ok('msg' in record) + assert.deepStrictEqual(record.msg, 'message') }) }) @@ -136,21 +136,21 @@ assert.deepStrictEqual(record['msg'], 'message') const record = JSON.parse(stream.write.firstCall.args[0].toString()) if (record.err) { // pino >=7 - assert.ok('message' in record.err); - assert.strictEqual(record.err['message'], error.message) - assert.ok('type' in record.err); - assert.strictEqual(record.err['type'], 'Error') - assert.ok('stack' in record.err); - assert.strictEqual(record.err['stack'], error.stack) + assert.ok('message' in record.err) + assert.strictEqual(record.err.message, error.message) + assert.ok('type' in record.err) + assert.strictEqual(record.err.type, 'Error') + assert.ok('stack' in record.err) + assert.strictEqual(record.err.stack, error.stack) } else { // pino <7 - assert.ok('msg' in record); - assert.strictEqual(record['msg'], error.message) + assert.ok('msg' in record) + assert.strictEqual(record.msg, error.message) // ** TODO ** add this back once we fix it if (NODE_MAJOR < 21) { - assert.ok('type' in record); - assert.strictEqual(record['type'], 'Error') - assert.ok('stack' in record); - assert.strictEqual(record['stack'], error.stack) + assert.ok('type' in record) + assert.strictEqual(record.type, 'Error') + assert.ok('stack' in record) + assert.strictEqual(record.stack, error.stack) } } }) @@ -178,8 +178,8 @@ assert.deepStrictEqual(record['msg'], 'message') assert.ok('dd' in record) assert.ok(!('trace_id' in record.dd)) assert.ok(!('span_id' in record.dd)) - assert.ok('msg' in record); -assert.deepStrictEqual(record['msg'], 'message') + assert.ok('msg' in record) + assert.deepStrictEqual(record.msg, 'message') }) if (semver.intersects(version, '>=5.14.0')) { @@ -204,10 +204,10 @@ assert.deepStrictEqual(record['msg'], 'message') span_id: span.context().toSpanId() }) - assert.ok('msg' in record); -assert.deepStrictEqual(record['msg'], 'message') - assert.ok('addedMixin' in record); -assert.deepStrictEqual(record['addedMixin'], true) + assert.ok('msg' in record) + assert.deepStrictEqual(record.msg, 'message') + assert.ok('addedMixin' in record) + assert.deepStrictEqual(record.addedMixin, true) }) }) } diff --git a/packages/datadog-plugin-redis/test/integration-test/client.spec.js b/packages/datadog-plugin-redis/test/integration-test/client.spec.js index b70ac54c87b..1437f6286a2 100644 --- a/packages/datadog-plugin-redis/test/integration-test/client.spec.js +++ b/packages/datadog-plugin-redis/test/integration-test/client.spec.js @@ -30,7 +30,7 @@ describe('esm', () => { it('is instrumented', async () => { const res = agent.assertMessageReceived(({ headers, payload }) => { - assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.strictEqual(headers.host, `127.0.0.1:${agent.port}`) assert.ok(Array.isArray(payload)) assert.strictEqual(checkSpansForServiceName(payload, 'redis.command'), true) }) diff --git a/packages/datadog-plugin-restify/test/integration-test/client.spec.js b/packages/datadog-plugin-restify/test/integration-test/client.spec.js index 9a5e00ff171..6c73a63efe3 100644 --- a/packages/datadog-plugin-restify/test/integration-test/client.spec.js +++ b/packages/datadog-plugin-restify/test/integration-test/client.spec.js @@ -33,7 +33,7 @@ describe('esm', () => { proc = await spawnPluginIntegrationTestProc(sandboxCwd(), 'server.mjs', agent.port) return curlAndAssertMessage(agent, proc, ({ headers, payload }) => { - assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.strictEqual(headers.host, `127.0.0.1:${agent.port}`) assert.ok(Array.isArray(payload)) assert.strictEqual(checkSpansForServiceName(payload, 'restify.request'), true) }) diff --git a/packages/datadog-plugin-rhea/test/index.spec.js b/packages/datadog-plugin-rhea/test/index.spec.js index 821800d101d..f8ebc215042 100644 --- a/packages/datadog-plugin-rhea/test/index.spec.js +++ b/packages/datadog-plugin-rhea/test/index.spec.js @@ -277,10 +277,10 @@ describe('Plugin', () => { it('should use the configuration for the receiver', (done) => { agent.assertSomeTraces(traces => { const span = traces[0][0] - assert.ok('name' in span); - assert.strictEqual(span['name'], expectedSchema.receive.opName) - assert.ok('service' in span); - assert.strictEqual(span['service'], 'a_test_service') + assert.ok('name' in span) + assert.strictEqual(span.name, expectedSchema.receive.opName) + assert.ok('service' in span) + assert.strictEqual(span.service, 'a_test_service') }) .then(done, done) context.sender.send({ body: 'Hello World!' }) @@ -289,10 +289,10 @@ describe('Plugin', () => { it('should use the configuration for the sender', (done) => { agent.assertSomeTraces(traces => { const span = traces[0][0] - assert.ok('name' in span); - assert.strictEqual(span['name'], expectedSchema.send.opName) - assert.ok('service' in span); - assert.strictEqual(span['service'], 'a_test_service') + assert.ok('name' in span) + assert.strictEqual(span.name, expectedSchema.send.opName) + assert.ok('service' in span) + assert.strictEqual(span.service, 'a_test_service') }) .then(done, done) context.sender.send({ body: 'Hello World!' }) diff --git a/packages/datadog-plugin-rhea/test/integration-test/client.spec.js b/packages/datadog-plugin-rhea/test/integration-test/client.spec.js index 8bc19734da5..a6ded49c956 100644 --- a/packages/datadog-plugin-rhea/test/integration-test/client.spec.js +++ b/packages/datadog-plugin-rhea/test/integration-test/client.spec.js @@ -29,7 +29,7 @@ describe('esm', () => { it('is instrumented', async () => { const res = agent.assertMessageReceived(({ headers, payload }) => { - assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.strictEqual(headers.host, `127.0.0.1:${agent.port}`) assert.ok(Array.isArray(payload)) assert.strictEqual(checkSpansForServiceName(payload, 'amqp.send'), true) }) diff --git a/packages/datadog-plugin-router/test/integration-test/client.spec.js b/packages/datadog-plugin-router/test/integration-test/client.spec.js index 228daf5cf82..e1e60d981f5 100644 --- a/packages/datadog-plugin-router/test/integration-test/client.spec.js +++ b/packages/datadog-plugin-router/test/integration-test/client.spec.js @@ -32,7 +32,7 @@ describe('esm', () => { proc = await spawnPluginIntegrationTestProc(sandboxCwd(), 'server.mjs', agent.port) return curlAndAssertMessage(agent, proc, ({ headers, payload }) => { - assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.strictEqual(headers.host, `127.0.0.1:${agent.port}`) assert.ok(Array.isArray(payload)) assert.strictEqual(checkSpansForServiceName(payload, 'router.middleware'), true) }) diff --git a/packages/datadog-plugin-sharedb/test/index.spec.js b/packages/datadog-plugin-sharedb/test/index.spec.js index abef60f4937..7f77b8b49db 100644 --- a/packages/datadog-plugin-sharedb/test/index.spec.js +++ b/packages/datadog-plugin-sharedb/test/index.spec.js @@ -95,8 +95,8 @@ describe('Plugin', () => { agent.assertSomeTraces(traces => { assert.strictEqual(traces[0][0].service, 'test') - assert.ok('resource' in traces[0][0]); - assert.strictEqual(traces[0][0]['resource'], 'query-fetch some-collection {"randomValues":{"property":"?","one":"?"}}') + assert.ok('resource' in traces[0][0]) + assert.strictEqual(traces[0][0].resource, 'query-fetch some-collection {"randomValues":{"property":"?","one":"?"}}') assert.strictEqual(traces[0][0].meta['span.kind'], 'server') assert.strictEqual(traces[0][0].meta.service, 'test') assert.strictEqual(traces[0][0].meta['sharedb.action'], 'query-fetch') diff --git a/packages/datadog-plugin-sharedb/test/integration-test/client.spec.js b/packages/datadog-plugin-sharedb/test/integration-test/client.spec.js index bfa3529dd16..1ad3e4cd221 100644 --- a/packages/datadog-plugin-sharedb/test/integration-test/client.spec.js +++ b/packages/datadog-plugin-sharedb/test/integration-test/client.spec.js @@ -30,7 +30,7 @@ describe('esm', () => { it('is instrumented', async () => { const res = agent.assertMessageReceived(({ headers, payload }) => { - assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.strictEqual(headers.host, `127.0.0.1:${agent.port}`) assert.ok(Array.isArray(payload)) assert.strictEqual(checkSpansForServiceName(payload, 'sharedb.request'), true) }) diff --git a/packages/datadog-plugin-tedious/test/integration-test/client.spec.js b/packages/datadog-plugin-tedious/test/integration-test/client.spec.js index 4e3a595ef1d..6cd38b5bb21 100644 --- a/packages/datadog-plugin-tedious/test/integration-test/client.spec.js +++ b/packages/datadog-plugin-tedious/test/integration-test/client.spec.js @@ -37,7 +37,7 @@ describe('esm', () => { it('is instrumented', async () => { const res = agent.assertMessageReceived(({ headers, payload }) => { - assert.strictEqual(headers['host'], `127.0.0.1:${agent.port}`) + assert.strictEqual(headers.host, `127.0.0.1:${agent.port}`) assert.ok(Array.isArray(payload)) assert.strictEqual(checkSpansForServiceName(payload, 'tedious.request'), true) }) diff --git a/packages/datadog-plugin-winston/test/index.spec.js b/packages/datadog-plugin-winston/test/index.spec.js index da75184cef2..6eedc0afbaf 100644 --- a/packages/datadog-plugin-winston/test/index.spec.js +++ b/packages/datadog-plugin-winston/test/index.spec.js @@ -392,10 +392,10 @@ describe('Plugin', () => { assert.strictEqual(loggedInfo.message, 'test error with stack') assert.ok('dd' in loggedInfo) - assert.ok('trace_id' in loggedInfo.dd); - assert.strictEqual(loggedInfo.dd['trace_id'], span.context().toTraceId(true)) - assert.ok('span_id' in loggedInfo.dd); - assert.strictEqual(loggedInfo.dd['span_id'], span.context().toSpanId()) + assert.ok('trace_id' in loggedInfo.dd) + assert.strictEqual(loggedInfo.dd.trace_id, span.context().toTraceId(true)) + assert.ok('span_id' in loggedInfo.dd) + assert.strictEqual(loggedInfo.dd.span_id, span.context().toSpanId()) }) }) }) diff --git a/packages/dd-trace/test/appsec/iast/overhead-controller.spec.js b/packages/dd-trace/test/appsec/iast/overhead-controller.spec.js index 731d2ea1e50..5d65a008d42 100644 --- a/packages/dd-trace/test/appsec/iast/overhead-controller.spec.js +++ b/packages/dd-trace/test/appsec/iast/overhead-controller.spec.js @@ -229,15 +229,15 @@ describe('Overhead controller', () => { }) it('should populate initial context with available tokens', () => { - assert.ok(`tokens.${OPERATION.name}` in iastContext[oceContextKey]); - assert.strictEqual(iastContext[oceContextKey][`tokens.${OPERATION.name}`], OPERATION.initialTokenBucketSize()) + assert.ok(`tokens.${OPERATION.name}` in iastContext[oceContextKey]) + assert.strictEqual(iastContext[oceContextKey][`tokens.${OPERATION.name}`], OPERATION.initialTokenBucketSize()) }) it('should allow when available tokens', () => { iastContext[overheadController.OVERHEAD_CONTROLLER_CONTEXT_KEY].tokens[OPERATION.name] = 2 assert.strictEqual(overheadController.hasQuota(OPERATION, iastContext, vulnerabilities.SSRF), true) - assert.ok(`tokens.${OPERATION.name}` in iastContext[oceContextKey]); - assert.strictEqual(iastContext[oceContextKey][`tokens.${OPERATION.name}`], 1) + assert.ok(`tokens.${OPERATION.name}` in iastContext[oceContextKey]) + assert.strictEqual(iastContext[oceContextKey][`tokens.${OPERATION.name}`], 1) }) it('should detect the first vulnerability of the type ' + @@ -246,8 +246,8 @@ describe('Overhead controller', () => { iastContext[overheadController.OVERHEAD_CONTROLLER_CONTEXT_KEY].tokens[OPERATION.name] = 1 assert.strictEqual(overheadController.hasQuota(OPERATION, iastContext, vulnerabilities.SSRF), true) overheadController.consolidateVulnerabilities(iastContext) - assert.ok(`tokens.${OPERATION.name}` in iastContext[oceContextKey]); - assert.strictEqual(iastContext[oceContextKey][`tokens.${OPERATION.name}`], 0) + assert.ok(`tokens.${OPERATION.name}` in iastContext[oceContextKey]) + assert.strictEqual(iastContext[oceContextKey][`tokens.${OPERATION.name}`], 0) // Ignoring the first SSRF in the next request iastContext = { req } @@ -267,8 +267,8 @@ describe('Overhead controller', () => { iastContext[overheadController.OVERHEAD_CONTROLLER_CONTEXT_KEY].tokens[OPERATION.name] = 1 assert.strictEqual(overheadController.hasQuota(OPERATION, iastContext, vulnerabilities.SSRF), true) overheadController.consolidateVulnerabilities(iastContext) - assert.ok(`tokens.${OPERATION.name}` in iastContext[oceContextKey]); - assert.strictEqual(iastContext[oceContextKey][`tokens.${OPERATION.name}`], 0) + assert.ok(`tokens.${OPERATION.name}` in iastContext[oceContextKey]) + assert.strictEqual(iastContext[oceContextKey][`tokens.${OPERATION.name}`], 0) // Ignoring the first SSRF in the next request iastContext = { req } @@ -286,8 +286,8 @@ describe('Overhead controller', () => { iastContext[overheadController.OVERHEAD_CONTROLLER_CONTEXT_KEY].tokens[OPERATION.name] = 1 assert.strictEqual(overheadController.hasQuota(OPERATION, iastContext, vulnerabilities.SSRF), true) overheadController.consolidateVulnerabilities(iastContext) - assert.ok(`tokens.${OPERATION.name}` in iastContext[oceContextKey]); - assert.strictEqual(iastContext[oceContextKey][`tokens.${OPERATION.name}`], 0) + assert.ok(`tokens.${OPERATION.name}` in iastContext[oceContextKey]) + assert.strictEqual(iastContext[oceContextKey][`tokens.${OPERATION.name}`], 0) // Detecting the first CODE_INJECTION in the next request iastContext = { req } @@ -307,8 +307,8 @@ describe('Overhead controller', () => { iastContext[overheadController.OVERHEAD_CONTROLLER_CONTEXT_KEY].tokens[OPERATION.name] = 1 assert.strictEqual(overheadController.hasQuota(OPERATION, iastContext, vulnerabilities.SSRF), true) overheadController.consolidateVulnerabilities(iastContext) - assert.ok(`tokens.${OPERATION.name}` in iastContext[oceContextKey]); - assert.strictEqual(iastContext[oceContextKey][`tokens.${OPERATION.name}`], 0) + assert.ok(`tokens.${OPERATION.name}` in iastContext[oceContextKey]) + assert.strictEqual(iastContext[oceContextKey][`tokens.${OPERATION.name}`], 0) // Detecting the first CODE_INJECTION in the next request iastContext = { req } @@ -323,8 +323,8 @@ describe('Overhead controller', () => { iastContext[overheadController.OVERHEAD_CONTROLLER_CONTEXT_KEY].tokens[OPERATION.name] = 1 assert.strictEqual(overheadController.hasQuota(OPERATION, iastContext, vulnerabilities.SSRF), true) overheadController.consolidateVulnerabilities(iastContext) - assert.ok(`tokens.${OPERATION.name}` in iastContext[oceContextKey]); - assert.strictEqual(iastContext[oceContextKey][`tokens.${OPERATION.name}`], 0) + assert.ok(`tokens.${OPERATION.name}` in iastContext[oceContextKey]) + assert.strictEqual(iastContext[oceContextKey][`tokens.${OPERATION.name}`], 0) // Detecting the first CODE_INJECTION in the next request req.method = 'POST' @@ -340,8 +340,8 @@ describe('Overhead controller', () => { iastContext[overheadController.OVERHEAD_CONTROLLER_CONTEXT_KEY].tokens[OPERATION.name] = 2 assert.strictEqual(overheadController.hasQuota(OPERATION, iastContext, vulnerabilities.SSRF), true) overheadController.consolidateVulnerabilities(iastContext) - assert.ok(`tokens.${OPERATION.name}` in iastContext[oceContextKey]); - assert.strictEqual(iastContext[oceContextKey][`tokens.${OPERATION.name}`], 1) + assert.ok(`tokens.${OPERATION.name}` in iastContext[oceContextKey]) + assert.strictEqual(iastContext[oceContextKey][`tokens.${OPERATION.name}`], 1) // Detecting the first CODE_INJECTION in the next request iastContext = { req } @@ -355,8 +355,8 @@ describe('Overhead controller', () => { iastContext[overheadController.OVERHEAD_CONTROLLER_CONTEXT_KEY].tokens[OPERATION.name] = 1 assert.strictEqual(overheadController.hasQuota(OPERATION, iastContext, vulnerabilities.SSRF), true) overheadController.consolidateVulnerabilities(iastContext) - assert.ok(`tokens.${OPERATION.name}` in iastContext[oceContextKey]); - assert.strictEqual(iastContext[oceContextKey][`tokens.${OPERATION.name}`], 0) + assert.ok(`tokens.${OPERATION.name}` in iastContext[oceContextKey]) + assert.strictEqual(iastContext[oceContextKey][`tokens.${OPERATION.name}`], 0) // second request using the whole budget iastContext = { req } @@ -364,8 +364,8 @@ describe('Overhead controller', () => { iastContext[overheadController.OVERHEAD_CONTROLLER_CONTEXT_KEY].tokens[OPERATION.name] = 1 assert.strictEqual(overheadController.hasQuota(OPERATION, iastContext, vulnerabilities.SSRF), false) assert.strictEqual(overheadController.hasQuota(OPERATION, iastContext, vulnerabilities.SSRF), true) - assert.ok(`tokens.${OPERATION.name}` in iastContext[oceContextKey]); - assert.strictEqual(iastContext[oceContextKey][`tokens.${OPERATION.name}`], 0) + assert.ok(`tokens.${OPERATION.name}` in iastContext[oceContextKey]) + assert.strictEqual(iastContext[oceContextKey][`tokens.${OPERATION.name}`], 0) overheadController.consolidateVulnerabilities(iastContext) // third request detecting only the third SSRF @@ -380,8 +380,8 @@ describe('Overhead controller', () => { it('should not allow when no available tokens', () => { iastContext[overheadController.OVERHEAD_CONTROLLER_CONTEXT_KEY].tokens[OPERATION.name] = 0 assert.strictEqual(overheadController.hasQuota(OPERATION, iastContext), false) - assert.ok(`tokens.${OPERATION.name}` in iastContext[oceContextKey]); - assert.strictEqual(iastContext[oceContextKey][`tokens.${OPERATION.name}`], 0) + assert.ok(`tokens.${OPERATION.name}` in iastContext[oceContextKey]) + assert.strictEqual(iastContext[oceContextKey][`tokens.${OPERATION.name}`], 0) }) }) diff --git a/packages/dd-trace/test/appsec/iast/taint-tracking/taint-tracking-impl.spec.js b/packages/dd-trace/test/appsec/iast/taint-tracking/taint-tracking-impl.spec.js index 43979afaa1c..97431a1f8dd 100644 --- a/packages/dd-trace/test/appsec/iast/taint-tracking/taint-tracking-impl.spec.js +++ b/packages/dd-trace/test/appsec/iast/taint-tracking/taint-tracking-impl.spec.js @@ -104,15 +104,15 @@ describe('TaintTracking', () => { const result = propFnInstrumented(jsonTainted) assert.strictEqual(isTainted(iastContext, result.command), true) assert.deepStrictEqual(getRanges(iastContext, result.command), [{ - start: 0, - end: 6, - iinfo: { - parameterName: 'command', - parameterValue: 'ls -la', - type: 'request.type' - }, - secureMarks: 0 - }]) + start: 0, + end: 6, + iinfo: { + parameterName: 'command', + parameterValue: 'ls -la', + type: 'request.type' + }, + secureMarks: 0 + }]) const resultOrig = propFnOriginal(jsonTainted) assert.deepStrictEqual(result, resultOrig) diff --git a/packages/dd-trace/test/appsec/iast/taint-tracking/taint-tracking-operations.spec.js b/packages/dd-trace/test/appsec/iast/taint-tracking/taint-tracking-operations.spec.js index 95000a49ad5..bfbf2898e1a 100644 --- a/packages/dd-trace/test/appsec/iast/taint-tracking/taint-tracking-operations.spec.js +++ b/packages/dd-trace/test/appsec/iast/taint-tracking/taint-tracking-operations.spec.js @@ -566,7 +566,7 @@ describe('IAST TaintTracking Operations', () => { const noop = taintTrackingImpl.getTaintTrackingNoop() assert.strictEqual(Object.keys(noop).length, ((Array.isArray(Object.keys(tt)) ? Object.keys(tt) : [Object.keys(tt)])).length) -assert.ok(((Array.isArray(Object.keys(tt)) ? Object.keys(tt) : [Object.keys(tt)])).every(k => Object.hasOwn(noop, k))) + assert.ok(((Array.isArray(Object.keys(tt)) ? Object.keys(tt) : [Object.keys(tt)])).every(k => Object.hasOwn(noop, k))) }) it('should have the same properties as TaintTrackingDebug', () => { @@ -574,7 +574,7 @@ assert.ok(((Array.isArray(Object.keys(tt)) ? Object.keys(tt) : [Object.keys(tt)] const noop = taintTrackingImpl.getTaintTrackingNoop() assert.strictEqual(Object.keys(noop).length, ((Array.isArray(Object.keys(ttDebug)) ? Object.keys(ttDebug) : [Object.keys(ttDebug)])).length) -assert.ok(((Array.isArray(Object.keys(ttDebug)) ? Object.keys(ttDebug) : [Object.keys(ttDebug)])).every(k => Object.hasOwn(noop, k))) + assert.ok(((Array.isArray(Object.keys(ttDebug)) ? Object.keys(ttDebug) : [Object.keys(ttDebug)])).every(k => Object.hasOwn(noop, k))) }) it('should have the same properties as csiMethods', () => { @@ -583,7 +583,7 @@ assert.ok(((Array.isArray(Object.keys(ttDebug)) ? Object.keys(ttDebug) : [Object const csiExpectedMethods = getExpectedMethods() assert.strictEqual(Object.keys(tt).length, ((Array.isArray(csiExpectedMethods) ? csiExpectedMethods : [csiExpectedMethods])).length) -assert.ok(((Array.isArray(csiExpectedMethods) ? csiExpectedMethods : [csiExpectedMethods])).every(k => Object.hasOwn(tt, k))) + assert.ok(((Array.isArray(csiExpectedMethods) ? csiExpectedMethods : [csiExpectedMethods])).every(k => Object.hasOwn(tt, k))) }) }) }) diff --git a/packages/dd-trace/test/appsec/rasp/fs-plugin.spec.js b/packages/dd-trace/test/appsec/rasp/fs-plugin.spec.js index 7db78462f48..6f9ace71ad6 100644 --- a/packages/dd-trace/test/appsec/rasp/fs-plugin.spec.js +++ b/packages/dd-trace/test/appsec/rasp/fs-plugin.spec.js @@ -104,8 +104,8 @@ describe('AppsecFsPlugin', () => { let store = appsecFsPlugin._onFsOperationStart() assert.ok(Object.hasOwn(store, 'fs')) - assert.strictEqual(store.fs['parentStore'], origStore) - assert.strictEqual(store.fs['root'], true) + assert.strictEqual(store.fs.parentStore, origStore) + assert.strictEqual(store.fs.root, true) store = appsecFsPlugin._onFsOperationFinishOrRenderEnd() @@ -120,17 +120,17 @@ describe('AppsecFsPlugin', () => { const rootStore = appsecFsPlugin._onFsOperationStart() assert.ok(Object.hasOwn(rootStore, 'fs')) - assert.strictEqual(rootStore.fs['parentStore'], origStore) - assert.strictEqual(rootStore.fs['root'], true) + assert.strictEqual(rootStore.fs.parentStore, origStore) + assert.strictEqual(rootStore.fs.root, true) storage('legacy').enterWith(rootStore) let store = appsecFsPlugin._onFsOperationStart() assert.ok(Object.hasOwn(store, 'fs')) - assert.strictEqual(store.fs['parentStore'], rootStore) - assert.strictEqual(store.fs['root'], false) - assert.strictEqual(store['orig'], true) + assert.strictEqual(store.fs.parentStore, rootStore) + assert.strictEqual(store.fs.root, false) + assert.strictEqual(store.orig, true) storage('legacy').enterWith(store) @@ -155,8 +155,8 @@ describe('AppsecFsPlugin', () => { let store = appsecFsPlugin._onResponseRenderStart() assert.ok(Object.hasOwn(store, 'fs')) - assert.strictEqual(store.fs['parentStore'], origStore) - assert.strictEqual(store.fs['opExcluded'], true) + assert.strictEqual(store.fs.parentStore, origStore) + assert.strictEqual(store.fs.opExcluded, true) storage('legacy').enterWith(store) diff --git a/packages/dd-trace/test/appsec/rule_manager.spec.js b/packages/dd-trace/test/appsec/rule_manager.spec.js index 02317e93095..7c632bbbd40 100644 --- a/packages/dd-trace/test/appsec/rule_manager.spec.js +++ b/packages/dd-trace/test/appsec/rule_manager.spec.js @@ -14,7 +14,6 @@ const waf = require('../../src/appsec/waf') const { ACKNOWLEDGED, UNACKNOWLEDGED, ERROR } = require('../../src/remote_config/apply_states') const { getConfigFresh } = require('../helpers/config') - describe('AppSec Rule Manager', () => { let config diff --git a/packages/dd-trace/test/appsec/sdk/track_event-integration.spec.js b/packages/dd-trace/test/appsec/sdk/track_event-integration.spec.js index fbb9b7e619d..cc757c5f629 100644 --- a/packages/dd-trace/test/appsec/sdk/track_event-integration.spec.js +++ b/packages/dd-trace/test/appsec/sdk/track_event-integration.spec.js @@ -153,7 +153,7 @@ describe('track_event - Integration with the tracer', () => { res.end() } agent.assertSomeTraces(traces => { - assert.ok(!('_sampling_priority_v1' in traces[0][0].metrics) || traces[0][0].metrics['_sampling_priority_v1'] !== USER_KEEP) + assert.ok(!('_sampling_priority_v1' in traces[0][0].metrics) || traces[0][0].metrics._sampling_priority_v1 !== USER_KEEP) }).then(done).catch(done) axios.get(`http://localhost:${port}/`) }) diff --git a/packages/dd-trace/test/appsec/telemetry/waf.spec.js b/packages/dd-trace/test/appsec/telemetry/waf.spec.js index 9d3b81fb55a..72f71f070d5 100644 --- a/packages/dd-trace/test/appsec/telemetry/waf.spec.js +++ b/packages/dd-trace/test/appsec/telemetry/waf.spec.js @@ -365,8 +365,8 @@ describe('Appsec Waf Telemetry metrics', () => { describe('WAF Truncation metrics', () => { it('should report truncated string metrics', () => { const result = appsecTelemetry.updateWafRequestsMetricTags({ maxTruncatedString: 5000 }, req) - assert.ok('input_truncated' in result); - assert.strictEqual(result['input_truncated'], true) + assert.ok('input_truncated' in result) + assert.strictEqual(result.input_truncated, true) sinon.assert.calledWith(count, 'waf.input_truncated', { truncation_reason: 1 }) sinon.assert.calledWith(inc, 1) @@ -374,8 +374,8 @@ describe('Appsec Waf Telemetry metrics', () => { it('should report truncated container size metrics', () => { const result = appsecTelemetry.updateWafRequestsMetricTags({ maxTruncatedContainerSize: 300 }, req) - assert.ok('input_truncated' in result); - assert.strictEqual(result['input_truncated'], true) + assert.ok('input_truncated' in result) + assert.strictEqual(result.input_truncated, true) sinon.assert.calledWith(count, 'waf.input_truncated', { truncation_reason: 2 }) sinon.assert.calledWith(inc, 1) @@ -383,8 +383,8 @@ describe('Appsec Waf Telemetry metrics', () => { it('should report truncated container depth metrics', () => { const result = appsecTelemetry.updateWafRequestsMetricTags({ maxTruncatedContainerDepth: 20 }, req) - assert.ok('input_truncated' in result); - assert.strictEqual(result['input_truncated'], true) + assert.ok('input_truncated' in result) + assert.strictEqual(result.input_truncated, true) sinon.assert.calledWith(count, 'waf.input_truncated', { truncation_reason: 4 }) sinon.assert.calledWith(inc, 1) @@ -396,16 +396,16 @@ describe('Appsec Waf Telemetry metrics', () => { maxTruncatedContainerSize: 300, maxTruncatedContainerDepth: 20 }, req) - assert.ok('input_truncated' in result); - assert.strictEqual(result['input_truncated'], true) + assert.ok('input_truncated' in result) + assert.strictEqual(result.input_truncated, true) sinon.assert.calledWith(count, 'waf.input_truncated', { truncation_reason: 7 }) }) it('should not report truncation metrics when no truncation occurs', () => { const result = appsecTelemetry.updateWafRequestsMetricTags(metrics, req) - assert.ok('input_truncated' in result); - assert.strictEqual(result['input_truncated'], false) + assert.ok('input_truncated' in result) + assert.strictEqual(result.input_truncated, false) sinon.assert.neverCalledWith(count, 'waf.input_truncated') sinon.assert.neverCalledWith(distribution, 'waf.truncated_value_size') diff --git a/packages/dd-trace/test/debugger/devtools_client/send.spec.js b/packages/dd-trace/test/debugger/devtools_client/send.spec.js index b6c608ff77c..69404cbb33c 100644 --- a/packages/dd-trace/test/debugger/devtools_client/send.spec.js +++ b/packages/dd-trace/test/debugger/devtools_client/send.spec.js @@ -93,8 +93,8 @@ describe('input message http requests', function () { const opts = getRequestOptions(request) assert.strictEqual(opts.method, 'POST') - assert.ok('path' in opts); - assert.strictEqual(opts['path'], '/debugger/v1/input?ddtags=' + + assert.ok('path' in opts) + assert.strictEqual(opts.path, '/debugger/v1/input?ddtags=' + `env%3A${process.env.DD_ENV}%2C` + `version%3A${process.env.DD_VERSION}%2C` + `debugger_version%3A${version}%2C` + diff --git a/packages/dd-trace/test/debugger/devtools_client/snapshot/complex-types.spec.js b/packages/dd-trace/test/debugger/devtools_client/snapshot/complex-types.spec.js index ecfcb28d0b1..9a80f939a54 100644 --- a/packages/dd-trace/test/debugger/devtools_client/snapshot/complex-types.spec.js +++ b/packages/dd-trace/test/debugger/devtools_client/snapshot/complex-types.spec.js @@ -52,8 +52,8 @@ describe('debugger -> devtools client -> snapshot.getLocalStateForCallFrame', fu // ... tested individually in the remaining it-blocks inside this describe-block // from closure scope - assert.ok('ref' in state); -assert.deepStrictEqual(state['ref'], { + assert.ok('ref' in state) + assert.deepStrictEqual(state.ref, { type: 'Object', fields: { wmo1: { type: 'Object', fields: { a: { type: 'number', value: '1' } } }, @@ -63,8 +63,8 @@ assert.deepStrictEqual(state['ref'], { wso3: { type: 'Object', fields: { a: { type: 'number', value: '3' } } } } }) - assert.ok('get' in state); -assert.deepStrictEqual(state['get'], { + assert.ok('get' in state) + assert.deepStrictEqual(state.get, { type: 'Function', fields: { length: { type: 'number', value: '0' }, @@ -74,8 +74,8 @@ assert.deepStrictEqual(state['get'], { }) it('object literal', function () { - assert.ok('oblit' in state); -assert.deepStrictEqual(state['oblit'], { + assert.ok('oblit' in state) + assert.deepStrictEqual(state.oblit, { type: 'Object', fields: { a: { type: 'number', value: '1' }, @@ -90,8 +90,8 @@ assert.deepStrictEqual(state['oblit'], { }) it('custom object from class', function () { - assert.ok('obnew' in state); -assert.deepStrictEqual(state['obnew'], { + assert.ok('obnew' in state) + assert.deepStrictEqual(state.obnew, { type: 'MyClass', fields: { foo: { type: 'number', value: '42' }, @@ -101,8 +101,8 @@ assert.deepStrictEqual(state['obnew'], { }) it('Array', function () { - assert.ok('arr' in state); -assert.deepStrictEqual(state['arr'], { + assert.ok('arr' in state) + assert.deepStrictEqual(state.arr, { type: 'Array', elements: [ { type: 'number', value: '1' }, @@ -113,21 +113,21 @@ assert.deepStrictEqual(state['arr'], { }) it('RegExp', function () { - assert.ok('regex' in state); -assert.deepStrictEqual(state['regex'], { type: 'RegExp', value: '/foo/' }) + assert.ok('regex' in state) + assert.deepStrictEqual(state.regex, { type: 'RegExp', value: '/foo/' }) }) it('Date', function () { - assert.ok('date' in state); -assert.deepStrictEqual(state['date'], { + assert.ok('date' in state) + assert.deepStrictEqual(state.date, { type: 'Date', value: '2024-09-20T07:22:59Z' // missing milliseconds due to API limitation (should have been `998`) }) }) it('Map', function () { - assert.ok('map' in state); -assert.deepStrictEqual(state['map'], { + assert.ok('map' in state) + assert.deepStrictEqual(state.map, { type: 'Map', entries: [ [{ type: 'number', value: '1' }, { type: 'number', value: '2' }], @@ -137,8 +137,8 @@ assert.deepStrictEqual(state['map'], { }) it('Set', function () { - assert.ok('set' in state); -assert.deepStrictEqual(state['set'], { + assert.ok('set' in state) + assert.deepStrictEqual(state.set, { type: 'Set', elements: [ { @@ -157,11 +157,11 @@ assert.deepStrictEqual(state['set'], { it('WeakMap', function () { assert.ok(Object.hasOwn(state, 'wmap')) assert.strictEqual(Object.keys(state.wmap).length, (['type', 'entries']).length) -assert.ok((['type', 'entries']).every(k => Object.hasOwn(state.wmap, k))) + assert.ok((['type', 'entries']).every(k => Object.hasOwn(state.wmap, k))) assert.ok(Array.isArray(state.wmap.entries)) state.wmap.entries = state.wmap.entries.sort((a, b) => a[1].value - b[1].value) - assert.ok('wmap' in state); -assert.deepStrictEqual(state['wmap'], { + assert.ok('wmap' in state) + assert.deepStrictEqual(state.wmap, { type: 'WeakMap', entries: [[ { type: 'Object', fields: { a: { type: 'number', value: '1' } } }, @@ -176,11 +176,11 @@ assert.deepStrictEqual(state['wmap'], { it('WeakSet', function () { assert.ok(Object.hasOwn(state, 'wset')) assert.strictEqual(Object.keys(state.wset).length, (['type', 'elements']).length) -assert.ok((['type', 'elements']).every(k => Object.hasOwn(state.wset, k))) + assert.ok((['type', 'elements']).every(k => Object.hasOwn(state.wset, k))) assert.ok(Array.isArray(state.wset.elements)) state.wset.elements = state.wset.elements.sort((a, b) => a.fields.a.value - b.fields.a.value) - assert.ok('wset' in state); -assert.deepStrictEqual(state['wset'], { + assert.ok('wset' in state) + assert.deepStrictEqual(state.wset, { type: 'WeakSet', elements: [ { type: 'Object', fields: { a: { type: 'number', value: '1' } } }, @@ -191,8 +191,8 @@ assert.deepStrictEqual(state['wset'], { }) it('Generator', function () { - assert.ok('gen' in state); -assert.deepStrictEqual(state['gen'], { + assert.ok('gen' in state) + assert.deepStrictEqual(state.gen, { type: 'generator', fields: { foo: { type: 'number', value: '42' } } }) @@ -201,17 +201,17 @@ assert.deepStrictEqual(state['gen'], { it('Error', function () { assert.ok(Object.hasOwn(state, 'err')) assert.strictEqual(Object.keys(state.err).length, (['type', 'fields']).length) -assert.ok((['type', 'fields']).every(k => Object.hasOwn(state.err, k))) + assert.ok((['type', 'fields']).every(k => Object.hasOwn(state.err, k))) assert.strictEqual(state.err.type, 'CustomError') assert.ok(typeof state.err.fields === 'object' && state.err.fields !== null) assert.strictEqual(Object.keys(state.err.fields).length, (['stack', 'message', 'foo']).length) -assert.ok((['stack', 'message', 'foo']).every(k => Object.hasOwn(state.err.fields, k))) + assert.ok((['stack', 'message', 'foo']).every(k => Object.hasOwn(state.err.fields, k))) assertObjectContains(state.err.fields, { message: { type: 'string', value: 'boom!' }, foo: { type: 'number', value: '42' } }) assert.strictEqual(Object.keys(state.err.fields.stack).length, (['type', 'value', 'truncated', 'size']).length) -assert.ok((['type', 'value', 'truncated', 'size']).every(k => Object.hasOwn(state.err.fields.stack, k))) + assert.ok((['type', 'value', 'truncated', 'size']).every(k => Object.hasOwn(state.err.fields.stack, k))) assert.strictEqual(typeof state.err.fields.stack.value, 'string') assert.match(state.err.fields.stack.value, /^Error: boom!/) assert.strictEqual(typeof state.err.fields.stack.size, 'number') @@ -223,8 +223,8 @@ assert.ok((['type', 'value', 'truncated', 'size']).every(k => Object.hasOwn(stat }) it('Function', function () { - assert.ok('fn' in state); -assert.deepStrictEqual(state['fn'], { + assert.ok('fn' in state) + assert.deepStrictEqual(state.fn, { type: 'Function', fields: { foo: { @@ -238,8 +238,8 @@ assert.deepStrictEqual(state['fn'], { }) it('Bound function', function () { - assert.ok('bfn' in state); -assert.deepStrictEqual(state['bfn'], { + assert.ok('bfn' in state) + assert.deepStrictEqual(state.bfn, { type: 'Function', fields: { length: { type: 'number', value: '0' }, @@ -249,8 +249,8 @@ assert.deepStrictEqual(state['bfn'], { }) it('Arrow function', function () { - assert.ok('afn' in state); -assert.deepStrictEqual(state['afn'], { + assert.ok('afn' in state) + assert.deepStrictEqual(state.afn, { type: 'Function', fields: { length: { type: 'number', value: '0' }, @@ -260,18 +260,18 @@ assert.deepStrictEqual(state['afn'], { }) it('Class', function () { - assert.ok('cls' in state); -assert.deepStrictEqual(state['cls'], { type: 'class MyClass' }) + assert.ok('cls' in state) + assert.deepStrictEqual(state.cls, { type: 'class MyClass' }) }) it('Anonymous class', function () { - assert.ok('acls' in state); -assert.deepStrictEqual(state['acls'], { type: 'class' }) + assert.ok('acls' in state) + assert.deepStrictEqual(state.acls, { type: 'class' }) }) it('Proxy for object literal', function () { - assert.ok('prox' in state); -assert.deepStrictEqual(state['prox'], { + assert.ok('prox' in state) + assert.deepStrictEqual(state.prox, { type: NODE_20_PLUS ? 'Proxy(Object)' : 'Proxy', fields: { target: { type: 'boolean', value: 'true' } @@ -280,8 +280,8 @@ assert.deepStrictEqual(state['prox'], { }) it('Proxy for custom class', function () { - assert.ok('custProx' in state); -assert.deepStrictEqual(state['custProx'], { + assert.ok('custProx' in state) + assert.deepStrictEqual(state.custProx, { type: NODE_20_PLUS ? 'Proxy(MyClass)' : 'Proxy', fields: { foo: { type: 'number', value: '42' } @@ -290,8 +290,8 @@ assert.deepStrictEqual(state['custProx'], { }) it('Promise: Pending', function () { - assert.ok('pPen' in state); -assert.deepStrictEqual(state['pPen'], { + assert.ok('pPen' in state) + assert.deepStrictEqual(state.pPen, { type: 'Promise', fields: { '[[PromiseState]]': { type: 'string', value: 'pending' }, @@ -301,8 +301,8 @@ assert.deepStrictEqual(state['pPen'], { }) it('Promise: Resolved', function () { - assert.ok('pRes' in state); -assert.deepStrictEqual(state['pRes'], { + assert.ok('pRes' in state) + assert.deepStrictEqual(state.pRes, { type: 'Promise', fields: { '[[PromiseState]]': { type: 'string', value: 'fulfilled' }, @@ -312,8 +312,8 @@ assert.deepStrictEqual(state['pRes'], { }) it('Promise: Rejected', function () { - assert.ok('pRej' in state); -assert.deepStrictEqual(state['pRej'], { + assert.ok('pRej' in state) + assert.deepStrictEqual(state.pRej, { type: 'Promise', fields: { '[[PromiseState]]': { type: 'string', value: 'rejected' }, @@ -323,8 +323,8 @@ assert.deepStrictEqual(state['pRej'], { }) it('TypedArray', function () { - assert.ok('tarr' in state); -assert.deepStrictEqual(state['tarr'], { + assert.ok('tarr' in state) + assert.deepStrictEqual(state.tarr, { type: 'Int8Array', elements: [ { type: 'number', value: '72' }, @@ -335,16 +335,16 @@ assert.deepStrictEqual(state['tarr'], { }) it('ArrayBuffer', function () { - assert.ok('ab' in state); -assert.deepStrictEqual(state['ab'], { + assert.ok('ab' in state) + assert.deepStrictEqual(state.ab, { type: 'ArrayBuffer', value: 'HAL' }) }) it('SharedArrayBuffer', function () { - assert.ok('sab' in state); -assert.deepStrictEqual(state['sab'], { + assert.ok('sab' in state) + assert.deepStrictEqual(state.sab, { type: 'SharedArrayBuffer', value: 'hello\x01\x02\x03world' }) @@ -361,8 +361,8 @@ assert.deepStrictEqual(state['sab'], { }) it('non-enumerable property', function () { - assert.ok('hidden' in state); -assert.deepStrictEqual(state['hidden'], { type: 'string', value: 'secret' }) + assert.ok('hidden' in state) + assert.deepStrictEqual(state.hidden, { type: 'string', value: 'secret' }) }) }) }) diff --git a/packages/dd-trace/test/debugger/devtools_client/snapshot/max-collection-size.spec.js b/packages/dd-trace/test/debugger/devtools_client/snapshot/max-collection-size.spec.js index 49171b25d1b..caa0d1d4b7c 100644 --- a/packages/dd-trace/test/debugger/devtools_client/snapshot/max-collection-size.spec.js +++ b/packages/dd-trace/test/debugger/devtools_client/snapshot/max-collection-size.spec.js @@ -54,13 +54,13 @@ describe('debugger -> devtools client -> snapshot.getLocalStateForCallFrame', fu }) it('should have expected number of elements in state', function () { - assert.strictEqual(Object.keys(state).length, ((Array.isArray(['LARGE_SIZE', 'arr', 'map', 'set', 'wmap', 'wset', 'typedArray']) ? ['LARGE_SIZE', 'arr', 'map', 'set', 'wmap', 'wset', 'typedArray'] : [['LARGE_SIZE', 'arr', 'map', 'set', 'wmap', 'wset', 'typedArray']])).length) -assert.ok(((Array.isArray(['LARGE_SIZE', 'arr', 'map', 'set', 'wmap', 'wset', 'typedArray']) ? ['LARGE_SIZE', 'arr', 'map', 'set', 'wmap', 'wset', 'typedArray'] : [['LARGE_SIZE', 'arr', 'map', 'set', 'wmap', 'wset', 'typedArray']])).every(k => Object.hasOwn(state, k))) + assert.strictEqual(Object.keys(state).length, ((Array.isArray(['arr', 'map', 'set', 'wmap', 'wset', 'typedArray']) ? ['arr', 'map', 'set', 'wmap', 'wset', 'typedArray'] : [['arr', 'map', 'set', 'wmap', 'wset', 'typedArray']])).length) + assert.ok(((Array.isArray(['arr', 'map', 'set', 'wmap', 'wset', 'typedArray']) ? ['arr', 'map', 'set', 'wmap', 'wset', 'typedArray'] : [['arr', 'map', 'set', 'wmap', 'wset', 'typedArray']])).every(k => Object.hasOwn(state, k))) }) it('Array', function () { - assert.ok('arr' in state); -assert.deepStrictEqual(state['arr'], { + assert.ok('arr' in state) + assert.deepStrictEqual(state.arr, { type: 'Array', elements: expectedElements, notCapturedReason: 'collectionSize', @@ -69,8 +69,8 @@ assert.deepStrictEqual(state['arr'], { }) it('Map', function () { - assert.ok('map' in state); -assert.deepStrictEqual(state['map'], { + assert.ok('map' in state) + assert.deepStrictEqual(state.map, { type: 'Map', entries: expectedEntries, notCapturedReason: 'collectionSize', @@ -79,8 +79,8 @@ assert.deepStrictEqual(state['map'], { }) it('Set', function () { - assert.ok('set' in state); -assert.deepStrictEqual(state['set'], { + assert.ok('set' in state) + assert.deepStrictEqual(state.set, { type: 'Set', elements: expectedElements, notCapturedReason: 'collectionSize', @@ -130,8 +130,8 @@ assert.deepStrictEqual(state['set'], { }) it('TypedArray', function () { - assert.ok('typedArray' in state); -assert.deepStrictEqual(state['typedArray'], { + assert.ok('typedArray' in state) + assert.deepStrictEqual(state.typedArray, { type: 'Uint16Array', elements: expectedElements, notCapturedReason: 'collectionSize', diff --git a/packages/dd-trace/test/debugger/devtools_client/snapshot/max-field-count-scopes.spec.js b/packages/dd-trace/test/debugger/devtools_client/snapshot/max-field-count-scopes.spec.js index 0234c43b415..d17be63aa35 100644 --- a/packages/dd-trace/test/debugger/devtools_client/snapshot/max-field-count-scopes.spec.js +++ b/packages/dd-trace/test/debugger/devtools_client/snapshot/max-field-count-scopes.spec.js @@ -29,7 +29,7 @@ describe('debugger -> devtools client -> snapshot.getLocalStateForCallFrame', fu it('should capture expected snapshot', function () { // Expect the snapshot to have captured the first 3 fields from each scope assert.strictEqual(Object.keys(state).length, ((Array.isArray(['a1', 'b1', 'c1', 'a2', 'b2', 'c2']) ? ['a1', 'b1', 'c1', 'a2', 'b2', 'c2'] : [['a1', 'b1', 'c1', 'a2', 'b2', 'c2']])).length) -assert.ok(((Array.isArray(['a1', 'b1', 'c1', 'a2', 'b2', 'c2']) ? ['a1', 'b1', 'c1', 'a2', 'b2', 'c2'] : [['a1', 'b1', 'c1', 'a2', 'b2', 'c2']])).every(k => Object.hasOwn(state, k))) + assert.ok(((Array.isArray(['a1', 'b1', 'c1', 'a2', 'b2', 'c2']) ? ['a1', 'b1', 'c1', 'a2', 'b2', 'c2'] : [['a1', 'b1', 'c1', 'a2', 'b2', 'c2']])).every(k => Object.hasOwn(state, k))) }) }) }) diff --git a/packages/dd-trace/test/debugger/devtools_client/snapshot/max-field-count.spec.js b/packages/dd-trace/test/debugger/devtools_client/snapshot/max-field-count.spec.js index 4b007d4022a..5f3486a9bf5 100644 --- a/packages/dd-trace/test/debugger/devtools_client/snapshot/max-field-count.spec.js +++ b/packages/dd-trace/test/debugger/devtools_client/snapshot/max-field-count.spec.js @@ -41,9 +41,9 @@ function generateTestCases (config) { it('should capture expected snapshot', function () { assert.strictEqual(Object.keys(state).length, ((Array.isArray(['obj']) ? ['obj'] : [['obj']])).length) -assert.ok(((Array.isArray(['obj']) ? ['obj'] : [['obj']])).every(k => Object.hasOwn(state, k))) - assert.ok('obj' in state); -assert.deepStrictEqual(state['obj'], { + assert.ok(((Array.isArray(['obj']) ? ['obj'] : [['obj']])).every(k => Object.hasOwn(state, k))) + assert.ok('obj' in state) + assert.deepStrictEqual(state.obj, { type: 'Object', fields: expectedFields, notCapturedReason: 'fieldCount', diff --git a/packages/dd-trace/test/debugger/devtools_client/snapshot/max-reference-depth.spec.js b/packages/dd-trace/test/debugger/devtools_client/snapshot/max-reference-depth.spec.js index 4ae378f0e00..27e23224aa7 100644 --- a/packages/dd-trace/test/debugger/devtools_client/snapshot/max-reference-depth.spec.js +++ b/packages/dd-trace/test/debugger/devtools_client/snapshot/max-reference-depth.spec.js @@ -24,13 +24,13 @@ describe('debugger -> devtools client -> snapshot.getLocalStateForCallFrame', fu assert.ok(Object.hasOwn(state.myNestedObj, 'fields')) assert.strictEqual(Object.keys(state.myNestedObj).length, 2) - assert.ok('deepObj' in state.myNestedObj.fields); -assert.deepStrictEqual(state.myNestedObj.fields['deepObj'], { + assert.ok('deepObj' in state.myNestedObj.fields) + assert.deepStrictEqual(state.myNestedObj.fields.deepObj, { type: 'Object', notCapturedReason: 'depth' }) - assert.ok('deepArr' in state.myNestedObj.fields); -assert.deepStrictEqual(state.myNestedObj.fields['deepArr'], { + assert.ok('deepArr' in state.myNestedObj.fields) + assert.deepStrictEqual(state.myNestedObj.fields.deepArr, { type: 'Array', notCapturedReason: 'depth' }) }) @@ -47,8 +47,8 @@ assert.deepStrictEqual(state.myNestedObj.fields['deepArr'], { assert.ok(Object.hasOwn(state.myNestedObj, 'fields')) assert.strictEqual(Object.entries(state.myNestedObj).length, 2) - assert.ok('deepObj' in state.myNestedObj.fields); -assert.deepStrictEqual(state.myNestedObj.fields['deepObj'], { + assert.ok('deepObj' in state.myNestedObj.fields) + assert.deepStrictEqual(state.myNestedObj.fields.deepObj, { type: 'Object', fields: { foo: { @@ -70,8 +70,8 @@ assert.deepStrictEqual(state.myNestedObj.fields['deepObj'], { } }) - assert.ok('deepArr' in state.myNestedObj.fields); -assert.deepStrictEqual(state.myNestedObj.fields['deepArr'], { + assert.ok('deepArr' in state.myNestedObj.fields) + assert.deepStrictEqual(state.myNestedObj.fields.deepArr, { type: 'Array', elements: [{ type: 'Array', @@ -98,8 +98,8 @@ assert.deepStrictEqual(state.myNestedObj.fields['deepArr'], { assert.ok(Object.hasOwn(state.myNestedObj, 'fields')) assert.strictEqual(Object.entries(state.myNestedObj).length, 2) - assert.ok('deepObj' in state.myNestedObj.fields); -assert.deepStrictEqual(state.myNestedObj.fields['deepObj'], { + assert.ok('deepObj' in state.myNestedObj.fields) + assert.deepStrictEqual(state.myNestedObj.fields.deepObj, { type: 'Object', fields: { foo: { @@ -114,8 +114,8 @@ assert.deepStrictEqual(state.myNestedObj.fields['deepObj'], { } }) - assert.ok('deepArr' in state.myNestedObj.fields); -assert.deepStrictEqual(state.myNestedObj.fields['deepArr'], { + assert.ok('deepArr' in state.myNestedObj.fields) + assert.deepStrictEqual(state.myNestedObj.fields.deepArr, { type: 'Array', elements: [{ type: 'Array', diff --git a/packages/dd-trace/test/debugger/devtools_client/snapshot/primitives.spec.js b/packages/dd-trace/test/debugger/devtools_client/snapshot/primitives.spec.js index 6cacb6313ad..01ba2ccb0e7 100644 --- a/packages/dd-trace/test/debugger/devtools_client/snapshot/primitives.spec.js +++ b/packages/dd-trace/test/debugger/devtools_client/snapshot/primitives.spec.js @@ -18,20 +18,20 @@ describe('debugger -> devtools client -> snapshot.getLocalStateForCallFrame', fu it('should return expected object for primitives', function (done) { assertOnBreakpoint(done, (state) => { assert.strictEqual(Object.keys(state).length, 7) - assert.ok('undef' in state); -assert.deepStrictEqual(state['undef'], { type: 'undefined' }) - assert.ok('nil' in state); -assert.deepStrictEqual(state['nil'], { type: 'null', isNull: true }) - assert.ok('bool' in state); -assert.deepStrictEqual(state['bool'], { type: 'boolean', value: 'true' }) - assert.ok('num' in state); -assert.deepStrictEqual(state['num'], { type: 'number', value: '42' }) - assert.ok('bigint' in state); -assert.deepStrictEqual(state['bigint'], { type: 'bigint', value: '18014398509481982' }) - assert.ok('str' in state); -assert.deepStrictEqual(state['str'], { type: 'string', value: 'foo' }) - assert.ok('sym' in state); -assert.deepStrictEqual(state['sym'], { type: 'symbol', value: 'Symbol(foo)' }) + assert.ok('undef' in state) + assert.deepStrictEqual(state.undef, { type: 'undefined' }) + assert.ok('nil' in state) + assert.deepStrictEqual(state.nil, { type: 'null', isNull: true }) + assert.ok('bool' in state) + assert.deepStrictEqual(state.bool, { type: 'boolean', value: 'true' }) + assert.ok('num' in state) + assert.deepStrictEqual(state.num, { type: 'number', value: '42' }) + assert.ok('bigint' in state) + assert.deepStrictEqual(state.bigint, { type: 'bigint', value: '18014398509481982' }) + assert.ok('str' in state) + assert.deepStrictEqual(state.str, { type: 'string', value: 'foo' }) + assert.ok('sym' in state) + assert.deepStrictEqual(state.sym, { type: 'symbol', value: 'Symbol(foo)' }) }) setAndTriggerBreakpoint(target, 13) diff --git a/packages/dd-trace/test/debugger/devtools_client/snapshot/redaction.spec.js b/packages/dd-trace/test/debugger/devtools_client/snapshot/redaction.spec.js index ae0b0e35fdc..2b7b3aeef1f 100644 --- a/packages/dd-trace/test/debugger/devtools_client/snapshot/redaction.spec.js +++ b/packages/dd-trace/test/debugger/devtools_client/snapshot/redaction.spec.js @@ -17,16 +17,16 @@ describe('debugger -> devtools client -> snapshot.getLocalStateForCallFrame', fu it('should replace PII in keys/properties/variables with expected notCapturedReason', function (done) { assertOnBreakpoint(done, (state) => { assert.strictEqual(Object.keys(state).length, (['nonNormalizedSecretToken', 'foo', 'secret', 'Se_cret_$', 'weakMapKey', 'obj']).length) -assert.ok((['nonNormalizedSecretToken', 'foo', 'secret', 'Se_cret_$', 'weakMapKey', 'obj']).every(k => Object.hasOwn(state, k))) + assert.ok((['nonNormalizedSecretToken', 'foo', 'secret', 'Se_cret_$', 'weakMapKey', 'obj']).every(k => Object.hasOwn(state, k))) - assert.ok('foo' in state); -assert.deepStrictEqual(state['foo'], { type: 'string', value: 'bar' }) - assert.ok('secret' in state); -assert.deepStrictEqual(state['secret'], { type: 'string', notCapturedReason: 'redactedIdent' }) - assert.ok('Se_cret_$' in state); -assert.deepStrictEqual(state['Se_cret_$'], { type: 'string', notCapturedReason: 'redactedIdent' }) - assert.ok('weakMapKey' in state); -assert.deepStrictEqual(state['weakMapKey'], { + assert.ok('foo' in state) + assert.deepStrictEqual(state.foo, { type: 'string', value: 'bar' }) + assert.ok('secret' in state) + assert.deepStrictEqual(state.secret, { type: 'string', notCapturedReason: 'redactedIdent' }) + assert.ok('Se_cret_$' in state) + assert.deepStrictEqual(state.Se_cret_$, { type: 'string', notCapturedReason: 'redactedIdent' }) + assert.ok('weakMapKey' in state) + assert.deepStrictEqual(state.weakMapKey, { type: 'Object', fields: { secret: { type: 'string', notCapturedReason: 'redactedIdent' } } }) @@ -35,26 +35,26 @@ assert.deepStrictEqual(state['weakMapKey'], { const { fields } = state.obj assert.strictEqual(Object.keys(fields).length, (['foo', 'secret', '@Se-cret_$_', 'nested', 'arr', 'map', 'weakmap', 'password', 'Symbol(secret)', 'Symbol(@Se-cret_$_)']).length) -assert.ok((['foo', 'secret', '@Se-cret_$_', 'nested', 'arr', 'map', 'weakmap', 'password', 'Symbol(secret)', 'Symbol(@Se-cret_$_)']).every(k => Object.hasOwn(fields, k))) + assert.ok((['foo', 'secret', '@Se-cret_$_', 'nested', 'arr', 'map', 'weakmap', 'password', 'Symbol(secret)', 'Symbol(@Se-cret_$_)']).every(k => Object.hasOwn(fields, k))) - assert.ok('foo' in fields); -assert.deepStrictEqual(fields['foo'], { type: 'string', value: 'bar' }) - assert.ok('secret' in fields); -assert.deepStrictEqual(fields['secret'], { type: 'string', notCapturedReason: 'redactedIdent' }) - assert.ok('@Se-cret_$_' in fields); -assert.deepStrictEqual(fields['@Se-cret_$_'], { type: 'string', notCapturedReason: 'redactedIdent' }) - assert.ok('nested' in fields); -assert.deepStrictEqual(fields['nested'], { + assert.ok('foo' in fields) + assert.deepStrictEqual(fields.foo, { type: 'string', value: 'bar' }) + assert.ok('secret' in fields) + assert.deepStrictEqual(fields.secret, { type: 'string', notCapturedReason: 'redactedIdent' }) + assert.ok('@Se-cret_$_' in fields) + assert.deepStrictEqual(fields['@Se-cret_$_'], { type: 'string', notCapturedReason: 'redactedIdent' }) + assert.ok('nested' in fields) + assert.deepStrictEqual(fields.nested, { type: 'Object', fields: { secret: { type: 'string', notCapturedReason: 'redactedIdent' } } }) - assert.ok('arr' in fields); -assert.deepStrictEqual(fields['arr'], { + assert.ok('arr' in fields) + assert.deepStrictEqual(fields.arr, { type: 'Array', elements: [{ type: 'Object', fields: { secret: { type: 'string', notCapturedReason: 'redactedIdent' } } }] }) - assert.ok('map' in fields); -assert.deepStrictEqual(fields['map'], { + assert.ok('map' in fields) + assert.deepStrictEqual(fields.map, { type: 'Map', entries: [ [ @@ -79,18 +79,18 @@ assert.deepStrictEqual(fields['map'], { ] ] }) - assert.ok('weakmap' in fields); -assert.deepStrictEqual(fields['weakmap'], { + assert.ok('weakmap' in fields) + assert.deepStrictEqual(fields.weakmap, { type: 'WeakMap', entries: [[ { type: 'Object', fields: { secret: { type: 'string', notCapturedReason: 'redactedIdent' } } }, { type: 'number', value: '42' } ]] }) - assert.ok('password' in fields); -assert.deepStrictEqual(fields['password'], { type: 'string', notCapturedReason: 'redactedIdent' }) - assert.ok('Symbol(secret)' in fields); -assert.deepStrictEqual(fields['Symbol(secret)'], { type: 'string', notCapturedReason: 'redactedIdent' }) + assert.ok('password' in fields) + assert.deepStrictEqual(fields.password, { type: 'string', notCapturedReason: 'redactedIdent' }) + assert.ok('Symbol(secret)' in fields) + assert.deepStrictEqual(fields['Symbol(secret)'], { type: 'string', notCapturedReason: 'redactedIdent' }) }) setAndTriggerBreakpoint(target, BREAKPOINT_LINE_NUMBER) diff --git a/packages/dd-trace/test/debugger/devtools_client/snapshot/scopes.spec.js b/packages/dd-trace/test/debugger/devtools_client/snapshot/scopes.spec.js index 14e59ded9f8..e446bafb5c4 100644 --- a/packages/dd-trace/test/debugger/devtools_client/snapshot/scopes.spec.js +++ b/packages/dd-trace/test/debugger/devtools_client/snapshot/scopes.spec.js @@ -19,16 +19,16 @@ describe('debugger -> devtools client -> snapshot.getLocalStateForCallFrame', fu assertOnBreakpoint(done, (state) => { assert.strictEqual(Object.entries(state).length, 5) - assert.ok('a1' in state); -assert.deepStrictEqual(state['a1'], { type: 'number', value: '1' }) - assert.ok('a2' in state); -assert.deepStrictEqual(state['a2'], { type: 'number', value: '2' }) - assert.ok('total' in state); -assert.deepStrictEqual(state['total'], { type: 'number', value: '0' }) - assert.ok('i' in state); -assert.deepStrictEqual(state['i'], { type: 'number', value: '0' }) - assert.ok('inc' in state); -assert.deepStrictEqual(state['inc'], { type: 'number', value: '2' }) + assert.ok('a1' in state) + assert.deepStrictEqual(state.a1, { type: 'number', value: '1' }) + assert.ok('a2' in state) + assert.deepStrictEqual(state.a2, { type: 'number', value: '2' }) + assert.ok('total' in state) + assert.deepStrictEqual(state.total, { type: 'number', value: '0' }) + assert.ok('i' in state) + assert.deepStrictEqual(state.i, { type: 'number', value: '0' }) + assert.ok('inc' in state) + assert.deepStrictEqual(state.inc, { type: 'number', value: '2' }) }) setAndTriggerBreakpoint(target, 13) diff --git a/packages/dd-trace/test/llmobs/sdk/index.spec.js b/packages/dd-trace/test/llmobs/sdk/index.spec.js index a24cb03b76a..9d463104b3d 100644 --- a/packages/dd-trace/test/llmobs/sdk/index.spec.js +++ b/packages/dd-trace/test/llmobs/sdk/index.spec.js @@ -1212,8 +1212,8 @@ describe('sdk', () => { } }) - assert.ok('categorical_value' in LLMObsEvalMetricsWriter.prototype.append.getCall(0).args[0]); - assert.strictEqual(LLMObsEvalMetricsWriter.prototype.append.getCall(0).args[0]['categorical_value'], 'foo') + assert.ok('categorical_value' in LLMObsEvalMetricsWriter.prototype.append.getCall(0).args[0]) + assert.strictEqual(LLMObsEvalMetricsWriter.prototype.append.getCall(0).args[0].categorical_value, 'foo') }) it('defaults to the current time if no timestamp is provided', () => { @@ -1225,8 +1225,8 @@ describe('sdk', () => { value: 0.6 }) - assert.ok('timestamp_ms' in LLMObsEvalMetricsWriter.prototype.append.getCall(0).args[0]); - assert.strictEqual(LLMObsEvalMetricsWriter.prototype.append.getCall(0).args[0]['timestamp_ms'], 1234) + assert.ok('timestamp_ms' in LLMObsEvalMetricsWriter.prototype.append.getCall(0).args[0]) + assert.strictEqual(LLMObsEvalMetricsWriter.prototype.append.getCall(0).args[0].timestamp_ms, 1234) Date.now.restore() }) diff --git a/packages/dd-trace/test/log.spec.js b/packages/dd-trace/test/log.spec.js index 7253a0b1b4c..376d29c8b54 100644 --- a/packages/dd-trace/test/log.spec.js +++ b/packages/dd-trace/test/log.spec.js @@ -165,8 +165,8 @@ describe('log', () => { it('should call the logger in a noop context', () => { logger.debug = () => { - assert.ok('noop' in storage('legacy').getStore()); - assert.strictEqual(storage('legacy').getStore()['noop'], true) + assert.ok('noop' in storage('legacy').getStore()) + assert.strictEqual(storage('legacy').getStore().noop, true) } log.use(logger).debug('debug') diff --git a/packages/dd-trace/test/opentracing/propagation/text_map.spec.js b/packages/dd-trace/test/opentracing/propagation/text_map.spec.js index 6cbe77299ef..32e701b5ccf 100644 --- a/packages/dd-trace/test/opentracing/propagation/text_map.spec.js +++ b/packages/dd-trace/test/opentracing/propagation/text_map.spec.js @@ -101,12 +101,12 @@ describe('TextMapPropagator', () => { propagator.inject(spanContext, carrier) - assert.ok('x-datadog-trace-id' in carrier); - assert.strictEqual(carrier['x-datadog-trace-id'], '123') - assert.ok('x-datadog-parent-id' in carrier); - assert.strictEqual(carrier['x-datadog-parent-id'], '456') - assert.ok('ot-baggage-foo' in carrier); - assert.strictEqual(carrier['ot-baggage-foo'], 'bar') + assert.ok('x-datadog-trace-id' in carrier) + assert.strictEqual(carrier['x-datadog-trace-id'], '123') + assert.ok('x-datadog-parent-id' in carrier) + assert.strictEqual(carrier['x-datadog-parent-id'], '456') + assert.ok('ot-baggage-foo' in carrier) + assert.strictEqual(carrier['ot-baggage-foo'], 'bar') assert.strictEqual(carrier.baggage, undefined) }) @@ -165,8 +165,8 @@ describe('TextMapPropagator', () => { propagator.inject(spanContext, carrier) - assert.ok('x-datadog-sampling-priority' in carrier); - assert.strictEqual(carrier['x-datadog-sampling-priority'], '0') + assert.ok('x-datadog-sampling-priority' in carrier) + assert.strictEqual(carrier['x-datadog-sampling-priority'], '0') }) it('should inject the origin', () => { @@ -180,8 +180,8 @@ describe('TextMapPropagator', () => { propagator.inject(spanContext, carrier) - assert.ok('x-datadog-origin' in carrier); - assert.strictEqual(carrier['x-datadog-origin'], 'synthetics') + assert.ok('x-datadog-origin' in carrier) + assert.strictEqual(carrier['x-datadog-origin'], 'synthetics') }) it('should inject trace tags prefixed for propagation', () => { @@ -198,8 +198,8 @@ describe('TextMapPropagator', () => { propagator.inject(spanContext, carrier) - assert.ok('x-datadog-tags' in carrier); - assert.strictEqual(carrier['x-datadog-tags'], '_dd.p.foo=foo,_dd.p.baz=baz') + assert.ok('x-datadog-tags' in carrier) + assert.strictEqual(carrier['x-datadog-tags'], '_dd.p.foo=foo,_dd.p.baz=baz') }) it('should drop trace tags if too large', () => { @@ -279,16 +279,16 @@ describe('TextMapPropagator', () => { propagator.inject(spanContext, carrier) - assert.ok('x-b3-traceid' in carrier); - assert.strictEqual(carrier['x-b3-traceid'], '0000000000000123') - assert.ok('x-b3-spanid' in carrier); - assert.strictEqual(carrier['x-b3-spanid'], '0000000000000456') - assert.ok('x-b3-parentspanid' in carrier); - assert.strictEqual(carrier['x-b3-parentspanid'], '0000000000000789') - assert.ok('x-b3-sampled' in carrier); - assert.strictEqual(carrier['x-b3-sampled'], '1') - assert.ok('x-b3-flags' in carrier); - assert.strictEqual(carrier['x-b3-flags'], '1') + assert.ok('x-b3-traceid' in carrier) + assert.strictEqual(carrier['x-b3-traceid'], '0000000000000123') + assert.ok('x-b3-spanid' in carrier) + assert.strictEqual(carrier['x-b3-spanid'], '0000000000000456') + assert.ok('x-b3-parentspanid' in carrier) + assert.strictEqual(carrier['x-b3-parentspanid'], '0000000000000789') + assert.ok('x-b3-sampled' in carrier) + assert.strictEqual(carrier['x-b3-sampled'], '1') + assert.ok('x-b3-flags' in carrier) + assert.strictEqual(carrier['x-b3-flags'], '1') }) it('should inject the 128-bit trace ID in B3 headers when available as tag', () => { @@ -306,8 +306,8 @@ describe('TextMapPropagator', () => { propagator.inject(spanContext, carrier) - assert.ok('x-b3-traceid' in carrier); - assert.strictEqual(carrier['x-b3-traceid'], '00000000000002340000000000000123') + assert.ok('x-b3-traceid' in carrier) + assert.strictEqual(carrier['x-b3-traceid'], '00000000000002340000000000000123') }) it('should inject the 128-bit trace ID in B3 headers when available as ID', () => { @@ -325,8 +325,8 @@ describe('TextMapPropagator', () => { propagator.inject(spanContext, carrier) - assert.ok('x-b3-traceid' in carrier); - assert.strictEqual(carrier['x-b3-traceid'], '00000000000002340000000000000123') + assert.ok('x-b3-traceid' in carrier) + assert.strictEqual(carrier['x-b3-traceid'], '00000000000002340000000000000123') }) it('should inject the traceparent header', () => { @@ -350,10 +350,10 @@ describe('TextMapPropagator', () => { propagator.inject(spanContext, carrier) assert.strictEqual(spanContext._isRemote, false) - assert.ok('traceparent' in carrier); - assert.strictEqual(carrier['traceparent'], '00-1111aaaa2222bbbb3333cccc4444dddd-5555eeee6666ffff-01') - assert.ok('tracestate' in carrier); - assert.strictEqual(carrier['tracestate'], 'dd=t.foo_bar_baz_:abc_!@#$%^&*()_+`-~;p:5555eeee6666ffff;s:2;o:foo_bar~;t.dm:-4,other=bleh') + assert.ok('traceparent' in carrier) + assert.strictEqual(carrier.traceparent, '00-1111aaaa2222bbbb3333cccc4444dddd-5555eeee6666ffff-01') + assert.ok('tracestate' in carrier) + assert.strictEqual(carrier.tracestate, 'dd=t.foo_bar_baz_:abc_!@#$%^&*()_+`-~;p:5555eeee6666ffff;s:2;o:foo_bar~;t.dm:-4,other=bleh') }) it('should skip injection of B3 headers without the feature flag', () => { @@ -451,7 +451,7 @@ describe('TextMapPropagator', () => { propagator.inject(undefined, carrier) - sinon.assert.calledWith(tracerMetrics.count, + sinon.assert.calledWith(tracerMetrics.count, 'context_header.truncated', ['truncation_reason:baggage_item_count_exceeded'] ) @@ -471,7 +471,7 @@ describe('TextMapPropagator', () => { propagator.inject(undefined, carrier) - sinon.assert.calledWith(tracerMetrics.count, + sinon.assert.calledWith(tracerMetrics.count, 'context_header.truncated', ['truncation_reason:baggage_byte_count_exceeded'] ) @@ -715,8 +715,8 @@ describe('TextMapPropagator', () => { const carrier = textMap const spanContext = propagator.extract(carrier) - assert.ok('origin' in spanContext._trace); - assert.strictEqual(spanContext._trace['origin'], 'synthetics') + assert.ok('origin' in spanContext._trace) + assert.strictEqual(spanContext._trace.origin, 'synthetics') }) it('should extract trace tags', () => { @@ -846,8 +846,8 @@ describe('TextMapPropagator', () => { const carrier = textMap const spanContext = propagator.extract(carrier) - assert.ok('_dd.parent_id' in spanContext._trace.tags); - assert.strictEqual(spanContext._trace.tags['_dd.parent_id'], '2244eeee6666aaaa') + assert.ok('_dd.parent_id' in spanContext._trace.tags) + assert.strictEqual(spanContext._trace.tags['_dd.parent_id'], '2244eeee6666aaaa') }) it('should preserve trace header tid when tracestate contains an inconsistent tid', () => { @@ -859,8 +859,8 @@ describe('TextMapPropagator', () => { const spanContext = propagator.extract(carrier) assert.strictEqual(spanContext._traceId.toString(16), '640cfd8d00000000abcdefab12345678') - assert.ok('_dd.p.tid' in spanContext._trace.tags); - assert.strictEqual(spanContext._trace.tags['_dd.p.tid'], '640cfd8d00000000') + assert.ok('_dd.p.tid' in spanContext._trace.tags) + assert.strictEqual(spanContext._trace.tags['_dd.p.tid'], '640cfd8d00000000') }) it('should preserve trace header tid when tracestate contains a malformed tid', () => { @@ -872,8 +872,8 @@ describe('TextMapPropagator', () => { const spanContext = propagator.extract(carrier) assert.strictEqual(spanContext._traceId.toString(16), '640cfd8d00000000abcdefab12345678') - assert.ok('_dd.p.tid' in spanContext._trace.tags); - assert.strictEqual(spanContext._trace.tags['_dd.p.tid'], '640cfd8d00000000') + assert.ok('_dd.p.tid' in spanContext._trace.tags) + assert.strictEqual(spanContext._trace.tags['_dd.p.tid'], '640cfd8d00000000') }) it('should set the last datadog parent id to zero when p: is NOT in the tracestate', () => { @@ -919,8 +919,8 @@ describe('TextMapPropagator', () => { const spanContext = propagator.extract(carrier) assert.strictEqual(parseInt(spanContext._spanId.toString(), 16), 73456) assert.strictEqual(parseInt(spanContext._traceId.toString(), 16), 61185) - assert.ok('_dd.parent_id' in spanContext._trace.tags); - assert.strictEqual(spanContext._trace.tags['_dd.parent_id'], '000000000000000f') + assert.ok('_dd.parent_id' in spanContext._trace.tags) + assert.strictEqual(spanContext._trace.tags['_dd.parent_id'], '000000000000000f') }) it('extracts span_id from tracecontext headers and stores p value from tracestate in trace_distributed_tags', @@ -935,8 +935,8 @@ describe('TextMapPropagator', () => { const spanContext = propagator.extract(carrier) assert.strictEqual(parseInt(spanContext._spanId.toString(), 16), 73456) assert.strictEqual(parseInt(spanContext._traceId.toString(), 16), 61185) - assert.ok('_dd.parent_id' in spanContext._trace.tags); - assert.strictEqual(spanContext._trace.tags['_dd.parent_id'], '0000000000000001') + assert.ok('_dd.parent_id' in spanContext._trace.tags) + assert.strictEqual(spanContext._trace.tags['_dd.parent_id'], '0000000000000001') }) it('should publish spanContext and carrier', () => { @@ -1281,8 +1281,8 @@ describe('TextMapPropagator', () => { assert.strictEqual(spanContext._spanId.toString(16), '5555eeee6666ffff') assert.strictEqual(spanContext._sampling.priority, USER_KEEP) assert.strictEqual(spanContext._trace.origin, 'foo') - assert.ok('_dd.p.foo_bar_baz_' in spanContext._trace.tags); - assert.strictEqual(spanContext._trace.tags['_dd.p.foo_bar_baz_'], 'abc_!@#$%^&*()_+`-=') + assert.ok('_dd.p.foo_bar_baz_' in spanContext._trace.tags) + assert.strictEqual(spanContext._trace.tags['_dd.p.foo_bar_baz_'], 'abc_!@#$%^&*()_+`-=') assert.deepStrictEqual(spanContext._trace.tags['_dd.p.dm'], '-4') }) @@ -1294,8 +1294,8 @@ describe('TextMapPropagator', () => { const carrier = textMap const spanContext = propagator.extract(carrier) assert.strictEqual(spanContext._traceId.toString(16), '1111aaaa2222bbbb3333cccc4444dddd') - assert.ok('_dd.p.tid' in spanContext._trace.tags); - assert.strictEqual(spanContext._trace.tags['_dd.p.tid'], '1111aaaa2222bbbb') + assert.ok('_dd.p.tid' in spanContext._trace.tags) + assert.strictEqual(spanContext._trace.tags['_dd.p.tid'], '1111aaaa2222bbbb') }) it('should skip extracting upper bits for 64-bit trace IDs', () => { diff --git a/packages/dd-trace/test/opentracing/span.spec.js b/packages/dd-trace/test/opentracing/span.spec.js index 1ac27d89f82..3a79546ac68 100644 --- a/packages/dd-trace/test/opentracing/span.spec.js +++ b/packages/dd-trace/test/opentracing/span.spec.js @@ -215,9 +215,9 @@ describe('Span', () => { span = new Span(tracer, processor, prioritySampler, { operationName: 'operation', parent }) span.setBaggageItem('foo', 'bar') - assert.ok('foo' in span.context()._baggageItems); - assert.strictEqual(span.context()._baggageItems['foo'], 'bar') - assert.ok(!('foo' in parent._baggageItems) || parent._baggageItems['foo'] !== 'bar') + assert.ok('foo' in span.context()._baggageItems) + assert.strictEqual(span.context()._baggageItems.foo, 'bar') + assert.ok(!('foo' in parent._baggageItems) || parent._baggageItems.foo !== 'bar') }) it('should pass baggage items to future causal spans', () => { @@ -235,8 +235,8 @@ describe('Span', () => { span = new Span(tracer, processor, prioritySampler, { operationName: 'operation', parent }) - assert.ok('foo' in span.context()._baggageItems); - assert.strictEqual(span.context()._baggageItems['foo'], 'bar') + assert.ok('foo' in span.context()._baggageItems) + assert.strictEqual(span.context()._baggageItems.foo, 'bar') }) }) diff --git a/packages/dd-trace/test/plugins/util/test-environment.spec.js b/packages/dd-trace/test/plugins/util/test-environment.spec.js index fc900e5fcc7..c752c21be97 100644 --- a/packages/dd-trace/test/plugins/util/test-environment.spec.js +++ b/packages/dd-trace/test/plugins/util/test-environment.spec.js @@ -1,8 +1,8 @@ 'use strict' const assert = require('node:assert/strict') -const { assertObjectContains } = require('../../../../../integration-tests/helpers') +const { assertObjectContains } = require('../../../../../integration-tests/helpers') const { describe, it } = require('tap').mocha const fs = require('node:fs') const path = require('node:path') diff --git a/packages/dd-trace/test/plugins/util/web.spec.js b/packages/dd-trace/test/plugins/util/web.spec.js index a9475aad3be..dc65aa98dba 100644 --- a/packages/dd-trace/test/plugins/util/web.spec.js +++ b/packages/dd-trace/test/plugins/util/web.spec.js @@ -133,8 +133,8 @@ describe('plugins/util/web', () => { queryStringObfuscation: 'a*' }) - assert.ok('queryStringObfuscation' in config); -assert.deepStrictEqual(config['queryStringObfuscation'], /a*/gi) + assert.ok('queryStringObfuscation' in config) + assert.deepStrictEqual(config.queryStringObfuscation, /a*/gi) }) it('should default to true when passed a bad regex', () => { @@ -333,8 +333,8 @@ assert.deepStrictEqual(config['queryStringObfuscation'], /a*/gi) config.service = 'test2' web.instrument(tracer, config, req, res, 'test.request') - assert.ok('service.name' in span.context()._tags); - assert.strictEqual(span.context()._tags['service.name'], 'test2') + assert.ok('service.name' in span.context()._tags) + assert.strictEqual(span.context()._tags['service.name'], 'test2') }) }) diff --git a/packages/dd-trace/test/span_processor.spec.js b/packages/dd-trace/test/span_processor.spec.js index 47544990a55..cda79fcd4a1 100644 --- a/packages/dd-trace/test/span_processor.spec.js +++ b/packages/dd-trace/test/span_processor.spec.js @@ -84,12 +84,12 @@ describe('SpanProcessor', () => { processor.process(finishedSpan) - assert.ok('started' in trace); -assert.deepStrictEqual(trace['started'], []) - assert.ok('finished' in trace); -assert.deepStrictEqual(trace['finished'], []) - assert.ok('_tags' in finishedSpan.context()); -assert.deepStrictEqual(finishedSpan.context()['_tags'], {}) + assert.ok('started' in trace) + assert.deepStrictEqual(trace.started, []) + assert.ok('finished' in trace) + assert.deepStrictEqual(trace.finished, []) + assert.ok('_tags' in finishedSpan.context()) + assert.deepStrictEqual(finishedSpan.context()._tags, {}) }) it('should skip traces with unfinished spans', () => { @@ -120,10 +120,10 @@ assert.deepStrictEqual(finishedSpan.context()['_tags'], {}) { formatted: true } ]) - assert.ok('started' in trace); -assert.deepStrictEqual(trace['started'], [activeSpan]) - assert.ok('finished' in trace); -assert.deepStrictEqual(trace['finished'], []) + assert.ok('started' in trace) + assert.deepStrictEqual(trace.started, [activeSpan]) + assert.ok('finished' in trace) + assert.deepStrictEqual(trace.finished, []) }) it('should configure span sampler correctly', () => { @@ -162,12 +162,12 @@ assert.deepStrictEqual(trace['finished'], []) processor.process(finishedSpan) - assert.ok('started' in trace); -assert.deepStrictEqual(trace['started'], []) - assert.ok('finished' in trace); -assert.deepStrictEqual(trace['finished'], []) - assert.ok('_tags' in finishedSpan.context()); -assert.deepStrictEqual(finishedSpan.context()['_tags'], {}) + assert.ok('started' in trace) + assert.deepStrictEqual(trace.started, []) + assert.ok('finished' in trace) + assert.deepStrictEqual(trace.finished, []) + assert.ok('_tags' in finishedSpan.context()) + assert.deepStrictEqual(finishedSpan.context()._tags, {}) sinon.assert.notCalled(exporter.export) }) @@ -178,10 +178,10 @@ assert.deepStrictEqual(finishedSpan.context()['_tags'], {}) trace.finished = [finishedSpan] processor.process(activeSpan) - assert.ok('started' in trace); -assert.deepStrictEqual(trace['started'], [activeSpan]) - assert.ok('finished' in trace); -assert.deepStrictEqual(trace['finished'], []) + assert.ok('started' in trace) + assert.deepStrictEqual(trace.started, [activeSpan]) + assert.ok('finished' in trace) + assert.deepStrictEqual(trace.finished, []) assert.strictEqual(spanFormat.callCount, 1) sinon.assert.calledWith(spanFormat, finishedSpan, true) }) diff --git a/packages/dd-trace/test/standalone/index.spec.js b/packages/dd-trace/test/standalone/index.spec.js index da88bab4da1..3198317d3bb 100644 --- a/packages/dd-trace/test/standalone/index.spec.js +++ b/packages/dd-trace/test/standalone/index.spec.js @@ -358,7 +358,7 @@ describe('Disabled APM Tracing or Standalone', () => { const propagator = new TextMapPropagator(config) propagator.inject(span._spanContext, carrier) - assert.strictEqual(carrier['tracestate'], 'other=id:0xC0FFEE') + assert.strictEqual(carrier.tracestate, 'other=id:0xC0FFEE') assert.ok(!Object.hasOwn(carrier, 'traceparent')) }) }) diff --git a/packages/dd-trace/test/standalone/product.spec.js b/packages/dd-trace/test/standalone/product.spec.js index 2f812473716..1d8132d3292 100644 --- a/packages/dd-trace/test/standalone/product.spec.js +++ b/packages/dd-trace/test/standalone/product.spec.js @@ -31,20 +31,20 @@ describe('Disabled APM Tracing or Standalone - Product', () => { describe('getProductRateLimiter', () => { it('should return a drop all traces rateLimiter by default', () => { const rateLimiter = getProductRateLimiter({}) - assert.strictEqual(rateLimiter['limit'], 0) - assert.strictEqual(rateLimiter['interval'], 'second') + assert.strictEqual(rateLimiter.limit, 0) + assert.strictEqual(rateLimiter.interval, 'second') }) it('should return a 1req/min rateLimiter when appsec is enabled', () => { const rateLimiter = getProductRateLimiter({ appsec: { enabled: true } }) - assert.strictEqual(rateLimiter['limit'], 1) - assert.strictEqual(rateLimiter['interval'], 'minute') + assert.strictEqual(rateLimiter.limit, 1) + assert.strictEqual(rateLimiter.interval, 'minute') }) it('should return a 1req/min rateLimiter when iast is enabled', () => { const rateLimiter = getProductRateLimiter({ iast: { enabled: true } }) - assert.strictEqual(rateLimiter['limit'], 1) - assert.strictEqual(rateLimiter['interval'], 'minute') + assert.strictEqual(rateLimiter.limit, 1) + assert.strictEqual(rateLimiter.interval, 'minute') }) }) }) diff --git a/packages/dd-trace/test/telemetry/endpoints.spec.js b/packages/dd-trace/test/telemetry/endpoints.spec.js index d62cb6468fe..2cfa805e313 100644 --- a/packages/dd-trace/test/telemetry/endpoints.spec.js +++ b/packages/dd-trace/test/telemetry/endpoints.spec.js @@ -138,8 +138,8 @@ describe('endpoints telemetry', () => { const firstPayload = sendData.firstCall.args[4] const secondPayload = sendData.secondCall.args[4] - assert.ok('is_first' in firstPayload); - assert.strictEqual(firstPayload['is_first'], true) + assert.ok('is_first' in firstPayload) + assert.strictEqual(firstPayload.is_first, true) assert.strictEqual(Boolean(secondPayload.is_first), false) }) From e96695b31730552a8ceefc50a7fc19e11a1868c5 Mon Sep 17 00:00:00 2001 From: Ruben Bridgewater Date: Thu, 27 Nov 2025 01:10:57 +0900 Subject: [PATCH 5/5] fixup! manual things --- integration-tests/appsec/graphql.spec.js | 4 +- integration-tests/appsec/iast-esbuild.spec.js | 2 +- .../iast-stack-traces-with-sourcemaps.spec.js | 8 +- .../appsec/iast.esm-security-controls.spec.js | 12 +- integration-tests/appsec/iast.esm.spec.js | 4 +- integration-tests/appsec/index.spec.js | 4 +- .../appsec/standalone-asm.spec.js | 20 +- .../support/steps.js | 2 +- .../automatic-log-submission.spec.js | 28 +- .../automatic-log-submission-test.js | 2 +- .../parallel-test-hit-breakpoint-1.js | 2 +- .../parallel-test-hit-breakpoint-2.js | 2 +- .../test-hit-breakpoint.js | 2 +- .../test-not-hit-breakpoint.js | 2 +- .../features-selenium/support/steps.js | 2 +- .../ci-visibility/git-cache.spec.js | 14 +- .../jest-bad-import-test-pass-2.js | 2 +- .../jest-bad-import-test-pass.js | 2 +- .../jest-bad-import-test.js | 2 +- .../jest-bad-import-test-pass-2.js | 2 +- .../jest-bad-import-test-pass.js | 2 +- .../jest-bad-import/jest-bad-import-test.js | 2 +- .../jest-fast-check/jest-no-fast-check.js | 2 +- .../ci-visibility/jest-flaky/flaky-fails.js | 2 +- .../ci-visibility/jest-flaky/flaky-passes.js | 2 +- .../non-dependency-mock-test-2.js | 2 +- .../non-dependency-mock-test-3.js | 2 +- .../non-dependency-mock-test-4.js | 2 +- .../non-dependency-mock-test-5.js | 2 +- .../non-dependency-mock-test-6.js | 2 +- .../non-dependency-mock-test.js | 2 +- .../jest-plugin-tests/jest-inject-globals.js | 4 +- .../jest-plugin-tests/jest-test.js | 2 +- .../ci-visibility/jest/failing-test.js | 2 +- .../ci-visibility/jest/mocked-test.js | 2 +- .../mocha-plugin-tests/active-span-hooks.js | 2 +- .../mocha-plugin-tests/async-fail.js | 2 +- .../mocha-plugin-tests/async-pass.js | 2 +- .../mocha-plugin-tests/done-fail-badly.js | 2 +- .../mocha-plugin-tests/done-fail.js | 2 +- .../mocha-plugin-tests/done-pass.js | 2 +- .../mocha-plugin-tests/failing.js | 2 +- .../mocha-plugin-tests/hook-async-error.js | 2 +- .../mocha-plugin-tests/hook-sync-error.js | 2 +- .../mocha-plugin-tests/parameterized.js | 2 +- .../mocha-plugin-tests/passing.js | 2 +- .../mocha-plugin-tests/promise-fail.js | 2 +- .../mocha-plugin-tests/promise-pass.js | 2 +- .../mocha-plugin-tests/retries.js | 2 +- .../mocha-plugin-tests/skip-describe.js | 2 +- .../mocha-plugin-tests/skipping.js | 2 +- .../suite-level-fail-after-each.js | 2 +- .../suite-level-fail-skip-describe.js | 2 +- .../suite-level-fail-test.js | 2 +- .../mocha-plugin-tests/suite-level-pass.js | 2 +- .../ci-visibility/office-addin-mock/test.js | 2 +- .../sharding-test/sharding-test-1.js | 2 +- .../sharding-test/sharding-test-2.js | 2 +- .../sharding-test/sharding-test-3.js | 2 +- .../sharding-test/sharding-test-4.js | 2 +- .../sharding-test/sharding-test-5.js | 2 +- .../subproject/subproject-test.js | 2 +- .../ci-visibility/test-api-manual.spec.js | 11 +- .../test-custom-tags/custom-tags.js | 2 +- .../mocha-parameterized.js | 2 +- .../occasionally-failing-test.js | 2 +- .../skipped-and-todo-test.js | 2 +- .../test-parameterized.js | 2 +- .../test-early-flake-detection/test.js | 2 +- .../weird-test-names.js | 2 +- .../eventually-passing-test.js | 2 +- .../test-impacted-test/test-impacted-1.js | 2 +- .../test-impacted-test/test-impacted-2.js | 2 +- .../test-management/test-attempt-to-fix-1.js | 2 +- .../test-management/test-attempt-to-fix-2.js | 2 +- .../test-management/test-disabled-1.js | 2 +- .../test-management/test-disabled-2.js | 2 +- .../test-management/test-quarantine-1.js | 2 +- .../test-management/test-quarantine-2.js | 2 +- .../test-nested-hooks/test-nested-hooks.js | 2 +- .../test-optimization-startup.spec.js | 16 +- .../support/steps.js | 2 +- .../test-optimization-wrong-init.spec.js | 2 +- .../test-parsing-error/parsing-error-2.js | 4 +- .../test-parsing-error/parsing-error.js | 4 +- .../test-total-code-coverage/test-run.js | 2 +- .../test-total-code-coverage/test-skipped.js | 2 +- .../test/ci-visibility-test-2.js | 2 +- .../ci-visibility/test/ci-visibility-test.js | 2 +- .../test/efd-parallel/ci-visibility-test-2.js | 2 +- .../test/efd-parallel/ci-visibility-test-3.js | 2 +- .../test/efd-parallel/ci-visibility-test-4.js | 2 +- .../test/efd-parallel/ci-visibility-test.js | 2 +- .../ci-visibility/test/fail-test.js | 2 +- .../ci-visibility/test/selenium-test.js | 2 +- .../unskippable-test/test-to-run.js | 2 +- .../unskippable-test/test-to-skip.js | 2 +- .../unskippable-test/test-unskippable.js | 5 +- integration-tests/cucumber/cucumber.spec.js | 182 ++++---- integration-tests/cypress/cypress.spec.js | 246 +++++----- integration-tests/debugger/basic.spec.js | 64 +-- integration-tests/debugger/ddtags.spec.js | 23 +- integration-tests/debugger/redact.spec.js | 18 +- .../debugger/snapshot-pruning.spec.js | 4 +- integration-tests/debugger/snapshot.spec.js | 2 +- integration-tests/helpers/fake-agent.js | 2 - integration-tests/helpers/index.js | 30 +- integration-tests/jest/jest.spec.js | 435 ++++++++++-------- integration-tests/mocha/mocha.spec.js | 306 ++++++------ .../openfeature-exposure-events.spec.js | 23 +- integration-tests/opentelemetry.spec.js | 6 +- integration-tests/package-guardrails.spec.js | 10 +- integration-tests/pino.spec.js | 20 +- .../playwright/playwright.spec.js | 281 ++++++----- integration-tests/profiler/profiler.spec.js | 68 +-- integration-tests/selenium/selenium.spec.js | 21 +- integration-tests/vitest/vitest.spec.js | 149 +++--- packages/datadog-code-origin/test/helpers.js | 6 +- packages/datadog-core/test/storage.spec.js | 2 +- .../test/express-mongo-sanitize.spec.js | 11 +- .../test/helpers/check-require-cache.spec.js | 3 +- .../datadog-plugin-amqp10/test/index.spec.js | 2 +- .../datadog-plugin-amqplib/test/index.spec.js | 6 +- .../datadog-plugin-apollo/test/index.spec.js | 6 +- .../test/kinesis.spec.js | 4 +- .../datadog-plugin-aws-sdk/test/sns.spec.js | 2 +- .../datadog-plugin-bunyan/test/index.spec.js | 6 +- .../test/index.spec.js | 7 +- .../test/scrub-cmd-params.spec.js | 12 +- .../test/index.spec.js | 12 +- .../test/code_origin.spec.js | 2 +- .../datadog-plugin-express/test/index.spec.js | 2 +- .../test/code_origin.spec.js | 2 +- .../test/tracing.spec.js | 6 +- .../datadog-plugin-fetch/test/index.spec.js | 2 +- .../datadog-plugin-graphql/test/index.spec.js | 42 +- .../datadog-plugin-grpc/test/server.spec.js | 2 +- .../datadog-plugin-hapi/test/index.spec.js | 5 +- .../datadog-plugin-http/test/client.spec.js | 8 +- .../datadog-plugin-jest/test/util.spec.js | 10 +- .../datadog-plugin-kafkajs/test/index.spec.js | 76 ++- .../datadog-plugin-koa/test/index.spec.js | 2 +- .../test/index.spec.js | 2 +- .../test/index.spec.js | 2 +- .../test/core.spec.js | 2 +- .../datadog-plugin-openai/test/index.spec.js | 5 +- .../test/index.spec.js | 7 +- .../datadog-plugin-pino/test/index.spec.js | 8 +- .../datadog-plugin-rhea/test/index.spec.js | 6 +- .../datadog-plugin-sharedb/test/index.spec.js | 5 +- .../datadog-plugin-undici/test/index.spec.js | 2 +- .../datadog-plugin-winston/test/index.spec.js | 3 +- packages/dd-trace/src/id.js | 60 +++ .../hardcoded-password-analyzer.spec.js | 22 +- .../hardcoded-secret-analyzer.spec.js | 5 +- .../analyzers/vulnerability-analyzer.spec.js | 4 +- .../test/appsec/iast/iast-plugin.spec.js | 10 +- .../dd-trace/test/appsec/iast/index.spec.js | 15 +- .../overhead-controller.integration.spec.js | 2 +- .../appsec/iast/overhead-controller.spec.js | 39 +- .../taint-tracking-operations.spec.js | 12 +- packages/dd-trace/test/appsec/iast/utils.js | 11 +- .../iast/vulnerability-reporter.spec.js | 2 +- .../test/appsec/index.express.plugin.spec.js | 2 +- .../test/appsec/index.fastify.plugin.spec.js | 8 +- .../command_injection.integration.spec.js | 2 +- .../test/appsec/rasp/fs-plugin.spec.js | 4 +- .../lfi.integration.express.plugin.spec.js | 2 +- ...ql_injection.integration.pg.plugin.spec.js | 6 +- packages/dd-trace/test/appsec/rasp/utils.js | 4 +- .../dd-trace/test/appsec/reporter.spec.js | 2 +- .../test/appsec/response_blocking.spec.js | 34 +- .../dd-trace/test/appsec/rule_manager.spec.js | 12 +- .../dd-trace/test/appsec/sdk/set_user.spec.js | 4 +- .../sdk/track_event-integration.spec.js | 25 +- .../dd-trace/test/appsec/stack_trace.spec.js | 2 +- .../test/appsec/telemetry/waf.spec.js | 35 +- .../exporters/agent-proxy/agent-proxy.spec.js | 4 +- .../exporters/agentless/exporter.spec.js | 7 +- .../exporters/ci-visibility-exporter.spec.js | 14 +- .../exporters/git/git_metadata.spec.js | 18 +- packages/dd-trace/test/config.spec.js | 16 +- .../data_streams_checkpointer.spec.js | 7 +- .../snapshot/max-collection-size.spec.js | 6 +- .../snapshot/max-field-count-scopes.spec.js | 3 +- .../snapshot/redaction.spec.js | 30 +- packages/dd-trace/test/encode/0.5.spec.js | 12 +- .../encode/coverage-ci-visibility.spec.js | 37 +- .../dd-trace/test/encode/span-stats.spec.js | 11 +- .../common/agent-info-exporter.spec.js | 9 +- .../dd-trace/test/llmobs/sdk/index.spec.js | 1 - .../test/llmobs/span_processor.spec.js | 10 +- packages/dd-trace/test/llmobs/tagger.spec.js | 2 +- packages/dd-trace/test/llmobs/util.spec.js | 5 +- .../flagging_provider_timeout.spec.js | 7 +- .../dd-trace/test/opentelemetry/span.spec.js | 8 +- .../opentracing/propagation/text_map.spec.js | 56 ++- packages/dd-trace/test/plugins/agent.js | 14 +- .../dd-trace/test/plugins/log_plugin.spec.js | 4 +- .../dd-trace/test/plugins/outbound.spec.js | 2 +- .../dd-trace/test/plugins/util/llm.spec.js | 11 +- .../plugins/util/test-environment.spec.js | 12 +- .../dd-trace/test/plugins/util/web.spec.js | 10 +- .../dd-trace/test/priority_sampler.spec.js | 8 +- .../test/remote_config/manager.spec.js | 2 +- packages/dd-trace/test/span_format.spec.js | 24 +- packages/dd-trace/test/span_processor.spec.js | 12 +- .../dd-trace/test/standalone/index.spec.js | 16 +- .../test/standalone/tracesource.spec.js | 2 +- packages/dd-trace/test/tagger.spec.js | 14 +- .../dd-trace/test/telemetry/endpoints.spec.js | 6 +- .../dd-trace/test/telemetry/index.spec.js | 17 +- packages/dd-trace/test/tracer.spec.js | 4 +- scripts/codemods/chai-to-assert.js | 5 +- 214 files changed, 1780 insertions(+), 1446 deletions(-) diff --git a/integration-tests/appsec/graphql.spec.js b/integration-tests/appsec/graphql.spec.js index 1b040f2e972..cdcc7ebfdb3 100644 --- a/integration-tests/appsec/graphql.spec.js +++ b/integration-tests/appsec/graphql.spec.js @@ -45,8 +45,8 @@ describe('graphql', () => { assert.strictEqual(payload[1][0].name, 'web.request') assert.strictEqual(payload[1][0].metrics['_dd.appsec.enabled'], 1) assert.ok(Object.hasOwn(payload[1][0].metrics, '_dd.appsec.waf.duration')) - assert.ok(!Object.hasOwn(payload[1][0].meta, '_dd.appsec.event')) - assert.ok(!Object.hasOwn(payload[1][0].meta, '_dd.appsec.json')) + assert.ok(!('_dd.appsec.event' in payload[1][0].meta)) + assert.ok(!('_dd.appsec.json' in payload[1][0].meta)) }) await axios({ diff --git a/integration-tests/appsec/iast-esbuild.spec.js b/integration-tests/appsec/iast-esbuild.spec.js index ee27a868c90..58743870e75 100644 --- a/integration-tests/appsec/iast-esbuild.spec.js +++ b/integration-tests/appsec/iast-esbuild.spec.js @@ -54,7 +54,7 @@ describe('esbuild support for IAST', () => { return agent.assertMessageReceived(({ payload }) => { const spans = payload.flatMap(p => p.filter(span => span.name === 'express.request')) spans.forEach(span => { - assert.ok(!Object.hasOwn(span.meta, '_dd.iast.json')) + assert.ok(!('_dd.iast.json' in span.meta)) }) }, null, 1, true) } diff --git a/integration-tests/appsec/iast-stack-traces-with-sourcemaps.spec.js b/integration-tests/appsec/iast-stack-traces-with-sourcemaps.spec.js index e4818bdc1e9..4f78c7f26ad 100644 --- a/integration-tests/appsec/iast-stack-traces-with-sourcemaps.spec.js +++ b/integration-tests/appsec/iast-stack-traces-with-sourcemaps.spec.js @@ -49,13 +49,13 @@ describe('IAST stack traces and vulnerabilities with sourcemaps', () => { it('should detect correct stack trace in unnamed function', async () => { const response = await axios.get('/rewritten/stack-trace-from-unnamed-function') - assert.ok(response.data.includes('/rewritten-routes.ts:7:13')) + assert.match(response.data, /\/rewritten-routes\.ts:7:13/) }) it('should detect correct stack trace in named function', async () => { const response = await axios.get('/rewritten/stack-trace-from-named-function') - assert.ok(response.data.includes('/rewritten-routes.ts:11:13')) + assert.match(response.data, /\/rewritten-routes\.ts:11:13/) }) it('should detect vulnerability in the correct location', async () => { @@ -81,13 +81,13 @@ describe('IAST stack traces and vulnerabilities with sourcemaps', () => { it('should detect correct stack trace in unnamed function', async () => { const response = await axios.get('/not-rewritten/stack-trace-from-unnamed-function') - assert.ok(response.data.includes('/not-rewritten-routes.ts:7:13')) + assert.match(response.data, /\/not-rewritten-routes\.ts:7:13/) }) it('should detect correct stack trace in named function', async () => { const response = await axios.get('/not-rewritten/stack-trace-from-named-function') - assert.ok(response.data.includes('/not-rewritten-routes.ts:11:13')) + assert.match(response.data, /\/not-rewritten-routes\.ts:11:13/) }) it('should detect vulnerability in the correct location', async () => { diff --git a/integration-tests/appsec/iast.esm-security-controls.spec.js b/integration-tests/appsec/iast.esm-security-controls.spec.js index cfe9b924e84..540414218e1 100644 --- a/integration-tests/appsec/iast.esm-security-controls.spec.js +++ b/integration-tests/appsec/iast.esm-security-controls.spec.js @@ -52,7 +52,7 @@ describe('ESM Security controls', () => { const spans = payload.flatMap(p => p.filter(span => span.name === 'express.request')) spans.forEach(span => { assert.ok(Object.hasOwn(span.meta, '_dd.iast.json')) - assert.ok(span.meta['_dd.iast.json'].includes('"COMMAND_INJECTION"')) + assert.match(span.meta['_dd.iast.json'], /"COMMAND_INJECTION"/) }) }, null, 1, true) }) @@ -63,7 +63,7 @@ describe('ESM Security controls', () => { await agent.assertMessageReceived(({ payload }) => { const spans = payload.flatMap(p => p.filter(span => span.name === 'express.request')) spans.forEach(span => { - assert.ok(!Object.hasOwn(span.meta, '_dd.iast.json')) + assert.ok(!('_dd.iast.json' in span.meta)) assert.ok(Object.hasOwn(span.metrics, '_dd.iast.telemetry.suppressed.vulnerabilities.command_injection')) }) }, null, 1, true) @@ -75,7 +75,7 @@ describe('ESM Security controls', () => { await agent.assertMessageReceived(({ payload }) => { const spans = payload.flatMap(p => p.filter(span => span.name === 'express.request')) spans.forEach(span => { - assert.ok(!Object.hasOwn(span.meta, '_dd.iast.json')) + assert.ok(!('_dd.iast.json' in span.meta)) assert.ok(Object.hasOwn(span.metrics, '_dd.iast.telemetry.suppressed.vulnerabilities.command_injection')) }) }, null, 1, true) @@ -88,7 +88,7 @@ describe('ESM Security controls', () => { const spans = payload.flatMap(p => p.filter(span => span.name === 'express.request')) spans.forEach(span => { assert.ok(Object.hasOwn(span.meta, '_dd.iast.json')) - assert.ok(span.meta['_dd.iast.json'].includes('"COMMAND_INJECTION"')) + assert.match(span.meta['_dd.iast.json'], /"COMMAND_INJECTION"/) }) }, null, 1, true) }) @@ -99,7 +99,7 @@ describe('ESM Security controls', () => { await agent.assertMessageReceived(({ payload }) => { const spans = payload.flatMap(p => p.filter(span => span.name === 'express.request')) spans.forEach(span => { - assert.ok(!Object.hasOwn(span.meta, '_dd.iast.json')) + assert.ok(!('_dd.iast.json' in span.meta)) assert.ok(Object.hasOwn(span.metrics, '_dd.iast.telemetry.suppressed.vulnerabilities.command_injection')) }) }, null, 1, true) @@ -111,7 +111,7 @@ describe('ESM Security controls', () => { await agent.assertMessageReceived(({ payload }) => { const spans = payload.flatMap(p => p.filter(span => span.name === 'express.request')) spans.forEach(span => { - assert.ok(!Object.hasOwn(span.meta, '_dd.iast.json')) + assert.ok(!('_dd.iast.json' in span.meta)) assert.ok(Object.hasOwn(span.metrics, '_dd.iast.telemetry.suppressed.vulnerabilities.command_injection')) }) }, null, 1, true) diff --git a/integration-tests/appsec/iast.esm.spec.js b/integration-tests/appsec/iast.esm.spec.js index a2acdefd1eb..7dbb47d1de1 100644 --- a/integration-tests/appsec/iast.esm.spec.js +++ b/integration-tests/appsec/iast.esm.spec.js @@ -65,7 +65,7 @@ describe('ESM', () => { await agent.assertMessageReceived(({ payload }) => { verifySpan(payload, span => { assert.ok(Object.hasOwn(span.meta, '_dd.iast.json')) - assert.ok(span.meta['_dd.iast.json'].includes('"COMMAND_INJECTION"')) + assert.match(span.meta['_dd.iast.json'], /"COMMAND_INJECTION"/) }) }, null, 1, true) }) @@ -76,7 +76,7 @@ describe('ESM', () => { await agent.assertMessageReceived(({ payload }) => { verifySpan(payload, span => { assert.ok(Object.hasOwn(span.meta, '_dd.iast.json')) - assert.ok(span.meta['_dd.iast.json'].includes('"COMMAND_INJECTION"')) + assert.match(span.meta['_dd.iast.json'], /"COMMAND_INJECTION"/) }) }, null, 1, true) }) diff --git a/integration-tests/appsec/index.spec.js b/integration-tests/appsec/index.spec.js index 4fc6c939b69..158ca556f52 100644 --- a/integration-tests/appsec/index.spec.js +++ b/integration-tests/appsec/index.spec.js @@ -51,7 +51,7 @@ describe('RASP', () => { async function assertExploitDetected () { await agent.assertMessageReceived(({ headers, payload }) => { assert.ok(Object.hasOwn(payload[0][0].meta, '_dd.appsec.json')) - assert.ok(payload[0][0].meta['_dd.appsec.json'].includes('"test-rule-id-2"')) + assert.match(payload[0][0].meta['_dd.appsec.json'], /"test-rule-id-2"/) }) } @@ -400,7 +400,7 @@ describe('RASP', () => { } await agent.assertMessageReceived(({ headers, payload }) => { - assert.ok(!Object.hasOwn(payload[0][0].meta_struct, 'http.request.body')) + assert.ok(!('http.request.body' in payload[0][0].meta_struct)) }) } }) diff --git a/integration-tests/appsec/standalone-asm.spec.js b/integration-tests/appsec/standalone-asm.spec.js index 973c2b06ee1..576745735db 100644 --- a/integration-tests/appsec/standalone-asm.spec.js +++ b/integration-tests/appsec/standalone-asm.spec.js @@ -31,7 +31,7 @@ describe('Standalone ASM', () => { } function assertDrop ({ meta, metrics }) { - assert.ok(!Object.hasOwn(meta, '_dd.p.ts')) + assert.ok(!('_dd.p.ts' in meta)) assert.strictEqual(metrics._sampling_priority_v1, AUTO_REJECT) assert.strictEqual(metrics['_dd.apm.enabled'], 0) @@ -96,8 +96,8 @@ describe('Standalone ASM', () => { assert.strictEqual(fifthReq.length, 3) const { meta, metrics } = fifthReq[0] - assert.ok(!Object.hasOwn(meta, 'manual.keep')) - assert.ok(!Object.hasOwn(meta, '_dd.p.ts')) + assert.ok(!('manual.keep' in meta)) + assert.ok(!('_dd.p.ts' in meta)) assert.strictEqual(metrics._sampling_priority_v1, AUTO_KEEP) assert.strictEqual(metrics['_dd.apm.enabled'], 0) @@ -232,7 +232,7 @@ describe('Standalone ASM', () => { const innerReq = payload.find(p => p[0].resource === 'GET /down') assert.notStrictEqual(innerReq, undefined) - assert.ok(!Object.hasOwn(innerReq[0].meta, '_dd.p.other')) + assert.ok(!('_dd.p.other' in innerReq[0].meta)) }, undefined, undefined, true) }) @@ -323,7 +323,7 @@ describe('Standalone ASM', () => { it('should not add standalone related tags in iast events', () => { const url = proc.url + '/vulnerableHash' return curlAndAssertMessage(agent, url, ({ headers, payload }) => { - assert.ok(!Object.hasOwn(headers, 'datadog-client-computed-stats')) + assert.ok(!('datadog-client-computed-stats' in headers)) assert.ok(Array.isArray(payload)) assert.strictEqual(payload.length, 1) assert.ok(Array.isArray(payload[0])) @@ -334,8 +334,8 @@ describe('Standalone ASM', () => { const { meta, metrics } = payload[0][0] assert.ok(Object.hasOwn(meta, '_dd.iast.json')) // WEAK_HASH and XCONTENTTYPE_HEADER_MISSING reported - assert.ok(!Object.hasOwn(meta, '_dd.p.ts')) - assert.ok(!Object.hasOwn(metrics, '_dd.apm.enabled')) + assert.ok(!('_dd.p.ts' in meta)) + assert.ok(!('_dd.apm.enabled' in metrics)) }) }) @@ -343,7 +343,7 @@ describe('Standalone ASM', () => { const urlAttack = proc.url + '?query=1 or 1=1' return curlAndAssertMessage(agent, urlAttack, ({ headers, payload }) => { - assert.ok(!Object.hasOwn(headers, 'datadog-client-computed-stats')) + assert.ok(!('datadog-client-computed-stats' in headers)) assert.ok(Array.isArray(payload)) assert.strictEqual(payload.length, 1) assert.ok(Array.isArray(payload[0])) @@ -354,8 +354,8 @@ describe('Standalone ASM', () => { const { meta, metrics } = payload[0][0] assert.ok(Object.hasOwn(meta, '_dd.appsec.json')) // crs-942-100 triggered - assert.ok(!Object.hasOwn(meta, '_dd.p.ts')) - assert.ok(!Object.hasOwn(metrics, '_dd.apm.enabled')) + assert.ok(!('_dd.p.ts' in meta)) + assert.ok(!('_dd.apm.enabled' in metrics)) }) }) }) diff --git a/integration-tests/ci-visibility/automatic-log-submission-cucumber/support/steps.js b/integration-tests/ci-visibility/automatic-log-submission-cucumber/support/steps.js index 759d1a18589..4cfbd9e7288 100644 --- a/integration-tests/ci-visibility/automatic-log-submission-cucumber/support/steps.js +++ b/integration-tests/ci-visibility/automatic-log-submission-cucumber/support/steps.js @@ -1,6 +1,6 @@ 'use strict' -const assert = require('node:assert/strict') +const assert = require('assert') const { When, Then } = require('@cucumber/cucumber') diff --git a/integration-tests/ci-visibility/automatic-log-submission.spec.js b/integration-tests/ci-visibility/automatic-log-submission.spec.js index dae27e3089a..5f1f1810ea7 100644 --- a/integration-tests/ci-visibility/automatic-log-submission.spec.js +++ b/integration-tests/ci-visibility/automatic-log-submission.spec.js @@ -1,15 +1,15 @@ 'use strict' +const assert = require('assert') const { exec, execSync } = require('child_process') const { once } = require('events') -const { assert } = require('chai') - const { sandboxCwd, useSandbox, getCiVisAgentlessConfig, - getCiVisEvpProxyConfig + getCiVisEvpProxyConfig, + assertObjectContains } = require('../helpers') const { FakeCiVisIntake } = require('../ci-visibility-intake') const webAppServer = require('./web-app-server') @@ -99,10 +99,10 @@ describe('test optimization automatic log submission', () => { logMessages.forEach(({ dd, level }) => { assert.equal(level, 'info') assert.equal(dd.service, 'my-service') - assert.hasAllKeys(dd, ['trace_id', 'span_id', 'service']) + assert.deepStrictEqual(['service', 'span_id', 'trace_id'], Object.keys(dd).sort()) }) - assert.includeMembers(logMessages.map(({ message }) => message), [ + assertObjectContains(logMessages.map(({ message }) => message), [ 'Hello simple log!', 'sum function being called' ]) @@ -155,15 +155,15 @@ describe('test optimization automatic log submission', () => { const { logSpanId, logTraceId } = logIds const { testSpanId, testTraceId } = testIds - assert.include(testOutput, 'Hello simple log!') - assert.include(testOutput, 'sum function being called') + assert.match(testOutput, /Hello simple log!/) + assert.match(testOutput, /sum function being called/) // cucumber has `cucumber.step`, and that's the active span, not the test. // logs are queried by trace id, so it should be OK if (name !== 'cucumber') { - assert.include(testOutput, `"span_id":"${testSpanId}"`) + assert.match(testOutput, new RegExp(`"span_id":"${testSpanId}"`)) assert.equal(logSpanId, testSpanId) } - assert.include(testOutput, `"trace_id":"${testTraceId}"`) + assert.match(testOutput, new RegExp(`"trace_id":"${testTraceId}"`)) assert.equal(logTraceId, testTraceId) }) @@ -200,9 +200,9 @@ describe('test optimization automatic log submission', () => { logsPromise, ]) - assert.include(testOutput, 'Hello simple log!') - assert.include(testOutput, 'span_id') - assert.isFalse(hasReceivedEvents) + assert.match(testOutput, /Hello simple log!/) + assert.match(testOutput, /span_id/) + assert.strictEqual(hasReceivedEvents, false) }) it('does not submit logs when DD_AGENTLESS_LOG_SUBMISSION_ENABLED is set but DD_API_KEY is not', async () => { @@ -236,8 +236,8 @@ describe('test optimization automatic log submission', () => { once(childProcess.stderr, 'end'), ]) - assert.include(testOutput, 'Hello simple log!') - assert.include(testOutput, 'no automatic log submission will be performed') + assert.match(testOutput, /Hello simple log!/) + assert.match(testOutput, /no automatic log submission will be performed/) }) }) }) diff --git a/integration-tests/ci-visibility/automatic-log-submission/automatic-log-submission-test.js b/integration-tests/ci-visibility/automatic-log-submission/automatic-log-submission-test.js index 97b6eb30300..82317d1d328 100644 --- a/integration-tests/ci-visibility/automatic-log-submission/automatic-log-submission-test.js +++ b/integration-tests/ci-visibility/automatic-log-submission/automatic-log-submission-test.js @@ -1,6 +1,6 @@ 'use strict' -const assert = require('node:assert/strict') +const assert = require('assert') const logger = require('./logger') const sum = require('./sum') diff --git a/integration-tests/ci-visibility/dynamic-instrumentation/parallel-test-hit-breakpoint-1.js b/integration-tests/ci-visibility/dynamic-instrumentation/parallel-test-hit-breakpoint-1.js index 9d12396f8aa..ad3dbc5b135 100644 --- a/integration-tests/ci-visibility/dynamic-instrumentation/parallel-test-hit-breakpoint-1.js +++ b/integration-tests/ci-visibility/dynamic-instrumentation/parallel-test-hit-breakpoint-1.js @@ -1,6 +1,6 @@ 'use strict' -const assert = require('node:assert/strict') +const assert = require('assert') const sum = require('./dependency') describe('dynamic-instrumentation', () => { diff --git a/integration-tests/ci-visibility/dynamic-instrumentation/parallel-test-hit-breakpoint-2.js b/integration-tests/ci-visibility/dynamic-instrumentation/parallel-test-hit-breakpoint-2.js index 12e687ff613..7520dd354fb 100644 --- a/integration-tests/ci-visibility/dynamic-instrumentation/parallel-test-hit-breakpoint-2.js +++ b/integration-tests/ci-visibility/dynamic-instrumentation/parallel-test-hit-breakpoint-2.js @@ -1,6 +1,6 @@ 'use strict' -const assert = require('node:assert/strict') +const assert = require('assert') describe('dynamic-instrumentation 2', () => { it('is not retried', () => { assert.strictEqual(1 + 2, 3) diff --git a/integration-tests/ci-visibility/dynamic-instrumentation/test-hit-breakpoint.js b/integration-tests/ci-visibility/dynamic-instrumentation/test-hit-breakpoint.js index 1be2d27d21a..37dbac7ee78 100644 --- a/integration-tests/ci-visibility/dynamic-instrumentation/test-hit-breakpoint.js +++ b/integration-tests/ci-visibility/dynamic-instrumentation/test-hit-breakpoint.js @@ -1,6 +1,6 @@ 'use strict' -const assert = require('node:assert/strict') +const assert = require('assert') const sum = require('./dependency') let count = 0 diff --git a/integration-tests/ci-visibility/dynamic-instrumentation/test-not-hit-breakpoint.js b/integration-tests/ci-visibility/dynamic-instrumentation/test-not-hit-breakpoint.js index 2408a0e2aeb..2f0cd669aeb 100644 --- a/integration-tests/ci-visibility/dynamic-instrumentation/test-not-hit-breakpoint.js +++ b/integration-tests/ci-visibility/dynamic-instrumentation/test-not-hit-breakpoint.js @@ -1,6 +1,6 @@ 'use strict' -const assert = require('node:assert/strict') +const assert = require('assert') const sum = require('./dependency') let count = 0 diff --git a/integration-tests/ci-visibility/features-selenium/support/steps.js b/integration-tests/ci-visibility/features-selenium/support/steps.js index 77c54b105b2..e7a51457771 100644 --- a/integration-tests/ci-visibility/features-selenium/support/steps.js +++ b/integration-tests/ci-visibility/features-selenium/support/steps.js @@ -1,6 +1,6 @@ 'use strict' -const assert = require('node:assert/strict') +const assert = require('assert') const { When, Then, Before, After } = require('@cucumber/cucumber') const { By, Builder } = require('selenium-webdriver') diff --git a/integration-tests/ci-visibility/git-cache.spec.js b/integration-tests/ci-visibility/git-cache.spec.js index 24bd1894598..bba8c0c321b 100644 --- a/integration-tests/ci-visibility/git-cache.spec.js +++ b/integration-tests/ci-visibility/git-cache.spec.js @@ -2,12 +2,11 @@ const { execSync } = require('child_process') const fs = require('fs') -const assert = require('node:assert/strict') +const assert = require('assert') const os = require('os') const path = require('path') const { sandboxCwd, useSandbox } = require('../helpers') -const { assertObjectContains } = require('../helpers') const FIXED_COMMIT_MESSAGE = 'Test commit message for caching' const GET_COMMIT_MESSAGE_COMMAND_ARGS = ['log', '-1', '--pretty=format:%s'] @@ -105,7 +104,7 @@ describe('git-cache integration tests', () => { } assert.ok(secondError instanceof Error) assert.strictEqual(secondError.code, 'ENOENT') - assertObjectContains(secondError.message, 'git') + assert.match(secondError.message, /git/) }) it('should cache git command failures and throw the same error on subsequent calls', function () { @@ -122,10 +121,9 @@ describe('git-cache integration tests', () => { const cacheKey = gitCache.getCacheKey('git', gitArgs) const cacheFilePath = gitCache.getCacheFilePath(cacheKey) - assert.strictEqual(fs.existsSync(cacheFilePath), true) - const cachedData = fs.readFileSync(cacheFilePath, 'utf8') - assertObjectContains(cachedData, '__GIT_COMMAND_FAILED__') + + assert.match(cachedData, /__GIT_COMMAND_FAILED__/) removeGitFromPath() @@ -169,7 +167,7 @@ describe('git-cache integration tests', () => { assert.ok(secondError instanceof Error) assert.strictEqual(secondError.code, 'ENOENT') - assertObjectContains(secondError.message, 'git') + assert.match(secondError.message, /git/) }) context('invalid DD_EXPERIMENTAL_TEST_OPT_GIT_CACHE_DIR', () => { @@ -198,7 +196,7 @@ describe('git-cache integration tests', () => { assert.ok(secondError instanceof Error) assert.strictEqual(secondError.code, 'ENOENT') - assertObjectContains(secondError.message, 'git') + assert.match(secondError.message, /git/) } it('set to a file', () => { diff --git a/integration-tests/ci-visibility/jest-bad-import-torn-down/jest-bad-import-test-pass-2.js b/integration-tests/ci-visibility/jest-bad-import-torn-down/jest-bad-import-test-pass-2.js index e9fed73447e..e4e7cb41a02 100644 --- a/integration-tests/ci-visibility/jest-bad-import-torn-down/jest-bad-import-test-pass-2.js +++ b/integration-tests/ci-visibility/jest-bad-import-torn-down/jest-bad-import-test-pass-2.js @@ -1,6 +1,6 @@ 'use strict' -const assert = require('node:assert/strict') +const assert = require('assert') it('works', () => { assert.strictEqual(true, true) diff --git a/integration-tests/ci-visibility/jest-bad-import-torn-down/jest-bad-import-test-pass.js b/integration-tests/ci-visibility/jest-bad-import-torn-down/jest-bad-import-test-pass.js index e9fed73447e..e4e7cb41a02 100644 --- a/integration-tests/ci-visibility/jest-bad-import-torn-down/jest-bad-import-test-pass.js +++ b/integration-tests/ci-visibility/jest-bad-import-torn-down/jest-bad-import-test-pass.js @@ -1,6 +1,6 @@ 'use strict' -const assert = require('node:assert/strict') +const assert = require('assert') it('works', () => { assert.strictEqual(true, true) diff --git a/integration-tests/ci-visibility/jest-bad-import-torn-down/jest-bad-import-test.js b/integration-tests/ci-visibility/jest-bad-import-torn-down/jest-bad-import-test.js index 99898f15961..731068103b4 100644 --- a/integration-tests/ci-visibility/jest-bad-import-torn-down/jest-bad-import-test.js +++ b/integration-tests/ci-visibility/jest-bad-import-torn-down/jest-bad-import-test.js @@ -1,6 +1,6 @@ 'use strict' -const assert = require('node:assert/strict') +const assert = require('assert') afterAll(() => { process.nextTick(() => { diff --git a/integration-tests/ci-visibility/jest-bad-import/jest-bad-import-test-pass-2.js b/integration-tests/ci-visibility/jest-bad-import/jest-bad-import-test-pass-2.js index e9fed73447e..e4e7cb41a02 100644 --- a/integration-tests/ci-visibility/jest-bad-import/jest-bad-import-test-pass-2.js +++ b/integration-tests/ci-visibility/jest-bad-import/jest-bad-import-test-pass-2.js @@ -1,6 +1,6 @@ 'use strict' -const assert = require('node:assert/strict') +const assert = require('assert') it('works', () => { assert.strictEqual(true, true) diff --git a/integration-tests/ci-visibility/jest-bad-import/jest-bad-import-test-pass.js b/integration-tests/ci-visibility/jest-bad-import/jest-bad-import-test-pass.js index e9fed73447e..e4e7cb41a02 100644 --- a/integration-tests/ci-visibility/jest-bad-import/jest-bad-import-test-pass.js +++ b/integration-tests/ci-visibility/jest-bad-import/jest-bad-import-test-pass.js @@ -1,6 +1,6 @@ 'use strict' -const assert = require('node:assert/strict') +const assert = require('assert') it('works', () => { assert.strictEqual(true, true) diff --git a/integration-tests/ci-visibility/jest-bad-import/jest-bad-import-test.js b/integration-tests/ci-visibility/jest-bad-import/jest-bad-import-test.js index dd2e858c9a3..3a93063dd92 100644 --- a/integration-tests/ci-visibility/jest-bad-import/jest-bad-import-test.js +++ b/integration-tests/ci-visibility/jest-bad-import/jest-bad-import-test.js @@ -1,6 +1,6 @@ 'use strict' -const assert = require('node:assert/strict') +const assert = require('assert') it('will fail', () => { setTimeout(() => { diff --git a/integration-tests/ci-visibility/jest-fast-check/jest-no-fast-check.js b/integration-tests/ci-visibility/jest-fast-check/jest-no-fast-check.js index baee3d62949..fc895c08140 100644 --- a/integration-tests/ci-visibility/jest-fast-check/jest-no-fast-check.js +++ b/integration-tests/ci-visibility/jest-fast-check/jest-no-fast-check.js @@ -1,6 +1,6 @@ 'use strict' -const assert = require('node:assert/strict') +const assert = require('assert') describe('fast check with seed', () => { it('should include seed (with seed=12)', () => { diff --git a/integration-tests/ci-visibility/jest-flaky/flaky-fails.js b/integration-tests/ci-visibility/jest-flaky/flaky-fails.js index c48bd85b369..b500b46f312 100644 --- a/integration-tests/ci-visibility/jest-flaky/flaky-fails.js +++ b/integration-tests/ci-visibility/jest-flaky/flaky-fails.js @@ -1,6 +1,6 @@ 'use strict' -const assert = require('node:assert/strict') +const assert = require('assert') describe('test-flaky-test-retries', () => { it('can retry failed tests', () => { diff --git a/integration-tests/ci-visibility/jest-flaky/flaky-passes.js b/integration-tests/ci-visibility/jest-flaky/flaky-passes.js index 3e08ee07a59..b951062666e 100644 --- a/integration-tests/ci-visibility/jest-flaky/flaky-passes.js +++ b/integration-tests/ci-visibility/jest-flaky/flaky-passes.js @@ -1,6 +1,6 @@ 'use strict' -const assert = require('node:assert/strict') +const assert = require('assert') let counter = 0 diff --git a/integration-tests/ci-visibility/jest-package-mock/non-dependency-mock-test-2.js b/integration-tests/ci-visibility/jest-package-mock/non-dependency-mock-test-2.js index 1a0bea5139f..709aaf35e5e 100644 --- a/integration-tests/ci-visibility/jest-package-mock/non-dependency-mock-test-2.js +++ b/integration-tests/ci-visibility/jest-package-mock/non-dependency-mock-test-2.js @@ -1,6 +1,6 @@ 'use strict' -const assert = require('node:assert/strict') +const assert = require('assert') const hello = jest.requireActual('some-package') diff --git a/integration-tests/ci-visibility/jest-package-mock/non-dependency-mock-test-3.js b/integration-tests/ci-visibility/jest-package-mock/non-dependency-mock-test-3.js index 38c64e0f74e..e5b5a0ef1cd 100644 --- a/integration-tests/ci-visibility/jest-package-mock/non-dependency-mock-test-3.js +++ b/integration-tests/ci-visibility/jest-package-mock/non-dependency-mock-test-3.js @@ -1,6 +1,6 @@ 'use strict' -const assert = require('node:assert/strict') +const assert = require('assert') const hello = require('some-package') diff --git a/integration-tests/ci-visibility/jest-package-mock/non-dependency-mock-test-4.js b/integration-tests/ci-visibility/jest-package-mock/non-dependency-mock-test-4.js index 38c64e0f74e..e5b5a0ef1cd 100644 --- a/integration-tests/ci-visibility/jest-package-mock/non-dependency-mock-test-4.js +++ b/integration-tests/ci-visibility/jest-package-mock/non-dependency-mock-test-4.js @@ -1,6 +1,6 @@ 'use strict' -const assert = require('node:assert/strict') +const assert = require('assert') const hello = require('some-package') diff --git a/integration-tests/ci-visibility/jest-package-mock/non-dependency-mock-test-5.js b/integration-tests/ci-visibility/jest-package-mock/non-dependency-mock-test-5.js index 38c64e0f74e..e5b5a0ef1cd 100644 --- a/integration-tests/ci-visibility/jest-package-mock/non-dependency-mock-test-5.js +++ b/integration-tests/ci-visibility/jest-package-mock/non-dependency-mock-test-5.js @@ -1,6 +1,6 @@ 'use strict' -const assert = require('node:assert/strict') +const assert = require('assert') const hello = require('some-package') diff --git a/integration-tests/ci-visibility/jest-package-mock/non-dependency-mock-test-6.js b/integration-tests/ci-visibility/jest-package-mock/non-dependency-mock-test-6.js index 38c64e0f74e..e5b5a0ef1cd 100644 --- a/integration-tests/ci-visibility/jest-package-mock/non-dependency-mock-test-6.js +++ b/integration-tests/ci-visibility/jest-package-mock/non-dependency-mock-test-6.js @@ -1,6 +1,6 @@ 'use strict' -const assert = require('node:assert/strict') +const assert = require('assert') const hello = require('some-package') diff --git a/integration-tests/ci-visibility/jest-package-mock/non-dependency-mock-test.js b/integration-tests/ci-visibility/jest-package-mock/non-dependency-mock-test.js index 38c64e0f74e..e5b5a0ef1cd 100644 --- a/integration-tests/ci-visibility/jest-package-mock/non-dependency-mock-test.js +++ b/integration-tests/ci-visibility/jest-package-mock/non-dependency-mock-test.js @@ -1,6 +1,6 @@ 'use strict' -const assert = require('node:assert/strict') +const assert = require('assert') const hello = require('some-package') diff --git a/integration-tests/ci-visibility/jest-plugin-tests/jest-inject-globals.js b/integration-tests/ci-visibility/jest-plugin-tests/jest-inject-globals.js index 04c7c72ca69..99b14736416 100644 --- a/integration-tests/ci-visibility/jest-plugin-tests/jest-inject-globals.js +++ b/integration-tests/ci-visibility/jest-plugin-tests/jest-inject-globals.js @@ -1,11 +1,9 @@ 'use strict' -const assert = require('node:assert/strict') - const { describe, it, expect } = require('@jest/globals') describe('jest-inject-globals', () => { it('will be run', () => { - assert.deepStrictEqual(true, true) + expect(true).toEqual(true) }) }) diff --git a/integration-tests/ci-visibility/jest-plugin-tests/jest-test.js b/integration-tests/ci-visibility/jest-plugin-tests/jest-test.js index c2db2e0bfe8..5aed8a33376 100644 --- a/integration-tests/ci-visibility/jest-plugin-tests/jest-test.js +++ b/integration-tests/ci-visibility/jest-plugin-tests/jest-test.js @@ -1,7 +1,7 @@ 'use strict' const http = require('http') -const assert = require('node:assert/strict') +const assert = require('assert') const tracer = require('dd-trace') diff --git a/integration-tests/ci-visibility/jest/failing-test.js b/integration-tests/ci-visibility/jest/failing-test.js index 6d713411836..8288b115938 100644 --- a/integration-tests/ci-visibility/jest/failing-test.js +++ b/integration-tests/ci-visibility/jest/failing-test.js @@ -1,6 +1,6 @@ 'use strict' -const assert = require('node:assert/strict') +const assert = require('assert') describe('failing', () => { it.failing('can report failed tests', () => { assert.strictEqual(1 + 2, 4) diff --git a/integration-tests/ci-visibility/jest/mocked-test.js b/integration-tests/ci-visibility/jest/mocked-test.js index b3a5a2f0527..a8a3de98415 100644 --- a/integration-tests/ci-visibility/jest/mocked-test.js +++ b/integration-tests/ci-visibility/jest/mocked-test.js @@ -1,6 +1,6 @@ 'use strict' -const assert = require('node:assert/strict') +const assert = require('assert') jest.mock('../test/sum.js') diff --git a/integration-tests/ci-visibility/mocha-plugin-tests/active-span-hooks.js b/integration-tests/ci-visibility/mocha-plugin-tests/active-span-hooks.js index 0e66b3a14c7..94703904927 100644 --- a/integration-tests/ci-visibility/mocha-plugin-tests/active-span-hooks.js +++ b/integration-tests/ci-visibility/mocha-plugin-tests/active-span-hooks.js @@ -1,6 +1,6 @@ 'use strict' -const assert = require('node:assert/strict') +const assert = require('assert') let currentTestTraceId describe('mocha-active-span-in-hooks', function () { diff --git a/integration-tests/ci-visibility/mocha-plugin-tests/async-fail.js b/integration-tests/ci-visibility/mocha-plugin-tests/async-fail.js index 8e0097eb5dc..626f319f7d5 100644 --- a/integration-tests/ci-visibility/mocha-plugin-tests/async-fail.js +++ b/integration-tests/ci-visibility/mocha-plugin-tests/async-fail.js @@ -1,6 +1,6 @@ 'use strict' -const assert = require('node:assert/strict') +const assert = require('assert') describe('mocha-test-async-fail', () => { it('can do failed async tests', async () => { await new Promise(resolve => { diff --git a/integration-tests/ci-visibility/mocha-plugin-tests/async-pass.js b/integration-tests/ci-visibility/mocha-plugin-tests/async-pass.js index 3841dfc62ff..bff7fcb106c 100644 --- a/integration-tests/ci-visibility/mocha-plugin-tests/async-pass.js +++ b/integration-tests/ci-visibility/mocha-plugin-tests/async-pass.js @@ -1,6 +1,6 @@ 'use strict' -const assert = require('node:assert/strict') +const assert = require('assert') describe('mocha-test-async-pass', () => { it('can do passed async tests', async () => { await new Promise(resolve => { diff --git a/integration-tests/ci-visibility/mocha-plugin-tests/done-fail-badly.js b/integration-tests/ci-visibility/mocha-plugin-tests/done-fail-badly.js index ce43ce3e4c8..4143b392da7 100644 --- a/integration-tests/ci-visibility/mocha-plugin-tests/done-fail-badly.js +++ b/integration-tests/ci-visibility/mocha-plugin-tests/done-fail-badly.js @@ -1,6 +1,6 @@ 'use strict' -const assert = require('node:assert/strict') +const assert = require('assert') describe('mocha-test-done-fail', () => { it('can do badly setup failed tests with done', (done) => { setTimeout(() => { diff --git a/integration-tests/ci-visibility/mocha-plugin-tests/done-fail.js b/integration-tests/ci-visibility/mocha-plugin-tests/done-fail.js index 38b964bd8b7..a012a4ed8f3 100644 --- a/integration-tests/ci-visibility/mocha-plugin-tests/done-fail.js +++ b/integration-tests/ci-visibility/mocha-plugin-tests/done-fail.js @@ -1,6 +1,6 @@ 'use strict' -const assert = require('node:assert/strict') +const assert = require('assert') describe('mocha-test-done-fail', () => { it('can do failed tests with done', (done) => { setTimeout(() => { diff --git a/integration-tests/ci-visibility/mocha-plugin-tests/done-pass.js b/integration-tests/ci-visibility/mocha-plugin-tests/done-pass.js index edeb067654d..34437184500 100644 --- a/integration-tests/ci-visibility/mocha-plugin-tests/done-pass.js +++ b/integration-tests/ci-visibility/mocha-plugin-tests/done-pass.js @@ -1,6 +1,6 @@ 'use strict' -const assert = require('node:assert/strict') +const assert = require('assert') describe('mocha-test-done-pass', () => { it('can do passed tests with done', (done) => { setTimeout(() => { diff --git a/integration-tests/ci-visibility/mocha-plugin-tests/failing.js b/integration-tests/ci-visibility/mocha-plugin-tests/failing.js index 3a2261560a3..2d24e195adc 100644 --- a/integration-tests/ci-visibility/mocha-plugin-tests/failing.js +++ b/integration-tests/ci-visibility/mocha-plugin-tests/failing.js @@ -1,6 +1,6 @@ 'use strict' -const assert = require('node:assert/strict') +const assert = require('assert') describe('mocha-test-fail', () => { it('can fail', () => { assert.strictEqual(true, false) diff --git a/integration-tests/ci-visibility/mocha-plugin-tests/hook-async-error.js b/integration-tests/ci-visibility/mocha-plugin-tests/hook-async-error.js index 44d7bfa872c..9809624aaae 100644 --- a/integration-tests/ci-visibility/mocha-plugin-tests/hook-async-error.js +++ b/integration-tests/ci-visibility/mocha-plugin-tests/hook-async-error.js @@ -1,6 +1,6 @@ 'use strict' -const assert = require('node:assert/strict') +const assert = require('assert') describe('mocha-fail-before-all', function () { before((done) => { done(new Error('this should not stop execution')) diff --git a/integration-tests/ci-visibility/mocha-plugin-tests/hook-sync-error.js b/integration-tests/ci-visibility/mocha-plugin-tests/hook-sync-error.js index fb531c43dca..66c492e613b 100644 --- a/integration-tests/ci-visibility/mocha-plugin-tests/hook-sync-error.js +++ b/integration-tests/ci-visibility/mocha-plugin-tests/hook-sync-error.js @@ -1,6 +1,6 @@ 'use strict' -const assert = require('node:assert/strict') +const assert = require('assert') describe('mocha-fail-hook-sync', () => { beforeEach(() => { const value = '' diff --git a/integration-tests/ci-visibility/mocha-plugin-tests/parameterized.js b/integration-tests/ci-visibility/mocha-plugin-tests/parameterized.js index 8583c85e302..e375514ef9d 100644 --- a/integration-tests/ci-visibility/mocha-plugin-tests/parameterized.js +++ b/integration-tests/ci-visibility/mocha-plugin-tests/parameterized.js @@ -1,6 +1,6 @@ 'use strict' -const assert = require('node:assert/strict') +const assert = require('assert') const forEach = require('mocha-each') describe('mocha-parameterized', () => { diff --git a/integration-tests/ci-visibility/mocha-plugin-tests/passing.js b/integration-tests/ci-visibility/mocha-plugin-tests/passing.js index 6deddb9b28b..c5c81745c2d 100644 --- a/integration-tests/ci-visibility/mocha-plugin-tests/passing.js +++ b/integration-tests/ci-visibility/mocha-plugin-tests/passing.js @@ -1,6 +1,6 @@ 'use strict' -const assert = require('node:assert/strict') +const assert = require('assert') describe('mocha-test-pass', () => { it('can pass', () => { assert.strictEqual(true, true) diff --git a/integration-tests/ci-visibility/mocha-plugin-tests/promise-fail.js b/integration-tests/ci-visibility/mocha-plugin-tests/promise-fail.js index f9cec459600..7a4e3a120d3 100644 --- a/integration-tests/ci-visibility/mocha-plugin-tests/promise-fail.js +++ b/integration-tests/ci-visibility/mocha-plugin-tests/promise-fail.js @@ -1,6 +1,6 @@ 'use strict' -const assert = require('node:assert/strict') +const assert = require('assert') describe('mocha-test-promise-fail', () => { it('can do failed promise tests', () => { return new Promise((resolve, reject) => { diff --git a/integration-tests/ci-visibility/mocha-plugin-tests/promise-pass.js b/integration-tests/ci-visibility/mocha-plugin-tests/promise-pass.js index e07d4c578ba..42ef20dbe3b 100644 --- a/integration-tests/ci-visibility/mocha-plugin-tests/promise-pass.js +++ b/integration-tests/ci-visibility/mocha-plugin-tests/promise-pass.js @@ -1,6 +1,6 @@ 'use strict' -const assert = require('node:assert/strict') +const assert = require('assert') describe('mocha-test-promise-pass', () => { it('can do passed promise tests', () => { return new Promise((resolve) => { diff --git a/integration-tests/ci-visibility/mocha-plugin-tests/retries.js b/integration-tests/ci-visibility/mocha-plugin-tests/retries.js index dac3f6d39f3..78bbabb9193 100644 --- a/integration-tests/ci-visibility/mocha-plugin-tests/retries.js +++ b/integration-tests/ci-visibility/mocha-plugin-tests/retries.js @@ -1,6 +1,6 @@ 'use strict' -const assert = require('node:assert/strict') +const assert = require('assert') let attempt = 0 describe('mocha-test-retries', function () { diff --git a/integration-tests/ci-visibility/mocha-plugin-tests/skip-describe.js b/integration-tests/ci-visibility/mocha-plugin-tests/skip-describe.js index 07bd0f00098..0229001a5aa 100644 --- a/integration-tests/ci-visibility/mocha-plugin-tests/skip-describe.js +++ b/integration-tests/ci-visibility/mocha-plugin-tests/skip-describe.js @@ -1,6 +1,6 @@ 'use strict' -const assert = require('node:assert/strict') +const assert = require('assert') describe('mocha-test-skip-describe', () => { before(function () { this.skip() diff --git a/integration-tests/ci-visibility/mocha-plugin-tests/skipping.js b/integration-tests/ci-visibility/mocha-plugin-tests/skipping.js index edb63eee69b..55c75c91752 100644 --- a/integration-tests/ci-visibility/mocha-plugin-tests/skipping.js +++ b/integration-tests/ci-visibility/mocha-plugin-tests/skipping.js @@ -1,6 +1,6 @@ 'use strict' -const assert = require('node:assert/strict') +const assert = require('assert') describe('mocha-test-skip', () => { it.skip('can skip', () => { assert.strictEqual(true, false) diff --git a/integration-tests/ci-visibility/mocha-plugin-tests/suite-level-fail-after-each.js b/integration-tests/ci-visibility/mocha-plugin-tests/suite-level-fail-after-each.js index 6523a9b0f11..fe6771d5d52 100644 --- a/integration-tests/ci-visibility/mocha-plugin-tests/suite-level-fail-after-each.js +++ b/integration-tests/ci-visibility/mocha-plugin-tests/suite-level-fail-after-each.js @@ -1,6 +1,6 @@ 'use strict' -const assert = require('node:assert/strict') +const assert = require('assert') describe('mocha-test-suite-level-pass', function () { it('will pass', () => { assert.strictEqual(2, 2) diff --git a/integration-tests/ci-visibility/mocha-plugin-tests/suite-level-fail-skip-describe.js b/integration-tests/ci-visibility/mocha-plugin-tests/suite-level-fail-skip-describe.js index 7db8d7f5d69..699f90206e8 100644 --- a/integration-tests/ci-visibility/mocha-plugin-tests/suite-level-fail-skip-describe.js +++ b/integration-tests/ci-visibility/mocha-plugin-tests/suite-level-fail-skip-describe.js @@ -1,6 +1,6 @@ 'use strict' -const assert = require('node:assert/strict') +const assert = require('assert') describe('mocha-test-suite-level-fail', function () { it('will pass', () => { assert.strictEqual(2, 2) diff --git a/integration-tests/ci-visibility/mocha-plugin-tests/suite-level-fail-test.js b/integration-tests/ci-visibility/mocha-plugin-tests/suite-level-fail-test.js index 695533042c6..83d93d65269 100644 --- a/integration-tests/ci-visibility/mocha-plugin-tests/suite-level-fail-test.js +++ b/integration-tests/ci-visibility/mocha-plugin-tests/suite-level-fail-test.js @@ -1,6 +1,6 @@ 'use strict' -const assert = require('node:assert/strict') +const assert = require('assert') describe('mocha-test-suite-level-fail', function () { it('will pass', () => { assert.strictEqual(2, 2) diff --git a/integration-tests/ci-visibility/mocha-plugin-tests/suite-level-pass.js b/integration-tests/ci-visibility/mocha-plugin-tests/suite-level-pass.js index bb0e389d1f1..d394e277133 100644 --- a/integration-tests/ci-visibility/mocha-plugin-tests/suite-level-pass.js +++ b/integration-tests/ci-visibility/mocha-plugin-tests/suite-level-pass.js @@ -1,6 +1,6 @@ 'use strict' -const assert = require('node:assert/strict') +const assert = require('assert') describe('mocha-test-suite-level-fail', function () { it('will pass', () => { assert.strictEqual(2, 2) diff --git a/integration-tests/ci-visibility/office-addin-mock/test.js b/integration-tests/ci-visibility/office-addin-mock/test.js index 0ec8218aff6..1e38716b7fd 100644 --- a/integration-tests/ci-visibility/office-addin-mock/test.js +++ b/integration-tests/ci-visibility/office-addin-mock/test.js @@ -1,6 +1,6 @@ 'use strict' -const assert = require('node:assert/strict') +const assert = require('assert') const sum = require('./dependency') test('can sum', () => { diff --git a/integration-tests/ci-visibility/sharding-test/sharding-test-1.js b/integration-tests/ci-visibility/sharding-test/sharding-test-1.js index 3490957122d..bcc2d1f9010 100644 --- a/integration-tests/ci-visibility/sharding-test/sharding-test-1.js +++ b/integration-tests/ci-visibility/sharding-test/sharding-test-1.js @@ -1,6 +1,6 @@ 'use strict' -const assert = require('node:assert/strict') +const assert = require('assert') describe('sharding test 1', () => { it('can report tests', () => { assert.strictEqual(1 + 2, 3) diff --git a/integration-tests/ci-visibility/sharding-test/sharding-test-2.js b/integration-tests/ci-visibility/sharding-test/sharding-test-2.js index 380a43db236..ccb2a6c5e2a 100644 --- a/integration-tests/ci-visibility/sharding-test/sharding-test-2.js +++ b/integration-tests/ci-visibility/sharding-test/sharding-test-2.js @@ -1,6 +1,6 @@ 'use strict' -const assert = require('node:assert/strict') +const assert = require('assert') describe('sharding test 2', () => { it('can report tests', () => { assert.strictEqual(1 + 2, 3) diff --git a/integration-tests/ci-visibility/sharding-test/sharding-test-3.js b/integration-tests/ci-visibility/sharding-test/sharding-test-3.js index e9219819fcc..28c46dab9e8 100644 --- a/integration-tests/ci-visibility/sharding-test/sharding-test-3.js +++ b/integration-tests/ci-visibility/sharding-test/sharding-test-3.js @@ -1,6 +1,6 @@ 'use strict' -const assert = require('node:assert/strict') +const assert = require('assert') describe('sharding test 3', () => { it('can report tests', () => { assert.strictEqual(1 + 2, 3) diff --git a/integration-tests/ci-visibility/sharding-test/sharding-test-4.js b/integration-tests/ci-visibility/sharding-test/sharding-test-4.js index e06bf5348bf..29a097fa6e7 100644 --- a/integration-tests/ci-visibility/sharding-test/sharding-test-4.js +++ b/integration-tests/ci-visibility/sharding-test/sharding-test-4.js @@ -1,6 +1,6 @@ 'use strict' -const assert = require('node:assert/strict') +const assert = require('assert') describe('sharding test 4', () => { it('can report tests', () => { assert.strictEqual(1 + 2, 3) diff --git a/integration-tests/ci-visibility/sharding-test/sharding-test-5.js b/integration-tests/ci-visibility/sharding-test/sharding-test-5.js index b8b39b175d7..2a5255f20a4 100644 --- a/integration-tests/ci-visibility/sharding-test/sharding-test-5.js +++ b/integration-tests/ci-visibility/sharding-test/sharding-test-5.js @@ -1,6 +1,6 @@ 'use strict' -const assert = require('node:assert/strict') +const assert = require('assert') describe('sharding test 5', () => { it('can report tests', () => { assert.strictEqual(1 + 2, 3) diff --git a/integration-tests/ci-visibility/subproject/subproject-test.js b/integration-tests/ci-visibility/subproject/subproject-test.js index 545ab81d8db..5af9f5204ee 100644 --- a/integration-tests/ci-visibility/subproject/subproject-test.js +++ b/integration-tests/ci-visibility/subproject/subproject-test.js @@ -1,6 +1,6 @@ 'use strict' -const assert = require('node:assert/strict') +const assert = require('assert') const dependency = require('./dependency') diff --git a/integration-tests/ci-visibility/test-api-manual.spec.js b/integration-tests/ci-visibility/test-api-manual.spec.js index 609a7e23d57..e73810a36cc 100644 --- a/integration-tests/ci-visibility/test-api-manual.spec.js +++ b/integration-tests/ci-visibility/test-api-manual.spec.js @@ -1,12 +1,13 @@ 'use strict' -const assert = require('node:assert/strict') +const assert = require('assert') const { exec } = require('child_process') const { sandboxCwd, useSandbox, - getCiVisAgentlessConfig + getCiVisAgentlessConfig, + assertObjectContains } = require('../helpers') const { FakeCiVisIntake } = require('../ci-visibility-intake') const { @@ -36,18 +37,18 @@ describe('test-api-manual', () => { const events = payloads.flatMap(({ payload }) => payload.events) const testEvents = events.filter(event => event.type === 'test') - assert.includeMembers(testEvents.map(test => test.content.resource), [ + assertObjectContains(testEvents.map(test => test.content.resource), [ 'ci-visibility/test-api-manual/test.fake.js.second test will fail', 'ci-visibility/test-api-manual/test.fake.js.first test will pass', 'ci-visibility/test-api-manual/test.fake.js.async test will pass', 'ci-visibility/test-api-manual/test.fake.js.integration test' ]) - assert.includeMembers(testEvents.map(test => test.content.meta[TEST_STATUS]), [ + assertObjectContains(testEvents.map(test => test.content.meta[TEST_STATUS]), [ + 'fail', 'pass', 'pass', 'pass', - 'fail' ]) const passedTest = testEvents.find( diff --git a/integration-tests/ci-visibility/test-custom-tags/custom-tags.js b/integration-tests/ci-visibility/test-custom-tags/custom-tags.js index 0c81bacb762..eb994e5e98a 100644 --- a/integration-tests/ci-visibility/test-custom-tags/custom-tags.js +++ b/integration-tests/ci-visibility/test-custom-tags/custom-tags.js @@ -1,6 +1,6 @@ 'use strict' -const assert = require('node:assert/strict') +const assert = require('assert') const tracer = require('dd-trace') diff --git a/integration-tests/ci-visibility/test-early-flake-detection/mocha-parameterized.js b/integration-tests/ci-visibility/test-early-flake-detection/mocha-parameterized.js index ad4698deb28..09cbeff8d40 100644 --- a/integration-tests/ci-visibility/test-early-flake-detection/mocha-parameterized.js +++ b/integration-tests/ci-visibility/test-early-flake-detection/mocha-parameterized.js @@ -1,6 +1,6 @@ 'use strict' -const assert = require('node:assert/strict') +const assert = require('assert') const forEach = require('mocha-each') describe('parameterized', () => { diff --git a/integration-tests/ci-visibility/test-early-flake-detection/occasionally-failing-test.js b/integration-tests/ci-visibility/test-early-flake-detection/occasionally-failing-test.js index 749ed6f238c..d2ed7b52434 100644 --- a/integration-tests/ci-visibility/test-early-flake-detection/occasionally-failing-test.js +++ b/integration-tests/ci-visibility/test-early-flake-detection/occasionally-failing-test.js @@ -1,6 +1,6 @@ 'use strict' -const assert = require('node:assert/strict') +const assert = require('assert') let globalCounter = 0 describe('fail', () => { diff --git a/integration-tests/ci-visibility/test-early-flake-detection/skipped-and-todo-test.js b/integration-tests/ci-visibility/test-early-flake-detection/skipped-and-todo-test.js index f4783e4e901..3bffff44a34 100644 --- a/integration-tests/ci-visibility/test-early-flake-detection/skipped-and-todo-test.js +++ b/integration-tests/ci-visibility/test-early-flake-detection/skipped-and-todo-test.js @@ -1,6 +1,6 @@ 'use strict' -const assert = require('node:assert/strict') +const assert = require('assert') describe('ci visibility', () => { it('can report tests', () => { assert.strictEqual(1 + 2, 3) diff --git a/integration-tests/ci-visibility/test-early-flake-detection/test-parameterized.js b/integration-tests/ci-visibility/test-early-flake-detection/test-parameterized.js index a4d3099f719..7ad0d1114e6 100644 --- a/integration-tests/ci-visibility/test-early-flake-detection/test-parameterized.js +++ b/integration-tests/ci-visibility/test-early-flake-detection/test-parameterized.js @@ -1,6 +1,6 @@ 'use strict' -const assert = require('node:assert/strict') +const assert = require('assert') describe('parameterized', () => { test.each(['parameter 1', 'parameter 2'])('test %s', (value) => { assert.deepStrictEqual(value.startsWith('parameter'), true) diff --git a/integration-tests/ci-visibility/test-early-flake-detection/test.js b/integration-tests/ci-visibility/test-early-flake-detection/test.js index 53de41a3938..62e696ae6f0 100644 --- a/integration-tests/ci-visibility/test-early-flake-detection/test.js +++ b/integration-tests/ci-visibility/test-early-flake-detection/test.js @@ -1,6 +1,6 @@ 'use strict' -const assert = require('node:assert/strict') +const assert = require('assert') describe('ci visibility', () => { it('can report tests', () => { assert.strictEqual(1 + 2, 3) diff --git a/integration-tests/ci-visibility/test-early-flake-detection/weird-test-names.js b/integration-tests/ci-visibility/test-early-flake-detection/weird-test-names.js index 4dd562db02f..f45fdb2c99c 100644 --- a/integration-tests/ci-visibility/test-early-flake-detection/weird-test-names.js +++ b/integration-tests/ci-visibility/test-early-flake-detection/weird-test-names.js @@ -1,6 +1,6 @@ 'use strict' -const assert = require('node:assert/strict') +const assert = require('assert') it('no describe can do stuff', () => { assert.strictEqual(1, 1) }) diff --git a/integration-tests/ci-visibility/test-flaky-test-retries/eventually-passing-test.js b/integration-tests/ci-visibility/test-flaky-test-retries/eventually-passing-test.js index bc0d02b7df2..d355111f9a0 100644 --- a/integration-tests/ci-visibility/test-flaky-test-retries/eventually-passing-test.js +++ b/integration-tests/ci-visibility/test-flaky-test-retries/eventually-passing-test.js @@ -1,6 +1,6 @@ 'use strict' -const assert = require('node:assert/strict') +const assert = require('assert') let counter = 0 describe('test-flaky-test-retries', () => { diff --git a/integration-tests/ci-visibility/test-impacted-test/test-impacted-1.js b/integration-tests/ci-visibility/test-impacted-test/test-impacted-1.js index 783efc7bc2b..cc73d758bc1 100644 --- a/integration-tests/ci-visibility/test-impacted-test/test-impacted-1.js +++ b/integration-tests/ci-visibility/test-impacted-test/test-impacted-1.js @@ -1,6 +1,6 @@ 'use strict' -const assert = require('node:assert/strict') +const assert = require('assert') describe('impacted tests', () => { it('can pass normally', () => { assert.strictEqual(1 + 2, 3) diff --git a/integration-tests/ci-visibility/test-impacted-test/test-impacted-2.js b/integration-tests/ci-visibility/test-impacted-test/test-impacted-2.js index 8d510c8ce75..9d230e5b01e 100644 --- a/integration-tests/ci-visibility/test-impacted-test/test-impacted-2.js +++ b/integration-tests/ci-visibility/test-impacted-test/test-impacted-2.js @@ -1,6 +1,6 @@ 'use strict' -const assert = require('node:assert/strict') +const assert = require('assert') describe('impacted tests 2', () => { it('can pass normally', () => { assert.strictEqual(1 + 2, 3) diff --git a/integration-tests/ci-visibility/test-management/test-attempt-to-fix-1.js b/integration-tests/ci-visibility/test-management/test-attempt-to-fix-1.js index 36ff9c5cd80..74bcddc3ea2 100644 --- a/integration-tests/ci-visibility/test-management/test-attempt-to-fix-1.js +++ b/integration-tests/ci-visibility/test-management/test-attempt-to-fix-1.js @@ -1,6 +1,6 @@ 'use strict' -const assert = require('node:assert/strict') +const assert = require('assert') let numAttempts = 0 describe('attempt to fix tests', () => { diff --git a/integration-tests/ci-visibility/test-management/test-attempt-to-fix-2.js b/integration-tests/ci-visibility/test-management/test-attempt-to-fix-2.js index a2a7920c9b2..d4457603030 100644 --- a/integration-tests/ci-visibility/test-management/test-attempt-to-fix-2.js +++ b/integration-tests/ci-visibility/test-management/test-attempt-to-fix-2.js @@ -1,6 +1,6 @@ 'use strict' -const assert = require('node:assert/strict') +const assert = require('assert') describe('attempt to fix tests 2', () => { it('can attempt to fix a test', () => { // eslint-disable-next-line no-console diff --git a/integration-tests/ci-visibility/test-management/test-disabled-1.js b/integration-tests/ci-visibility/test-management/test-disabled-1.js index 3b7c8787a9d..d7cf86501c5 100644 --- a/integration-tests/ci-visibility/test-management/test-disabled-1.js +++ b/integration-tests/ci-visibility/test-management/test-disabled-1.js @@ -1,6 +1,6 @@ 'use strict' -const assert = require('node:assert/strict') +const assert = require('assert') describe('disable tests', () => { it('can disable a test', () => { // eslint-disable-next-line no-console diff --git a/integration-tests/ci-visibility/test-management/test-disabled-2.js b/integration-tests/ci-visibility/test-management/test-disabled-2.js index 643455b20a5..d68f9e9ee53 100644 --- a/integration-tests/ci-visibility/test-management/test-disabled-2.js +++ b/integration-tests/ci-visibility/test-management/test-disabled-2.js @@ -1,6 +1,6 @@ 'use strict' -const assert = require('node:assert/strict') +const assert = require('assert') describe('disable tests 2', () => { it('can disable a test', () => { assert.strictEqual(1 + 2, 3) diff --git a/integration-tests/ci-visibility/test-management/test-quarantine-1.js b/integration-tests/ci-visibility/test-management/test-quarantine-1.js index 6971e33d5d3..2671d4aaf4f 100644 --- a/integration-tests/ci-visibility/test-management/test-quarantine-1.js +++ b/integration-tests/ci-visibility/test-management/test-quarantine-1.js @@ -1,6 +1,6 @@ 'use strict' -const assert = require('node:assert/strict') +const assert = require('assert') describe('quarantine tests', () => { it('can quarantine a test', () => { // eslint-disable-next-line no-console diff --git a/integration-tests/ci-visibility/test-management/test-quarantine-2.js b/integration-tests/ci-visibility/test-management/test-quarantine-2.js index b6930c20262..9bf8787ae9c 100644 --- a/integration-tests/ci-visibility/test-management/test-quarantine-2.js +++ b/integration-tests/ci-visibility/test-management/test-quarantine-2.js @@ -1,6 +1,6 @@ 'use strict' -const assert = require('node:assert/strict') +const assert = require('assert') describe('quarantine tests 2', () => { it('can quarantine a test', () => { assert.strictEqual(1 + 2, 3) diff --git a/integration-tests/ci-visibility/test-nested-hooks/test-nested-hooks.js b/integration-tests/ci-visibility/test-nested-hooks/test-nested-hooks.js index 6ebc7f67876..2407846cf1a 100644 --- a/integration-tests/ci-visibility/test-nested-hooks/test-nested-hooks.js +++ b/integration-tests/ci-visibility/test-nested-hooks/test-nested-hooks.js @@ -1,6 +1,6 @@ 'use strict' -const assert = require('node:assert/strict') +const assert = require('assert') let globalAttempts = 0 describe('describe', function () { diff --git a/integration-tests/ci-visibility/test-optimization-startup.spec.js b/integration-tests/ci-visibility/test-optimization-startup.spec.js index 8d0ac6f5474..2a08da4b2f2 100644 --- a/integration-tests/ci-visibility/test-optimization-startup.spec.js +++ b/integration-tests/ci-visibility/test-optimization-startup.spec.js @@ -1,6 +1,6 @@ 'use strict' -const assert = require('node:assert/strict') +const assert = require('assert') const { exec } = require('child_process') const { once } = require('events') @@ -55,7 +55,7 @@ describe('test optimization startup', () => { once(childProcess.stderr, 'end') ]) - assert.ok(processOutput.includes('dd-trace is not initialized in a package manager')) + assert.match(processOutput, /dd-trace is not initialized in a package manager/) }) }) @@ -85,8 +85,8 @@ describe('test optimization startup', () => { once(childProcess.stderr, 'end') ]) - assert.ok(processOutput.includes('hello!')) - assert.ok(!processOutput.includes('dd-trace is not initialized in a package manager')) + assert.match(processOutput, /hello!/) + assert.doesNotMatch(processOutput, /dd-trace is not initialized in a package manager/) }) it('fails if DD_API_KEY is not set when in a non test worker', async () => { @@ -116,8 +116,8 @@ describe('test optimization startup', () => { once(childProcess.stderr, 'end') ]) - assert.ok(processOutput.includes('hello!')) - assert.ok(processOutput.includes('dd-trace will not be initialized')) + assert.match(processOutput, /hello!/) + assert.match(processOutput, /dd-trace will not be initialized/) }) it('does not fail if DD_API_KEY is not set when in a test worker', async () => { @@ -148,7 +148,7 @@ describe('test optimization startup', () => { once(childProcess.stderr, 'end') ]) - assert.ok(processOutput.includes('hello!')) - assert.ok(!processOutput.includes('dd-trace will not be initialized')) + assert.match(processOutput, /hello!/) + assert.doesNotMatch(processOutput, /dd-trace will not be initialized/) }) }) diff --git a/integration-tests/ci-visibility/test-optimization-wrong-init-cucumber/support/steps.js b/integration-tests/ci-visibility/test-optimization-wrong-init-cucumber/support/steps.js index 60ca39f6327..543c92aa780 100644 --- a/integration-tests/ci-visibility/test-optimization-wrong-init-cucumber/support/steps.js +++ b/integration-tests/ci-visibility/test-optimization-wrong-init-cucumber/support/steps.js @@ -1,6 +1,6 @@ 'use strict' -const assert = require('node:assert/strict') +const assert = require('assert') const { Given, When, Then } = require('@cucumber/cucumber') const tracer = require('dd-trace') diff --git a/integration-tests/ci-visibility/test-optimization-wrong-init.spec.js b/integration-tests/ci-visibility/test-optimization-wrong-init.spec.js index ea4424a0caf..f4e7b3af47e 100644 --- a/integration-tests/ci-visibility/test-optimization-wrong-init.spec.js +++ b/integration-tests/ci-visibility/test-optimization-wrong-init.spec.js @@ -122,7 +122,7 @@ testFrameworks.forEach(({ testFramework, command, expectedOutput, extraTestConte `Plugin "${testFramework}" is not initialized because Test Optimization mode is not enabled.` ) ) - assert.ok(processOutput.includes(expectedOutput)) + assert.match(processOutput, new RegExp(expectedOutput)) }) }) }) diff --git a/integration-tests/ci-visibility/test-parsing-error/parsing-error-2.js b/integration-tests/ci-visibility/test-parsing-error/parsing-error-2.js index b55bb87eb6f..bb43f645de4 100644 --- a/integration-tests/ci-visibility/test-parsing-error/parsing-error-2.js +++ b/integration-tests/ci-visibility/test-parsing-error/parsing-error-2.js @@ -1,11 +1,9 @@ 'use strict' -const assert = require('node:assert/strict') - const { expect } = require('chao') describe('test-parsing-error-2', () => { it('can report tests', () => { - assert.strictEqual(1 + 2, 3) + expect(1 + 2).to.equal(3) }) }) diff --git a/integration-tests/ci-visibility/test-parsing-error/parsing-error.js b/integration-tests/ci-visibility/test-parsing-error/parsing-error.js index f7d79b911ed..9ede9a25a37 100644 --- a/integration-tests/ci-visibility/test-parsing-error/parsing-error.js +++ b/integration-tests/ci-visibility/test-parsing-error/parsing-error.js @@ -1,11 +1,9 @@ 'use strict' -const assert = require('node:assert/strict') - const { expect } = require('chao') describe('test-parsing-error', () => { it('can report tests', () => { - assert.strictEqual(1 + 2, 3) + expect(1 + 2).to.equal(3) }) }) diff --git a/integration-tests/ci-visibility/test-total-code-coverage/test-run.js b/integration-tests/ci-visibility/test-total-code-coverage/test-run.js index 838710a2449..6c0db731a65 100644 --- a/integration-tests/ci-visibility/test-total-code-coverage/test-run.js +++ b/integration-tests/ci-visibility/test-total-code-coverage/test-run.js @@ -1,6 +1,6 @@ 'use strict' -const assert = require('node:assert/strict') +const assert = require('assert') const sum = require('./used-dependency') describe('test-run', () => { diff --git a/integration-tests/ci-visibility/test-total-code-coverage/test-skipped.js b/integration-tests/ci-visibility/test-total-code-coverage/test-skipped.js index 9fcc000c82a..05b3d25704f 100644 --- a/integration-tests/ci-visibility/test-total-code-coverage/test-skipped.js +++ b/integration-tests/ci-visibility/test-total-code-coverage/test-skipped.js @@ -1,6 +1,6 @@ 'use strict' -const assert = require('node:assert/strict') +const assert = require('assert') const sum = require('./unused-dependency') describe('test-skipped', () => { diff --git a/integration-tests/ci-visibility/test/ci-visibility-test-2.js b/integration-tests/ci-visibility/test/ci-visibility-test-2.js index 527690a12ce..8254ac17a7e 100644 --- a/integration-tests/ci-visibility/test/ci-visibility-test-2.js +++ b/integration-tests/ci-visibility/test/ci-visibility-test-2.js @@ -1,6 +1,6 @@ 'use strict' -const assert = require('node:assert/strict') +const assert = require('assert') const sum = require('./sum') describe('ci visibility 2', () => { diff --git a/integration-tests/ci-visibility/test/ci-visibility-test.js b/integration-tests/ci-visibility/test/ci-visibility-test.js index 0790a04acb8..fe8fa4ec26b 100644 --- a/integration-tests/ci-visibility/test/ci-visibility-test.js +++ b/integration-tests/ci-visibility/test/ci-visibility-test.js @@ -1,6 +1,6 @@ 'use strict' -const assert = require('node:assert/strict') +const assert = require('assert') const sum = require('./sum') describe('ci visibility', () => { diff --git a/integration-tests/ci-visibility/test/efd-parallel/ci-visibility-test-2.js b/integration-tests/ci-visibility/test/efd-parallel/ci-visibility-test-2.js index 8420b7d71ac..313a265db6c 100644 --- a/integration-tests/ci-visibility/test/efd-parallel/ci-visibility-test-2.js +++ b/integration-tests/ci-visibility/test/efd-parallel/ci-visibility-test-2.js @@ -1,6 +1,6 @@ 'use strict' -const assert = require('node:assert/strict') +const assert = require('assert') const sum = require('../sum') diff --git a/integration-tests/ci-visibility/test/efd-parallel/ci-visibility-test-3.js b/integration-tests/ci-visibility/test/efd-parallel/ci-visibility-test-3.js index 18e3f89b90a..139f3dee2eb 100644 --- a/integration-tests/ci-visibility/test/efd-parallel/ci-visibility-test-3.js +++ b/integration-tests/ci-visibility/test/efd-parallel/ci-visibility-test-3.js @@ -1,6 +1,6 @@ 'use strict' -const assert = require('node:assert/strict') +const assert = require('assert') const sum = require('../sum') diff --git a/integration-tests/ci-visibility/test/efd-parallel/ci-visibility-test-4.js b/integration-tests/ci-visibility/test/efd-parallel/ci-visibility-test-4.js index 577be5b6557..0ef8a1c8f66 100644 --- a/integration-tests/ci-visibility/test/efd-parallel/ci-visibility-test-4.js +++ b/integration-tests/ci-visibility/test/efd-parallel/ci-visibility-test-4.js @@ -1,6 +1,6 @@ 'use strict' -const assert = require('node:assert/strict') +const assert = require('assert') const sum = require('../sum') diff --git a/integration-tests/ci-visibility/test/efd-parallel/ci-visibility-test.js b/integration-tests/ci-visibility/test/efd-parallel/ci-visibility-test.js index b192019d261..d4a93c818e0 100644 --- a/integration-tests/ci-visibility/test/efd-parallel/ci-visibility-test.js +++ b/integration-tests/ci-visibility/test/efd-parallel/ci-visibility-test.js @@ -1,6 +1,6 @@ 'use strict' -const assert = require('node:assert/strict') +const assert = require('assert') const sum = require('../sum') diff --git a/integration-tests/ci-visibility/test/fail-test.js b/integration-tests/ci-visibility/test/fail-test.js index c0fbfbf685a..4ce4cb1ae41 100644 --- a/integration-tests/ci-visibility/test/fail-test.js +++ b/integration-tests/ci-visibility/test/fail-test.js @@ -1,6 +1,6 @@ 'use strict' -const assert = require('node:assert/strict') +const assert = require('assert') describe('fail', () => { it('can report failed tests', () => { assert.strictEqual(1 + 2, 4) diff --git a/integration-tests/ci-visibility/test/selenium-test.js b/integration-tests/ci-visibility/test/selenium-test.js index c0581fbbfae..125943e8e20 100644 --- a/integration-tests/ci-visibility/test/selenium-test.js +++ b/integration-tests/ci-visibility/test/selenium-test.js @@ -1,6 +1,6 @@ 'use strict' -const assert = require('node:assert/strict') +const assert = require('assert') const { By, Builder } = require('selenium-webdriver') const chrome = require('selenium-webdriver/chrome') diff --git a/integration-tests/ci-visibility/unskippable-test/test-to-run.js b/integration-tests/ci-visibility/unskippable-test/test-to-run.js index d20cf9e8cec..babf104fec5 100644 --- a/integration-tests/ci-visibility/unskippable-test/test-to-run.js +++ b/integration-tests/ci-visibility/unskippable-test/test-to-run.js @@ -1,6 +1,6 @@ 'use strict' -const assert = require('node:assert/strict') +const assert = require('assert') describe('test-to-run', () => { it('can report tests', () => { assert.strictEqual(1 + 2, 3) diff --git a/integration-tests/ci-visibility/unskippable-test/test-to-skip.js b/integration-tests/ci-visibility/unskippable-test/test-to-skip.js index ed28293926c..f8452e04d5c 100644 --- a/integration-tests/ci-visibility/unskippable-test/test-to-skip.js +++ b/integration-tests/ci-visibility/unskippable-test/test-to-skip.js @@ -1,6 +1,6 @@ 'use strict' -const assert = require('node:assert/strict') +const assert = require('assert') describe('test-to-skip', () => { it('can report tests', () => { assert.strictEqual(1 + 2, 3) diff --git a/integration-tests/ci-visibility/unskippable-test/test-unskippable.js b/integration-tests/ci-visibility/unskippable-test/test-unskippable.js index 1dabec4d0cb..6f3cb8d9aea 100644 --- a/integration-tests/ci-visibility/unskippable-test/test-unskippable.js +++ b/integration-tests/ci-visibility/unskippable-test/test-unskippable.js @@ -1,5 +1,3 @@ -const assert = require('node:assert/strict') - /** Some comment */ /* eslint-disable jsdoc/valid-types */ /** @@ -7,6 +5,9 @@ const assert = require('node:assert/strict') */ /* Some other comment */ 'use strict' + +const assert = require('assert') + describe('test-unskippable', () => { it('can report tests', () => { assert.strictEqual(1 + 2, 3) diff --git a/integration-tests/cucumber/cucumber.spec.js b/integration-tests/cucumber/cucumber.spec.js index 97287c9d851..08902664a28 100644 --- a/integration-tests/cucumber/cucumber.spec.js +++ b/integration-tests/cucumber/cucumber.spec.js @@ -179,7 +179,7 @@ describe(`cucumber@${version} commonJS`, () => { const resourceNames = testSpans.map(span => span.resource) - assert.includeMembers(resourceNames, [ + assertObjectContains(resourceNames, [ 'ci-visibility/cucumber-plugin-tests/features/simple.feature.pass scenario', 'ci-visibility/cucumber-plugin-tests/features/simple.feature.fail scenario', 'ci-visibility/cucumber-plugin-tests/features/simple.feature.skip scenario', @@ -204,7 +204,11 @@ describe(`cucumber@${version} commonJS`, () => { assert.ok(testSpan.meta[TEST_FRAMEWORK_VERSION] != null) assert.strictEqual(testSpan.meta[TEST_CODE_OWNERS], JSON.stringify(['@datadog-dd-trace-js'])) assert.strictEqual(testSpan.meta[TEST_SUITE], 'ci-visibility/cucumber-plugin-tests/features/simple.feature') - assert.strictEqual(testSpan.meta[TEST_SOURCE_FILE], 'ci-visibility/cucumber-plugin-tests/features/simple.feature') + assert.strictEqual( + testSpan.meta[TEST_SOURCE_FILE], + 'ci-visibility/cucumber-plugin-tests/features/simple.feature', + 'Test source file should be the simple feature' + ) assert.ok(testSpan.metrics[TEST_SOURCE_START] != null) assert.strictEqual(testSpan.type, 'test') assert.strictEqual(testSpan.name, 'cucumber.test') @@ -229,18 +233,18 @@ describe(`cucumber@${version} commonJS`, () => { if (testName === 'fail scenario') { assert.strictEqual(testSpan.meta[ERROR_TYPE], 'Error') const errorMessage = testSpan.meta[ERROR_MESSAGE] - assert.ok(errorMessage.includes('AssertionError')) - assert.ok(errorMessage.includes('datadog')) - assert.ok(errorMessage.includes('godatad')) + assert.match(errorMessage, /AssertionError/) + assert.match(errorMessage, /datadog/) + assert.match(errorMessage, /godatad/) assert.ok(testSpan.meta[ERROR_STACK] != null) } if (testName === 'hooks fail') { assert.strictEqual(testSpan.meta[ERROR_TYPE], 'Error') const errorMessage = testSpan.meta[ERROR_MESSAGE] - assert.ok(errorMessage.includes('TypeError: Cannot set')) - assert.ok(errorMessage.includes('of undefined')) - assert.ok(errorMessage.includes('boom')) + assert.match(errorMessage, /TypeError: Cannot set/) + assert.match(errorMessage, /of undefined/) + assert.match(errorMessage, /boom/) assert.ok(testSpan.meta[ERROR_STACK] != null) } @@ -336,13 +340,16 @@ describe(`cucumber@${version} commonJS`, () => { assert.ok(testModuleEventContent.meta[TEST_MODULE] != null) assert.strictEqual(testModuleEventContent.resource.startsWith('test_module.'), true) assert.strictEqual(testModuleEventContent.meta[TEST_STATUS], 'fail') - assert.strictEqual(testModuleEventContent.test_session_id.toString(10), testSessionEventContent.test_session_id.toString(10)) + assert.strictEqual( + testModuleEventContent.test_session_id.toString(10), + testSessionEventContent.test_session_id.toString(10) + ) - assert.includeMembers(testSuiteEvents.map(suite => suite.content.resource), [ + assertObjectContains(testSuiteEvents.map(suite => suite.content.resource), [ `test_suite.${featuresPath}farewell.feature`, `test_suite.${featuresPath}greetings.feature` ]) - assert.includeMembers(testSuiteEvents.map(suite => suite.content.meta[TEST_STATUS]), [ + assertObjectContains(testSuiteEvents.map(suite => suite.content.meta[TEST_STATUS]), [ 'pass', 'fail' ]) @@ -366,19 +373,21 @@ describe(`cucumber@${version} commonJS`, () => { assert.ok(metrics[DD_HOST_CPU_COUNT] != null) }) - assert.includeMembers(testEvents.map(test => test.content.resource), [ + assert.deepStrictEqual(testEvents.map(test => test.content.resource).sort(), [ `${featuresPath}farewell.feature.Say farewell`, + `${featuresPath}farewell.feature.Say whatever`, `${featuresPath}greetings.feature.Say greetings`, + `${featuresPath}greetings.feature.Say skip`, `${featuresPath}greetings.feature.Say yeah`, `${featuresPath}greetings.feature.Say yo`, - `${featuresPath}greetings.feature.Say skip` ]) - assert.includeMembers(testEvents.map(test => test.content.meta[TEST_STATUS]), [ + assert.deepStrictEqual(testEvents.map(test => test.content.meta[TEST_STATUS]).sort(), [ + 'fail', 'pass', 'pass', 'pass', - 'fail', - 'skip' + 'pass', + 'skip', ]) testEvents.forEach(({ @@ -457,12 +466,12 @@ describe(`cucumber@${version} commonJS`, () => { assert.strictEqual(searchCommitRequest.headers['dd-api-key'], '1') assert.strictEqual(packfileRequest.headers['dd-api-key'], '1') } else { - assert.ok(!Object.hasOwn(searchCommitRequest.headers, 'dd-api-key')) - assert.ok(!Object.hasOwn(packfileRequest.headers, 'dd-api-key')) + assert.ok(!('dd-api-key' in searchCommitRequest.headers)) + assert.ok(!('dd-api-key' in packfileRequest.headers)) } const eventTypes = eventsRequest.payload.events.map(event => event.type) - assert.includeMembers(eventTypes, ['test', 'test_suite_end', 'test_module_end', 'test_session_end']) + assertObjectContains(eventTypes, ['test', 'test_session_end', 'test_module_end', 'test_suite_end']) const numSuites = eventTypes.reduce( (acc, type) => type === 'test_suite_end' ? acc + 1 : acc, 0 ) @@ -498,28 +507,34 @@ describe(`cucumber@${version} commonJS`, () => { assert.strictEqual(libraryConfigRequest.headers['dd-api-key'], '1') assert.strictEqual(codeCovRequest.headers['dd-api-key'], '1') } else { - assert.ok(!Object.hasOwn(libraryConfigRequest.headers, 'dd-api-key')) - assert.ok(!Object.hasOwn(codeCovRequest.headers, 'dd-api-key')) + assert.ok(!('dd-api-key' in libraryConfigRequest.headers)) + assert.ok(!('dd-api-key' in codeCovRequest.headers)) } - assert.strictEqual(coveragePayload.name, 'coverage1') - assert.strictEqual(coveragePayload.filename, 'coverage1.msgpack') - assert.strictEqual(coveragePayload.type, 'application/msgpack') - assert.ok(coveragePayload.content.includes({ - version: 2 - })) + assertObjectContains(coveragePayload, { + name: 'coverage1', + filename: 'coverage1.msgpack', + type: 'application/msgpack', + content: { + version: 2 + } + }) const allCoverageFiles = codeCovRequest.payload .flatMap(coverage => coverage.content.coverages) .flatMap(file => file.files) .map(file => file.filename) - assert.includeMembers(allCoverageFiles, [ + assertObjectContains(allCoverageFiles, [ `${featuresPath}support/steps.${fileExtension}`, `${featuresPath}farewell.feature`, `${featuresPath}greetings.feature` ]) // steps is twice because there are two suites using it - assert.strictEqual(allCoverageFiles.filter(file => file === `${featuresPath}support/steps.${fileExtension}`).length, 2) + assert.strictEqual( + allCoverageFiles.filter(file => file === `${featuresPath}support/steps.${fileExtension}`).length, + 2, + 'Steps should be covered twice' + ) assert.ok(coveragePayload.content.coverages[0].test_session_id != null) assert.ok(coveragePayload.content.coverages[0].test_suite_id != null) @@ -531,7 +546,7 @@ describe(`cucumber@${version} commonJS`, () => { assert.ok(testSession.metrics[TEST_CODE_COVERAGE_LINES_PCT] != null) const eventTypes = eventsRequest.payload.events.map(event => event.type) - assert.includeMembers(eventTypes, ['test', 'test_suite_end', 'test_module_end', 'test_session_end']) + assertObjectContains(eventTypes, ['test', 'test_session_end', 'test_module_end', 'test_suite_end']) const numSuites = eventTypes.reduce( (acc, type) => type === 'test_suite_end' ? acc + 1 : acc, 0 ) @@ -554,7 +569,7 @@ describe(`cucumber@${version} commonJS`, () => { }) childProcess.on('exit', () => { // check that reported coverage is still the same - assert.ok(testOutput.includes('Lines : 100%')) + assert.match(testOutput, /Lines {8}: 100%/) done() }) }) @@ -573,7 +588,7 @@ describe(`cucumber@${version} commonJS`, () => { receiver.assertPayloadReceived(({ payload }) => { const eventTypes = payload.events.map(event => event.type) - assert.includeMembers(eventTypes, ['test', 'test_session_end', 'test_module_end', 'test_suite_end']) + assertObjectContains(eventTypes, ['test', 'test_session_end', 'test_module_end', 'test_suite_end']) const testSession = payload.events.find(event => event.type === 'test_session_end').content assert.strictEqual(testSession.meta[TEST_ITR_TESTS_SKIPPED], 'false') assert.strictEqual(testSession.meta[TEST_CODE_COVERAGE_ENABLED], 'false') @@ -620,9 +635,9 @@ describe(`cucumber@${version} commonJS`, () => { assert.strictEqual(coverageRequest.headers['dd-api-key'], '1') assert.strictEqual(eventsRequest.headers['dd-api-key'], '1') } else { - assert.ok(!Object.hasOwn(skippableRequest.headers, 'dd-api-key')) - assert.ok(!Object.hasOwn(coverageRequest.headers, 'dd-api-key')) - assert.ok(!Object.hasOwn(eventsRequest.headers, 'dd-api-key')) + assert.ok(!('dd-api-key' in skippableRequest.headers)) + assert.ok(!('dd-api-key' in coverageRequest.headers)) + assert.ok(!('dd-api-key' in eventsRequest.headers)) } assert.strictEqual(coveragePayload.name, 'coverage1') assert.strictEqual(coveragePayload.filename, 'coverage1.msgpack') @@ -636,7 +651,7 @@ describe(`cucumber@${version} commonJS`, () => { assert.strictEqual(skippedSuite.meta[TEST_STATUS], 'skip') assert.strictEqual(skippedSuite.meta[TEST_SKIPPED_BY_ITR], 'true') - assert.includeMembers(eventTypes, ['test', 'test_suite_end', 'test_module_end', 'test_session_end']) + assertObjectContains(eventTypes, ['test', 'test_session_end', 'test_module_end', 'test_suite_end']) const numSuites = eventTypes.reduce( (acc, type) => type === 'test_suite_end' ? acc + 1 : acc, 0 ) @@ -687,7 +702,7 @@ describe(`cucumber@${version} commonJS`, () => { receiver.assertPayloadReceived(({ payload }) => { const eventTypes = payload.events.map(event => event.type) // because they are not skipped - assert.includeMembers(eventTypes, ['test', 'test_suite_end', 'test_module_end', 'test_session_end']) + assertObjectContains(eventTypes, ['test', 'test_session_end', 'test_module_end', 'test_suite_end']) const numSuites = eventTypes.reduce( (acc, type) => type === 'test_suite_end' ? acc + 1 : acc, 0 ) @@ -734,7 +749,7 @@ describe(`cucumber@${version} commonJS`, () => { receiver.assertPayloadReceived(({ payload }) => { const eventTypes = payload.events.map(event => event.type) // because they are not skipped - assert.includeMembers(eventTypes, ['test', 'test_suite_end', 'test_module_end', 'test_session_end']) + assertObjectContains(eventTypes, ['test', 'test_session_end', 'test_module_end', 'test_suite_end']) const numSuites = eventTypes.reduce( (acc, type) => type === 'test_suite_end' ? acc + 1 : acc, 0 ) @@ -796,8 +811,8 @@ describe(`cucumber@${version} commonJS`, () => { ).content assert.strictEqual(skippedSuite.meta[TEST_STATUS], 'skip') - assert.ok(!Object.hasOwn(skippedSuite.meta, TEST_ITR_UNSKIPPABLE)) - assert.ok(!Object.hasOwn(skippedSuite.meta, TEST_ITR_FORCED_RUN)) + assert.ok(!('TEST_ITR_UNSKIPPABLE' in skippedSuite.meta)) + assert.ok(!('TEST_ITR_FORCED_RUN' in skippedSuite.meta)) assert.strictEqual(forcedToRunSuite.meta[TEST_STATUS], 'fail') assert.strictEqual(forcedToRunSuite.meta[TEST_ITR_UNSKIPPABLE], 'true') @@ -847,9 +862,9 @@ describe(`cucumber@${version} commonJS`, () => { const testModule = events.find(event => event.type === 'test_session_end').content assert.strictEqual(testSession.meta[TEST_ITR_UNSKIPPABLE], 'true') - assert.ok(!Object.hasOwn(testSession.meta, TEST_ITR_FORCED_RUN)) + assert.ok(!('TEST_ITR_FORCED_RUN' in testSession.meta)) assert.strictEqual(testModule.meta[TEST_ITR_UNSKIPPABLE], 'true') - assert.ok(!Object.hasOwn(testModule.meta, TEST_ITR_FORCED_RUN)) + assert.ok(!('TEST_ITR_FORCED_RUN' in testModule.meta)) const skippedSuite = suites.find( event => event.content.resource === 'test_suite.ci-visibility/features/farewell.feature' @@ -859,12 +874,12 @@ describe(`cucumber@${version} commonJS`, () => { ) assert.strictEqual(skippedSuite.content.meta[TEST_STATUS], 'skip') - assert.ok(!Object.hasOwn(skippedSuite.content.meta, TEST_ITR_UNSKIPPABLE)) - assert.ok(!Object.hasOwn(skippedSuite.content.meta, TEST_ITR_FORCED_RUN)) + assert.ok(!('TEST_ITR_UNSKIPPABLE' in skippedSuite.content.meta)) + assert.ok(!('TEST_ITR_FORCED_RUN' in skippedSuite.content.meta)) assert.strictEqual(failedSuite.content.meta[TEST_STATUS], 'fail') assert.strictEqual(failedSuite.content.meta[TEST_ITR_UNSKIPPABLE], 'true') - assert.ok(!Object.hasOwn(failedSuite.content.meta, TEST_ITR_FORCED_RUN)) + assert.ok(!('TEST_ITR_FORCED_RUN' in failedSuite.content.meta)) }, 25000) childProcess = exec( @@ -946,7 +961,7 @@ describe(`cucumber@${version} commonJS`, () => { const testSpans = payload.flatMap(trace => trace) const resourceNames = testSpans.map(span => span.resource) - assert.includeMembers(resourceNames, + assertObjectContains(resourceNames, [ `${featuresPath}farewell.feature.Say farewell`, `${featuresPath}greetings.feature.Say greetings`, @@ -1011,7 +1026,7 @@ describe(`cucumber@${version} commonJS`, () => { .flatMap(({ files }) => files) .map(({ filename }) => filename) - assert.includeMembers(coveredFiles, [ + assertObjectContains(coveredFiles, [ 'ci-visibility/subproject/features/support/steps.js', 'ci-visibility/subproject/features/greetings.feature' ]) @@ -1114,7 +1129,7 @@ describe(`cucumber@${version} commonJS`, () => { .gatherPayloadsMaxTimeout(({ url }) => url.endsWith('/api/v2/citestcycle'), (payloads) => { const events = payloads.flatMap(({ payload }) => payload.events) const testSession = events.find(event => event.type === 'test_session_end').content - assert.ok(!Object.hasOwn(testSession.meta, TEST_EARLY_FLAKE_ENABLED)) + assert.ok(!('TEST_EARLY_FLAKE_ENABLED' in testSession.meta)) const tests = events.filter(event => event.type === 'test').map(event => event.content) const newTests = tests.filter(test => @@ -1277,7 +1292,7 @@ describe(`cucumber@${version} commonJS`, () => { const events = payloads.flatMap(({ payload }) => payload.events) const testSession = events.find(event => event.type === 'test_session_end').content - assert.ok(!Object.hasOwn(testSession.meta, TEST_EARLY_FLAKE_ENABLED)) + assert.ok(!('TEST_EARLY_FLAKE_ENABLED' in testSession.meta)) const tests = events.filter(event => event.type === 'test').map(event => event.content) assert.strictEqual(tests.length, 6) @@ -1324,7 +1339,7 @@ describe(`cucumber@${version} commonJS`, () => { const events = payloads.flatMap(({ payload }) => payload.events) const testSession = events.find(event => event.type === 'test_session_end').content - assert.ok(!Object.hasOwn(testSession.meta, TEST_EARLY_FLAKE_ENABLED)) + assert.ok(!('TEST_EARLY_FLAKE_ENABLED' in testSession.meta)) assert.strictEqual(testSession.meta[TEST_EARLY_FLAKE_ABORT_REASON], 'faulty') const tests = events.filter(event => event.type === 'test').map(event => event.content) @@ -1377,7 +1392,7 @@ describe(`cucumber@${version} commonJS`, () => { const events = payloads.flatMap(({ payload }) => payload.events) const testSession = events.find(event => event.type === 'test_session_end').content - assert.ok(!Object.hasOwn(testSession.meta, TEST_EARLY_FLAKE_ENABLED)) + assert.ok(!('TEST_EARLY_FLAKE_ENABLED' in testSession.meta)) const tests = events.filter(event => event.type === 'test').map(event => event.content) // no new tests detected @@ -1555,7 +1570,7 @@ describe(`cucumber@${version} commonJS`, () => { const events = payloads.flatMap(({ payload }) => payload.events) const testSession = events.find(event => event.type === 'test_session_end').content - assert.ok(!Object.hasOwn(testSession.meta, TEST_EARLY_FLAKE_ENABLED)) + assert.ok(!('TEST_EARLY_FLAKE_ENABLED' in testSession.meta)) assert.strictEqual(testSession.meta[TEST_EARLY_FLAKE_ABORT_REASON], 'faulty') assert.strictEqual(testSession.meta[CUCUMBER_IS_PARALLEL], 'true') @@ -1660,7 +1675,7 @@ describe(`cucumber@${version} commonJS`, () => { const events = payloads.flatMap(({ payload }) => payload.events) const testSession = events.find(event => event.type === 'test_session_end').content - assert.ok(!Object.hasOwn(testSession.meta, TEST_EARLY_FLAKE_ENABLED)) + assert.ok(!('TEST_EARLY_FLAKE_ENABLED' in testSession.meta)) assert.strictEqual(testSession.meta[TEST_EARLY_FLAKE_ABORT_REASON], 'faulty') assert.strictEqual(testSession.meta[CUCUMBER_IS_PARALLEL], 'true') @@ -1980,7 +1995,7 @@ describe(`cucumber@${version} commonJS`, () => { level: 'error' }) assert.strictEqual(diLog.debugger.snapshot.language, 'javascript') - assert.deepInclude(diLog.debugger.snapshot.captures.lines['6'].locals, { + assertObjectContains(diLog.debugger.snapshot.captures.lines['6'].locals, { a: { type: 'number', value: '11' @@ -2227,7 +2242,7 @@ describe(`cucumber@${version} commonJS`, () => { const events = payloads.flatMap(({ payload }) => payload.events) const testSession = events.find(event => event.type === 'test_session_end').content - assert.ok(!Object.hasOwn(testSession.meta, TEST_EARLY_FLAKE_ENABLED)) + assert.ok(!('TEST_EARLY_FLAKE_ENABLED' in testSession.meta)) const tests = events.filter(event => event.type === 'test').map(event => event.content) // new tests detected but not retried @@ -2320,7 +2335,7 @@ describe(`cucumber@${version} commonJS`, () => { if (isAttemptToFix) { assert.strictEqual(testSession.meta[TEST_MANAGEMENT_ENABLED], 'true') } else { - assert.ok(!Object.hasOwn(testSession.meta, TEST_MANAGEMENT_ENABLED)) + assert.ok(!('TEST_MANAGEMENT_ENABLED' in testSession.meta)) } const retriedTests = tests.filter( @@ -2339,15 +2354,18 @@ describe(`cucumber@${version} commonJS`, () => { const isLastAttempt = i === retriedTests.length - 1 const test = retriedTests[i] - assert.strictEqual(test.resource, 'ci-visibility/features-test-management/attempt-to-fix.feature.Say attempt to fix') + assert.strictEqual( + test.resource, + 'ci-visibility/features-test-management/attempt-to-fix.feature.Say attempt to fix' + ) if (isDisabled) { assert.strictEqual(test.meta[TEST_MANAGEMENT_IS_DISABLED], 'true') } else if (isQuarantined) { assert.strictEqual(test.meta[TEST_MANAGEMENT_IS_QUARANTINED], 'true') } else { - assert.ok(!Object.hasOwn(test.meta, TEST_MANAGEMENT_IS_DISABLED)) - assert.ok(!Object.hasOwn(test.meta, TEST_MANAGEMENT_IS_QUARANTINED)) + assert.ok(!('TEST_MANAGEMENT_IS_DISABLED' in test.meta)) + assert.ok(!('TEST_MANAGEMENT_IS_QUARANTINED' in test.meta)) } if (isAttemptToFix) { @@ -2359,7 +2377,7 @@ describe(`cucumber@${version} commonJS`, () => { if (isLastAttempt) { if (shouldFailSometimes) { assert.strictEqual(test.meta[TEST_MANAGEMENT_ATTEMPT_TO_FIX_PASSED], 'false') - assert.ok(!Object.hasOwn(test.meta, TEST_HAS_FAILED_ALL_RETRIES)) + assert.ok(!('TEST_HAS_FAILED_ALL_RETRIES' in test.meta)) } else if (shouldAlwaysPass) { assert.strictEqual(test.meta[TEST_MANAGEMENT_ATTEMPT_TO_FIX_PASSED], 'true') } else { @@ -2368,9 +2386,9 @@ describe(`cucumber@${version} commonJS`, () => { } } } else { - assert.ok(!Object.hasOwn(test.meta, TEST_MANAGEMENT_IS_ATTEMPT_TO_FIX)) - assert.ok(!Object.hasOwn(test.meta, TEST_IS_RETRY)) - assert.ok(!Object.hasOwn(test.meta, TEST_RETRY_REASON)) + assert.ok(!('TEST_MANAGEMENT_IS_ATTEMPT_TO_FIX' in test.meta)) + assert.ok(!('TEST_IS_RETRY' in test.meta)) + assert.ok(!('TEST_RETRY_REASON' in test.meta)) } } }) @@ -2412,7 +2430,7 @@ describe(`cucumber@${version} commonJS`, () => { childProcess.on('exit', exitCode => { testAssertions.then(() => { - assert.ok(stdout.includes('I am running')) + assert.match(stdout, /I am running/) if (isQuarantined || isDisabled || shouldAlwaysPass) { assert.strictEqual(exitCode, 0) } else { @@ -2536,7 +2554,7 @@ describe(`cucumber@${version} commonJS`, () => { assert.strictEqual(testSession.meta[TEST_MANAGEMENT_ENABLED], 'true') assert.strictEqual(testSession.meta[TEST_STATUS], 'pass') } else { - assert.ok(!Object.hasOwn(testSession.meta, TEST_MANAGEMENT_ENABLED)) + assert.ok(!('TEST_MANAGEMENT_ENABLED' in testSession.meta)) assert.strictEqual(testSession.meta[TEST_STATUS], 'fail') } @@ -2547,7 +2565,7 @@ describe(`cucumber@${version} commonJS`, () => { assert.strictEqual(tests.meta[TEST_MANAGEMENT_IS_DISABLED], 'true') } else { assert.strictEqual(tests.meta[TEST_STATUS], 'fail') - assert.ok(!Object.hasOwn(tests.meta, TEST_MANAGEMENT_IS_DISABLED)) + assert.ok(!('TEST_MANAGEMENT_IS_DISABLED' in tests.meta)) } }) @@ -2574,10 +2592,10 @@ describe(`cucumber@${version} commonJS`, () => { childProcess.on('exit', exitCode => { testAssertionsPromise.then(() => { if (isDisabling) { - assert.ok(!stdout.includes('I am running')) + assert.doesNotMatch(stdout, /I am running/) assert.strictEqual(exitCode, 0) } else { - assert.ok(stdout.includes('I am running')) + assert.match(stdout, /I am running/) assert.strictEqual(exitCode, 1) } done() @@ -2633,16 +2651,19 @@ describe(`cucumber@${version} commonJS`, () => { if (isQuarantining) { assert.strictEqual(testSession.meta[TEST_MANAGEMENT_ENABLED], 'true') } else { - assert.ok(!Object.hasOwn(testSession.meta, TEST_MANAGEMENT_ENABLED)) + assert.ok(!('TEST_MANAGEMENT_ENABLED' in testSession.meta)) } - assert.strictEqual(failedTest.resource, 'ci-visibility/features-test-management/quarantine.feature.Say quarantine') + assert.strictEqual( + failedTest.resource, + 'ci-visibility/features-test-management/quarantine.feature.Say quarantine' + ) assert.strictEqual(failedTest.meta[TEST_STATUS], 'fail') if (isQuarantining) { assert.strictEqual(failedTest.meta[TEST_MANAGEMENT_IS_QUARANTINED], 'true') } else { - assert.ok(!Object.hasOwn(failedTest.meta, TEST_MANAGEMENT_IS_QUARANTINED)) + assert.ok(!('TEST_MANAGEMENT_IS_QUARANTINED' in failedTest.meta)) } }) @@ -2668,7 +2689,7 @@ describe(`cucumber@${version} commonJS`, () => { childProcess.on('exit', exitCode => { testAssertionsPromise.then(() => { // Regardless of whether the test is quarantined or not, it will be run - assert.ok(stdout.includes('I am running as quarantine')) + assert.match(stdout, /I am running as quarantine/) if (isQuarantining) { // even though a test fails, the exit code is 1 because the test is quarantined assert.strictEqual(exitCode, 0) @@ -2711,7 +2732,7 @@ describe(`cucumber@${version} commonJS`, () => { .gatherPayloadsMaxTimeout(({ url }) => url.endsWith('/api/v2/citestcycle'), (payloads) => { const events = payloads.flatMap(({ payload }) => payload.events) const testSession = events.find(event => event.type === 'test_session_end').content - assert.ok(!Object.hasOwn(testSession.meta, TEST_MANAGEMENT_ENABLED)) + assert.ok(!('TEST_MANAGEMENT_ENABLED' in testSession.meta)) const tests = events.filter(event => event.type === 'test').map(event => event.content) // it is not retried assert.strictEqual(tests.length, 1) @@ -2742,7 +2763,7 @@ describe(`cucumber@${version} commonJS`, () => { once(childProcess.stderr, 'end'), eventsPromise ]) - assert.ok(testOutput.includes('Test management tests could not be fetched')) + assert.match(testOutput, /Test management tests could not be fetched/) }) }) @@ -2844,21 +2865,22 @@ describe(`cucumber@${version} commonJS`, () => { if (isEfd) { assert.strictEqual(testSession.meta[TEST_EARLY_FLAKE_ENABLED], 'true') } else { - assert.ok(!Object.hasOwn(testSession.meta, TEST_EARLY_FLAKE_ENABLED)) + assert.ok(!('TEST_EARLY_FLAKE_ENABLED' in testSession.meta)) } const resourceNames = tests.map(span => span.resource) - assert.includeMembers(resourceNames, + // TODO: This is a duplication of the code below. We should refactor this. + assertObjectContains(resourceNames, [ 'ci-visibility/features-impacted-test/impacted-test.feature.Say impacted test' ] ) if (isParallel) { - assert.includeMembers(resourceNames, [ + assert.deepStrictEqual(resourceNames, [ + 'ci-visibility/features-impacted-test/impacted-test-2.feature.Say impacted test 2', 'ci-visibility/features-impacted-test/impacted-test.feature.Say impacted test', - 'ci-visibility/features-impacted-test/impacted-test-2.feature.Say impacted test 2' ]) } @@ -2877,12 +2899,12 @@ describe(`cucumber@${version} commonJS`, () => { if (isModified) { assert.strictEqual(impactedTest.meta[TEST_IS_MODIFIED], 'true') } else { - assert.ok(!Object.hasOwn(impactedTest.meta, TEST_IS_MODIFIED)) + assert.ok(!('TEST_IS_MODIFIED' in impactedTest.meta)) } if (isNew) { assert.strictEqual(impactedTest.meta[TEST_IS_NEW], 'true') } else { - assert.ok(!Object.hasOwn(impactedTest.meta, TEST_IS_NEW)) + assert.ok(!('TEST_IS_NEW' in impactedTest.meta)) } } diff --git a/integration-tests/cypress/cypress.spec.js b/integration-tests/cypress/cypress.spec.js index 4bbd36d2ecf..3f668066549 100644 --- a/integration-tests/cypress/cypress.spec.js +++ b/integration-tests/cypress/cypress.spec.js @@ -6,14 +6,14 @@ const { once } = require('node:events') const fs = require('node:fs') const http = require('node:http') const path = require('node:path') -const { promisify } = require('node:util') const semver = require('semver') const { sandboxCwd, useSandbox, getCiVisAgentlessConfig, - getCiVisEvpProxyConfig + getCiVisEvpProxyConfig, + assertObjectContains } = require('../helpers') const { FakeCiVisIntake } = require('../ci-visibility-intake') const { createWebAppServer } = require('../ci-visibility/web-app-server') @@ -67,8 +67,6 @@ const { DD_HOST_CPU_COUNT } = require('../../packages/dd-trace/src/plugins/util/ const { ERROR_MESSAGE, ERROR_TYPE, COMPONENT } = require('../../packages/dd-trace/src/constants') const { DD_MAJOR, NODE_MAJOR } = require('../../version') -const execPromise = promisify(exec) - const RECEIVER_STOP_TIMEOUT = 20000 const version = process.env.CYPRESS_VERSION const hookFile = 'dd-trace/loader-hook.mjs' @@ -234,7 +232,7 @@ moduleTypes.forEach(({ assert.strictEqual(passedTestSpan.meta[TEST_FRAMEWORK], 'cypress') assert.strictEqual(passedTestSpan.meta[TEST_TYPE], 'browser') assert.ok(passedTestSpan.meta[TEST_SOURCE_FILE] != null) - assert.ok(passedTestSpan.meta[TEST_SOURCE_FILE].includes('cypress/e2e/basic-pass.js')) + assert.match(passedTestSpan.meta[TEST_SOURCE_FILE], /cypress\/e2e\/basic-pass\.js/) assert.ok(passedTestSpan.meta[TEST_FRAMEWORK_VERSION] != null) assert.ok(passedTestSpan.meta[COMPONENT] != null) assert.ok(passedTestSpan.metrics[TEST_SOURCE_START] != null) @@ -253,11 +251,11 @@ moduleTypes.forEach(({ assert.strictEqual(failedTestSpan.meta[TEST_FRAMEWORK], 'cypress') assert.strictEqual(failedTestSpan.meta[TEST_TYPE], 'browser') assert.ok(failedTestSpan.meta[TEST_SOURCE_FILE] != null) - assert.ok(failedTestSpan.meta[TEST_SOURCE_FILE].includes('cypress/e2e/basic-fail.js')) + assert.match(failedTestSpan.meta[TEST_SOURCE_FILE], /cypress\/e2e\/basic-fail\.js/) assert.ok(failedTestSpan.meta[TEST_FRAMEWORK_VERSION] != null) assert.ok(failedTestSpan.meta[COMPONENT] != null) assert.ok(failedTestSpan.meta[ERROR_MESSAGE] != null) - assert.ok(failedTestSpan.meta[ERROR_MESSAGE].includes('expected')) + assert.match(failedTestSpan.meta[ERROR_MESSAGE], /expected/) assert.ok(failedTestSpan.meta[ERROR_TYPE] != null) assert.ok(failedTestSpan.metrics[TEST_SOURCE_START] != null) assert.strictEqual(passedTestSpan.meta[TEST_CODE_OWNERS], JSON.stringify(['@datadog-dd-trace-js'])) @@ -265,7 +263,7 @@ moduleTypes.forEach(({ assert.strictEqual(failedTestSpan.meta.addTagsBeforeEach, 'customBeforeEach') assert.strictEqual(failedTestSpan.meta.addTagsAfterEach, 'customAfterEach') // Tags added after failure should not be present because test failed - assert.ok(!Object.hasOwn(failedTestSpan.meta, 'addTagsAfterFailure')) + assert.ok(!('addTagsAfterFailure' in failedTestSpan.meta)) }, 60000) const { @@ -328,8 +326,10 @@ moduleTypes.forEach(({ once(childProcess, 'exit'), once(childProcess.stdout, 'end') ]) - assert.ok(stdout.includes('WARNING: dd-trace support for Cypress<10.2.0 is deprecated' + - ' and will not be supported in future versions of dd-trace.')) + assert.match( + stdout, + /WARNING: dd-trace support for Cypress<10.2.0 is deprecated and will not be supported in future versions of dd-trace./ + ) }) } @@ -378,8 +378,8 @@ moduleTypes.forEach(({ assert.strictEqual(hasReceivedEvents, false) // TODO: remove try/catch once we find the source of flakiness try { - assert.ok(!testOutput.includes('TypeError')) - assert.ok(testOutput.includes('1 of 1 failed')) + assert.doesNotMatch(testOutput, /TypeError/) + assert.match(testOutput, /1 of 1 failed/) } catch (e) { // eslint-disable-next-line no-console console.log('---- Actual test output -----') @@ -413,10 +413,10 @@ moduleTypes.forEach(({ ) assert.strictEqual(passedTest.content.meta[TEST_STATUS], 'pass') assert.strictEqual(failedTest.content.meta[TEST_STATUS], 'fail') - assert.ok(failedTest.content.meta[ERROR_MESSAGE].includes('error in after each hook')) + assert.match(failedTest.content.meta[ERROR_MESSAGE], /error in after each hook/) assert.strictEqual(skippedTest.content.meta[TEST_STATUS], 'skip') assert.strictEqual(testHookSuite.content.meta[TEST_STATUS], 'fail') - assert.ok(testHookSuite.content.meta[ERROR_MESSAGE].includes('error in after each hook')) + assert.match(testHookSuite.content.meta[ERROR_MESSAGE], /error in after each hook/) // describe level hooks const describeHookSuite = events.find( @@ -433,10 +433,10 @@ moduleTypes.forEach(({ ) assert.strictEqual(passedTestDescribe.content.meta[TEST_STATUS], 'pass') assert.strictEqual(failedTestDescribe.content.meta[TEST_STATUS], 'fail') - assert.ok(failedTestDescribe.content.meta[ERROR_MESSAGE].includes('error in after hook')) + assert.match(failedTestDescribe.content.meta[ERROR_MESSAGE], /error in after hook/) assert.strictEqual(skippedTestDescribe.content.meta[TEST_STATUS], 'skip') assert.strictEqual(describeHookSuite.content.meta[TEST_STATUS], 'fail') - assert.ok(describeHookSuite.content.meta[ERROR_MESSAGE].includes('error in after hook')) + assert.match(describeHookSuite.content.meta[ERROR_MESSAGE], /error in after hook/) }, 25000) const { @@ -494,15 +494,18 @@ moduleTypes.forEach(({ assert.ok(testModuleEventContent.meta[TEST_MODULE] != null) assert.strictEqual(testModuleEventContent.resource.startsWith('test_module.'), true) assert.strictEqual(testModuleEventContent.meta[TEST_STATUS], 'fail') - assert.strictEqual(testModuleEventContent.test_session_id.toString(10), testSessionEventContent.test_session_id.toString(10)) + assert.strictEqual( + testModuleEventContent.test_session_id.toString(10), + testSessionEventContent.test_session_id.toString(10) + ) assert.ok(testModuleEventContent.meta[TEST_FRAMEWORK_VERSION] != null) - assert.includeMembers(testSuiteEvents.map(suite => suite.content.resource), [ + assertObjectContains(testSuiteEvents.map(suite => suite.content.resource), [ 'test_suite.cypress/e2e/other.cy.js', 'test_suite.cypress/e2e/spec.cy.js' ]) - assert.includeMembers(testSuiteEvents.map(suite => suite.content.meta[TEST_STATUS]), [ + assertObjectContains(testSuiteEvents.map(suite => suite.content.meta[TEST_STATUS]), [ 'pass', 'fail' ]) @@ -526,13 +529,13 @@ moduleTypes.forEach(({ assert.ok(metrics[DD_HOST_CPU_COUNT] != null) }) - assert.includeMembers(testEvents.map(test => test.content.resource), [ + assertObjectContains(testEvents.map(test => test.content.resource), [ 'cypress/e2e/other.cy.js.context passes', 'cypress/e2e/spec.cy.js.context passes', 'cypress/e2e/spec.cy.js.other context fails' ]) - assert.includeMembers(testEvents.map(test => test.content.meta[TEST_STATUS]), [ + assertObjectContains(testEvents.map(test => test.content.meta[TEST_STATUS]), [ 'pass', 'pass', 'fail' @@ -610,7 +613,7 @@ moduleTypes.forEach(({ .flatMap(coverageAttachment => coverageAttachment.files) .map(file => file.filename) - assert.includeMembers(fileNames, Object.keys(coverageFixture)) + assertObjectContains(fileNames, Object.keys(coverageFixture)) }, 25000) childProcess = exec( @@ -687,7 +690,7 @@ moduleTypes.forEach(({ .gatherPayloadsMaxTimeout(({ url }) => url.endsWith('/api/v2/citestcycle'), (payloads) => { const events = payloads.flatMap(({ payload }) => payload.events) const eventTypes = events.map(event => event.type) - assert.includeMembers(eventTypes, ['test', 'test_session_end', 'test_module_end', 'test_suite_end']) + assertObjectContains(eventTypes, ['test', 'test_session_end', 'test_module_end', 'test_suite_end']) }, 25000) const { @@ -734,7 +737,7 @@ moduleTypes.forEach(({ assert.strictEqual(skippedTest.meta[TEST_STATUS], 'skip') assert.strictEqual(skippedTest.meta[TEST_SKIPPED_BY_ITR], 'true') - assert.includeMembers(eventTypes, ['test', 'test_suite_end', 'test_module_end', 'test_session_end']) + assertObjectContains(eventTypes, ['test', 'test_session_end', 'test_module_end', 'test_suite_end']) const testSession = events.find(event => event.type === 'test_session_end').content assert.strictEqual(testSession.meta[TEST_ITR_TESTS_SKIPPED], 'true') @@ -897,7 +900,7 @@ moduleTypes.forEach(({ assert.strictEqual(unskippableFailedTest.content.meta[TEST_STATUS], 'fail') assert.strictEqual(unskippableFailedTest.content.meta[TEST_ITR_UNSKIPPABLE], 'true') // This was not going to be skipped - assert.ok(!Object.hasOwn(unskippableFailedTest.content.meta, TEST_ITR_FORCED_RUN)) + assert.ok(!('TEST_ITR_FORCED_RUN' in unskippableFailedTest.content.meta)) }, 25000) const { @@ -952,9 +955,9 @@ moduleTypes.forEach(({ const testModule = events.find(event => event.type === 'test_session_end').content assert.strictEqual(testSession.meta[TEST_ITR_UNSKIPPABLE], 'true') - assert.ok(!Object.hasOwn(testSession.meta, TEST_ITR_FORCED_RUN)) + assert.ok(!('TEST_ITR_FORCED_RUN' in testSession.meta)) assert.strictEqual(testModule.meta[TEST_ITR_UNSKIPPABLE], 'true') - assert.ok(!Object.hasOwn(testModule.meta, TEST_ITR_FORCED_RUN)) + assert.ok(!('TEST_ITR_FORCED_RUN' in testModule.meta)) const unskippablePassedTest = events.find(event => event.content.resource === 'cypress/e2e/spec.cy.js.context passes' @@ -965,12 +968,12 @@ moduleTypes.forEach(({ assert.strictEqual(unskippablePassedTest.content.meta[TEST_STATUS], 'pass') assert.strictEqual(unskippablePassedTest.content.meta[TEST_ITR_UNSKIPPABLE], 'true') // This was not going to be skipped - assert.ok(!Object.hasOwn(unskippablePassedTest.content.meta, TEST_ITR_FORCED_RUN)) + assert.ok(!('TEST_ITR_FORCED_RUN' in unskippablePassedTest.content.meta)) assert.strictEqual(unskippableFailedTest.content.meta[TEST_STATUS], 'fail') assert.strictEqual(unskippableFailedTest.content.meta[TEST_ITR_UNSKIPPABLE], 'true') // This was not going to be skipped - assert.ok(!Object.hasOwn(unskippableFailedTest.content.meta, TEST_ITR_FORCED_RUN)) + assert.ok(!('TEST_ITR_FORCED_RUN' in unskippableFailedTest.content.meta)) }, 25000) const { @@ -1125,7 +1128,7 @@ moduleTypes.forEach(({ .flatMap(({ files }) => files) .map(({ filename }) => filename) - assert.includeMembers(coveredFiles, [ + assertObjectContains(coveredFiles, [ 'ci-visibility/subproject/src/utils.tsx', 'ci-visibility/subproject/src/App.tsx', 'ci-visibility/subproject/src/index.tsx', @@ -1387,7 +1390,7 @@ moduleTypes.forEach(({ assert.strictEqual(retriedTests.length, 0) const testSession = events.find(event => event.type === 'test_session_end').content - assert.ok(!Object.hasOwn(testSession.meta, TEST_EARLY_FLAKE_ENABLED)) + assert.ok(!('TEST_EARLY_FLAKE_ENABLED' in testSession.meta)) }, 25000) const specToRun = 'cypress/e2e/spec.cy.js' @@ -1493,7 +1496,7 @@ moduleTypes.forEach(({ .gatherPayloadsMaxTimeout(({ url }) => url.endsWith('/api/v2/citestcycle'), payloads => { const events = payloads.flatMap(({ payload }) => payload.events) const testSession = events.find(event => event.type === 'test_session_end').content - assert.ok(!Object.hasOwn(testSession.meta, TEST_EARLY_FLAKE_ENABLED)) + assert.ok(!('TEST_EARLY_FLAKE_ENABLED' in testSession.meta)) const tests = events.filter(event => event.type === 'test').map(event => event.content) assert.strictEqual(tests.length, 2) @@ -1562,7 +1565,7 @@ moduleTypes.forEach(({ assert.strictEqual(retriedTests.length, 0) const testSession = events.find(event => event.type === 'test_session_end').content - assert.ok(!Object.hasOwn(testSession.meta, TEST_EARLY_FLAKE_ENABLED)) + assert.ok(!('TEST_EARLY_FLAKE_ENABLED' in testSession.meta)) }, 25000) const specToRun = 'cypress/e2e/spec.cy.js' @@ -1624,7 +1627,7 @@ moduleTypes.forEach(({ assert.strictEqual(retriedTests.length, 0) const testSession = events.find(event => event.type === 'test_session_end').content - assert.ok(!Object.hasOwn(testSession.meta, TEST_EARLY_FLAKE_ENABLED)) + assert.ok(!('TEST_EARLY_FLAKE_ENABLED' in testSession.meta)) }, 25000) const specToRun = 'cypress/e2e/spec.cy.js' @@ -1687,7 +1690,9 @@ moduleTypes.forEach(({ }) const testSession = events.find(event => event.type === 'test_session_end').content - assert.propertyVal(testSession.meta, TEST_EARLY_FLAKE_ENABLED, 'true') + assertObjectContains(testSession.meta, { + [TEST_EARLY_FLAKE_ENABLED]: 'true' + }) }, 25000) const { @@ -1760,28 +1765,18 @@ moduleTypes.forEach(({ // 4. "other context fails" (retry 2) // 5. "other context fails" (retry 3) - assert.equal(testExecutionOrder[0].name, 'context passes') - assert.equal(testExecutionOrder[0].isRetry, false) - assert.equal(testExecutionOrder[0].isNew, false) - - assert.equal(testExecutionOrder[1].name, 'other context fails') - assert.equal(testExecutionOrder[1].isRetry, false) - assert.equal(testExecutionOrder[1].isNew, true) - - assert.equal(testExecutionOrder[2].name, 'other context fails') - assert.equal(testExecutionOrder[2].isRetry, true) - assert.equal(testExecutionOrder[2].isNew, true) - - assert.equal(testExecutionOrder[3].name, 'other context fails') - assert.equal(testExecutionOrder[3].isRetry, true) - assert.equal(testExecutionOrder[3].isNew, true) - - assert.equal(testExecutionOrder[4].name, 'other context fails') - assert.equal(testExecutionOrder[4].isRetry, true) - assert.equal(testExecutionOrder[4].isNew, true) + assertObjectContains(testExecutionOrder, [ + { name: 'context passes', isRetry: false, isNew: false }, + { name: 'other context fails', isRetry: false, isNew: true }, + { name: 'other context fails', isRetry: true, isNew: true }, + { name: 'other context fails', isRetry: true, isNew: true }, + { name: 'other context fails', isRetry: true, isNew: true } + ]) const testSession = events.find(event => event.type === 'test_session_end').content - assert.propertyVal(testSession.meta, TEST_EARLY_FLAKE_ENABLED, 'true') + assertObjectContains(testSession.meta, { + [TEST_EARLY_FLAKE_ENABLED]: 'true' + }) }, 25000) const { @@ -1817,7 +1812,7 @@ moduleTypes.forEach(({ once(childProcess.stderr, 'end'), receiverPromise ]) - assert.include(testOutput, 'Retrying "other context fails" to detect flakes because it is new') + assert.match(testOutput, /Retrying "other context fails" to detect flakes because it is new/) }) }) @@ -1843,7 +1838,7 @@ moduleTypes.forEach(({ const tests = events.filter(event => event.type === 'test').map(event => event.content) assert.strictEqual(tests.length, 10) - assert.includeMembers(tests.map(test => test.resource), [ + assertObjectContains(tests.map(test => test.resource), [ 'cypress/e2e/flaky-test-retries.js.flaky test retry eventually passes', 'cypress/e2e/flaky-test-retries.js.flaky test retry eventually passes', // passes at the second retry @@ -1933,12 +1928,12 @@ moduleTypes.forEach(({ const tests = events.filter(event => event.type === 'test').map(event => event.content) assert.strictEqual(tests.length, 3) - assert.includeMembers(tests.map(test => test.resource), [ + assertObjectContains(tests.map(test => test.resource), [ 'cypress/e2e/flaky-test-retries.js.flaky test retry eventually passes', 'cypress/e2e/flaky-test-retries.js.flaky test retry never passes', 'cypress/e2e/flaky-test-retries.js.flaky test retry always passes' ]) - assert.strictEqual(tests.filter(test => test.meta[TEST_RETRY_REASON] === TEST_RETRY_REASON_TYPES.atr).length, 0) + assert.ok(!tests.some(test => test.meta[TEST_RETRY_REASON] === TEST_RETRY_REASON_TYPES.atr)) }, 25000) const { @@ -1989,7 +1984,7 @@ moduleTypes.forEach(({ const tests = events.filter(event => event.type === 'test').map(event => event.content) assert.strictEqual(tests.length, 5) - assert.includeMembers(tests.map(test => test.resource), [ + assertObjectContains(tests.map(test => test.resource), [ 'cypress/e2e/flaky-test-retries.js.flaky test retry eventually passes', 'cypress/e2e/flaky-test-retries.js.flaky test retry eventually passes', 'cypress/e2e/flaky-test-retries.js.flaky test retry never passes', @@ -1997,7 +1992,10 @@ moduleTypes.forEach(({ 'cypress/e2e/flaky-test-retries.js.flaky test retry always passes' ]) - assert.strictEqual(tests.filter(test => test.meta[TEST_RETRY_REASON] === TEST_RETRY_REASON_TYPES.atr).length, 2) + assert.strictEqual( + tests.filter(test => test.meta[TEST_RETRY_REASON] === TEST_RETRY_REASON_TYPES.atr).length, + 2 + ) }, 25000) const { @@ -2235,7 +2233,7 @@ moduleTypes.forEach(({ assert.strictEqual(retriedTests.length, 0) const testSession = events.find(event => event.type === 'test_session_end').content - assert.ok(!Object.hasOwn(testSession.meta, TEST_EARLY_FLAKE_ENABLED)) + assert.ok(!('TEST_EARLY_FLAKE_ENABLED' in testSession.meta)) }, 25000) const specToRun = 'cypress/e2e/spec.cy.js' @@ -2391,12 +2389,12 @@ moduleTypes.forEach(({ if (isAttemptToFix) { assert.strictEqual(testSession.meta[TEST_MANAGEMENT_ENABLED], 'true') } else { - assert.ok(!Object.hasOwn(testSession.meta, TEST_MANAGEMENT_ENABLED)) + assert.ok(!('TEST_MANAGEMENT_ENABLED' in testSession.meta)) } const resourceNames = tests.map(span => span.resource) - assert.includeMembers(resourceNames, + assertObjectContains(resourceNames, [ 'cypress/e2e/attempt-to-fix.js.attempt to fix is attempt to fix' ] @@ -2415,9 +2413,9 @@ moduleTypes.forEach(({ for (let i = attemptToFixTests.length - 1; i >= 0; i--) { const test = attemptToFixTests[i] if (!isAttemptToFix) { - assert.ok(!Object.hasOwn(test.meta, TEST_MANAGEMENT_IS_ATTEMPT_TO_FIX)) - assert.ok(!Object.hasOwn(test.meta, TEST_IS_RETRY)) - assert.ok(!Object.hasOwn(test.meta, TEST_RETRY_REASON)) + assert.ok(!('TEST_MANAGEMENT_IS_ATTEMPT_TO_FIX' in test.meta)) + assert.ok(!('TEST_IS_RETRY' in test.meta)) + assert.ok(!('TEST_RETRY_REASON' in test.meta)) continue } if (isQuarantined) { @@ -2433,19 +2431,19 @@ moduleTypes.forEach(({ const isFirstAttempt = i === 0 assert.strictEqual(test.meta[TEST_MANAGEMENT_IS_ATTEMPT_TO_FIX], 'true') if (isFirstAttempt) { - assert.ok(!Object.hasOwn(test.meta, TEST_IS_RETRY)) - assert.ok(!Object.hasOwn(test.meta, TEST_RETRY_REASON)) + assert.ok(!('TEST_IS_RETRY' in test.meta)) + assert.ok(!('TEST_RETRY_REASON' in test.meta)) } else { assert.strictEqual(test.meta[TEST_IS_RETRY], 'true') assert.strictEqual(test.meta[TEST_RETRY_REASON], TEST_RETRY_REASON_TYPES.atf) } if (isLastAttempt) { if (shouldFailSometimes) { - assert.ok(!Object.hasOwn(test.meta, TEST_HAS_FAILED_ALL_RETRIES)) + assert.ok(!('TEST_HAS_FAILED_ALL_RETRIES' in test.meta)) assert.strictEqual(test.meta[TEST_MANAGEMENT_ATTEMPT_TO_FIX_PASSED], 'false') } else if (shouldAlwaysPass) { assert.strictEqual(test.meta[TEST_MANAGEMENT_ATTEMPT_TO_FIX_PASSED], 'true') - assert.ok(!Object.hasOwn(test.meta, TEST_HAS_FAILED_ALL_RETRIES)) + assert.ok(!('TEST_HAS_FAILED_ALL_RETRIES' in test.meta)) } else { assert.strictEqual(test.meta[TEST_HAS_FAILED_ALL_RETRIES], 'true') assert.strictEqual(test.meta[TEST_MANAGEMENT_ATTEMPT_TO_FIX_PASSED], 'false') @@ -2628,7 +2626,7 @@ moduleTypes.forEach(({ if (isDisabling) { assert.strictEqual(testSession.meta[TEST_MANAGEMENT_ENABLED], 'true') } else { - assert.ok(!Object.hasOwn(testSession.meta, TEST_MANAGEMENT_ENABLED)) + assert.ok(!('TEST_MANAGEMENT_ENABLED' in testSession.meta)) } assert.strictEqual(failedTest.resource, 'cypress/e2e/disable.js.disable is disabled') @@ -2638,7 +2636,7 @@ moduleTypes.forEach(({ assert.strictEqual(failedTest.meta[TEST_MANAGEMENT_IS_DISABLED], 'true') } else { assert.strictEqual(failedTest.meta[TEST_STATUS], 'fail') - assert.ok(!Object.hasOwn(failedTest.meta, TEST_MANAGEMENT_IS_DISABLED)) + assert.ok(!('TEST_MANAGEMENT_IS_DISABLED' in failedTest.meta)) } }, 25000) @@ -2726,7 +2724,7 @@ moduleTypes.forEach(({ if (isQuarantining) { assert.strictEqual(testSession.meta[TEST_MANAGEMENT_ENABLED], 'true') } else { - assert.ok(!Object.hasOwn(testSession.meta, TEST_MANAGEMENT_ENABLED)) + assert.ok(!('TEST_MANAGEMENT_ENABLED' in testSession.meta)) } assert.strictEqual(failedTest.resource, 'cypress/e2e/quarantine.js.quarantine is quarantined') @@ -2737,7 +2735,7 @@ moduleTypes.forEach(({ assert.strictEqual(failedTest.meta[TEST_MANAGEMENT_IS_QUARANTINED], 'true') } else { assert.strictEqual(failedTest.meta[TEST_STATUS], 'fail') - assert.ok(!Object.hasOwn(failedTest.meta, TEST_MANAGEMENT_IS_QUARANTINED)) + assert.ok(!('TEST_MANAGEMENT_IS_QUARANTINED' in failedTest.meta)) } }, 25000) @@ -2807,7 +2805,7 @@ moduleTypes.forEach(({ .gatherPayloadsMaxTimeout(({ url }) => url.endsWith('/api/v2/citestcycle'), (payloads) => { const events = payloads.flatMap(({ payload }) => payload.events) const testSession = events.find(event => event.type === 'test_session_end').content - assert.ok(!Object.hasOwn(testSession.meta, TEST_MANAGEMENT_ENABLED)) + assert.ok(!('TEST_MANAGEMENT_ENABLED' in testSession.meta)) const tests = events.filter(event => event.type === 'test').map(event => event.content) // it is not retried assert.strictEqual(tests.length, 1) @@ -2867,7 +2865,9 @@ moduleTypes.forEach(({ const tests = events.filter(event => event.type === 'test').map(event => event.content) const testSession = events.find(event => event.type === 'test_session_end').content - assert.propertyVal(testSession.meta, TEST_MANAGEMENT_ENABLED, 'true') + assertObjectContains(testSession.meta, { + [TEST_MANAGEMENT_ENABLED]: 'true' + }) const attemptToFixTests = tests.filter( test => test.meta[TEST_NAME] === 'attempt to fix is attempt to fix' @@ -2878,9 +2878,9 @@ moduleTypes.forEach(({ attemptToFixTests.forEach(test => { // No retries should occur - assert.notProperty(test.meta, TEST_MANAGEMENT_IS_ATTEMPT_TO_FIX) - assert.notProperty(test.meta, TEST_IS_RETRY) - assert.notProperty(test.meta, TEST_RETRY_REASON) + assert.ok(!(TEST_MANAGEMENT_IS_ATTEMPT_TO_FIX in test.meta)) + assert.ok(!(TEST_IS_RETRY in test.meta)) + assert.ok(!(TEST_RETRY_REASON in test.meta)) }) }, 25000) @@ -2961,32 +2961,19 @@ moduleTypes.forEach(({ // 5. "second test" (retry 3) // 6. "third test" (original, no retries) - assert.equal(testExecutionOrder[0].name, 'attempt to fix order first test') - assert.equal(testExecutionOrder[0].isRetry, false) - assert.equal(testExecutionOrder[0].isAttemptToFix, false) - - assert.equal(testExecutionOrder[1].name, 'attempt to fix order second test') - assert.equal(testExecutionOrder[1].isRetry, false) - assert.equal(testExecutionOrder[1].isAttemptToFix, true) - - assert.equal(testExecutionOrder[2].name, 'attempt to fix order second test') - assert.equal(testExecutionOrder[2].isRetry, true) - assert.equal(testExecutionOrder[2].isAttemptToFix, true) - - assert.equal(testExecutionOrder[3].name, 'attempt to fix order second test') - assert.equal(testExecutionOrder[3].isRetry, true) - assert.equal(testExecutionOrder[3].isAttemptToFix, true) - - assert.equal(testExecutionOrder[4].name, 'attempt to fix order second test') - assert.equal(testExecutionOrder[4].isRetry, true) - assert.equal(testExecutionOrder[4].isAttemptToFix, true) - - assert.equal(testExecutionOrder[5].name, 'attempt to fix order third test') - assert.equal(testExecutionOrder[5].isRetry, false) - assert.equal(testExecutionOrder[5].isAttemptToFix, false) + assertObjectContains(testExecutionOrder, [ + { name: 'attempt to fix order first test', isRetry: false, isAttemptToFix: false }, + { name: 'attempt to fix order second test', isRetry: false, isAttemptToFix: true }, + { name: 'attempt to fix order second test', isRetry: true, isAttemptToFix: true }, + { name: 'attempt to fix order second test', isRetry: true, isAttemptToFix: true }, + { name: 'attempt to fix order second test', isRetry: true, isAttemptToFix: true }, + { name: 'attempt to fix order third test', isRetry: false, isAttemptToFix: false } + ]) const testSession = events.find(event => event.type === 'test_session_end').content - assert.propertyVal(testSession.meta, TEST_MANAGEMENT_ENABLED, 'true') + assertObjectContains(testSession.meta, { + [TEST_MANAGEMENT_ENABLED]: 'true' + }) }, 25000) const { @@ -3023,7 +3010,7 @@ moduleTypes.forEach(({ receiverPromise ]) - assert.include(testOutput, 'Retrying "attempt to fix order second test" because it is an attempt to fix') + assert.match(testOutput, /Retrying "attempt to fix order second test" because it is an attempt to fix/) }) }) @@ -3131,12 +3118,12 @@ moduleTypes.forEach(({ if (isEfd) { assert.strictEqual(testSession.meta[TEST_EARLY_FLAKE_ENABLED], 'true') } else { - assert.ok(!Object.hasOwn(testSession.meta, TEST_EARLY_FLAKE_ENABLED)) + assert.ok(!('TEST_EARLY_FLAKE_ENABLED' in testSession.meta)) } const resourceNames = tests.map(span => span.resource) - assert.includeMembers(resourceNames, + assertObjectContains(resourceNames, [ 'cypress/e2e/impacted-test.js.impacted test is impacted test' ] @@ -3156,12 +3143,12 @@ moduleTypes.forEach(({ if (isModified) { assert.strictEqual(impactedTest.meta[TEST_IS_MODIFIED], 'true') } else { - assert.ok(!Object.hasOwn(impactedTest.meta, TEST_IS_MODIFIED)) + assert.ok(!('TEST_IS_MODIFIED' in impactedTest.meta)) } if (isNew) { assert.strictEqual(impactedTest.meta[TEST_IS_NEW], 'true') } else { - assert.ok(!Object.hasOwn(impactedTest.meta, TEST_IS_NEW)) + assert.ok(!('TEST_IS_NEW' in impactedTest.meta)) } } @@ -3287,7 +3274,9 @@ moduleTypes.forEach(({ const tests = events.filter(event => event.type === 'test').map(event => event.content) const testSession = events.find(event => event.type === 'test_session_end').content - assert.propertyVal(testSession.meta, TEST_EARLY_FLAKE_ENABLED, 'true') + assertObjectContains(testSession.meta, { + [TEST_EARLY_FLAKE_ENABLED]: 'true' + }) const impactedTests = tests.filter(test => test.meta[TEST_SOURCE_FILE] === 'cypress/e2e/impacted-test.js' && @@ -3297,7 +3286,9 @@ moduleTypes.forEach(({ assert.equal(impactedTests.length, 1) for (const impactedTest of impactedTests) { - assert.propertyVal(impactedTest.meta, TEST_IS_MODIFIED, 'true') + assertObjectContains(impactedTest.meta, { + [TEST_IS_MODIFIED]: 'true' + }) } // No retries should occur when testIsolation is false @@ -3387,26 +3378,19 @@ moduleTypes.forEach(({ // 5. "second test" (retry 1) // 6. "second test" (retry 2) - assert.equal(testExecutionOrder[0].name, 'impacted test order first test') - assert.equal(testExecutionOrder[0].isRetry, false) - - assert.equal(testExecutionOrder[1].name, 'impacted test order first test') - assert.equal(testExecutionOrder[1].isRetry, true) - - assert.equal(testExecutionOrder[2].name, 'impacted test order first test') - assert.equal(testExecutionOrder[2].isRetry, true) - - assert.equal(testExecutionOrder[3].name, 'impacted test order second test') - assert.equal(testExecutionOrder[3].isRetry, false) - - assert.equal(testExecutionOrder[4].name, 'impacted test order second test') - assert.equal(testExecutionOrder[4].isRetry, true) - - assert.equal(testExecutionOrder[5].name, 'impacted test order second test') - assert.equal(testExecutionOrder[5].isRetry, true) + assertObjectContains(testExecutionOrder, [ + { name: 'impacted test order first test', isRetry: false }, + { name: 'impacted test order first test', isRetry: true }, + { name: 'impacted test order first test', isRetry: true }, + { name: 'impacted test order second test', isRetry: false }, + { name: 'impacted test order second test', isRetry: true }, + { name: 'impacted test order second test', isRetry: true } + ]) const testSession = events.find(event => event.type === 'test_session_end').content - assert.propertyVal(testSession.meta, TEST_EARLY_FLAKE_ENABLED, 'true') + assertObjectContains(testSession.meta, { + [TEST_EARLY_FLAKE_ENABLED]: 'true' + }) }, 25000) const { @@ -3444,8 +3428,8 @@ moduleTypes.forEach(({ receiverPromise ]) - assert.include(testOutput, 'Retrying "impacted test order first test" to detect flakes because it is modified') - assert.include(testOutput, 'Retrying "impacted test order second test" to detect flakes because it is modified') + assert.match(testOutput, /Retrying "impacted test order first test" to detect flakes because it is modified/) + assert.match(testOutput, /Retrying "impacted test order second test" to detect flakes because it is modified/) }) }) }) diff --git a/integration-tests/debugger/basic.spec.js b/integration-tests/debugger/basic.spec.js index 62db49a2506..6578801f0b0 100644 --- a/integration-tests/debugger/basic.spec.js +++ b/integration-tests/debugger/basic.spec.js @@ -4,7 +4,7 @@ const { writeFileSync } = require('fs') const os = require('os') const { join } = require('path') -const { assert } = require('chai') +const assert = require('assert') const { pollInterval, setup } = require('./utils') const { assertObjectContains, assertUUID } = require('../helpers') const { UNACKNOWLEDGED, ACKNOWLEDGED, ERROR } = require('../../packages/dd-trace/src/remote_config/apply_states') @@ -46,7 +46,7 @@ describe('Dynamic Instrumentation', function () { assert.strictEqual(id, t.rcConfig.id) assert.strictEqual(version, 1) assert.strictEqual(state, ACKNOWLEDGED) - assert.notOk(error) // falsy check since error will be an empty string, but that's an implementation detail + assert.ok(!error) // falsy check since error will be an empty string, but that's an implementation detail receivedAckUpdate = true endIfDone() @@ -114,7 +114,7 @@ describe('Dynamic Instrumentation', function () { assert.strictEqual(id, t.rcConfig.id) assert.strictEqual(version, ++receivedAckUpdates) assert.strictEqual(state, ACKNOWLEDGED) - assert.notOk(error) // falsy check since error will be an empty string, but that's an implementation detail + assert.ok(!error) // falsy check since error will be an empty string, but that's an implementation detail endIfDone() }) @@ -162,7 +162,7 @@ describe('Dynamic Instrumentation', function () { assert.strictEqual(id, t.rcConfig.id) assert.strictEqual(version, 1) assert.strictEqual(state, ACKNOWLEDGED) - assert.notOk(error) // falsy check since error will be an empty string, but that's an implementation detail + assert.ok(!error) // falsy check since error will be an empty string, but that's an implementation detail receivedAckUpdate = true endIfDone() @@ -244,10 +244,10 @@ describe('Dynamic Instrumentation', function () { assertUUID(diagnostics.runtimeId) if (diagnostics.status === 'ERROR') { - assert.property(diagnostics, 'exception') - assert.hasAllKeys(diagnostics.exception, ['message', 'stacktrace']) - assert.typeOf(diagnostics.exception.message, 'string') - assert.typeOf(diagnostics.exception.stacktrace, 'string') + assert.ok(Object.hasOwn(diagnostics, 'exception')) + assert.deepStrictEqual(['message', 'stacktrace'], Object.keys(diagnostics.exception).sort()) + assert.strictEqual(typeof diagnostics.exception.message, 'string') + assert.strictEqual(typeof diagnostics.exception.stacktrace, 'string') } endIfDone() @@ -583,8 +583,8 @@ describe('Dynamic Instrumentation', function () { clearTimeout(timer) // Allow for a variance of +50ms (time will tell if this is enough) - assert.isAtLeast(duration, 1000) - assert.isBelow(duration, 1050) + assert.ok(duration >= 1000) + assert.ok(duration < 1050) // Wait at least a full sampling period, to see if we get any more payloads timer = setTimeout(done, 1250) @@ -636,8 +636,8 @@ describe('Dynamic Instrumentation', function () { clearTimeout(_state.timer) // Allow for a variance of +50ms (time will tell if this is enough) - assert.isAtLeast(duration, 1000) - assert.isBelow(duration, 1050) + assert.ok(duration >= 1000) + assert.ok(duration < 1050) // Wait at least a full sampling period, to see if we get any more payloads _state.timer = setTimeout(doneWhenCalledTwice, 1250) @@ -830,12 +830,12 @@ function setupAssertionListeners (t, done, probe) { assertBasicInputPayload(t, payload, probe) payload = payload[0] - assert.isObject(payload.dd) - assert.hasAllKeys(payload.dd, ['trace_id', 'span_id']) - assert.typeOf(payload.dd.trace_id, 'string') - assert.typeOf(payload.dd.span_id, 'string') - assert.isAbove(payload.dd.trace_id.length, 0) - assert.isAbove(payload.dd.span_id.length, 0) + assert.ok(typeof payload.dd === 'object' && payload.dd !== null) + assert.deepStrictEqual(['span_id', 'trace_id'], Object.keys(payload.dd).sort()) + assert.strictEqual(typeof payload.dd.trace_id, 'string') + assert.strictEqual(typeof payload.dd.span_id, 'string') + assert.ok(payload.dd.trace_id.length > 0) + assert.ok(payload.dd.span_id.length > 0) dd = payload.dd assertDD() @@ -854,7 +854,7 @@ function testBasicInputWithoutDD (t, done) { t.agent.on('debugger-input', ({ payload }) => { assertBasicInputPayload(t, payload) - assert.doesNotHaveAnyKeys(payload[0], ['dd']) + assert.ok(!('dd' in payload[0])) done() }) @@ -862,8 +862,8 @@ function testBasicInputWithoutDD (t, done) { } function assertBasicInputPayload (t, payload, probe = t.rcConfig.config) { - assert.isArray(payload) - assert.lengthOf(payload, 1) + assert.ok(Array.isArray(payload)) + assert.strictEqual(payload.length, 1) payload = payload[0] const expected = { @@ -894,19 +894,19 @@ function assertBasicInputPayload (t, payload, probe = t.rcConfig.config) { assert.match(payload.logger.thread_id, /^pid:\d+$/) assertUUID(payload.debugger.snapshot.id) - assert.isNumber(payload.debugger.snapshot.timestamp) - assert.isTrue(payload.debugger.snapshot.timestamp > Date.now() - 1000 * 60) - assert.isTrue(payload.debugger.snapshot.timestamp <= Date.now()) + assert.strictEqual(typeof payload.debugger.snapshot.timestamp, 'number') + assert.ok(payload.debugger.snapshot.timestamp > Date.now() - 1000 * 60) + assert.ok(payload.debugger.snapshot.timestamp <= Date.now()) - assert.isArray(payload.debugger.snapshot.stack) - assert.isAbove(payload.debugger.snapshot.stack.length, 0) + assert.ok(Array.isArray(payload.debugger.snapshot.stack)) + assert.ok(payload.debugger.snapshot.stack.length > 0) for (const frame of payload.debugger.snapshot.stack) { - assert.isObject(frame) - assert.hasAllKeys(frame, ['fileName', 'function', 'lineNumber', 'columnNumber']) - assert.isString(frame.fileName) - assert.isString(frame.function) - assert.isAbove(frame.lineNumber, 0) - assert.isAbove(frame.columnNumber, 0) + assert.ok(typeof frame === 'object' && frame !== null) + assert.deepStrictEqual(['columnNumber', 'fileName', 'function', 'lineNumber'], Object.keys(frame).sort()) + assert.strictEqual(typeof frame.fileName, 'string') + assert.strictEqual(typeof frame.function, 'string') + assert.ok(frame.lineNumber > 0) + assert.ok(frame.columnNumber > 0) } const topFrame = payload.debugger.snapshot.stack[0] // path seems to be prefixed with `/private` on Mac diff --git a/integration-tests/debugger/ddtags.spec.js b/integration-tests/debugger/ddtags.spec.js index 31e37218f95..9901b267d65 100644 --- a/integration-tests/debugger/ddtags.spec.js +++ b/integration-tests/debugger/ddtags.spec.js @@ -2,7 +2,7 @@ const os = require('os') -const { assert } = require('chai') +const assert = require('assert') const { setup } = require('./utils') const { version } = require('../../package.json') @@ -24,18 +24,18 @@ describe('Dynamic Instrumentation', function () { t.triggerBreakpoint() t.agent.on('debugger-input', ({ query }) => { - assert.property(query, 'ddtags') + assert.ok(Object.hasOwn(query, 'ddtags')) const ddtags = extractDDTagsFromQuery(query) - assert.hasAllKeys(ddtags, [ - 'env', - 'version', + assert.deepStrictEqual([ 'debugger_version', - 'host_name', + 'env', 'git.commit.sha', - 'git.repository_url' - ]) + 'git.repository_url', + 'host_name', + 'version', + ], Object.keys(ddtags).sort()) assert.strictEqual(ddtags.env, 'test-env') assert.strictEqual(ddtags.version, 'test-version') @@ -58,14 +58,11 @@ describe('Dynamic Instrumentation', function () { t.triggerBreakpoint() t.agent.on('debugger-input', ({ query }) => { - assert.property(query, 'ddtags') + assert.ok(Object.hasOwn(query, 'ddtags')) const ddtags = extractDDTagsFromQuery(query) - assert.hasAllKeys(ddtags, [ - 'debugger_version', - 'host_name' - ]) + assert.deepStrictEqual(['debugger_version', 'host_name'], Object.keys(ddtags).sort()) done() }) diff --git a/integration-tests/debugger/redact.spec.js b/integration-tests/debugger/redact.spec.js index f4daeb7832a..3cfc7237272 100644 --- a/integration-tests/debugger/redact.spec.js +++ b/integration-tests/debugger/redact.spec.js @@ -1,8 +1,8 @@ 'use strict' -const assert = require('node:assert/strict') const { setup } = require('./utils') const { once } = require('node:events') +const { assertObjectContains } = require('../helpers') // Default settings is tested in unit tests, so we only need to test the env vars here describe('Dynamic Instrumentation snapshot PII redaction', function () { @@ -22,12 +22,14 @@ describe('Dynamic Instrumentation snapshot PII redaction', function () { const [{ payload: [{ debugger: { snapshot: { captures } } }] }] = await promise const { locals } = captures.lines[t.breakpoint.line] - assert.deepPropertyVal(locals, 'foo', { type: 'string', notCapturedReason: 'redactedIdent' }) - assert.deepPropertyVal(locals, 'bar', { type: 'string', notCapturedReason: 'redactedIdent' }) - assert.deepPropertyVal(locals, 'baz', { type: 'string', value: 'c' }) + assertObjectContains(locals, { + foo: { type: 'string', notCapturedReason: 'redactedIdent' }, + bar: { type: 'string', notCapturedReason: 'redactedIdent' }, + baz: { type: 'string', value: 'c' } + }) // existing redaction should not be impacted - assert.deepPropertyVal(locals, 'secret', { type: 'string', notCapturedReason: 'redactedIdent' }) + assertObjectContains(locals, { secret: { type: 'string', notCapturedReason: 'redactedIdent' } }) }) }) @@ -47,8 +49,10 @@ describe('Dynamic Instrumentation snapshot PII redaction', function () { const [{ payload: [{ debugger: { snapshot: { captures } } }] }] = await promise const { locals } = captures.lines[t.breakpoint.line] - assert.deepPropertyVal(locals, 'secret', { type: 'string', value: 'shh!' }) - assert.deepPropertyVal(locals, 'password', { type: 'string', notCapturedReason: 'redactedIdent' }) + assertObjectContains(locals, { + secret: { type: 'string', value: 'shh!' }, + password: { type: 'string', notCapturedReason: 'redactedIdent' } + }) }) }) }) diff --git a/integration-tests/debugger/snapshot-pruning.spec.js b/integration-tests/debugger/snapshot-pruning.spec.js index 6004e78c27b..8efb63af62f 100644 --- a/integration-tests/debugger/snapshot-pruning.spec.js +++ b/integration-tests/debugger/snapshot-pruning.spec.js @@ -12,8 +12,8 @@ describe('Dynamic Instrumentation', function () { it('should prune snapshot if payload is too large', function (done) { t.agent.on('debugger-input', ({ payload: [payload] }) => { - assert.isBelow(Buffer.byteLength(JSON.stringify(payload)), 1024 * 1024) // 1MB - assert.ok(!Object.hasOwn(payload.debugger.snapshot, 'captures')) + assert.ok(Buffer.byteLength(JSON.stringify(payload)) < 1024 * 1024) // 1MB + assert.ok(!('captures' in payload.debugger.snapshot)) assert.strictEqual( payload.debugger.snapshot.captureError, 'Snapshot was too large (max allowed size is 1 MiB). ' + diff --git a/integration-tests/debugger/snapshot.spec.js b/integration-tests/debugger/snapshot.spec.js index 44d636d96c7..bd176731597 100644 --- a/integration-tests/debugger/snapshot.spec.js +++ b/integration-tests/debugger/snapshot.spec.js @@ -98,7 +98,7 @@ describe('Dynamic Instrumentation', function () { // from closure scope // There's no reason to test the `fastify` object 100%, instead just check its fingerprint assert.strictEqual(fastify.type, 'Object') - assert.strictEqual(typeof fastify.fields, 'Object') + assert.strictEqual(typeof fastify.fields, 'object') assert.deepStrictEqual(getUndefined, { type: 'Function', diff --git a/integration-tests/helpers/fake-agent.js b/integration-tests/helpers/fake-agent.js index e4c982f6bfa..572b9304c1a 100644 --- a/integration-tests/helpers/fake-agent.js +++ b/integration-tests/helpers/fake-agent.js @@ -1,7 +1,5 @@ 'use strict' -const assert = require('node:assert/strict') - const { createHash } = require('crypto') const { EventEmitter, once } = require('events') const http = require('http') diff --git a/integration-tests/helpers/index.js b/integration-tests/helpers/index.js index 794620470b0..7ecc37b8d13 100644 --- a/integration-tests/helpers/index.js +++ b/integration-tests/helpers/index.js @@ -1,14 +1,16 @@ 'use strict' +const assert = require('assert') const childProcess = require('child_process') const { execSync, fork, spawn } = childProcess -const http = require('http') const { existsSync, readFileSync, unlinkSync, writeFileSync } = require('fs') const fs = require('fs/promises') +const http = require('http') const { builtinModules } = require('module') const os = require('os') const path = require('path') -const assert = require('assert') +const { inspect } = require('util') + const FakeAgent = require('./fake-agent') const id = require('../../packages/dd-trace/src/id') const { getCappedRange } = require('../../packages/dd-trace/test/plugins/versions') @@ -635,9 +637,14 @@ function setShouldKill (value) { // @ts-expect-error assert.partialDeepStrictEqual does not exist on older Node.js versions // eslint-disable-next-line n/no-unsupported-features/node-builtins -const assertObjectContains = assert.partialDeepStrictEqual || function assertObjectContains (actual, expected) { +const assertObjectContains = assert.partialDeepStrictEqual || function assertObjectContains (actual, expected, msg) { + if (expected === null || typeof expected !== 'object') { + assert.strictEqual(actual, expected, msg) + return + } + if (Array.isArray(expected)) { - assert.ok(Array.isArray(actual), `Expected array but got ${typeof actual}`) + assert.ok(Array.isArray(actual), `${msg ?? ''}Expected array but got ${inspect(actual)}`) let startIndex = 0 for (const expectedItem of expected) { let found = false @@ -645,9 +652,9 @@ const assertObjectContains = assert.partialDeepStrictEqual || function assertObj const actualItem = actual[i] try { if (expectedItem !== null && typeof expectedItem === 'object') { - assertObjectContains(actualItem, expectedItem) + assertObjectContains(actualItem, expectedItem, msg) } else { - assert.strictEqual(actualItem, expectedItem) + assert.strictEqual(actualItem, expectedItem, msg) } startIndex = i + 1 found = true @@ -656,19 +663,18 @@ const assertObjectContains = assert.partialDeepStrictEqual || function assertObj continue } } - assert.ok(found, `Expected array to contain ${JSON.stringify(expectedItem)}`) + assert.ok(found, `${msg ?? ''}Expected array ${inspect(actual)} to contain ${inspect(expectedItem)}`) } return } for (const [key, val] of Object.entries(expected)) { + assert.ok(Object.hasOwn(actual, key), msg) if (val !== null && typeof val === 'object') { - assert.ok(Object.hasOwn(actual, key)) - assert.notStrictEqual(actual[key], null) - assert.strictEqual(typeof actual[key], 'object') - assertObjectContains(actual[key], val) + assertObjectContains(actual[key], val, msg) } else { - assert.strictEqual(actual[key], expected[key]) + assert.ok(actual, msg) + assert.strictEqual(actual[key], expected[key], msg) } } } diff --git a/integration-tests/jest/jest.spec.js b/integration-tests/jest/jest.spec.js index c9a511223d9..32e04324a4b 100644 --- a/integration-tests/jest/jest.spec.js +++ b/integration-tests/jest/jest.spec.js @@ -131,6 +131,7 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { context('older versions of the agent (APM protocol)', () => { let oldApmProtocolEnvVars = {} + beforeEach(() => { receiver.setInfoResponse({ endpoints: [] }) oldApmProtocolEnvVars = { @@ -142,36 +143,9 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { DD_CIVISIBILITY_AGENTLESS_ENABLED: '0', } }) - it('can run tests and report tests', (done) => { - receiver.payloadReceived(({ url }) => url === '/v0.4/traces').then(({ payload }) => { - const testSpans = payload.flatMap(trace => trace) - const resourceNames = testSpans.map(span => span.resource) - - assert.includeMembers(resourceNames, - [ - 'ci-visibility/test/ci-visibility-test.js.ci visibility can report tests', - 'ci-visibility/test/ci-visibility-test-2.js.ci visibility 2 can report tests 2' - ] - ) - - const areAllTestSpans = testSpans.every(span => span.name === 'jest.test') - assert.strictEqual(areAllTestSpans, true) - - assert.ok(testOutput.includes(expectedStdout)) - // Can read DD_TAGS - testSpans.forEach(testSpan => { - assert.strictEqual(testSpan.meta['test.customtag'], 'customvalue') - assert.strictEqual(testSpan.meta['test.customtag2'], 'customvalue2') - }) - - testSpans.forEach(testSpan => { - assert.strictEqual(testSpan.meta[TEST_SOURCE_FILE].startsWith('ci-visibility/test/ci-visibility-test'), true) - assert.ok(testSpan.metrics[TEST_SOURCE_START] != null) - }) - - done() - }) + it('can run tests and report tests', async () => { + const payloadPromise = receiver.payloadReceived(({ url }) => url === '/v0.4/traces') childProcess = fork(startupTestFile, { cwd, @@ -189,6 +163,36 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { childProcess.stderr.on('data', (chunk) => { testOutput += chunk.toString() }) + + const { payload } = await payloadPromise + + const testSpans = payload.flatMap(trace => trace) + const resourceNames = testSpans.map(span => span.resource) + + assertObjectContains(resourceNames, + [ + 'ci-visibility/test/ci-visibility-test-2.js.ci visibility 2 can report tests 2', + 'ci-visibility/test/ci-visibility-test.js.ci visibility can report tests', + ] + ) + + const areAllTestSpans = testSpans.every(span => span.name === 'jest.test') + assert.strictEqual(areAllTestSpans, true) + + assert.match(testOutput, new RegExp(expectedStdout)) + + // Can read DD_TAGS + testSpans.forEach(testSpan => { + assertObjectContains(testSpan.meta, { + 'test.customtag': 'customvalue', + 'test.customtag2': 'customvalue2' + }) + }) + + testSpans.forEach(testSpan => { + assert.strictEqual(testSpan.meta[TEST_SOURCE_FILE].startsWith('ci-visibility/test/ci-visibility-test'), true) + assert.ok(testSpan.metrics[TEST_SOURCE_START] != null) + }) }) it('should create test spans for sync, async, integration, parameterized and retried tests', async () => { @@ -251,7 +255,7 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { assert.strictEqual(test.meta[JEST_TEST_RUNNER], 'jest-circus') assert.strictEqual(test.meta[LIBRARY_VERSION], ddTraceVersion) assert.strictEqual(test.meta[COMPONENT], 'jest') - assert.ok(test.meta[TEST_CODE_OWNERS].includes('@datadog-dd-trace-js')) + assert.match(test.meta[TEST_CODE_OWNERS], /@datadog-dd-trace-js/) assert.strictEqual(test.type, 'test') assert.strictEqual(test.name, 'jest.test') @@ -268,14 +272,14 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { } if (error) { - assert.ok(test.meta[ERROR_MESSAGE].includes(error)) + assert.match(test.meta[ERROR_MESSAGE], new RegExp(error)) } // TODO: why did this work in jsdom before? if (name === 'jest-test-suite can do integration http') { const httpSpan = spans.find(span => span.name === 'http.request') assert.strictEqual(httpSpan.meta[ORIGIN_KEY], CI_APP_ORIGIN) - assert.ok(httpSpan.meta['http.url'].includes('/info')) + assert.match(httpSpan.meta['http.url'], /\/info/) assert.strictEqual(httpSpan.parent_id.toString(), test.span_id.toString()) } }) @@ -446,52 +450,62 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { if (reportingOption === 'evp proxy') { receiver.setInfoResponse({ endpoints: ['/evp_proxy/v4'] }) } + receiver.gatherPayloadsMaxTimeout(({ url }) => url.endsWith('citestcycle'), (payloads) => { - const metadataDicts = payloads.flatMap(({ payload }) => payload.metadata) + try { + const metadataDicts = payloads.flatMap(({ payload }) => payload.metadata) - metadataDicts.forEach(metadata => { - for (const testLevel of TEST_LEVEL_EVENT_TYPES) { - assert.strictEqual(metadata[testLevel][TEST_SESSION_NAME], 'my-test-session') - } - }) + metadataDicts.forEach(metadata => { + for (const testLevel of TEST_LEVEL_EVENT_TYPES) { + assert.strictEqual(metadata[testLevel][TEST_SESSION_NAME], 'my-test-session') + } + }) - const events = payloads.flatMap(({ payload }) => payload.events) - const sessionEventContent = events.find(event => event.type === 'test_session_end').content - const moduleEventContent = events.find(event => event.type === 'test_module_end').content - const suites = events.filter(event => event.type === 'test_suite_end').map(event => event.content) - const tests = events.filter(event => event.type === 'test').map(event => event.content) + const events = payloads.flatMap(({ payload }) => payload.events) + const sessionEventContent = events.find(event => event.type === 'test_session_end').content + const moduleEventContent = events.find(event => event.type === 'test_module_end').content + const suites = events.filter(event => event.type === 'test_suite_end').map(event => event.content) + const tests = events.filter(event => event.type === 'test').map(event => event.content) - const resourceNames = tests.map(span => span.resource) + const resourceNames = tests.map(span => span.resource) - assert.includeMembers(resourceNames, - [ - 'ci-visibility/test/ci-visibility-test.js.ci visibility can report tests', - 'ci-visibility/test/ci-visibility-test-2.js.ci visibility 2 can report tests 2' - ] - ) - assert.strictEqual(suites.length, 2) - assert.ok(sessionEventContent != null) - assert.ok(moduleEventContent != null) - - assert.ok(testOutput.includes(expectedStdout)) - - tests.forEach(testEvent => { - assert.strictEqual(testEvent.meta[TEST_SOURCE_FILE].startsWith('ci-visibility/test/ci-visibility-test'), true) - assert.ok(testEvent.metrics[TEST_SOURCE_START] != null) - assert.strictEqual(testEvent.meta[DD_TEST_IS_USER_PROVIDED_SERVICE], 'false') - // Can read DD_TAGS - assert.strictEqual(testEvent.meta['test.customtag'], 'customvalue') - assert.strictEqual(testEvent.meta['test.customtag2'], 'customvalue2') - assert.ok(testEvent.metrics[DD_HOST_CPU_COUNT] != null) - }) + assertObjectContains(resourceNames, + [ + 'ci-visibility/test/ci-visibility-test-2.js.ci visibility 2 can report tests 2', + 'ci-visibility/test/ci-visibility-test.js.ci visibility can report tests', + ] + ) + assert.strictEqual(suites.length, 2) + assert.ok(sessionEventContent != null) + assert.ok(moduleEventContent != null) - suites.forEach(testSuite => { - assert.strictEqual(testSuite.meta[TEST_SOURCE_FILE].startsWith('ci-visibility/test/ci-visibility-test'), true) - assert.strictEqual(testSuite.metrics[TEST_SOURCE_START], 1) - assert.ok(testSuite.metrics[DD_HOST_CPU_COUNT] != null) - }) + assert.match(testOutput, new RegExp(expectedStdout)) - done() + tests.forEach(testEvent => { + assert.strictEqual( + testEvent.meta[TEST_SOURCE_FILE].startsWith('ci-visibility/test/ci-visibility-test'), + true + ) + assert.ok(testEvent.metrics[TEST_SOURCE_START] != null) + assert.strictEqual(testEvent.meta[DD_TEST_IS_USER_PROVIDED_SERVICE], 'false') + // Can read DD_TAGS + assert.strictEqual(testEvent.meta['test.customtag'], 'customvalue') + assert.strictEqual(testEvent.meta['test.customtag2'], 'customvalue2') + assert.ok(testEvent.metrics[DD_HOST_CPU_COUNT] != null) + }) + + suites.forEach(testSuite => { + assert.strictEqual( + testSuite.meta[TEST_SOURCE_FILE].startsWith('ci-visibility/test/ci-visibility-test'), + true + ) + assert.strictEqual(testSuite.metrics[TEST_SOURCE_START], 1) + assert.ok(testSuite.metrics[DD_HOST_CPU_COUNT] != null) + }) + done() + } catch (error) { + done(error) + } }) childProcess = fork(startupTestFile, { @@ -607,7 +621,7 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { testOutput += chunk.toString() }) childProcess.on('message', () => { - assert.ok(testOutput.includes(expectedStdout)) + assert.match(testOutput, new RegExp(expectedStdout)) done() }) }) @@ -631,9 +645,9 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { testOutput += chunk.toString() }) childProcess.on('message', () => { - assert.ok(!testOutput.includes('TypeError')) - assert.ok(!testOutput.includes('Uncaught error outside test suite')) - assert.ok(testOutput.includes(expectedStdout)) + assert.doesNotMatch(testOutput, /TypeError/) + assert.doesNotMatch(testOutput, /Uncaught error outside test suite/) + assert.match(testOutput, new RegExp(expectedStdout)) done() }) }) @@ -681,7 +695,7 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { assert.strictEqual(testSuiteEvents.length, 3) const testSuites = testSuiteEvents.map(span => span.content.meta[TEST_SUITE]) - assert.includeMembers(testSuites, + assertObjectContains(testSuites, [ 'ci-visibility/sharding-test/sharding-test-5.js', 'ci-visibility/sharding-test/sharding-test-4.js', @@ -772,8 +786,8 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { testOutput += chunk.toString() }) childProcess.on('message', () => { - assert.ok(!testOutput.includes('TypeError')) - assert.ok(testOutput.includes(expectedStdout)) + assert.doesNotMatch(testOutput, /TypeError/) + assert.match(testOutput, new RegExp(expectedStdout)) done() }) }) @@ -796,7 +810,7 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { testOutput += chunk.toString() }) childProcess.on('message', () => { - assert.ok(!testOutput.includes('TypeError')) + assert.doesNotMatch(testOutput, /TypeError/) done() }) }) @@ -818,8 +832,8 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { const testSpans = tracesRequests.flatMap(trace => trace.payload).flatMap(request => request) assert.strictEqual(testSpans.length, 2) const spanTypes = testSpans.map(span => span.type) - assert.includeMembers(spanTypes, ['test']) - assert.ok(!spanTypes.includes(['test_session_end', 'test_suite_end', 'test_module_end'])) + assertObjectContains(spanTypes, ['test']) + assert.ok(!spanTypes.some(type => ['test_session_end', 'test_suite_end', 'test_module_end'].includes(type))) receiver.setInfoResponse({ endpoints: ['/evp_proxy/v2'] }) done() }).catch(done) @@ -849,7 +863,7 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { const events = eventsRequests.map(({ payload }) => payload) .flatMap(({ events }) => events) const eventTypes = events.map(event => event.type) - assert.includeMembers(eventTypes, ['test', 'test_suite_end', 'test_module_end', 'test_session_end']) + assertObjectContains(eventTypes, ['test', 'test_suite_end', 'test_session_end', 'test_module_end']) done() }).catch(done) @@ -871,7 +885,7 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { .flatMap(({ events }) => events) .map(event => event.type) - assert.includeMembers(eventTypes, ['test', 'test_suite_end', 'test_module_end', 'test_session_end']) + assertObjectContains(eventTypes, ['test', 'test_suite_end', 'test_session_end', 'test_module_end']) done() }).catch(done) }) @@ -909,7 +923,7 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { const notRetriedTest = tests.find(test => test.meta[TEST_NAME].includes('is not retried')) - assert.ok(!Object.hasOwn(notRetriedTest.meta, DI_ERROR_DEBUG_INFO_CAPTURED)) + assert.ok(!('DI_ERROR_DEBUG_INFO_CAPTURED' in notRetriedTest.meta)) }) const logsPromise = receiver @@ -982,13 +996,13 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { const resourceNames = suites.map(suite => suite.content.resource) - assert.includeMembers(resourceNames, [ + assertObjectContains(resourceNames, [ 'test_suite.ci-visibility/test-parsing-error/parsing-error-2.js', 'test_suite.ci-visibility/test-parsing-error/parsing-error.js' ]) suites.forEach(suite => { assert.strictEqual(suite.content.meta[TEST_STATUS], 'fail') - assert.ok(suite.content.meta[ERROR_MESSAGE].includes('chao')) + assert.match(suite.content.meta[ERROR_MESSAGE], /chao/) }) }) childProcess = fork(testFile, { @@ -1021,7 +1035,9 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { const [failedTestSuite] = failedTestSuites assert.strictEqual(failedTestSuite.content.meta[TEST_STATUS], 'fail') - assert.ok(failedTestSuite.content.meta[ERROR_MESSAGE].includes('a file outside of the scope of the test code')) + assert.ok( + failedTestSuite.content.meta[ERROR_MESSAGE].includes('a file outside of the scope of the test code') + ) assert.strictEqual(failedTestSuite.content.meta[ERROR_TYPE], 'Error') const passedTestSuites = suites.filter( @@ -1063,12 +1079,18 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { // jest still reports the test suite as passing assert.strictEqual(badImportTestSuite.content.meta[TEST_STATUS], 'pass') - assert.ok(badImportTestSuite.content.meta[ERROR_MESSAGE].includes('a file after the Jest environment has been torn down')) - assert.ok(badImportTestSuite.content.meta[ERROR_MESSAGE].includes('From ci-visibility/jest-bad-import-torn-down/jest-bad-import-test.js')) + assert.ok( + badImportTestSuite.content.meta[ERROR_MESSAGE] + .includes('a file after the Jest environment has been torn down') + ) + assert.ok( + badImportTestSuite.content.meta[ERROR_MESSAGE] + .includes('From ci-visibility/jest-bad-import-torn-down/jest-bad-import-test.js') + ) // This is the error message that jest should show. We check that we don't mess it up. - assert.ok(badImportTestSuite.content.meta[ERROR_MESSAGE].includes('off-timing-import')) - assert.ok(badImportTestSuite.content.meta[ERROR_MESSAGE].includes('afterAll')) - assert.ok(badImportTestSuite.content.meta[ERROR_MESSAGE].includes('nextTick')) + assert.match(badImportTestSuite.content.meta[ERROR_MESSAGE], /off-timing-import/) + assert.match(badImportTestSuite.content.meta[ERROR_MESSAGE], /afterAll/) + assert.match(badImportTestSuite.content.meta[ERROR_MESSAGE], /nextTick/) const passedTestSuites = suites.filter( suite => suite.content.meta[TEST_STATUS] === 'pass' @@ -1102,7 +1124,7 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { receiver.assertPayloadReceived(({ payload }) => { const testSession = payload.events.find(event => event.type === 'test_session_end').content - assert.ok(!Object.hasOwn(testSession.metrics, TEST_CODE_COVERAGE_LINES_PCT)) + assert.ok(!('TEST_CODE_COVERAGE_LINES_PCT' in testSession.metrics)) }, ({ url }) => url === '/api/v2/citestcycle').then(() => done()).catch(done) childProcess = exec( @@ -1140,7 +1162,7 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { it('works with --forceExit and logs a warning', (done) => { const eventsPromise = receiver .gatherPayloadsMaxTimeout(({ url }) => url.endsWith('/api/v2/citestcycle'), (payloads) => { - assert.ok(testOutput.includes("Jest's '--forceExit' flag has been passed")) + assert.match(testOutput, /Jest's '--forceExit' flag has been passed/) const events = payloads.flatMap(({ payload }) => payload.events) const testSession = events.find(event => event.type === 'test_session_end') @@ -1195,13 +1217,9 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { stdio: 'inherit' } ) - const EXPECTED_FORCE_EXIT_LOG_MESSAGE = "Jest's '--forceExit' flag has been passed" - const EXPECTED_TIMEOUT_LOG_MESSAGE = 'Timeout waiting for the tracer to flush' childProcess.on('exit', () => { - assert.ok(testOutput.includes(EXPECTED_FORCE_EXIT_LOG_MESSAGE, - `"${EXPECTED_FORCE_EXIT_LOG_MESSAGE}" log message is not in test output: ${testOutput}`)) - assert.ok(testOutput.includes(EXPECTED_TIMEOUT_LOG_MESSAGE, - `"${EXPECTED_TIMEOUT_LOG_MESSAGE}" log message is not in the test output: ${testOutput}`)) + assert.match(testOutput, /Jest's '--forceExit' flag has been passed/) + assert.match(testOutput, /Timeout waiting for the tracer to flush/) done() }) childProcess.stdout.on('data', (chunk) => { @@ -1254,8 +1272,7 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { const events = payloads.flatMap(({ payload }) => payload.events) const testSession = events.find(event => event.type === 'test_session_end').content assert.strictEqual(testSession.meta[TEST_STATUS], 'fail') - const errorMessage = 'Failed test suites: 1. Failed tests: 1' - assert.ok(testSession.meta[ERROR_MESSAGE].includes(errorMessage)) + assert.match(testSession.meta[ERROR_MESSAGE], /Failed test suites: 1. Failed tests: 1/) }) childProcess = exec( @@ -1296,10 +1313,11 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { testOutput += chunk.toString() }) childProcess.on('message', () => { - assert.ok(testOutput.includes(expectedStdout)) - assert.ok(testOutput.includes('DD_CIVISIBILITY_AGENTLESS_ENABLED is set, ' + - 'but neither DD_API_KEY nor DATADOG_API_KEY are set in your environment, ' + - 'so dd-trace will not be initialized.')) + assert.match(testOutput, new RegExp(expectedStdout)) + assert.match( + testOutput, + /DD_CIVISIBILITY_AGENTLESS_ENABLED is set, but neither DD_API_KEY nor DATADOG_API_KEY are set in your environment, so dd-trace will not be initialized./ + ) done() }) }) @@ -1320,7 +1338,7 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { assert.strictEqual(packfileRequest.headers['dd-api-key'], '1') const eventTypes = eventsRequest.payload.events.map(event => event.type) - assert.includeMembers(eventTypes, ['test', 'test_suite_end', 'test_module_end', 'test_session_end']) + assertObjectContains(eventTypes, ['test', 'test_suite_end', 'test_session_end', 'test_module_end']) const numSuites = eventTypes.reduce( (acc, type) => type === 'test_suite_end' ? acc + 1 : acc, 0 ) @@ -1362,10 +1380,10 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { const testSpans = payload.flatMap(trace => trace) const resourceNames = testSpans.map(span => span.resource) - assert.includeMembers(resourceNames, + assertObjectContains(resourceNames, [ + 'ci-visibility/test/ci-visibility-test-2.js.ci visibility 2 can report tests 2', 'ci-visibility/test/ci-visibility-test.js.ci visibility can report tests', - 'ci-visibility/test/ci-visibility-test-2.js.ci visibility 2 can report tests 2' ] ) }, ({ url }) => url === '/v0.4/traces').then(() => done()).catch(done) @@ -1392,21 +1410,27 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { ]).then(([libraryConfigRequest, codeCovRequest, eventsRequest]) => { assert.strictEqual(libraryConfigRequest.headers['dd-api-key'], '1') - const [coveragePayload] = codeCovRequest.payload - assert.strictEqual(codeCovRequest.headers['dd-api-key'], '1') - - assert.strictEqual(coveragePayload.name, 'coverage1') - assert.strictEqual(coveragePayload.filename, 'coverage1.msgpack') - assert.strictEqual(coveragePayload.type, 'application/msgpack') - assert.ok(coveragePayload.content.includes({ - version: 2 - })) + assertObjectContains(codeCovRequest, { + headers: { + 'dd-api-key': '1' + }, + payload: [{ + name: 'coverage1', + filename: 'coverage1.msgpack', + type: 'application/msgpack', + content: { + version: 2 + } + }] + }) const allCoverageFiles = codeCovRequest.payload .flatMap(coverage => coverage.content.coverages) .flatMap(file => file.files) .map(file => file.filename) - assert.includeMembers(allCoverageFiles, expectedCoverageFiles) + assertObjectContains(allCoverageFiles.sort(), expectedCoverageFiles.sort()) + + const [coveragePayload] = codeCovRequest.payload assert.ok(coveragePayload.content.coverages[0].test_session_id != null) assert.ok(coveragePayload.content.coverages[0].test_suite_id != null) @@ -1414,7 +1438,7 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { assert.ok(testSession.metrics[TEST_CODE_COVERAGE_LINES_PCT] != null) const eventTypes = eventsRequest.payload.events.map(event => event.type) - assert.includeMembers(eventTypes, ['test', 'test_suite_end', 'test_module_end', 'test_session_end']) + assertObjectContains(eventTypes, ['test', 'test_suite_end', 'test_session_end', 'test_module_end']) const numSuites = eventTypes.reduce( (acc, type) => type === 'test_suite_end' ? acc + 1 : acc, 0 ) @@ -1453,7 +1477,7 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { receiver.assertPayloadReceived(({ headers, payload }) => { assert.strictEqual(headers['dd-api-key'], '1') const eventTypes = payload.events.map(event => event.type) - assert.includeMembers(eventTypes, ['test', 'test_session_end', 'test_module_end', 'test_suite_end']) + assertObjectContains(eventTypes, ['test', 'test_suite_end', 'test_session_end', 'test_module_end']) const testSession = payload.events.find(event => event.type === 'test_session_end').content assert.strictEqual(testSession.meta[TEST_ITR_TESTS_SKIPPED], 'false') assert.strictEqual(testSession.meta[TEST_CODE_COVERAGE_ENABLED], 'false') @@ -1510,7 +1534,7 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { assert.strictEqual(skippedSuite.meta[TEST_STATUS], 'skip') assert.strictEqual(skippedSuite.meta[TEST_SKIPPED_BY_ITR], 'true') - assert.includeMembers(eventTypes, ['test', 'test_suite_end', 'test_module_end', 'test_session_end']) + assertObjectContains(eventTypes, ['test', 'test_suite_end', 'test_session_end', 'test_module_end']) const numSuites = eventTypes.reduce( (acc, type) => type === 'test_suite_end' ? acc + 1 : acc, 0 ) @@ -1598,7 +1622,7 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { assert.strictEqual(headers['dd-api-key'], '1') const eventTypes = payload.events.map(event => event.type) // because they are not skipped - assert.includeMembers(eventTypes, ['test', 'test_suite_end', 'test_module_end', 'test_session_end']) + assertObjectContains(eventTypes, ['test', 'test_suite_end', 'test_session_end', 'test_module_end']) const numSuites = eventTypes.reduce( (acc, type) => type === 'test_suite_end' ? acc + 1 : acc, 0 ) @@ -1646,7 +1670,7 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { assert.strictEqual(headers['dd-api-key'], '1') const eventTypes = payload.events.map(event => event.type) // because they are not skipped - assert.includeMembers(eventTypes, ['test', 'test_suite_end', 'test_module_end', 'test_session_end']) + assertObjectContains(eventTypes, ['test', 'test_suite_end', 'test_session_end', 'test_module_end']) const numSuites = eventTypes.reduce( (acc, type) => type === 'test_suite_end' ? acc + 1 : acc, 0 ) @@ -1704,12 +1728,12 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { ) // It does not mark as unskippable if there is no docblock assert.strictEqual(passedSuite.content.meta[TEST_STATUS], 'pass') - assert.ok(!Object.hasOwn(passedSuite.content.meta, TEST_ITR_UNSKIPPABLE)) - assert.ok(!Object.hasOwn(passedSuite.content.meta, TEST_ITR_FORCED_RUN)) + assert.ok(!('TEST_ITR_UNSKIPPABLE' in passedSuite.content.meta)) + assert.ok(!('TEST_ITR_FORCED_RUN' in passedSuite.content.meta)) assert.strictEqual(skippedSuite.content.meta[TEST_STATUS], 'skip') - assert.ok(!Object.hasOwn(skippedSuite.content.meta, TEST_ITR_UNSKIPPABLE)) - assert.ok(!Object.hasOwn(skippedSuite.content.meta, TEST_ITR_FORCED_RUN)) + assert.ok(!('TEST_ITR_UNSKIPPABLE' in skippedSuite.content.meta)) + assert.ok(!('TEST_ITR_FORCED_RUN' in skippedSuite.content.meta)) assert.strictEqual(forcedToRunSuite.content.meta[TEST_STATUS], 'pass') assert.strictEqual(forcedToRunSuite.content.meta[TEST_ITR_UNSKIPPABLE], 'true') @@ -1754,9 +1778,9 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { const testSession = events.find(event => event.type === 'test_session_end').content const testModule = events.find(event => event.type === 'test_module_end').content - assert.ok(!Object.hasOwn(testSession.meta, TEST_ITR_FORCED_RUN)) + assert.ok(!('TEST_ITR_FORCED_RUN' in testSession.meta)) assert.strictEqual(testSession.meta[TEST_ITR_UNSKIPPABLE], 'true') - assert.ok(!Object.hasOwn(testModule.meta, TEST_ITR_FORCED_RUN)) + assert.ok(!('TEST_ITR_FORCED_RUN' in testModule.meta)) assert.strictEqual(testModule.meta[TEST_ITR_UNSKIPPABLE], 'true') const passedSuite = suites.find( @@ -1771,15 +1795,15 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { // It does not mark as unskippable if there is no docblock assert.strictEqual(passedSuite.content.meta[TEST_STATUS], 'pass') - assert.ok(!Object.hasOwn(passedSuite.content.meta, TEST_ITR_UNSKIPPABLE)) - assert.ok(!Object.hasOwn(passedSuite.content.meta, TEST_ITR_FORCED_RUN)) + assert.ok(!('TEST_ITR_UNSKIPPABLE' in passedSuite.content.meta)) + assert.ok(!('TEST_ITR_FORCED_RUN' in passedSuite.content.meta)) assert.strictEqual(skippedSuite.meta[TEST_STATUS], 'skip') assert.strictEqual(nonSkippedSuite.meta[TEST_STATUS], 'pass') assert.strictEqual(nonSkippedSuite.meta[TEST_ITR_UNSKIPPABLE], 'true') // it was not forced to run because it wasn't going to be skipped - assert.ok(!Object.hasOwn(nonSkippedSuite.meta, TEST_ITR_FORCED_RUN)) + assert.ok(!('TEST_ITR_FORCED_RUN' in nonSkippedSuite.meta)) }, 25000) childProcess = exec( @@ -1970,7 +1994,7 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { .flatMap(({ files }) => files) .map(({ filename }) => filename) - assert.includeMembers(coveredFiles, [ + assertObjectContains(coveredFiles, [ 'ci-visibility/subproject/dependency.js', 'ci-visibility/subproject/subproject-test.js' ]) @@ -2008,7 +2032,7 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { .flatMap(file => file.files) .map(file => file.filename) - assert.includeMembers(allCoverageFiles, [ + assertObjectContains(allCoverageFiles, [ 'ci-visibility/test/sum.js', 'ci-visibility/jest/mocked-test.js' ]) @@ -2065,7 +2089,7 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { test.meta[TEST_SUITE] === 'ci-visibility/test/ci-visibility-test.js' ) oldTests.forEach(test => { - assert.ok(!Object.hasOwn(test.meta, TEST_IS_NEW)) + assert.ok(!('TEST_IS_NEW' in test.meta)) }) assert.strictEqual(oldTests.length, 1) @@ -2150,9 +2174,15 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { assert.strictEqual(testsForFirstParameter.length, testsForSecondParameter.length) // all but one have been retried - assert.strictEqual(testsForFirstParameter.length - 1, testsForFirstParameter.filter(test => test.meta[TEST_IS_RETRY] === 'true').length) + assert.strictEqual( + testsForFirstParameter.length - 1, + testsForFirstParameter.filter(test => test.meta[TEST_IS_RETRY] === 'true').length + ) - assert.strictEqual(testsForSecondParameter.length - 1, testsForSecondParameter.filter(test => test.meta[TEST_IS_RETRY] === 'true').length) + assert.strictEqual( + testsForSecondParameter.length - 1, + testsForSecondParameter.filter(test => test.meta[TEST_IS_RETRY] === 'true').length + ) }) childProcess = exec( @@ -2193,7 +2223,7 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { .gatherPayloadsMaxTimeout(({ url }) => url.endsWith('/api/v2/citestcycle'), (payloads) => { const events = payloads.flatMap(({ payload }) => payload.events) const testSession = events.find(event => event.type === 'test_session_end').content - assert.ok(!Object.hasOwn(testSession.meta, TEST_EARLY_FLAKE_ENABLED)) + assert.ok(!('TEST_EARLY_FLAKE_ENABLED' in testSession.meta)) const tests = events.filter(event => event.type === 'test').map(event => event.content) const newTests = tests.filter(test => @@ -2317,13 +2347,13 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { test => test.meta[TEST_NAME] === 'ci visibility skip will not be retried' ) assert.strictEqual(newSkippedTests.length, 1) - assert.ok(!Object.hasOwn(newSkippedTests[0].meta, TEST_IS_RETRY)) + assert.ok(!('TEST_IS_RETRY' in newSkippedTests[0].meta)) const newTodoTests = tests.filter( test => test.meta[TEST_NAME] === 'ci visibility todo will not be retried' ) assert.strictEqual(newTodoTests.length, 1) - assert.ok(!Object.hasOwn(newTodoTests[0].meta, TEST_IS_RETRY)) + assert.ok(!('TEST_IS_RETRY' in newTodoTests[0].meta)) }) childProcess = exec( @@ -2376,7 +2406,7 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { const resourceNames = tests.map(test => test.resource) - assert.includeMembers(resourceNames, + assertObjectContains(resourceNames, [ 'ci-visibility/test-early-flake-detection/weird-test-names.js.no describe can do stuff', 'ci-visibility/test-early-flake-detection/weird-test-names.js.describe trailing space ' @@ -2429,7 +2459,7 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { const events = payloads.flatMap(({ payload }) => payload.events) const testSession = events.find(event => event.type === 'test_session_end').content - assert.ok(!Object.hasOwn(testSession.meta, TEST_EARLY_FLAKE_ENABLED)) + assert.ok(!('TEST_EARLY_FLAKE_ENABLED' in testSession.meta)) const tests = events.filter(event => event.type === 'test').map(event => event.content) @@ -2519,7 +2549,7 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { }) childProcess.on('exit', (exitCode) => { - assert.ok(testOutput.includes('2 failed, 2 passed')) + assert.match(testOutput, /2 failed, 2 passed/) assert.strictEqual(exitCode, 0) eventsPromise.then(() => { done() @@ -2734,7 +2764,7 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { test.meta[TEST_SUITE] === 'ci-visibility/test/ci-visibility-test.js' ) oldTests.forEach(test => { - assert.ok(!Object.hasOwn(test.meta, TEST_IS_NEW)) + assert.ok(!('TEST_IS_NEW' in test.meta)) }) assert.strictEqual(oldTests.length, 1) @@ -2806,7 +2836,7 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { test.meta[TEST_SUITE] === 'ci-visibility/test/ci-visibility-test.js' ) oldTests.forEach(test => { - assert.ok(!Object.hasOwn(test.meta, TEST_IS_NEW)) + assert.ok(!('TEST_IS_NEW' in test.meta)) }) assert.strictEqual(oldTests.length, 1) @@ -2869,7 +2899,7 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { const events = payloads.flatMap(({ payload }) => payload.events) const testSession = events.find(event => event.type === 'test_session_end').content - assert.ok(!Object.hasOwn(testSession.meta, TEST_EARLY_FLAKE_ENABLED)) + assert.ok(!('TEST_EARLY_FLAKE_ENABLED' in testSession.meta)) const tests = events.filter(event => event.type === 'test').map(event => event.content) @@ -2877,14 +2907,14 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { test.meta[TEST_SUITE] === 'ci-visibility/test/ci-visibility-test.js' ) oldTests.forEach(test => { - assert.ok(!Object.hasOwn(test.meta, TEST_IS_NEW)) + assert.ok(!('TEST_IS_NEW' in test.meta)) }) assert.strictEqual(oldTests.length, 1) const newTests = tests.filter(test => test.meta[TEST_SUITE] === 'ci-visibility/test/ci-visibility-test-2.js' ) newTests.forEach(test => { - assert.ok(!Object.hasOwn(test.meta, TEST_IS_NEW)) + assert.ok(!('TEST_IS_NEW' in test.meta)) }) const retriedTests = newTests.filter(test => test.meta[TEST_IS_RETRY] === 'true') assert.strictEqual(retriedTests.length, 0) @@ -2932,7 +2962,7 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { test.meta[TEST_SUITE] === 'ci-visibility/jest/failing-test.js' ) newTests.forEach(test => { - assert.ok(!Object.hasOwn(test.meta, TEST_IS_NEW)) + assert.ok(!('TEST_IS_NEW' in test.meta)) }) assert.strictEqual(newTests.length, 2) @@ -3005,7 +3035,7 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { test.meta[TEST_SUITE] !== 'ci-visibility/test/efd-parallel/ci-visibility-test-4.js' ) oldTests.forEach(test => { - assert.ok(!Object.hasOwn(test.meta, TEST_IS_NEW)) + assert.ok(!('TEST_IS_NEW' in test.meta)) }) assert.strictEqual(oldTests.length, 3) @@ -3068,7 +3098,7 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { const events = payloads.flatMap(({ payload }) => payload.events) const testSession = events.find(event => event.type === 'test_session_end').content - assert.ok(!Object.hasOwn(testSession.meta, TEST_EARLY_FLAKE_ENABLED)) + assert.ok(!('TEST_EARLY_FLAKE_ENABLED' in testSession.meta)) assert.strictEqual(testSession.meta[TEST_EARLY_FLAKE_ABORT_REASON], 'faulty') const tests = events.filter(event => event.type === 'test').map(event => event.content) @@ -3193,13 +3223,14 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { const tests = events.filter(event => event.type === 'test').map(event => event.content) assert.strictEqual(tests.length, 10) - assert.includeMembers(tests.map(test => test.resource), [ + assertObjectContains(tests.map(test => test.resource), [ + // retries twice and passes + 'ci-visibility/jest-flaky/flaky-passes.js.test-flaky-test-retries can retry flaky tests', // does not retry 'ci-visibility/jest-flaky/flaky-passes.js.test-flaky-test-retries will not retry passed tests', 'ci-visibility/jest-flaky/flaky-passes.js.test-flaky-test-retries can retry flaky tests', 'ci-visibility/jest-flaky/flaky-passes.js.test-flaky-test-retries can retry flaky tests', // retries twice and passes - 'ci-visibility/jest-flaky/flaky-passes.js.test-flaky-test-retries can retry flaky tests', 'ci-visibility/jest-flaky/flaky-fails.js.test-flaky-test-retries can retry failed tests', 'ci-visibility/jest-flaky/flaky-fails.js.test-flaky-test-retries can retry failed tests', 'ci-visibility/jest-flaky/flaky-fails.js.test-flaky-test-retries can retry failed tests', @@ -3283,10 +3314,10 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { const tests = events.filter(event => event.type === 'test').map(event => event.content) assert.strictEqual(tests.length, 3) - assert.includeMembers(tests.map(test => test.resource), [ + assertObjectContains(tests.map(test => test.resource), [ // does not retry anything - 'ci-visibility/jest-flaky/flaky-passes.js.test-flaky-test-retries will not retry passed tests', 'ci-visibility/jest-flaky/flaky-passes.js.test-flaky-test-retries can retry flaky tests', + 'ci-visibility/jest-flaky/flaky-passes.js.test-flaky-test-retries will not retry passed tests', 'ci-visibility/jest-flaky/flaky-fails.js.test-flaky-test-retries can retry failed tests' ]) @@ -3332,13 +3363,16 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { const tests = events.filter(event => event.type === 'test').map(event => event.content) assert.strictEqual(tests.filter(test => test.meta[TEST_IS_RETRY] === 'true').length, 2) - assert.strictEqual(tests.filter(test => test.meta[TEST_RETRY_REASON] === TEST_RETRY_REASON_TYPES.atr).length, 2) + assert.strictEqual( + tests.filter(test => test.meta[TEST_RETRY_REASON] === TEST_RETRY_REASON_TYPES.atr).length, + 2 + ) assert.strictEqual(tests.length, 5) // only one retry - assert.includeMembers(tests.map(test => test.resource), [ - 'ci-visibility/jest-flaky/flaky-passes.js.test-flaky-test-retries will not retry passed tests', + assertObjectContains(tests.map(test => test.resource), [ 'ci-visibility/jest-flaky/flaky-passes.js.test-flaky-test-retries can retry flaky tests', + 'ci-visibility/jest-flaky/flaky-passes.js.test-flaky-test-retries will not retry passed tests', 'ci-visibility/jest-flaky/flaky-passes.js.test-flaky-test-retries can retry flaky tests', 'ci-visibility/jest-flaky/flaky-fails.js.test-flaky-test-retries can retry failed tests', 'ci-visibility/jest-flaky/flaky-fails.js.test-flaky-test-retries can retry failed tests' @@ -3493,7 +3527,7 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { const notRetriedTest = tests.find(test => test.meta[TEST_NAME].includes('is not retried')) - assert.ok(!Object.hasOwn(notRetriedTest.meta, DI_ERROR_DEBUG_INFO_CAPTURED)) + assert.ok(!('DI_ERROR_DEBUG_INFO_CAPTURED' in notRetriedTest.meta)) }) const logsPromise = receiver @@ -3504,7 +3538,7 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { level: 'error' }) assert.strictEqual(diLog.debugger.snapshot.language, 'javascript') - assert.deepInclude(diLog.debugger.snapshot.captures.lines['6'].locals, { + assertObjectContains(diLog.debugger.snapshot.captures.lines['6'].locals, { a: { type: 'number', value: '11' @@ -3577,7 +3611,7 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { const notRetriedTest = tests.find(test => test.meta[TEST_NAME].includes('is not retried')) - assert.ok(!Object.hasOwn(notRetriedTest.meta, DI_ERROR_DEBUG_INFO_CAPTURED)) + assert.ok(!('DI_ERROR_DEBUG_INFO_CAPTURED' in notRetriedTest.meta)) }) const logsPromise = receiver @@ -3590,7 +3624,7 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { assert.ok(diLog.ddtags.includes('git.repository_url:')) assert.ok(diLog.ddtags.includes('git.commit.sha:')) assert.strictEqual(diLog.debugger.snapshot.language, 'javascript') - assert.deepInclude(diLog.debugger.snapshot.captures.lines['6'].locals, { + assertObjectContains(diLog.debugger.snapshot.captures.lines['6'].locals, { a: { type: 'number', value: '11' @@ -3780,7 +3814,7 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { const events = payloads.flatMap(({ payload }) => payload.events) const testSession = events.find(event => event.type === 'test_session_end').content - assert.ok(!Object.hasOwn(testSession.meta, TEST_EARLY_FLAKE_ENABLED)) + assert.ok(!('TEST_EARLY_FLAKE_ENABLED' in testSession.meta)) const tests = events.filter(event => event.type === 'test').map(event => event.content) @@ -3789,7 +3823,7 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { test.meta[TEST_SUITE] === 'ci-visibility/test/ci-visibility-test.js' ) oldTests.forEach(test => { - assert.ok(!Object.hasOwn(test.meta, TEST_IS_NEW)) + assert.ok(!('TEST_IS_NEW' in test.meta)) }) assert.strictEqual(oldTests.length, 1) @@ -3888,12 +3922,12 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { if (isAttemptToFix) { assert.strictEqual(testSession.meta[TEST_MANAGEMENT_ENABLED], 'true') } else { - assert.ok(!Object.hasOwn(testSession.meta, TEST_MANAGEMENT_ENABLED)) + assert.ok(!('TEST_MANAGEMENT_ENABLED' in testSession.meta)) } const resourceNames = tests.map(span => span.resource) - assert.includeMembers(resourceNames, + assertObjectContains(resourceNames, [ 'ci-visibility/test-management/test-attempt-to-fix-1.js.attempt to fix tests can attempt to fix a test' ] @@ -3905,7 +3939,7 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { // so we can be sure that parallel mode is on const parallelTestName = 'ci-visibility/test-management/test-attempt-to-fix-2.js.' + 'attempt to fix tests 2 can attempt to fix a test' - assert.includeMembers(resourceNames, [parallelTestName]) + assertObjectContains(resourceNames, [parallelTestName]) } const retriedTests = tests.filter( @@ -3915,9 +3949,9 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { for (let i = 0; i < retriedTests.length; i++) { const test = retriedTests[i] if (!isAttemptToFix) { - assert.ok(!Object.hasOwn(test.meta, TEST_MANAGEMENT_IS_ATTEMPT_TO_FIX)) - assert.ok(!Object.hasOwn(test.meta, TEST_IS_RETRY)) - assert.ok(!Object.hasOwn(test.meta, TEST_RETRY_REASON)) + assert.ok(!('TEST_MANAGEMENT_IS_ATTEMPT_TO_FIX' in test.meta)) + assert.ok(!('TEST_IS_RETRY' in test.meta)) + assert.ok(!('TEST_RETRY_REASON' in test.meta)) continue } @@ -3934,8 +3968,8 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { assert.strictEqual(test.meta[TEST_MANAGEMENT_IS_ATTEMPT_TO_FIX], 'true') if (isFirstAttempt) { - assert.ok(!Object.hasOwn(test.meta, TEST_IS_RETRY)) - assert.ok(!Object.hasOwn(test.meta, TEST_RETRY_REASON)) + assert.ok(!('TEST_IS_RETRY' in test.meta)) + assert.ok(!('TEST_RETRY_REASON' in test.meta)) } else { assert.strictEqual(test.meta[TEST_IS_RETRY], 'true') assert.strictEqual(test.meta[TEST_RETRY_REASON], TEST_RETRY_REASON_TYPES.atf) @@ -3945,7 +3979,7 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { if (shouldAlwaysPass) { assert.strictEqual(test.meta[TEST_MANAGEMENT_ATTEMPT_TO_FIX_PASSED], 'true') } else if (shouldFailSometimes) { - assert.ok(!Object.hasOwn(test.meta, TEST_HAS_FAILED_ALL_RETRIES)) + assert.ok(!('TEST_HAS_FAILED_ALL_RETRIES' in test.meta)) assert.strictEqual(test.meta[TEST_MANAGEMENT_ATTEMPT_TO_FIX_PASSED], 'false') } else { assert.strictEqual(test.meta[TEST_HAS_FAILED_ALL_RETRIES], 'true') @@ -4000,7 +4034,7 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { childProcess.on('exit', exitCode => { testAssertionsPromise.then(() => { - assert.ok(stdout.includes('I am running when attempt to fix')) + assert.match(stdout, /I am running when attempt to fix/) if (isQuarantined || shouldAlwaysPass || isDisabled) { // even though a test fails, the exit code is 0 because the test is quarantined assert.strictEqual(exitCode, 0) @@ -4383,12 +4417,12 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { if (isDisabling) { assert.strictEqual(testSession.meta[TEST_MANAGEMENT_ENABLED], 'true') } else { - assert.ok(!Object.hasOwn(testSession.meta, TEST_MANAGEMENT_ENABLED)) + assert.ok(!('TEST_MANAGEMENT_ENABLED' in testSession.meta)) } const resourceNames = tests.map(span => span.resource) - assert.includeMembers(resourceNames, + assertObjectContains(resourceNames, [ 'ci-visibility/test-management/test-disabled-1.js.disable tests can disable a test' ] @@ -4398,7 +4432,7 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { // Parallel mode in jest requires more than a single test suite // Here we check that the second test suite is actually running, // so we can be sure that parallel mode is on - assert.includeMembers(resourceNames, [ + assertObjectContains(resourceNames, [ 'ci-visibility/test-management/test-disabled-2.js.disable tests 2 can disable a test' ]) } @@ -4412,7 +4446,7 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { assert.strictEqual(skippedTest.meta[TEST_MANAGEMENT_IS_DISABLED], 'true') } else { assert.strictEqual(skippedTest.meta[TEST_STATUS], 'fail') - assert.ok(!Object.hasOwn(skippedTest.meta, TEST_MANAGEMENT_IS_DISABLED)) + assert.ok(!('TEST_MANAGEMENT_IS_DISABLED' in skippedTest.meta)) } }) @@ -4442,11 +4476,11 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { childProcess.on('exit', exitCode => { testAssertionsPromise.then(() => { if (isDisabling) { - assert.ok(!stdout.includes('I am running')) + assert.doesNotMatch(stdout, /I am running/) // even though a test fails, the exit code is 0 because the test is disabled assert.strictEqual(exitCode, 0) } else { - assert.ok(stdout.includes('I am running')) + assert.match(stdout, /I am running/) assert.strictEqual(exitCode, 1) } done() @@ -4517,12 +4551,12 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { if (isQuarantining) { assert.strictEqual(testSession.meta[TEST_MANAGEMENT_ENABLED], 'true') } else { - assert.ok(!Object.hasOwn(testSession.meta, TEST_MANAGEMENT_ENABLED)) + assert.ok(!('TEST_MANAGEMENT_ENABLED' in testSession.meta)) } const resourceNames = tests.map(span => span.resource) - assert.includeMembers(resourceNames, + assertObjectContains(resourceNames, [ 'ci-visibility/test-management/test-quarantine-1.js.quarantine tests can quarantine a test', 'ci-visibility/test-management/test-quarantine-1.js.quarantine tests can pass normally' @@ -4533,7 +4567,7 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { // Parallel mode in jest requires more than a single test suite // Here we check that the second test suite is actually running, // so we can be sure that parallel mode is on - assert.includeMembers(resourceNames, [ + assertObjectContains(resourceNames, [ 'ci-visibility/test-management/test-quarantine-2.js.quarantine tests 2 can quarantine a test', 'ci-visibility/test-management/test-quarantine-2.js.quarantine tests 2 can pass normally' ]) @@ -4547,7 +4581,7 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { if (isQuarantining) { assert.strictEqual(failedTest.meta[TEST_MANAGEMENT_IS_QUARANTINED], 'true') } else { - assert.ok(!Object.hasOwn(failedTest.meta, TEST_MANAGEMENT_IS_QUARANTINED)) + assert.ok(!('TEST_MANAGEMENT_IS_QUARANTINED' in failedTest.meta)) } }) @@ -4577,7 +4611,7 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { childProcess.on('exit', exitCode => { testAssertionsPromise.then(() => { // it runs regardless of quarantine status - assert.ok(stdout.includes('I am running when quarantined')) + assert.match(stdout, /I am running when quarantined/) if (isQuarantining) { // even though a test fails, the exit code is 0 because the test is quarantined assert.strictEqual(exitCode, 0) @@ -4635,7 +4669,7 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { .gatherPayloadsMaxTimeout(({ url }) => url.endsWith('/api/v2/citestcycle'), (payloads) => { const events = payloads.flatMap(({ payload }) => payload.events) const testSession = events.find(event => event.type === 'test_session_end').content - assert.ok(!Object.hasOwn(testSession.meta, TEST_MANAGEMENT_ENABLED)) + assert.ok(!('TEST_MANAGEMENT_ENABLED' in testSession.meta)) const tests = events.filter(event => event.type === 'test').map(event => event.content) // it is not retried assert.strictEqual(tests.length, 1) @@ -4664,7 +4698,7 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { once(childProcess.stderr, 'end'), eventsPromise ]) - assert.ok(testOutput.includes('Test management tests could not be fetched')) + assert.match(testOutput, /Test management tests could not be fetched/) }) }) @@ -4716,10 +4750,13 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { const events = payloads.flatMap(({ payload }) => payload.events) const test = events.find(event => event.type === 'test').content - assert.ok(test.meta.length > 0) - assert.strictEqual(test.meta['custom_tag.beforeEach'], 'true') - assert.strictEqual(test.meta['custom_tag.it'], 'true') - assert.strictEqual(test.meta['custom_tag.afterEach'], 'true') + assertObjectContains(test, { + meta: { + 'custom_tag.beforeEach': 'true', + 'custom_tag.it': 'true', + 'custom_tag.afterEach': 'true' + } + }) }) childProcess = exec( @@ -4794,12 +4831,12 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { if (isEfd) { assert.strictEqual(testSession.meta[TEST_EARLY_FLAKE_ENABLED], 'true') } else { - assert.ok(!Object.hasOwn(testSession.meta, TEST_EARLY_FLAKE_ENABLED)) + assert.ok(!('TEST_EARLY_FLAKE_ENABLED' in testSession.meta)) } const resourceNames = tests.map(span => span.resource) - assert.includeMembers(resourceNames, + assertObjectContains(resourceNames, [ 'ci-visibility/test-impacted-test/test-impacted-1.js.impacted tests can pass normally', 'ci-visibility/test-impacted-test/test-impacted-1.js.impacted tests can fail' @@ -4810,7 +4847,7 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { // Parallel mode in jest requires more than a single test suite // Here we check that the second test suite is actually running, // so we can be sure that parallel mode is on - assert.includeMembers(resourceNames, [ + assertObjectContains(resourceNames, [ 'ci-visibility/test-impacted-test/test-impacted-2.js.impacted tests 2 can pass normally', 'ci-visibility/test-impacted-test/test-impacted-2.js.impacted tests 2 can fail' ]) @@ -4830,12 +4867,12 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { if (isModified) { assert.strictEqual(impactedTest.meta[TEST_IS_MODIFIED], 'true') } else { - assert.ok(!Object.hasOwn(impactedTest.meta, TEST_IS_MODIFIED)) + assert.ok(!('TEST_IS_MODIFIED' in impactedTest.meta)) } if (isNew) { assert.strictEqual(impactedTest.meta[TEST_IS_NEW], 'true') } else { - assert.ok(!Object.hasOwn(impactedTest.meta, TEST_IS_NEW)) + assert.ok(!('TEST_IS_NEW' in impactedTest.meta)) } } @@ -5048,7 +5085,7 @@ describe(`jest@${JEST_VERSION} commonJS`, () => { assert.strictEqual(tests.every(test => test.meta[TEST_STATUS] === 'pass'), true) }) ]) - assert.ok(!testOutput.includes('Cannot find module')) - assert.ok(testOutput.includes('6 passed')) + assert.doesNotMatch(testOutput, /Cannot find module/) + assert.match(testOutput, /6 passed/) }) }) diff --git a/integration-tests/mocha/mocha.spec.js b/integration-tests/mocha/mocha.spec.js index 75f37a38c35..af50f45e597 100644 --- a/integration-tests/mocha/mocha.spec.js +++ b/integration-tests/mocha/mocha.spec.js @@ -126,7 +126,7 @@ describe(`mocha@${MOCHA_VERSION}`, function () { const testSpans = payload.flatMap(trace => trace) const resourceNames = testSpans.map(span => span.resource) - assert.includeMembers(resourceNames, + assertObjectContains(resourceNames, [ 'ci-visibility/test/ci-visibility-test.js.ci visibility can report tests', 'ci-visibility/test/ci-visibility-test-2.js.ci visibility 2 can report tests 2' @@ -136,10 +136,10 @@ describe(`mocha@${MOCHA_VERSION}`, function () { const areAllTestSpans = testSpans.every(span => span.name === 'mocha.test') assert.strictEqual(areAllTestSpans, true) - assert.ok(testOutput.includes(expectedStdout)) + assert.match(testOutput, new RegExp(expectedStdout)) if (extraStdout) { - assert.ok(testOutput.includes(extraStdout)) + assert.match(testOutput, new RegExp(extraStdout)) } // Can read DD_TAGS testSpans.forEach(testSpan => { @@ -205,7 +205,7 @@ describe(`mocha@${MOCHA_VERSION}`, function () { const resourceNames = tests.map(span => span.resource) - assert.includeMembers(resourceNames, + assertObjectContains(resourceNames, [ 'ci-visibility/test/ci-visibility-test.js.ci visibility can report tests', 'ci-visibility/test/ci-visibility-test-2.js.ci visibility 2 can report tests 2' @@ -216,7 +216,10 @@ describe(`mocha@${MOCHA_VERSION}`, function () { assert.ok(moduleEventContent != null) tests.forEach(testEvent => { - assert.strictEqual(testEvent.meta[TEST_SOURCE_FILE].startsWith('ci-visibility/test/ci-visibility-test'), true) + assert.strictEqual( + testEvent.meta[TEST_SOURCE_FILE].startsWith('ci-visibility/test/ci-visibility-test'), + true + ) assert.ok(testEvent.metrics[TEST_SOURCE_START] != null) assert.strictEqual(testEvent.meta[DD_TEST_IS_USER_PROVIDED_SERVICE], 'false') // Can read DD_TAGS @@ -226,7 +229,10 @@ describe(`mocha@${MOCHA_VERSION}`, function () { }) suites.forEach(testSuite => { - assert.strictEqual(testSuite.meta[TEST_SOURCE_FILE].startsWith('ci-visibility/test/ci-visibility-test'), true) + assert.strictEqual( + testSuite.meta[TEST_SOURCE_FILE].startsWith('ci-visibility/test/ci-visibility-test'), + true + ) assert.strictEqual(testSuite.metrics[TEST_SOURCE_START], 1) assert.ok(testSuite.metrics[DD_HOST_CPU_COUNT] != null) }) @@ -256,8 +262,8 @@ describe(`mocha@${MOCHA_VERSION}`, function () { once(childProcess.stderr, 'end'), once(childProcess, 'exit') ]) - assert.ok(testOutput.includes(expectedStdout)) - assert.ok(testOutput.includes(extraStdout)) + assert.match(testOutput, new RegExp(expectedStdout)) + assert.match(testOutput, new RegExp(extraStdout)) }) it('passing tests', async () => { @@ -273,7 +279,7 @@ describe(`mocha@${MOCHA_VERSION}`, function () { const tests = events.filter(event => event.type === 'test').map(event => event.content) assert.strictEqual(tests.length, 4) - assert.includeMembers(tests.map(test => test.meta[TEST_NAME]), testNames) + assertObjectContains(tests.map(test => test.meta[TEST_NAME]), testNames) tests.forEach(test => { assert.strictEqual(test.parent_id.toString(), '0') @@ -317,7 +323,7 @@ describe(`mocha@${MOCHA_VERSION}`, function () { assert.strictEqual(test.meta[TEST_SUITE], 'ci-visibility/mocha-plugin-tests/failing.js') assert.strictEqual(test.meta[TEST_SOURCE_FILE], 'ci-visibility/mocha-plugin-tests/failing.js') assert.strictEqual(test.meta[ERROR_TYPE], 'AssertionError') - assert.strictEqual(test.meta[ERROR_MESSAGE], 'expected true to equal false') + assert.strictEqual(test.meta[ERROR_MESSAGE], 'Expected values to be strictly equal:\n\ntrue !== false\n') assert.ok(test.metrics[TEST_SOURCE_START] != null) assert.ok(test.meta[ERROR_STACK] != null) assert.strictEqual(test.parent_id.toString(), '0') @@ -353,7 +359,7 @@ describe(`mocha@${MOCHA_VERSION}`, function () { const events = payloads.flatMap(({ payload }) => payload.events) const tests = events.filter(event => event.type === 'test').map(event => event.content) assert.strictEqual(tests.length, 4) - assert.includeMembers(tests.map(test => test.meta[TEST_NAME]), testNames) + assertObjectContains(tests.map(test => test.meta[TEST_NAME]), testNames) tests.forEach(test => { assert.strictEqual(test.parent_id.toString(), '0') @@ -428,7 +434,7 @@ describe(`mocha@${MOCHA_VERSION}`, function () { assert.strictEqual(test.meta[TEST_SUITE], 'ci-visibility/mocha-plugin-tests/done-fail.js') assert.strictEqual(test.meta[TEST_SOURCE_FILE], 'ci-visibility/mocha-plugin-tests/done-fail.js') assert.strictEqual(test.meta[ERROR_TYPE], 'AssertionError') - assert.strictEqual(test.meta[ERROR_MESSAGE], 'expected true to equal false') + assert.strictEqual(test.meta[ERROR_MESSAGE], 'Expected values to be strictly equal:\n\ntrue !== false\n') assert.ok(test.meta[ERROR_STACK] != null) }) @@ -493,7 +499,7 @@ describe(`mocha@${MOCHA_VERSION}`, function () { assert.strictEqual(test.meta[TEST_SUITE], 'ci-visibility/mocha-plugin-tests/promise-fail.js') assert.strictEqual(test.meta[TEST_SOURCE_FILE], 'ci-visibility/mocha-plugin-tests/promise-fail.js') assert.strictEqual(test.meta[ERROR_TYPE], 'AssertionError') - assert.strictEqual(test.meta[ERROR_MESSAGE], 'expected true to equal false') + assert.strictEqual(test.meta[ERROR_MESSAGE], 'Expected values to be strictly equal:\n\ntrue !== false\n') assert.ok(test.meta[ERROR_STACK] != null) }) @@ -558,7 +564,7 @@ describe(`mocha@${MOCHA_VERSION}`, function () { assert.strictEqual(test.meta[TEST_SUITE], 'ci-visibility/mocha-plugin-tests/async-fail.js') assert.strictEqual(test.meta[TEST_SOURCE_FILE], 'ci-visibility/mocha-plugin-tests/async-fail.js') assert.strictEqual(test.meta[ERROR_TYPE], 'AssertionError') - assert.strictEqual(test.meta[ERROR_MESSAGE], 'expected true to equal false') + assert.strictEqual(test.meta[ERROR_MESSAGE], 'Expected values to be strictly equal:\n\ntrue !== false\n') assert.ok(test.meta[ERROR_STACK] != null) }) @@ -592,7 +598,7 @@ describe(`mocha@${MOCHA_VERSION}`, function () { assert.strictEqual(test.meta[TEST_SUITE], 'ci-visibility/mocha-plugin-tests/timeout-fail.js') assert.strictEqual(test.meta[TEST_SOURCE_FILE], 'ci-visibility/mocha-plugin-tests/timeout-fail.js') assert.strictEqual(test.meta[ERROR_TYPE], 'Error') - assert.ok(test.meta[ERROR_MESSAGE].includes('Timeout')) + assert.match(test.meta[ERROR_MESSAGE], /Timeout/) assert.ok(test.meta[ERROR_STACK] != null) }) @@ -736,8 +742,11 @@ describe(`mocha@${MOCHA_VERSION}`, function () { assert.strictEqual(test.meta[COMPONENT], 'mocha') assert.strictEqual(test.meta[TEST_STATUS], 'fail') assert.strictEqual(test.meta[ERROR_TYPE], 'TypeError') - assert.ok(test.meta[ERROR_MESSAGE].includes('mocha-fail-hook-sync "before each" hook for "will not run but be reported as failed":')) - assert.ok(test.meta[ERROR_MESSAGE].includes('Cannot set ')) + assert.ok( + test.meta[ERROR_MESSAGE] + .includes('mocha-fail-hook-sync "before each" hook for "will not run but be reported as failed":') + ) + assert.match(test.meta[ERROR_MESSAGE], /Cannot set /) assert.ok(test.meta[ERROR_STACK] != null) }) @@ -766,7 +775,7 @@ describe(`mocha@${MOCHA_VERSION}`, function () { const events = payloads.flatMap(({ payload }) => payload.events) const tests = events.filter(event => event.type === 'test').map(event => event.content) assert.strictEqual(tests.length, 2) - assert.includeMembers(tests.map(test => test.meta[TEST_NAME]), testNames) + assertObjectContains(tests.map(test => test.meta[TEST_NAME]), testNames) tests.forEach(test => { assert.strictEqual(test.meta[TEST_STATUS], 'pass') @@ -862,7 +871,7 @@ describe(`mocha@${MOCHA_VERSION}`, function () { assert.strictEqual(test.meta[TEST_NAME], 'mocha-test-done-fail can do badly setup failed tests with done') assert.strictEqual(test.meta[TEST_STATUS], 'fail') assert.strictEqual(test.meta[ERROR_TYPE], 'AssertionError') - assert.strictEqual(test.meta[ERROR_MESSAGE], 'expected true to equal false') + assert.strictEqual(test.meta[ERROR_MESSAGE], 'Expected values to be strictly equal:\n\ntrue !== false\n') assert.ok(test.meta[ERROR_STACK] != null) }) @@ -1000,7 +1009,7 @@ describe(`mocha@${MOCHA_VERSION}`, function () { assert.strictEqual(testModuleEvent.meta[TEST_STATUS], 'fail') // Check that all suites have the same session ID - assert.isTrue( + assert.ok( testSuiteEvents.every( suite => suite.test_session_id.toString() === testSessionEvent.test_session_id.toString() ), @@ -1008,7 +1017,7 @@ describe(`mocha@${MOCHA_VERSION}`, function () { ) // Check that all suites have the same module ID - assert.isTrue( + assert.ok( testSuiteEvents.every( suite => suite.test_module_id.toString() === testModuleEvent.test_module_id.toString() ), @@ -1016,11 +1025,14 @@ describe(`mocha@${MOCHA_VERSION}`, function () { ) // Check that all suites have a test_suite_id - assert.strictEqual(testSuiteEvents.every(suite => suite.test_suite_id !== undefined), - 'All suites should have a test_suite_id', true) + assert.strictEqual( + testSuiteEvents.every(suite => suite.test_suite_id !== undefined), + true, + 'All suites should have a test_suite_id' + ) // Check that all suites match expected suite names - assert.isTrue( + assert.ok( testSuiteEvents.every(suite => suites.includes(suite.meta[TEST_SUITE])), 'All suites should match expected suite names' ) @@ -1030,8 +1042,10 @@ describe(`mocha@${MOCHA_VERSION}`, function () { assert.strictEqual(passedSuites.length, 1, 'Should have 1 passing suite') assert.strictEqual(failedSuites.length, 3, 'Should have 3 failing suites') - assert.strictEqual(failedSuites.every(suite => suite.meta[ERROR_MESSAGE] !== undefined), - 'All failed suites should have an error message', true) + assert.ok( + failedSuites.every(suite => suite.meta[ERROR_MESSAGE] !== undefined), + 'All failed suites should have an error message' + ) }) childProcess = exec( @@ -1077,7 +1091,7 @@ describe(`mocha@${MOCHA_VERSION}`, function () { testOutput += chunk.toString() }) childProcess.on('message', () => { - assert.ok(testOutput.includes(expectedStdout)) + assert.match(testOutput, new RegExp(expectedStdout)) done() }) }) @@ -1091,10 +1105,13 @@ describe(`mocha@${MOCHA_VERSION}`, function () { const events = payloads.flatMap(({ payload }) => payload.events) const test = events.find(event => event.type === 'test').content - assert.ok(test.meta.length > 0) - assert.strictEqual(test.meta['custom_tag.beforeEach'], 'true') - assert.strictEqual(test.meta['custom_tag.it'], 'true') - assert.strictEqual(test.meta['custom_tag.afterEach'], 'true') + assertObjectContains(test, { + meta: { + 'custom_tag.beforeEach': 'true', + 'custom_tag.it': 'true', + 'custom_tag.afterEach': 'true' + } + }) }) childProcess = exec( @@ -1136,9 +1153,9 @@ describe(`mocha@${MOCHA_VERSION}`, function () { testOutput += chunk.toString() }) childProcess.on('message', () => { - assert.ok(!testOutput.includes('TypeError')) - assert.ok(!testOutput.includes('Uncaught error outside test suite')) - assert.ok(testOutput.includes(expectedStdout)) + assert.doesNotMatch(testOutput, /TypeError/) + assert.doesNotMatch(testOutput, /Uncaught error outside test suite/) + assert.match(testOutput, new RegExp(expectedStdout)) done() }) }) @@ -1203,8 +1220,8 @@ describe(`mocha@${MOCHA_VERSION}`, function () { testOutput += chunk.toString() }) childProcess.on('exit', () => { - assert.ok(testOutput.includes('Invalid URL')) - assert.ok(testOutput.includes('1 passing')) // we only run one file here + assert.match(testOutput, /Invalid URL/) + assert.match(testOutput, /1 passing/) // we only run one file here done() }) }) @@ -1227,7 +1244,10 @@ describe(`mocha@${MOCHA_VERSION}`, function () { const tests = events.filter(event => event.type === 'test').map(event => event.content) assert.strictEqual(sessionEventContent.meta[MOCHA_IS_PARALLEL], 'true') - assert.strictEqual(sessionEventContent.test_session_id.toString(10), moduleEventContent.test_session_id.toString(10)) + assert.strictEqual( + sessionEventContent.test_session_id.toString(10), + moduleEventContent.test_session_id.toString(10) + ) suites.forEach(({ meta, test_suite_id: testSuiteId, @@ -1277,7 +1297,7 @@ describe(`mocha@${MOCHA_VERSION}`, function () { }) childProcess.on('message', () => { eventsPromise.then(() => { - assert.ok(!testOutput.includes('TypeError')) + assert.doesNotMatch(testOutput, /TypeError/) done() }).catch(done) }) @@ -1310,7 +1330,7 @@ describe(`mocha@${MOCHA_VERSION}`, function () { }) childProcess.on('exit', () => { eventsPromise.then(() => { - assert.ok(!testOutput.includes('TypeError')) + assert.doesNotMatch(testOutput, /TypeError/) done() }).catch(done) }) @@ -1329,7 +1349,7 @@ describe(`mocha@${MOCHA_VERSION}`, function () { testOutput += chunk.toString() }) childProcess.on('exit', (code) => { - assert.ok(testOutput.includes('result 7')) + assert.match(testOutput, /result 7/) assert.strictEqual(code, 0) done() }) @@ -1342,7 +1362,7 @@ describe(`mocha@${MOCHA_VERSION}`, function () { const testSession = events.find(event => event.type === 'test_session_end').content assert.strictEqual(testSession.meta[TEST_STATUS], 'fail') const errorMessage = 'Failed tests: 1' - assert.ok(testSession.meta[ERROR_MESSAGE].includes(errorMessage)) + assert.match(testSession.meta[ERROR_MESSAGE], new RegExp(errorMessage)) }) childProcess = exec( @@ -1385,10 +1405,11 @@ describe(`mocha@${MOCHA_VERSION}`, function () { testOutput += chunk.toString() }) childProcess.on('message', () => { - assert.ok(testOutput.includes(expectedStdout)) - assert.ok(testOutput.includes('DD_CIVISIBILITY_AGENTLESS_ENABLED is set, ' + - 'but neither DD_API_KEY nor DATADOG_API_KEY are set in your environment, ' + - 'so dd-trace will not be initialized.')) + assert.match(testOutput, new RegExp(expectedStdout)) + assert.match( + testOutput, + /DD_CIVISIBILITY_AGENTLESS_ENABLED is set, but neither DD_API_KEY nor DATADOG_API_KEY are set in your environment, so dd-trace will not be initialized./ + ) done() }) }) @@ -1409,7 +1430,7 @@ describe(`mocha@${MOCHA_VERSION}`, function () { assert.strictEqual(packfileRequest.headers['dd-api-key'], '1') const eventTypes = eventsRequest.payload.events.map(event => event.type) - assert.includeMembers(eventTypes, ['test', 'test_suite_end', 'test_module_end', 'test_session_end']) + assertObjectContains(eventTypes, ['test', 'test_session_end', 'test_module_end', 'test_suite_end']) const numSuites = eventTypes.reduce( (acc, type) => type === 'test_suite_end' ? acc + 1 : acc, 0 ) @@ -1451,7 +1472,7 @@ describe(`mocha@${MOCHA_VERSION}`, function () { const testSpans = payload.flatMap(trace => trace) const resourceNames = testSpans.map(span => span.resource) - assert.includeMembers(resourceNames, + assertObjectContains(resourceNames, [ 'ci-visibility/test/ci-visibility-test.js.ci visibility can report tests', 'ci-visibility/test/ci-visibility-test-2.js.ci visibility 2 can report tests 2' @@ -1482,27 +1503,34 @@ describe(`mocha@${MOCHA_VERSION}`, function () { ]).then(([libraryConfigRequest, codeCovRequest, eventsRequest]) => { assert.strictEqual(libraryConfigRequest.headers['dd-api-key'], '1') - const [coveragePayload] = codeCovRequest.payload - assert.strictEqual(codeCovRequest.headers['dd-api-key'], '1') + assertObjectContains(codeCovRequest, { + headers: { + 'dd-api-key': '1' + }, + payload: [{ + name: 'coverage1', + filename: 'coverage1.msgpack', + type: 'application/msgpack', + content: { + version: 2 + } + }] + }) - assert.strictEqual(coveragePayload.name, 'coverage1') - assert.strictEqual(coveragePayload.filename, 'coverage1.msgpack') - assert.strictEqual(coveragePayload.type, 'application/msgpack') - assert.ok(coveragePayload.content.includes({ - version: 2 - })) const allCoverageFiles = codeCovRequest.payload .flatMap(coverage => coverage.content.coverages) .flatMap(file => file.files) .map(file => file.filename) - assert.includeMembers(allCoverageFiles, + assertObjectContains(allCoverageFiles, [ 'ci-visibility/test/sum.js', 'ci-visibility/test/ci-visibility-test.js', 'ci-visibility/test/ci-visibility-test-2.js' ] ) + + const [coveragePayload] = codeCovRequest.payload assert.ok(coveragePayload.content.coverages[0].test_session_id != null) assert.ok(coveragePayload.content.coverages[0].test_suite_id != null) @@ -1510,7 +1538,7 @@ describe(`mocha@${MOCHA_VERSION}`, function () { assert.ok(testSession.metrics[TEST_CODE_COVERAGE_LINES_PCT] != null) const eventTypes = eventsRequest.payload.events.map(event => event.type) - assert.includeMembers(eventTypes, ['test', 'test_suite_end', 'test_module_end', 'test_session_end']) + assertObjectContains(eventTypes, ['test', 'test_session_end', 'test_module_end', 'test_suite_end']) const numSuites = eventTypes.reduce( (acc, type) => type === 'test_suite_end' ? acc + 1 : acc, 0 ) @@ -1530,7 +1558,7 @@ describe(`mocha@${MOCHA_VERSION}`, function () { }) childProcess.on('exit', () => { // coverage report - assert.ok(testOutput.includes('Lines ')) + assert.match(testOutput, /Lines {7}/) done() }) }) @@ -1550,7 +1578,7 @@ describe(`mocha@${MOCHA_VERSION}`, function () { receiver.assertPayloadReceived(({ headers, payload }) => { assert.strictEqual(headers['dd-api-key'], '1') const eventTypes = payload.events.map(event => event.type) - assert.includeMembers(eventTypes, ['test', 'test_session_end', 'test_module_end', 'test_suite_end']) + assertObjectContains(eventTypes, ['test', 'test_session_end', 'test_module_end', 'test_suite_end']) const testSession = payload.events.find(event => event.type === 'test_session_end').content assert.strictEqual(testSession.meta[TEST_ITR_TESTS_SKIPPED], 'false') assert.strictEqual(testSession.meta[TEST_CODE_COVERAGE_ENABLED], 'false') @@ -1604,7 +1632,7 @@ describe(`mocha@${MOCHA_VERSION}`, function () { assert.strictEqual(skippedSuite.meta[TEST_STATUS], 'skip') assert.strictEqual(skippedSuite.meta[TEST_SKIPPED_BY_ITR], 'true') - assert.includeMembers(eventTypes, ['test', 'test_suite_end', 'test_module_end', 'test_session_end']) + assertObjectContains(eventTypes, ['test', 'test_session_end', 'test_module_end', 'test_suite_end']) const numSuites = eventTypes.reduce( (acc, type) => type === 'test_suite_end' ? acc + 1 : acc, 0 ) @@ -1692,7 +1720,7 @@ describe(`mocha@${MOCHA_VERSION}`, function () { assert.strictEqual(headers['dd-api-key'], '1') const eventTypes = payload.events.map(event => event.type) // because they are not skipped - assert.includeMembers(eventTypes, ['test', 'test_suite_end', 'test_module_end', 'test_session_end']) + assertObjectContains(eventTypes, ['test', 'test_session_end', 'test_module_end', 'test_suite_end']) const numSuites = eventTypes.reduce( (acc, type) => type === 'test_suite_end' ? acc + 1 : acc, 0 ) @@ -1740,7 +1768,7 @@ describe(`mocha@${MOCHA_VERSION}`, function () { assert.strictEqual(headers['dd-api-key'], '1') const eventTypes = payload.events.map(event => event.type) // because they are not skipped - assert.includeMembers(eventTypes, ['test', 'test_suite_end', 'test_module_end', 'test_session_end']) + assertObjectContains(eventTypes, ['test', 'test_session_end', 'test_module_end', 'test_suite_end']) const numSuites = eventTypes.reduce( (acc, type) => type === 'test_suite_end' ? acc + 1 : acc, 0 ) @@ -1798,12 +1826,12 @@ describe(`mocha@${MOCHA_VERSION}`, function () { ) // It does not mark as unskippable if there is no docblock assert.strictEqual(passedSuite.content.meta[TEST_STATUS], 'pass') - assert.ok(!Object.hasOwn(passedSuite.content.meta, TEST_ITR_UNSKIPPABLE)) - assert.ok(!Object.hasOwn(passedSuite.content.meta, TEST_ITR_FORCED_RUN)) + assert.ok(!('TEST_ITR_UNSKIPPABLE' in passedSuite.content.meta)) + assert.ok(!('TEST_ITR_FORCED_RUN' in passedSuite.content.meta)) assert.strictEqual(skippedSuite.content.meta[TEST_STATUS], 'skip') - assert.ok(!Object.hasOwn(skippedSuite.content.meta, TEST_ITR_UNSKIPPABLE)) - assert.ok(!Object.hasOwn(skippedSuite.content.meta, TEST_ITR_FORCED_RUN)) + assert.ok(!('TEST_ITR_UNSKIPPABLE' in skippedSuite.content.meta)) + assert.ok(!('TEST_ITR_FORCED_RUN' in skippedSuite.content.meta)) assert.strictEqual(forcedToRunSuite.content.meta[TEST_STATUS], 'pass') assert.strictEqual(forcedToRunSuite.content.meta[TEST_ITR_UNSKIPPABLE], 'true') @@ -1852,9 +1880,9 @@ describe(`mocha@${MOCHA_VERSION}`, function () { const testSession = events.find(event => event.type === 'test_session_end').content const testModule = events.find(event => event.type === 'test_module_end').content - assert.ok(!Object.hasOwn(testSession.meta, TEST_ITR_FORCED_RUN)) + assert.ok(!('TEST_ITR_FORCED_RUN' in testSession.meta)) assert.strictEqual(testSession.meta[TEST_ITR_UNSKIPPABLE], 'true') - assert.ok(!Object.hasOwn(testModule.meta, TEST_ITR_FORCED_RUN)) + assert.ok(!('TEST_ITR_FORCED_RUN' in testModule.meta)) assert.strictEqual(testModule.meta[TEST_ITR_UNSKIPPABLE], 'true') const passedSuite = suites.find( @@ -1869,15 +1897,15 @@ describe(`mocha@${MOCHA_VERSION}`, function () { // It does not mark as unskippable if there is no docblock assert.strictEqual(passedSuite.content.meta[TEST_STATUS], 'pass') - assert.ok(!Object.hasOwn(passedSuite.content.meta, TEST_ITR_UNSKIPPABLE)) - assert.ok(!Object.hasOwn(passedSuite.content.meta, TEST_ITR_FORCED_RUN)) + assert.ok(!('TEST_ITR_UNSKIPPABLE' in passedSuite.content.meta)) + assert.ok(!('TEST_ITR_FORCED_RUN' in passedSuite.content.meta)) assert.strictEqual(skippedSuite.meta[TEST_STATUS], 'skip') assert.strictEqual(nonSkippedSuite.meta[TEST_STATUS], 'pass') assert.strictEqual(nonSkippedSuite.meta[TEST_ITR_UNSKIPPABLE], 'true') // it was not forced to run because it wasn't going to be skipped - assert.ok(!Object.hasOwn(nonSkippedSuite.meta, TEST_ITR_FORCED_RUN)) + assert.ok(!('TEST_ITR_FORCED_RUN' in nonSkippedSuite.meta)) }, 25000) childProcess = exec( @@ -1979,7 +2007,7 @@ describe(`mocha@${MOCHA_VERSION}`, function () { .flatMap(({ files }) => files) .map(({ filename }) => filename) - assert.includeMembers(coveredFiles, [ + assertObjectContains(coveredFiles, [ 'ci-visibility/subproject/dependency.js', 'ci-visibility/subproject/subproject-test.js' ]) @@ -2037,7 +2065,7 @@ describe(`mocha@${MOCHA_VERSION}`, function () { test.meta[TEST_SUITE] === 'ci-visibility/test/ci-visibility-test.js' ) oldTests.forEach(test => { - assert.ok(!Object.hasOwn(test.meta, TEST_IS_NEW)) + assert.ok(!('TEST_IS_NEW' in test.meta)) }) assert.strictEqual(oldTests.length, 1) @@ -2126,9 +2154,15 @@ describe(`mocha@${MOCHA_VERSION}`, function () { assert.strictEqual(testsForFirstParameter.length, testsForSecondParameter.length) // all but one have been retried - assert.strictEqual(testsForFirstParameter.length - 1, testsForFirstParameter.filter(test => test.meta[TEST_IS_RETRY] === 'true').length) + assert.strictEqual( + testsForFirstParameter.length - 1, + testsForFirstParameter.filter(test => test.meta[TEST_IS_RETRY] === 'true').length + ) - assert.strictEqual(testsForSecondParameter.length - 1, testsForSecondParameter.filter(test => test.meta[TEST_IS_RETRY] === 'true').length) + assert.strictEqual( + testsForSecondParameter.length - 1, + testsForSecondParameter.filter(test => test.meta[TEST_IS_RETRY] === 'true').length + ) }) childProcess = exec( @@ -2174,7 +2208,7 @@ describe(`mocha@${MOCHA_VERSION}`, function () { .gatherPayloadsMaxTimeout(({ url }) => url.endsWith('/api/v2/citestcycle'), (payloads) => { const events = payloads.flatMap(({ payload }) => payload.events) const testSession = events.find(event => event.type === 'test_session_end').content - assert.ok(!Object.hasOwn(testSession.meta, TEST_EARLY_FLAKE_ENABLED)) + assert.ok(!('TEST_EARLY_FLAKE_ENABLED' in testSession.meta)) const tests = events.filter(event => event.type === 'test').map(event => event.content) const newTests = tests.filter(test => @@ -2308,7 +2342,7 @@ describe(`mocha@${MOCHA_VERSION}`, function () { test => test.meta[TEST_NAME] === 'ci visibility skip will not be retried' ) assert.strictEqual(newSkippedTests.length, 1) - assert.ok(!Object.hasOwn(newSkippedTests[0].meta, TEST_IS_RETRY)) + assert.ok(!('TEST_IS_RETRY' in newSkippedTests[0].meta)) }) childProcess = exec( @@ -2362,7 +2396,7 @@ describe(`mocha@${MOCHA_VERSION}`, function () { const resourceNames = tests.map(test => test.resource) - assert.includeMembers(resourceNames, + assertObjectContains(resourceNames, [ 'ci-visibility/test-early-flake-detection/weird-test-names.js.no describe can do stuff', 'ci-visibility/test-early-flake-detection/weird-test-names.js.describe trailing space ' @@ -2416,7 +2450,7 @@ describe(`mocha@${MOCHA_VERSION}`, function () { const events = payloads.flatMap(({ payload }) => payload.events) const testSession = events.find(event => event.type === 'test_session_end').content - assert.ok(!Object.hasOwn(testSession.meta, TEST_EARLY_FLAKE_ENABLED)) + assert.ok(!('TEST_EARLY_FLAKE_ENABLED' in testSession.meta)) const tests = events.filter(event => event.type === 'test').map(event => event.content) @@ -2510,8 +2544,8 @@ describe(`mocha@${MOCHA_VERSION}`, function () { }) childProcess.on('exit', (exitCode) => { - assert.ok(testOutput.includes('2 passing')) - assert.ok(testOutput.includes('2 failing')) + assert.match(testOutput, /2 passing/) + assert.match(testOutput, /2 failing/) assert.strictEqual(exitCode, 0) eventsPromise.then(() => { done() @@ -2544,7 +2578,7 @@ describe(`mocha@${MOCHA_VERSION}`, function () { const events = payloads.flatMap(({ payload }) => payload.events) const testSession = events.find(event => event.type === 'test_session_end').content - assert.ok(!Object.hasOwn(testSession.meta, TEST_EARLY_FLAKE_ENABLED)) + assert.ok(!('TEST_EARLY_FLAKE_ENABLED' in testSession.meta)) assert.strictEqual(testSession.meta[TEST_EARLY_FLAKE_ABORT_REASON], 'faulty') const tests = events.filter(event => event.type === 'test').map(event => event.content) @@ -2734,7 +2768,7 @@ describe(`mocha@${MOCHA_VERSION}`, function () { const events = payloads.flatMap(({ payload }) => payload.events) const testSession = events.find(event => event.type === 'test_session_end').content - assert.ok(!Object.hasOwn(testSession.meta, TEST_EARLY_FLAKE_ENABLED)) + assert.ok(!('TEST_EARLY_FLAKE_ENABLED' in testSession.meta)) assert.strictEqual(testSession.meta[TEST_EARLY_FLAKE_ABORT_REASON], 'faulty') const tests = events.filter(event => event.type === 'test').map(event => event.content) @@ -2794,7 +2828,7 @@ describe(`mocha@${MOCHA_VERSION}`, function () { const events = payloads.flatMap(({ payload }) => payload.events) const testSession = events.find(event => event.type === 'test_session_end').content - assert.ok(!Object.hasOwn(testSession.meta, TEST_EARLY_FLAKE_ENABLED)) + assert.ok(!('TEST_EARLY_FLAKE_ENABLED' in testSession.meta)) const tests = events.filter(event => event.type === 'test').map(event => event.content) @@ -2850,7 +2884,7 @@ describe(`mocha@${MOCHA_VERSION}`, function () { const events = payloads.flatMap(({ payload }) => payload.events) const testSession = events.find(event => event.type === 'test_session_end').content - assert.ok(!Object.hasOwn(testSession.meta, TEST_EARLY_FLAKE_ENABLED)) + assert.ok(!('TEST_EARLY_FLAKE_ENABLED' in testSession.meta)) const tests = events.filter(event => event.type === 'test').map(event => event.content) @@ -2858,14 +2892,14 @@ describe(`mocha@${MOCHA_VERSION}`, function () { test.meta[TEST_SUITE] === 'ci-visibility/test/ci-visibility-test.js' ) oldTests.forEach(test => { - assert.ok(!Object.hasOwn(test.meta, TEST_IS_NEW)) + assert.ok(!('TEST_IS_NEW' in test.meta)) }) assert.strictEqual(oldTests.length, 1) const newTests = tests.filter(test => test.meta[TEST_SUITE] === 'ci-visibility/test/ci-visibility-test-2.js' ) newTests.forEach(test => { - assert.ok(!Object.hasOwn(test.meta, TEST_IS_NEW)) + assert.ok(!('TEST_IS_NEW' in test.meta)) }) const retriedTests = newTests.filter(test => test.meta[TEST_IS_RETRY] === 'true') assert.strictEqual(retriedTests.length, 0) @@ -2932,7 +2966,10 @@ describe(`mocha@${MOCHA_VERSION}`, function () { assert.strictEqual(failedAttempts.length, 2) failedAttempts.forEach((failedTest, index) => { - assert.ok(failedTest.meta[ERROR_MESSAGE].includes(`expected ${index + 1} to equal 3`)) + assert.match( + failedTest.meta[ERROR_MESSAGE], + new RegExp(`Expected values to be strictly equal:\n\n${index + 1} !== 3`) + ) }) // The first attempt is not marked as a retry @@ -3273,7 +3310,7 @@ describe(`mocha@${MOCHA_VERSION}`, function () { const notRetriedTest = tests.find(test => test.meta[TEST_NAME].includes('is not retried')) - assert.ok(!Object.hasOwn(notRetriedTest.meta, DI_ERROR_DEBUG_INFO_CAPTURED)) + assert.ok(!('DI_ERROR_DEBUG_INFO_CAPTURED' in notRetriedTest.meta)) }) const logsPromise = receiver @@ -3284,7 +3321,7 @@ describe(`mocha@${MOCHA_VERSION}`, function () { level: 'error' }) assert.strictEqual(diLog.debugger.snapshot.language, 'javascript') - assert.deepInclude(diLog.debugger.snapshot.captures.lines['6'].locals, { + assertObjectContains(diLog.debugger.snapshot.captures.lines['6'].locals, { a: { type: 'number', value: '11' @@ -3402,7 +3439,7 @@ describe(`mocha@${MOCHA_VERSION}`, function () { const events = payloads.flatMap(({ payload }) => payload.events) const testSession = events.find(event => event.type === 'test_session_end').content - assert.ok(!Object.hasOwn(testSession.meta, TEST_EARLY_FLAKE_ENABLED)) + assert.ok(!('TEST_EARLY_FLAKE_ENABLED' in testSession.meta)) const tests = events.filter(event => event.type === 'test').map(event => event.content) @@ -3411,7 +3448,7 @@ describe(`mocha@${MOCHA_VERSION}`, function () { test.meta[TEST_SUITE] === 'ci-visibility/test/ci-visibility-test.js' ) oldTests.forEach(test => { - assert.ok(!Object.hasOwn(test.meta, TEST_IS_NEW)) + assert.ok(!('TEST_IS_NEW' in test.meta)) }) assert.strictEqual(oldTests.length, 1) @@ -3519,12 +3556,12 @@ describe(`mocha@${MOCHA_VERSION}`, function () { if (isAttemptToFix) { assert.strictEqual(testSession.meta[TEST_MANAGEMENT_ENABLED], 'true') } else { - assert.ok(!Object.hasOwn(testSession.meta, TEST_MANAGEMENT_ENABLED)) + assert.ok(!('TEST_MANAGEMENT_ENABLED' in testSession.meta)) } const resourceNames = tests.map(span => span.resource) - assert.includeMembers(resourceNames, + assertObjectContains(resourceNames, [ 'ci-visibility/test-management/test-attempt-to-fix-1.js.attempt to fix tests can attempt to fix a test' ] @@ -3539,16 +3576,16 @@ describe(`mocha@${MOCHA_VERSION}`, function () { const isFirstAttempt = i === 0 const isLastAttempt = i === retriedTests.length - 1 if (!isAttemptToFix) { - assert.ok(!Object.hasOwn(test.meta, TEST_MANAGEMENT_IS_ATTEMPT_TO_FIX)) - assert.ok(!Object.hasOwn(test.meta, TEST_IS_RETRY)) - assert.ok(!Object.hasOwn(test.meta, TEST_RETRY_REASON)) + assert.ok(!('TEST_MANAGEMENT_IS_ATTEMPT_TO_FIX' in test.meta)) + assert.ok(!('TEST_IS_RETRY' in test.meta)) + assert.ok(!('TEST_RETRY_REASON' in test.meta)) continue } assert.strictEqual(test.meta[TEST_MANAGEMENT_IS_ATTEMPT_TO_FIX], 'true') if (isFirstAttempt) { - assert.ok(!Object.hasOwn(test.meta, TEST_IS_RETRY)) - assert.ok(!Object.hasOwn(test.meta, TEST_RETRY_REASON)) + assert.ok(!('TEST_IS_RETRY' in test.meta)) + assert.ok(!('TEST_RETRY_REASON' in test.meta)) } else { assert.strictEqual(test.meta[TEST_IS_RETRY], 'true') assert.strictEqual(test.meta[TEST_RETRY_REASON], TEST_RETRY_REASON_TYPES.atf) @@ -3565,9 +3602,9 @@ describe(`mocha@${MOCHA_VERSION}`, function () { if (isLastAttempt) { if (shouldAlwaysPass) { assert.strictEqual(test.meta[TEST_MANAGEMENT_ATTEMPT_TO_FIX_PASSED], 'true') - assert.ok(!Object.hasOwn(test.meta, TEST_HAS_FAILED_ALL_RETRIES)) + assert.ok(!('TEST_HAS_FAILED_ALL_RETRIES' in test.meta)) } else if (shouldFailSometimes) { - assert.ok(!Object.hasOwn(test.meta, TEST_HAS_FAILED_ALL_RETRIES)) + assert.ok(!('TEST_HAS_FAILED_ALL_RETRIES' in test.meta)) assert.strictEqual(test.meta[TEST_MANAGEMENT_ATTEMPT_TO_FIX_PASSED], 'false') } else { assert.strictEqual(test.meta[TEST_HAS_FAILED_ALL_RETRIES], 'true') @@ -3618,7 +3655,7 @@ describe(`mocha@${MOCHA_VERSION}`, function () { childProcess.on('exit', exitCode => { testAssertionsPromise.then(() => { - assert.ok(stdout.includes('I am running when attempt to fix')) + assert.match(stdout, /I am running when attempt to fix/) if (shouldAlwaysPass || isQuarantined || isDisabled) { // even though a test fails, the exit code is 0 because the test is quarantined or disabled assert.strictEqual(exitCode, 0) @@ -3734,12 +3771,12 @@ describe(`mocha@${MOCHA_VERSION}`, function () { if (isDisabling) { assert.strictEqual(testSession.meta[TEST_MANAGEMENT_ENABLED], 'true') } else { - assert.ok(!Object.hasOwn(testSession.meta, TEST_MANAGEMENT_ENABLED)) + assert.ok(!('TEST_MANAGEMENT_ENABLED' in testSession.meta)) } const resourceNames = tests.map(span => span.resource) - assert.includeMembers(resourceNames, + assertObjectContains(resourceNames, [ 'ci-visibility/test-management/test-disabled-1.js.disable tests can disable a test' ] @@ -3754,7 +3791,7 @@ describe(`mocha@${MOCHA_VERSION}`, function () { assert.strictEqual(skippedTests.meta[TEST_MANAGEMENT_IS_DISABLED], 'true') } else { assert.strictEqual(skippedTests.meta[TEST_STATUS], 'fail') - assert.ok(!Object.hasOwn(skippedTests.meta, TEST_MANAGEMENT_IS_DISABLED)) + assert.ok(!('TEST_MANAGEMENT_IS_DISABLED' in skippedTests.meta)) } }) @@ -3785,10 +3822,10 @@ describe(`mocha@${MOCHA_VERSION}`, function () { childProcess.on('exit', (exitCode) => { testAssertionsPromise.then(() => { if (isDisabling) { - assert.ok(!stdout.includes('I am running')) + assert.doesNotMatch(stdout, /I am running/) assert.strictEqual(exitCode, 0) } else { - assert.ok(stdout.includes('I am running')) + assert.match(stdout, /I am running/) assert.strictEqual(exitCode, 1) } done() @@ -3858,12 +3895,12 @@ describe(`mocha@${MOCHA_VERSION}`, function () { if (isQuarantining) { assert.strictEqual(testSession.meta[TEST_MANAGEMENT_ENABLED], 'true') } else { - assert.ok(!Object.hasOwn(testSession.meta, TEST_MANAGEMENT_ENABLED)) + assert.ok(!('TEST_MANAGEMENT_ENABLED' in testSession.meta)) } const resourceNames = tests.map(span => span.resource) - assert.includeMembers(resourceNames, + assertObjectContains(resourceNames, [ 'ci-visibility/test-management/test-quarantine-1.js.quarantine tests can quarantine a test', 'ci-visibility/test-management/test-quarantine-1.js.quarantine tests can pass normally' @@ -3879,7 +3916,7 @@ describe(`mocha@${MOCHA_VERSION}`, function () { if (isQuarantining) { assert.strictEqual(failedTest.meta[TEST_MANAGEMENT_IS_QUARANTINED], 'true') } else { - assert.ok(!Object.hasOwn(failedTest.meta, TEST_MANAGEMENT_IS_QUARANTINED)) + assert.ok(!('TEST_MANAGEMENT_IS_QUARANTINED' in failedTest.meta)) } }) @@ -3910,7 +3947,7 @@ describe(`mocha@${MOCHA_VERSION}`, function () { childProcess.on('exit', (exitCode) => { testAssertionsPromise.then(() => { // it runs regardless of the quarantine status - assert.ok(stdout.includes('I am running when quarantined')) + assert.match(stdout, /I am running when quarantined/) if (isQuarantining) { assert.strictEqual(exitCode, 0) } else { @@ -3966,7 +4003,7 @@ describe(`mocha@${MOCHA_VERSION}`, function () { .gatherPayloadsMaxTimeout(({ url }) => url.endsWith('/api/v2/citestcycle'), (payloads) => { const events = payloads.flatMap(({ payload }) => payload.events) const testSession = events.find(event => event.type === 'test_session_end').content - assert.ok(!Object.hasOwn(testSession.meta, TEST_MANAGEMENT_ENABLED)) + assert.ok(!('TEST_MANAGEMENT_ENABLED' in testSession.meta)) const tests = events.filter(event => event.type === 'test').map(event => event.content) // it is not retried assert.strictEqual(tests.length, 1) @@ -4000,7 +4037,7 @@ describe(`mocha@${MOCHA_VERSION}`, function () { once(childProcess.stderr, 'end'), eventsPromise ]) - assert.ok(testOutput.includes('Test management tests could not be fetched')) + assert.match(testOutput, /Test management tests could not be fetched/) }) }) @@ -4068,14 +4105,14 @@ describe(`mocha@${MOCHA_VERSION}`, function () { assert.strictEqual(tests.length, 2) - assert.includeMembers(tests.map(test => test.meta[TEST_STATUS]), [ + assertObjectContains(tests.map(test => test.meta[TEST_STATUS]), [ 'pass', 'pass' ]) - assert.includeMembers(tests.map(test => test.resource), [ + assertObjectContains(tests.map(test => test.resource), [ + 'ci-visibility/test-nested-hooks/test-nested-hooks.js.describe is not nested', 'ci-visibility/test-nested-hooks/test-nested-hooks.js.describe context nested test with retries', - 'ci-visibility/test-nested-hooks/test-nested-hooks.js.describe is not nested' ]) }) @@ -4103,11 +4140,11 @@ describe(`mocha@${MOCHA_VERSION}`, function () { eventsPromise ]) - assert.ok(stdout.includes('beforeEach')) - assert.ok(stdout.includes('beforeEach in context')) - assert.ok(stdout.includes('test')) - assert.ok(stdout.includes('afterEach')) - assert.ok(stdout.includes('afterEach in context')) + assert.match(stdout, /beforeEach/) + assert.match(stdout, /beforeEach in context/) + assert.match(stdout, /test/) + assert.match(stdout, /afterEach/) + assert.match(stdout, /afterEach in context/) }) onlyLatestIt('works when tests are retried', async () => { @@ -4118,15 +4155,16 @@ describe(`mocha@${MOCHA_VERSION}`, function () { assert.strictEqual(tests.length, 3) - assert.includeMembers(tests.map(test => test.meta[TEST_STATUS]), [ + assert.deepStrictEqual(tests.map(test => test.meta[TEST_STATUS]), [ 'fail', 'pass', 'pass' ]) - assert.includeMembers(tests.map(test => test.resource), [ + assert.deepStrictEqual(tests.map(test => test.resource), [ + 'ci-visibility/test-nested-hooks/test-nested-hooks.js.describe is not nested', + 'ci-visibility/test-nested-hooks/test-nested-hooks.js.describe is not nested', 'ci-visibility/test-nested-hooks/test-nested-hooks.js.describe context nested test with retries', - 'ci-visibility/test-nested-hooks/test-nested-hooks.js.describe is not nested' ]) const retriedTests = tests.filter(test => test.meta[TEST_IS_RETRY] === 'true') @@ -4169,11 +4207,11 @@ describe(`mocha@${MOCHA_VERSION}`, function () { eventsPromise ]) - assert.ok(stdout.includes('beforeEach')) - assert.ok(stdout.includes('beforeEach in context')) - assert.ok(stdout.includes('test')) - assert.ok(stdout.includes('afterEach')) - assert.ok(stdout.includes('afterEach in context')) + assert.match(stdout, /beforeEach/) + assert.match(stdout, /beforeEach in context/) + assert.match(stdout, /test/) + assert.match(stdout, /afterEach/) + assert.match(stdout, /afterEach in context/) }) }) @@ -4225,12 +4263,12 @@ describe(`mocha@${MOCHA_VERSION}`, function () { if (isEfd) { assert.strictEqual(testSession.meta[TEST_EARLY_FLAKE_ENABLED], 'true') } else { - assert.ok(!Object.hasOwn(testSession.meta, TEST_EARLY_FLAKE_ENABLED)) + assert.ok(!('TEST_EARLY_FLAKE_ENABLED' in testSession.meta)) } const resourceNames = tests.map(span => span.resource) - assert.includeMembers(resourceNames, + assertObjectContains(resourceNames, [ 'ci-visibility/test-impacted-test/test-impacted-1.js.impacted tests can pass normally', 'ci-visibility/test-impacted-test/test-impacted-1.js.impacted tests can fail' @@ -4241,7 +4279,7 @@ describe(`mocha@${MOCHA_VERSION}`, function () { // Parallel mode in mocha requires more than a single test suite // Here we check that the second test suite is actually running, // so we can be sure that parallel mode is on - assert.includeMembers(resourceNames, [ + assertObjectContains(resourceNames, [ 'ci-visibility/test-impacted-test/test-impacted-2.js.impacted tests 2 can pass normally', 'ci-visibility/test-impacted-test/test-impacted-2.js.impacted tests 2 can fail' ]) @@ -4261,12 +4299,12 @@ describe(`mocha@${MOCHA_VERSION}`, function () { if (isModified) { assert.strictEqual(impactedTest.meta[TEST_IS_MODIFIED], 'true') } else { - assert.ok(!Object.hasOwn(impactedTest.meta, TEST_IS_MODIFIED)) + assert.ok(!('TEST_IS_MODIFIED' in impactedTest.meta)) } if (isNew) { assert.strictEqual(impactedTest.meta[TEST_IS_NEW], 'true') } else { - assert.ok(!Object.hasOwn(impactedTest.meta, TEST_IS_NEW)) + assert.ok(!('TEST_IS_NEW' in impactedTest.meta)) } } diff --git a/integration-tests/openfeature/openfeature-exposure-events.spec.js b/integration-tests/openfeature/openfeature-exposure-events.spec.js index dc445ea1627..8a42de0c6ad 100644 --- a/integration-tests/openfeature/openfeature-exposure-events.spec.js +++ b/integration-tests/openfeature/openfeature-exposure-events.spec.js @@ -57,8 +57,8 @@ describe('OpenFeature Remote Config and Exposure Events Integration', () => { cwd, env: { DD_TRACE_AGENT_PORT: agent.port, - DD_REMOTE_CONFIG_POLL_INTERVAL_SECONDS: 0.1, - DD_EXPERIMENTAL_FLAGGING_PROVIDER_ENABLED: true + DD_REMOTE_CONFIG_POLL_INTERVAL_SECONDS: '0.1', + DD_EXPERIMENTAL_FLAGGING_PROVIDER_ENABLED: 'true' } }) }) @@ -142,8 +142,8 @@ describe('OpenFeature Remote Config and Exposure Events Integration', () => { cwd, env: { DD_TRACE_AGENT_PORT: agent.port, - DD_REMOTE_CONFIG_POLL_INTERVAL_SECONDS: 0.1, - DD_EXPERIMENTAL_FLAGGING_PROVIDER_ENABLED: true + DD_REMOTE_CONFIG_POLL_INTERVAL_SECONDS: '0.1', + DD_EXPERIMENTAL_FLAGGING_PROVIDER_ENABLED: 'true' } }) }) @@ -177,11 +177,8 @@ describe('OpenFeature Remote Config and Exposure Events Integration', () => { assert.strictEqual(stringEvents.length, 3) // Verify different users - const userIds = [...new Set(exposureEvents.map(e => e.subject.id))] - assert.strictEqual(userIds.length, 3) - assert.ok(userIds.includes('user-1')) - assert.ok(userIds.includes('user-2')) - assert.ok(userIds.includes('user-3')) + const userIds = new Set(exposureEvents.map(e => e.subject.id)) + assert.deepStrictEqual(userIds, new Set(['user-1', 'user-2', 'user-3'])) done() } catch (error) { @@ -221,8 +218,8 @@ describe('OpenFeature Remote Config and Exposure Events Integration', () => { cwd, env: { DD_TRACE_AGENT_PORT: agent.port, - DD_REMOTE_CONFIG_POLL_INTERVAL_SECONDS: 0.1, - DD_EXPERIMENTAL_FLAGGING_PROVIDER_ENABLED: true + DD_REMOTE_CONFIG_POLL_INTERVAL_SECONDS: '0.1', + DD_EXPERIMENTAL_FLAGGING_PROVIDER_ENABLED: 'true' } }) }) @@ -245,7 +242,7 @@ describe('OpenFeature Remote Config and Exposure Events Integration', () => { assert.strictEqual(id, configId) assert.strictEqual(version, 1) assert.strictEqual(state, ACKNOWLEDGED) - assert.notOk(error) // falsy check since error will be an empty string, but that's an implementation detail + assert.ok(!error) // falsy check since error will be an empty string, but that's an implementation detail receivedAckUpdate = true endIfDone() @@ -286,7 +283,7 @@ describe('OpenFeature Remote Config and Exposure Events Integration', () => { cwd, env: { DD_TRACE_AGENT_PORT: agent.port, - DD_EXPERIMENTAL_FLAGGING_PROVIDER_ENABLED: false + DD_EXPERIMENTAL_FLAGGING_PROVIDER_ENABLED: 'false' } }) }) diff --git a/integration-tests/opentelemetry.spec.js b/integration-tests/opentelemetry.spec.js index eea739a24d5..9684abdcfd7 100644 --- a/integration-tests/opentelemetry.spec.js +++ b/integration-tests/opentelemetry.spec.js @@ -390,7 +390,7 @@ describe('opentelemetry', () => { assert.strictEqual(eachEqual(trace, ['web.request', 'otel-sub', 'dd-sub'], span => span.name), true) // Should have matching trace ids - assert.isTrue(allEqual(trace, span => span.trace_id.toString())) + assert.ok(allEqual(trace, span => span.trace_id.toString())) // Should have matching service names assert.strictEqual(allEqual(trace, span => span.service), true) @@ -423,7 +423,7 @@ describe('opentelemetry', () => { assert.strictEqual(trace.length, 9) // Should have expected span names and ordering - assert.isTrue(eachEqual(trace, [ + assert.ok(eachEqual(trace, [ 'GET /second-endpoint', 'middleware - query', 'middleware - expressInit', @@ -436,7 +436,7 @@ describe('opentelemetry', () => { ], (span) => span.name)) - assert.isTrue(allEqual(trace, (span) => { + assert.ok(allEqual(trace, (span) => { span.trace_id.toString() })) diff --git a/integration-tests/package-guardrails.spec.js b/integration-tests/package-guardrails.spec.js index 8d194978243..da01718ad9c 100644 --- a/integration-tests/package-guardrails.spec.js +++ b/integration-tests/package-guardrails.spec.js @@ -119,11 +119,11 @@ addHook({ name: 'bluebird', versions: ['*'] }, Promise => { it('should not instrument the package', () => runTest( log => { - assert.ok(log.includes(` -Error during ddtrace instrumentation of application, aborting. -ReferenceError: this is a test error - at `)) - assert.ok(log.includes('\nfalse\n')) + assert.match( + log, + /\nError during ddtrace instrumentation of application, aborting.\nReferenceError: this is a test error\n {4}at /m + ) + assert.match(log, /\nfalse\n/) }, [])) }) }) diff --git a/integration-tests/pino.spec.js b/integration-tests/pino.spec.js index 4282e0818ed..8716377c9cf 100644 --- a/integration-tests/pino.spec.js +++ b/integration-tests/pino.spec.js @@ -56,22 +56,18 @@ describe('pino test', () => { cwd, env: { AGENT_PORT: agent.port, - lOG_INJECTION: true, + lOG_INJECTION: 'true', }, stdio: 'pipe', }) const [data] = await Promise.all([once(proc.stdout, 'data'), curl(proc)]) const stdoutData = JSON.parse(data.toString()) - assert.containsAllKeys(stdoutData, ['dd']) - assert.containsAllKeys(stdoutData.dd, ['trace_id', 'span_id']) - assert.strictEqual( - stdoutData.dd.trace_id, - stdoutData.custom.trace_id - ) - assert.strictEqual( - stdoutData.dd.span_id, - stdoutData.custom.span_id - ) + assertObjectContains(stdoutData, { + dd: { + trace_id: stdoutData.custom.trace_id, + span_id: stdoutData.custom.span_id + } + }) }) it('Log injection disabled', async () => { @@ -85,7 +81,7 @@ describe('pino test', () => { }) const [data] = await Promise.all([once(proc.stdout, 'data'), curl(proc)]) const stdoutData = JSON.parse(data.toString()) - assert.doesNotHaveAnyKeys(stdoutData, ['dd']) + assert.ok(!('dd' in stdoutData)) }) }) }) diff --git a/integration-tests/playwright/playwright.spec.js b/integration-tests/playwright/playwright.spec.js index 3db9a12080e..965b7914aa3 100644 --- a/integration-tests/playwright/playwright.spec.js +++ b/integration-tests/playwright/playwright.spec.js @@ -12,7 +12,8 @@ const { sandboxCwd, useSandbox, getCiVisAgentlessConfig, - getCiVisEvpProxyConfig + getCiVisEvpProxyConfig, + assertObjectContains } = require('../helpers') const { FakeCiVisIntake } = require('../ci-visibility-intake') const { createWebAppServer } = require('../ci-visibility/web-app-server') @@ -157,9 +158,9 @@ versions.forEach((version) => { const stepEvents = events.filter(event => event.type === 'span') - assert.include(testSessionEvent.content.resource, 'test_session.playwright test') + assert.ok(testSessionEvent.content.resource.includes('test_session.playwright test')) assert.equal(testSessionEvent.content.meta[TEST_STATUS], 'fail') - assert.include(testModuleEvent.content.resource, 'test_module.playwright test') + assert.ok(testModuleEvent.content.resource.includes('test_module.playwright test')) assert.equal(testModuleEvent.content.meta[TEST_STATUS], 'fail') assert.equal(testSessionEvent.content.meta[TEST_TYPE], 'browser') assert.equal(testModuleEvent.content.meta[TEST_TYPE], 'browser') @@ -167,15 +168,15 @@ versions.forEach((version) => { assert.exists(testSessionEvent.content.meta[ERROR_MESSAGE]) assert.exists(testModuleEvent.content.meta[ERROR_MESSAGE]) - assert.includeMembers(testSuiteEvents.map(suite => suite.content.resource), [ - 'test_suite.todo-list-page-test.js', + assert.deepStrictEqual(testSuiteEvents.map(suite => suite.content.resource).sort(), [ 'test_suite.landing-page-test.js', - 'test_suite.skipped-suite-test.js' + 'test_suite.skipped-suite-test.js', + 'test_suite.todo-list-page-test.js', ]) - assert.includeMembers(testSuiteEvents.map(suite => suite.content.meta[TEST_STATUS]), [ - 'pass', + assert.deepStrictEqual(testSuiteEvents.map(suite => suite.content.meta[TEST_STATUS]).sort(), [ 'fail', + 'pass', 'skip' ]) @@ -183,12 +184,12 @@ versions.forEach((version) => { if (testSuiteEvent.content.meta[TEST_STATUS] === 'fail') { assert.exists(testSuiteEvent.content.meta[ERROR_MESSAGE]) } - assert.isTrue(testSuiteEvent.content.meta[TEST_SOURCE_FILE].endsWith('-test.js')) + assert.ok(testSuiteEvent.content.meta[TEST_SOURCE_FILE].endsWith('-test.js')) assert.equal(testSuiteEvent.content.metrics[TEST_SOURCE_START], 1) assert.exists(testSuiteEvent.content.metrics[DD_HOST_CPU_COUNT]) }) - assert.includeMembers(testEvents.map(test => test.content.resource), [ + assert.deepStrictEqual(testEvents.map(test => test.content.resource), [ 'landing-page-test.js.highest-level-describe' + ' leading and trailing spaces should work with passing tests', 'landing-page-test.js.highest-level-describe' + @@ -197,11 +198,12 @@ versions.forEach((version) => { ' leading and trailing spaces should work with fixme', 'landing-page-test.js.highest-level-describe' + ' leading and trailing spaces should work with annotated tests', + 'todo-list-page-test.js.should work with fixme root', 'todo-list-page-test.js.playwright should work with failing tests', - 'todo-list-page-test.js.should work with fixme root' + 'skipped-suite-test.js.should work with fixme root', ]) - assert.includeMembers(testEvents.map(test => test.content.meta[TEST_STATUS]), [ + assertObjectContains(testEvents.map(test => test.content.meta[TEST_STATUS]), [ 'pass', 'fail', 'skip' @@ -214,39 +216,47 @@ versions.forEach((version) => { ) assert.equal(testEvent.content.meta[DD_TEST_IS_USER_PROVIDED_SERVICE], 'false') // Can read DD_TAGS - assert.propertyVal(testEvent.content.meta, 'test.customtag', 'customvalue') - assert.propertyVal(testEvent.content.meta, 'test.customtag2', 'customvalue2') - // Adds the browser used - assert.propertyVal(testEvent.content.meta, TEST_BROWSER_NAME, 'chromium') - assert.propertyVal( - testEvent.content.meta, - TEST_PARAMETERS, - JSON.stringify({ arguments: { browser: 'chromium' }, metadata: {} }) - ) + assertObjectContains(testEvent.content.meta, { + 'test.customtag': 'customvalue', + 'test.customtag2': 'customvalue2', + // Adds the browser used + [TEST_BROWSER_NAME]: 'chromium', + [TEST_PARAMETERS]: JSON.stringify({ arguments: { browser: 'chromium' }, metadata: {} }) + }) assert.exists(testEvent.content.metrics[DD_HOST_CPU_COUNT]) if (version === 'latest' || satisfies(version, '>=1.38.0')) { if (testEvent.content.meta[TEST_STATUS] !== 'skip' && testEvent.content.meta[TEST_SUITE].includes('landing-page-test.js')) { - assert.propertyVal(testEvent.content.meta, 'custom_tag.beforeEach', 'hello beforeEach') - assert.propertyVal(testEvent.content.meta, 'custom_tag.afterEach', 'hello afterEach') + assertObjectContains(testEvent.content.meta, { + 'custom_tag.beforeEach': 'hello beforeEach', + 'custom_tag.afterEach': 'hello afterEach' + }) } if (testEvent.content.meta[TEST_NAME].includes('should work with passing tests')) { - assert.propertyVal(testEvent.content.meta, 'custom_tag.it', 'hello it') + assertObjectContains(testEvent.content.meta, { + 'custom_tag.it': 'hello it' + }) } } }) stepEvents.forEach(stepEvent => { assert.equal(stepEvent.content.name, 'playwright.step') - assert.property(stepEvent.content.meta, 'playwright.step') + assert.ok(Object.hasOwn(stepEvent.content.meta, 'playwright.step')) }) const annotatedTest = testEvents.find(test => test.content.resource.endsWith('should work with annotated tests') ) - assert.propertyVal(annotatedTest.content.meta, 'test.memory.usage', 'low') - assert.propertyVal(annotatedTest.content.metrics, 'test.memory.allocations', 16) - assert.notProperty(annotatedTest.content.meta, 'test.invalid') + assertObjectContains(annotatedTest.content, { + meta: { + 'test.memory.usage': 'low', + }, + metrics: { + 'test.memory.allocations': 16 + } + }) + assert.ok(!('test.invalid' in annotatedTest.content.meta)) }).then(() => done()).catch(done) childProcess = exec( @@ -275,12 +285,12 @@ versions.forEach((version) => { receiver.gatherPayloadsMaxTimeout(({ url }) => url === '/api/v2/citestcycle', payloads => { const events = payloads.flatMap(({ payload }) => payload.events) const testEvents = events.filter(event => event.type === 'test') - assert.includeMembers(testEvents.map(test => test.content.resource), [ + assertObjectContains(testEvents.map(test => test.content.resource), [ + 'playwright-tests-ts/one-test.js.playwright should work with skipped tests', 'playwright-tests-ts/one-test.js.playwright should work with passing tests', - 'playwright-tests-ts/one-test.js.playwright should work with skipped tests' ]) - assert.include(testOutput, '1 passed') - assert.include(testOutput, '1 skipped') + assert.match(testOutput, /1 passed/) + assert.match(testOutput, /1 skipped/) assert.notInclude(testOutput, 'TypeError') }, 25000).then(() => done()).catch(done) @@ -312,10 +322,14 @@ versions.forEach((version) => { const testSuiteEvent = events.find(event => event.type === 'test_suite_end').content const testSessionEvent = events.find(event => event.type === 'test_session_end').content - assert.propertyVal(testSuiteEvent.meta, TEST_STATUS, 'fail') - assert.propertyVal(testSessionEvent.meta, TEST_STATUS, 'fail') + assertObjectContains(testSuiteEvent.meta, { + [TEST_STATUS]: 'fail' + }) + assertObjectContains(testSessionEvent.meta, { + [TEST_STATUS]: 'fail' + }) assert.exists(testSuiteEvent.meta[ERROR_MESSAGE]) - assert.include(testSessionEvent.meta[ERROR_MESSAGE], 'Test suites failed: 1') + assert.match(testSessionEvent.meta[ERROR_MESSAGE], /Test suites failed: 1/) }).then(() => done()).catch(done) childProcess = exec( @@ -372,14 +386,18 @@ versions.forEach((version) => { const events = payloads.flatMap(({ payload }) => payload.events) const testSession = events.find(event => event.type === 'test_session_end').content - assert.propertyVal(testSession.meta, TEST_EARLY_FLAKE_ENABLED, 'true') + assertObjectContains(testSession.meta, { + [TEST_EARLY_FLAKE_ENABLED]: 'true' + }) const tests = events.filter(event => event.type === 'test').map(event => event.content) const newPassingTests = tests.filter(test => test.resource.endsWith('should work with passing tests') ) newPassingTests.forEach(test => { - assert.propertyVal(test.meta, TEST_IS_NEW, 'true') + assertObjectContains(test.meta, { + [TEST_IS_NEW]: 'true' + }) }) assert.equal( newPassingTests.length, @@ -390,7 +408,9 @@ versions.forEach((version) => { test.resource.endsWith('should work with annotated tests') ) newAnnotatedTests.forEach(test => { - assert.propertyVal(test.meta, TEST_IS_NEW, 'true') + assertObjectContains(test.meta, { + [TEST_IS_NEW]: 'true' + }) }) assert.equal( newAnnotatedTests.length, @@ -420,7 +440,9 @@ versions.forEach((version) => { ) totalRetriedTests.forEach(test => { - assert.propertyVal(test.meta, TEST_RETRY_REASON, TEST_RETRY_REASON_TYPES.efd) + assertObjectContains(test.meta, { + [TEST_RETRY_REASON]: TEST_RETRY_REASON_TYPES.efd + }) }) // all but one has been retried @@ -487,7 +509,9 @@ versions.forEach((version) => { ) // new tests are detected but not retried newTests.forEach(test => { - assert.propertyVal(test.meta, TEST_IS_NEW, 'true') + assertObjectContains(test.meta, { + [TEST_IS_NEW]: 'true' + }) }) const retriedTests = tests.filter(test => test.meta[TEST_IS_RETRY] === 'true') @@ -557,7 +581,9 @@ versions.forEach((version) => { // no retries assert.equal(newTests.length, 2) newTests.forEach(test => { - assert.propertyVal(test.meta, TEST_IS_NEW, 'true') + assertObjectContains(test.meta, { + [TEST_IS_NEW]: 'true' + }) }) const retriedTests = tests.filter(test => test.meta[TEST_IS_RETRY] === 'true') @@ -605,7 +631,7 @@ versions.forEach((version) => { assert.equal(tests.length, 7) const testSession = events.find(event => event.type === 'test_session_end').content - assert.notProperty(testSession.meta, TEST_EARLY_FLAKE_ENABLED) + assert.ok(!(TEST_EARLY_FLAKE_ENABLED in testSession.meta)) const newTests = tests.filter(test => test.meta[TEST_IS_NEW] === 'true') assert.equal(newTests.length, 0) @@ -670,14 +696,14 @@ versions.forEach((version) => { const events = payloads.flatMap(({ payload }) => payload.events) const testSession = events.find(event => event.type === 'test_session_end').content - assert.notProperty(testSession.meta, TEST_EARLY_FLAKE_ENABLED) + assert.ok(!(TEST_EARLY_FLAKE_ENABLED in testSession.meta)) const tests = events.filter(event => event.type === 'test').map(event => event.content) const newTests = tests.filter(test => test.resource.endsWith('should work with passing tests') ) newTests.forEach(test => { - assert.notProperty(test.meta, TEST_IS_NEW) + assert.ok(!(TEST_IS_NEW in test.meta)) }) const retriedTests = tests.filter(test => test.meta[TEST_IS_RETRY] === 'true') @@ -723,15 +749,17 @@ versions.forEach((version) => { const events = payloads.flatMap(({ payload }) => payload.events) const testSession = events.find(event => event.type === 'test_session_end').content - assert.notProperty(testSession.meta, TEST_EARLY_FLAKE_ENABLED) - assert.propertyVal(testSession.meta, TEST_EARLY_FLAKE_ABORT_REASON, 'faulty') + assert.ok(!(TEST_EARLY_FLAKE_ENABLED in testSession.meta)) + assertObjectContains(testSession.meta, { + [TEST_EARLY_FLAKE_ABORT_REASON]: 'faulty' + }) const tests = events.filter(event => event.type === 'test').map(event => event.content) const newTests = tests.filter(test => test.resource.endsWith('should work with passing tests') ) newTests.forEach(test => { - assert.notProperty(test.meta, TEST_IS_NEW) + assert.ok(!(TEST_IS_NEW in test.meta)) }) const retriedTests = tests.filter(test => test.meta[TEST_IS_RETRY] === 'true') @@ -790,8 +818,10 @@ versions.forEach((version) => { const tests = events.filter(event => event.type === 'test').map(event => event.content) const testSession = events.find(event => event.type === 'test_session_end').content - assert.notProperty(testSession.meta, TEST_EARLY_FLAKE_ENABLED) - assert.propertyVal(testSession.meta, TEST_EARLY_FLAKE_ABORT_REASON, 'faulty') + assert.ok(!(TEST_EARLY_FLAKE_ENABLED in testSession.meta)) + assertObjectContains(testSession.meta, { + [TEST_EARLY_FLAKE_ABORT_REASON]: 'faulty' + }) const newTests = tests.filter(test => test.meta[TEST_IS_NEW] === 'true') assert.equal(newTests.length, 0) @@ -955,7 +985,7 @@ versions.forEach((version) => { const testEvents = events.filter(event => event.type === 'test') - assert.includeMembers(testEvents.map(test => test.content.resource), [ + assertObjectContains(testEvents.map(test => test.content.resource), [ 'failing-test-and-another-test.js.should work with failing tests', 'failing-test-and-another-test.js.does not crash afterwards' ]) @@ -968,7 +998,7 @@ versions.forEach((version) => { env: { ...getCiVisAgentlessConfig(receiver.port), PW_BASE_URL: `http://localhost:${webAppPort}`, - MAX_FAILURES: 1, + MAX_FAILURES: '1', TEST_DIR: './ci-visibility/playwright-tests-max-failures' }, stdio: 'pipe' @@ -1107,7 +1137,7 @@ versions.forEach((version) => { ...getCiVisAgentlessConfig(receiver.port), PW_BASE_URL: `http://localhost:${webAppPort}`, TEST_DIR: './ci-visibility/playwright-tests-automatic-retry', - DD_CIVISIBILITY_FLAKY_RETRY_COUNT: 1 + DD_CIVISIBILITY_FLAKY_RETRY_COUNT: '1' }, stdio: 'pipe' } @@ -1187,7 +1217,7 @@ versions.forEach((version) => { const events = payloads.flatMap(({ payload }) => payload.events) const testSession = events.find(event => event.type === 'test_session_end').content - assert.notProperty(testSession.meta, TEST_EARLY_FLAKE_ENABLED) + assert.ok(!(TEST_EARLY_FLAKE_ENABLED in testSession.meta)) const tests = events.filter(event => event.type === 'test').map(event => event.content) const newTests = tests.filter(test => @@ -1195,7 +1225,9 @@ versions.forEach((version) => { ) // new tests detected but no retries newTests.forEach(test => { - assert.propertyVal(test.meta, TEST_IS_NEW, 'true') + assertObjectContains(test.meta, { + [TEST_IS_NEW]: 'true' + }) }) const retriedTests = tests.filter(test => test.meta[TEST_IS_RETRY] === 'true') @@ -1290,9 +1322,11 @@ versions.forEach((version) => { const testSession = events.find(event => event.type === 'test_session_end').content if (isAttemptingToFix) { - assert.propertyVal(testSession.meta, TEST_MANAGEMENT_ENABLED, 'true') + assertObjectContains(testSession.meta, { + [TEST_MANAGEMENT_ENABLED]: 'true' + }) } else { - assert.notProperty(testSession.meta, TEST_MANAGEMENT_ENABLED) + assert.ok(!(TEST_MANAGEMENT_ENABLED in testSession.meta)) } const attemptedToFixTests = tests.filter( @@ -1301,7 +1335,7 @@ versions.forEach((version) => { if (isDisabled) { assert.equal(attemptedToFixTests.length, 2) - assert.isTrue(attemptedToFixTests.every(test => + assert.ok(attemptedToFixTests.every(test => test.meta[TEST_MANAGEMENT_IS_DISABLED] === 'true' )) // if the test is disabled, there will be no retries @@ -1597,7 +1631,7 @@ versions.forEach((version) => { const events = payloads.flatMap(({ payload }) => payload.events) const resourceNames = events.filter(event => event.type === 'test').map(event => event.content.resource) - assert.includeMembers(resourceNames, [ + assertObjectContains(resourceNames.sort(), [ 'disabled-test.js.disable should disable test', 'disabled-test.js.not disabled should not disable test', 'disabled-test.js.not disabled 2 should not disable test 2', @@ -1606,13 +1640,15 @@ versions.forEach((version) => { 'disabled-2-test.js.not disabled should not disable test', 'disabled-2-test.js.not disabled 2 should not disable test 2', 'disabled-2-test.js.not disabled 3 should not disable test 3', - ]) + ].sort()) const testSession = events.find(event => event.type === 'test_session_end').content if (isDisabling) { - assert.propertyVal(testSession.meta, TEST_MANAGEMENT_ENABLED, 'true') + assertObjectContains(testSession.meta, { + [TEST_MANAGEMENT_ENABLED]: 'true' + }) } else { - assert.notProperty(testSession.meta, TEST_MANAGEMENT_ENABLED) + assert.ok(!(TEST_MANAGEMENT_ENABLED in testSession.meta)) } const tests = events.filter(event => event.type === 'test').map(event => event.content) @@ -1624,10 +1660,12 @@ versions.forEach((version) => { disabledTests.forEach(test => { if (isDisabling) { assert.equal(test.meta[TEST_STATUS], 'skip') - assert.propertyVal(test.meta, TEST_MANAGEMENT_IS_DISABLED, 'true') + assertObjectContains(test.meta, { + [TEST_MANAGEMENT_IS_DISABLED]: 'true' + }) } else { assert.equal(test.meta[TEST_STATUS], 'fail') - assert.notProperty(test.meta, TEST_MANAGEMENT_IS_DISABLED) + assert.ok(!(TEST_MANAGEMENT_IS_DISABLED in test.meta)) } }) }, 25000) @@ -1665,10 +1703,10 @@ versions.forEach((version) => { // the testOutput checks whether the test is actually skipped if (isDisabling) { - assert.notInclude(testOutput, 'SHOULD NOT BE EXECUTED') + assert.notMatch(testOutput, /SHOULD NOT BE EXECUTED/) assert.equal(exitCode, 0) } else { - assert.include(testOutput, 'SHOULD NOT BE EXECUTED') + assert.match(testOutput, /SHOULD NOT BE EXECUTED/) assert.equal(exitCode, 1) } } @@ -1732,45 +1770,38 @@ versions.forEach((version) => { ) quarantinedTests.forEach(test => { - assert.propertyVal(test.meta, TEST_STATUS, 'fail') + assert.equal(test.meta[TEST_STATUS], 'fail') }) + if (hasFlakyTests) { + assert.equal(flakyTests.length, 2) // first attempt fails, second attempt passes + assert.equal(quarantinedTests.length, 2) // both fail + assert.ok(!(TEST_MANAGEMENT_IS_QUARANTINED in flakyTests[0].meta)) + assert.ok(!(TEST_MANAGEMENT_IS_QUARANTINED in flakyTests[1].meta)) + const failedFlakyTest = flakyTests.filter(test => test.meta[TEST_STATUS] === 'fail') + const passedFlakyTest = flakyTests.filter(test => test.meta[TEST_STATUS] === 'pass') + assert.equal(failedFlakyTest.length, 1) + assert.equal(passedFlakyTest.length, 1) + } + if (isQuarantining) { - assert.propertyVal(testSession.meta, TEST_MANAGEMENT_ENABLED, 'true') - assert.propertyVal(testSession.meta, TEST_STATUS, 'pass') if (hasFlakyTests) { - assert.equal(flakyTests.length, 2) // first attempt fails, second attempt passes - assert.equal(quarantinedTests.length, 2) // both fail - assert.notProperty(flakyTests[0].meta, TEST_MANAGEMENT_IS_QUARANTINED) - assert.notProperty(flakyTests[1].meta, TEST_MANAGEMENT_IS_QUARANTINED) - const failedFlakyTest = flakyTests.filter(test => test.meta[TEST_STATUS] === 'fail') - const passedFlakyTest = flakyTests.filter(test => test.meta[TEST_STATUS] === 'pass') - assert.isTrue(failedFlakyTest.length === 1) - assert.isTrue(passedFlakyTest.length === 1) - assert.propertyVal(quarantinedTests[0].meta, TEST_MANAGEMENT_IS_QUARANTINED, 'true') - assert.propertyVal(quarantinedTests[1].meta, TEST_MANAGEMENT_IS_QUARANTINED, 'true') + assert.equal(quarantinedTests[1].meta[TEST_MANAGEMENT_IS_QUARANTINED], 'true') } else { assert.equal(quarantinedTests.length, 1) - assert.propertyVal(quarantinedTests[0].meta, TEST_MANAGEMENT_IS_QUARANTINED, 'true') } + assert.equal(quarantinedTests[0].meta[TEST_MANAGEMENT_IS_QUARANTINED], 'true') + assertObjectContains(testSession.meta, { + [TEST_MANAGEMENT_ENABLED]: 'true' + }) } else { - assert.notProperty(testSession.meta, TEST_MANAGEMENT_ENABLED) - assert.propertyVal(testSession.meta, TEST_STATUS, 'fail') if (hasFlakyTests) { - assert.equal(flakyTests.length, 2) // first attempt fails, second attempt passes - assert.equal(quarantinedTests.length, 2) // both fail - assert.notProperty(flakyTests[0].meta, TEST_MANAGEMENT_IS_QUARANTINED) - assert.notProperty(flakyTests[1].meta, TEST_MANAGEMENT_IS_QUARANTINED) - const failedFlakyTest = flakyTests.filter(test => test.meta[TEST_STATUS] === 'fail') - const passedFlakyTest = flakyTests.filter(test => test.meta[TEST_STATUS] === 'pass') - assert.isTrue(failedFlakyTest.length === 1) - assert.isTrue(passedFlakyTest.length === 1) - assert.notProperty(quarantinedTests[0].meta, TEST_MANAGEMENT_IS_QUARANTINED) - assert.notProperty(quarantinedTests[1].meta, TEST_MANAGEMENT_IS_QUARANTINED) + assert.ok(!(TEST_MANAGEMENT_IS_QUARANTINED in quarantinedTests[1].meta)) } else { assert.equal(quarantinedTests.length, 1) - assert.notProperty(quarantinedTests[0].meta, TEST_MANAGEMENT_IS_QUARANTINED) } + assert.ok(!(TEST_MANAGEMENT_IS_QUARANTINED in quarantinedTests[0].meta)) + assert.ok(!(TEST_MANAGEMENT_ENABLED in testSession.meta)) } }, 25000) @@ -1863,7 +1894,7 @@ versions.forEach((version) => { .gatherPayloadsMaxTimeout(({ url }) => url.endsWith('/api/v2/citestcycle'), (payloads) => { const events = payloads.flatMap(({ payload }) => payload.events) const testSession = events.find(event => event.type === 'test_session_end').content - assert.notProperty(testSession.meta, TEST_MANAGEMENT_ENABLED) + assert.ok(!(TEST_MANAGEMENT_ENABLED in testSession.meta)) const tests = events.filter(event => event.type === 'test').map(event => event.content) // they are not retried assert.equal(tests.length, 2) @@ -1898,7 +1929,7 @@ versions.forEach((version) => { once(childProcess.stderr, 'end'), eventsPromise ]) - assert.include(testOutput, 'Test management tests could not be fetched') + assert.match(testOutput, /Test management tests could not be fetched/) }) }) @@ -1908,7 +1939,7 @@ versions.forEach((version) => { .gatherPayloadsMaxTimeout(({ url }) => url.endsWith('/api/v2/citestcycle'), payloads => { const metadataDicts = payloads.flatMap(({ payload }) => payload.metadata) - assert.isNotEmpty(metadataDicts) + assert.ok(metadataDicts.length > 0) metadataDicts.forEach(metadata => { assert.equal(metadata.test[DD_CAPABILITIES_TEST_IMPACT_ANALYSIS], undefined) assert.equal(metadata.test[DD_CAPABILITIES_AUTO_TEST_RETRIES], '1') @@ -2029,13 +2060,17 @@ versions.forEach((version) => { tests.forEach(test => { if (isRedirecting) { // can't do assertions because playwright has been redirected - assert.propertyVal(test.meta, TEST_STATUS, 'fail') - assert.notProperty(test.meta, TEST_IS_RUM_ACTIVE) - assert.notProperty(test.meta, TEST_BROWSER_VERSION) + assertObjectContains(test.meta, { + [TEST_STATUS]: 'fail' + }) + assert.ok(!(TEST_IS_RUM_ACTIVE in test.meta)) + assert.ok(!(TEST_BROWSER_VERSION in test.meta)) } else { - assert.propertyVal(test.meta, TEST_STATUS, 'pass') - assert.property(test.meta, TEST_IS_RUM_ACTIVE, 'true') - assert.property(test.meta, TEST_BROWSER_VERSION) + assertObjectContains(test.meta, { + [TEST_STATUS]: 'pass', + [TEST_IS_RUM_ACTIVE]: 'true', + }) + assert.ok(Object.hasOwn(test.meta, TEST_BROWSER_VERSION)) } }) }) @@ -2156,14 +2191,16 @@ versions.forEach((version) => { const testSession = events.find(event => event.type === 'test_session_end').content if (isEfd) { - assert.propertyVal(testSession.meta, TEST_EARLY_FLAKE_ENABLED, 'true') + assertObjectContains(testSession.meta, { + [TEST_EARLY_FLAKE_ENABLED]: 'true' + }) } else { - assert.notProperty(testSession.meta, TEST_EARLY_FLAKE_ENABLED) + assert.ok(!(TEST_EARLY_FLAKE_ENABLED in testSession.meta)) } const resourceNames = tests.map(span => span.resource) - assert.includeMembers(resourceNames, + assertObjectContains(resourceNames, [ 'impacted-test.js.impacted test should be impacted', 'impacted-test.js.impacted test 2 should be impacted 2' @@ -2181,14 +2218,18 @@ versions.forEach((version) => { for (const impactedTest of impactedTests) { if (isModified) { - assert.propertyVal(impactedTest.meta, TEST_IS_MODIFIED, 'true') + assertObjectContains(impactedTest.meta, { + [TEST_IS_MODIFIED]: 'true' + }) } else { - assert.notProperty(impactedTest.meta, TEST_IS_MODIFIED) + assert.ok(!(TEST_IS_MODIFIED in impactedTest.meta)) } if (isNew) { - assert.propertyVal(impactedTest.meta, TEST_IS_NEW, 'true') + assertObjectContains(impactedTest.meta, { + [TEST_IS_NEW]: 'true' + }) } else { - assert.notProperty(impactedTest.meta, TEST_IS_NEW) + assert.ok(!(TEST_IS_NEW in impactedTest.meta)) } } @@ -2294,8 +2335,8 @@ versions.forEach((version) => { assert.equal(tests.length, NUM_RETRIES_EFD + 1) for (const test of tests) { - assert.notProperty(test.meta, TEST_MANAGEMENT_ATTEMPT_TO_FIX_PASSED) - assert.notProperty(test.meta, TEST_HAS_FAILED_ALL_RETRIES) + assert.ok(!(TEST_MANAGEMENT_ATTEMPT_TO_FIX_PASSED in test.meta)) + assert.ok(!(TEST_HAS_FAILED_ALL_RETRIES in test.meta)) } }) @@ -2354,18 +2395,18 @@ versions.forEach((version) => { assert.equal(tests.length, 3) const skippedTest = tests.find(test => test.meta[TEST_STATUS] === 'skip') - assert.propertyVal( + assertObjectContains( skippedTest.meta, - TEST_NAME, - 'short suite should skip and not mess up the duration of the test suite' + { + [TEST_NAME]: 'short suite should skip and not mess up the duration of the test suite' + }, ) const shortSuite = testSuites.find(suite => suite.meta[TEST_SUITE].endsWith('short-suite-test.js')) const longSuite = testSuites.find(suite => suite.meta[TEST_SUITE].endsWith('long-suite-test.js')) // The values are not deterministic, so we can only assert that they're distant enough // This checks that the long suite takes at least twice longer than the short suite - assert.isAbove( - Number(longSuite.duration), - Number(shortSuite.duration) * 2, + assert.ok( + Number(longSuite.duration) > Number(shortSuite.duration) * 2, 'The long test suite should take at least twice as long as the short suite, ' + 'but their durations are: \n' + `- Long suite: ${Number(longSuite.duration) / 1e6}ms \n` + @@ -2404,9 +2445,13 @@ versions.forEach((version) => { const tests = events.filter(event => event.type === 'test').map(event => event.content) assert.equal(tests.length, 2) const failedTest = tests.find(test => test.meta[TEST_STATUS] === 'fail') - assert.propertyVal(failedTest.meta, TEST_NAME, 'failing test fails and causes early bail') + assertObjectContains(failedTest.meta, { + [TEST_NAME]: 'failing test fails and causes early bail' + }) const didNotRunTest = tests.find(test => test.meta[TEST_STATUS] === 'skip') - assert.propertyVal(didNotRunTest.meta, TEST_NAME, 'did not run because of early bail') + assertObjectContains(didNotRunTest.meta, { + [TEST_NAME]: 'did not run because of early bail' + }) }) childProcess = exec( diff --git a/integration-tests/profiler/profiler.spec.js b/integration-tests/profiler/profiler.spec.js index 574283ba34c..3c550d85443 100644 --- a/integration-tests/profiler/profiler.spec.js +++ b/integration-tests/profiler/profiler.spec.js @@ -4,6 +4,7 @@ const { FakeAgent, sandboxCwd, useSandbox, + assertObjectContains, } = require('../helpers') const childProcess = require('child_process') const { fork } = childProcess @@ -39,18 +40,26 @@ function expectProfileMessagePromise (agent, timeout, return agent.assertMessageReceived(({ headers, _, files }) => { let event try { - assert.propertyVal(headers, 'host', `127.0.0.1:${agent.port}`) - assert.propertyVal(files[0], 'originalname', 'event.json') + assertObjectContains(headers, { + host: `127.0.0.1:${agent.port}` + }) + assertObjectContains(files[0], { + originalname: 'event.json' + }) event = JSON.parse(files[0].buffer.toString()) - assert.propertyVal(event, 'family', 'node') - assert.isString(event.info.profiler.activation) - assert.isString(event.info.profiler.ssi.mechanism) + assertObjectContains(event, { + family: 'node' + }) + assert.strictEqual(typeof event.info.profiler.activation, 'string') + assert.strictEqual(typeof event.info.profiler.ssi.mechanism, 'string') const attachments = event.attachments - assert.isArray(attachments) + assert.ok(Array.isArray(attachments)) // Profiler encodes the files with Promise.all, so their ordering is not guaranteed assert.sameMembers(attachments, fileNames) for (const [index, fileName] of attachments.entries()) { - assert.propertyVal(files[index + 1], 'originalname', fileName) + assertObjectContains(files[index + 1], { + originalname: fileName + }) } if (expectSeq) { assert(event.tags_profiler.indexOf(',profile_seq:') !== -1) @@ -94,7 +103,7 @@ async function readLatestFile (cwd, pattern) { const dirEntries = await fs.readdir(cwd) // Get the latest file matching the pattern const pprofEntries = dirEntries.filter(name => pattern.test(name)) - assert.isTrue(pprofEntries.length > 0, `No file matching pattern ${pattern} found in ${cwd}`) + assert.ok(pprofEntries.length > 0, `No file matching pattern ${pattern} found in ${cwd}`) const pprofEntry = pprofEntries .map(name => ({ name, modified: fsync.statSync(path.join(cwd, name), { bigint: true }).mtimeNs })) .reduce((a, b) => a.modified > b.modified ? a : b) @@ -148,7 +157,7 @@ class NetworkEventProcessor extends TimelineEventProcessor { decorateEvent (ev, pl) { // Exactly one of these is defined - assert.isTrue(!!pl.address !== !!pl.host, this.encoded) + assert.ok(!!pl.address !== !!pl.host, this.encoded) if (pl.address) { ev.address = this.strings.strings[pl.address] } else { @@ -259,19 +268,20 @@ async function gatherTimelineEvents (cwd, scriptFilePath, agentPort, eventType, } } // Timestamp must be defined and be between process start and end time - assert.isDefined(ts, encoded) - assert.isTrue(ts <= procEnd, encoded) - assert.isTrue(ts >= procStart, encoded) + assert.notStrictEqual(ts, undefined, encoded) + assert.strictEqual(typeof ts, 'bigint', encoded) + assert.ok(ts <= procEnd, encoded) + assert.ok(ts >= procStart, encoded) // Gather only tested events if (event === eventValue) { if (process.platform !== 'win32') { - assert.isDefined(spanId, encoded) - assert.isDefined(localRootSpanId, encoded) + assert.notStrictEqual(spanId, undefined, encoded) + assert.notStrictEqual(localRootSpanId, undefined, encoded) } else { - assert.isUndefined(spanId, encoded) - assert.isUndefined(localRootSpanId, encoded) + assert.strictEqual(spanId, undefined, encoded) + assert.strictEqual(localRootSpanId, undefined, encoded) } - assert.isDefined(operation, encoded) + assert.notStrictEqual(operation, undefined, encoded) if (unexpectedLabels.length > 0) { const labelsStr = JSON.stringify(unexpectedLabels) const labelsStrStr = unexpectedLabels.map(k => strings.strings[k]).join(',') @@ -412,11 +422,11 @@ describe('profiler', () => { } if (threadName !== nonJSThreadNameValue) { // Timestamp must be defined and be between process start and end time - assert.isDefined(ts, encoded) - assert.isNumber(osThreadId, encoded) + assert.notStrictEqual(ts, undefined, encoded) + assert.strictEqual(typeof osThreadId, 'number', encoded) assert.equal(threadId, strings.dedup('0'), encoded) - assert.isTrue(ts <= procEnd, encoded) - assert.isTrue(ts >= procStart, encoded) + assert.ok(ts <= procEnd, encoded) + assert.ok(ts >= procStart, encoded) // Thread name must be defined and exactly equal "Main Event Loop" assert.equal(threadName, threadNameValue, encoded) } else { @@ -429,8 +439,8 @@ describe('profiler', () => { continue } if (spanId || rootSpanId) { - assert.isDefined(spanId, encoded) - assert.isDefined(rootSpanId, encoded) + assert.notStrictEqual(spanId, undefined, encoded) + assert.notStrictEqual(rootSpanId, undefined, encoded) rootSpans.add(rootSpanId) if (spanId === rootSpanId) { @@ -695,12 +705,12 @@ describe('profiler', () => { // There's a race between metrics and on-shutdown profile, so metric // value will be between 1 and 3 requestCount = requests.points[0][1] - assert.isAtLeast(requestCount, 1) - assert.isAtMost(requestCount, 3) + assert.ok(requestCount >= 1) + assert.ok(requestCount <= 3) const responses = series.find(s => s.metric === 'profile_api.responses') assert.equal(responses.type, 'count') - assert.include(responses.tags, 'status_code:200') + assert.match(responses.tags, /status_code:200/) // Same number of requests and responses assert.equal(responses.points[0][1], requestCount) @@ -710,7 +720,7 @@ describe('profiler', () => { const pp = payload.payload assert.equal(pp.namespace, 'profilers') const series = pp.series - assert.lengthOf(series, 2) + assert.strictEqual(series.length, 2) assert.equal(series[0].metric, 'profile_api.bytes') assert.equal(series[1].metric, 'profile_api.ms') @@ -752,9 +762,9 @@ describe('profiler', () => { assert.equal(pp.namespace, 'profilers'); ['live', 'used'].forEach(metricName => { const sampleContexts = pp.series.find(s => s.metric === `wall.async_contexts_${metricName}`) - assert.isDefined(sampleContexts) + assert.notStrictEqual(sampleContexts, undefined) assert.equal(sampleContexts.type, 'gauge') - assert.isAtLeast(sampleContexts.points[0][1], 1) + assert.ok(sampleContexts.points[0][1] >= 1) }) }, 'generate-metrics', timeout) diff --git a/integration-tests/selenium/selenium.spec.js b/integration-tests/selenium/selenium.spec.js index 66b68d67aef..f2b0eb7e6a6 100644 --- a/integration-tests/selenium/selenium.spec.js +++ b/integration-tests/selenium/selenium.spec.js @@ -6,7 +6,8 @@ const { exec } = require('child_process') const { sandboxCwd, useSandbox, - getCiVisAgentlessConfig + getCiVisAgentlessConfig, + assertObjectContains } = require('../helpers') const { FakeCiVisIntake } = require('../ci-visibility-intake') const { @@ -83,12 +84,16 @@ versionRange.forEach(version => { .gatherPayloadsMaxTimeout(({ url }) => url.endsWith('/api/v2/citestcycle'), (payloads) => { const events = payloads.flatMap(({ payload }) => payload.events) const seleniumTest = events.find(event => event.type === 'test').content - assert.ok(seleniumTest.meta.includes({ - [TEST_BROWSER_DRIVER]: 'selenium', - [TEST_BROWSER_NAME]: 'chrome', - [TEST_TYPE]: 'browser', - [TEST_IS_RUM_ACTIVE]: 'true' - })) + + assertObjectContains(seleniumTest, { + meta: { + [TEST_BROWSER_DRIVER]: 'selenium', + [TEST_BROWSER_NAME]: 'chrome', + [TEST_TYPE]: 'browser', + [TEST_IS_RUM_ACTIVE]: 'true', + } + }) + assert.ok(Object.hasOwn(seleniumTest.meta, TEST_BROWSER_VERSION)) assert.ok(Object.hasOwn(seleniumTest.meta, TEST_BROWSER_DRIVER_VERSION)) }) @@ -132,7 +137,7 @@ versionRange.forEach(version => { childProcess.on('exit', (code) => { assert.strictEqual(code, 0) - assert.ok(!testOutput.includes('InvalidArgumentError')) + assert.doesNotMatch(testOutput, /InvalidArgumentError/) done() }) diff --git a/integration-tests/vitest/vitest.spec.js b/integration-tests/vitest/vitest.spec.js index e3a872b4927..160eb098ea3 100644 --- a/integration-tests/vitest/vitest.spec.js +++ b/integration-tests/vitest/vitest.spec.js @@ -159,49 +159,50 @@ versions.forEach((version) => { ) assert.strictEqual(failedSuiteHooks.content.meta[TEST_STATUS], 'fail') - assert.includeMembers(testEvents.map(test => test.content.resource), + assert.deepStrictEqual(testEvents.map(test => test.content.resource).sort(), [ + 'ci-visibility/vitest-tests/test-visibility-failed-hooks.mjs.context can report failed test', + 'ci-visibility/vitest-tests/test-visibility-failed-hooks.mjs.context can report more', + 'ci-visibility/vitest-tests/test-visibility-failed-hooks.mjs.other context can report more', + 'ci-visibility/vitest-tests/test-visibility-failed-hooks.mjs.other context can report passed test', 'ci-visibility/vitest-tests/test-visibility-failed-suite.mjs' + '.test-visibility-failed-suite-first-describe can report failed test', 'ci-visibility/vitest-tests/test-visibility-failed-suite.mjs' + '.test-visibility-failed-suite-first-describe can report more', 'ci-visibility/vitest-tests/test-visibility-failed-suite.mjs' + - '.test-visibility-failed-suite-second-describe can report passed test', - 'ci-visibility/vitest-tests/test-visibility-failed-suite.mjs' + '.test-visibility-failed-suite-second-describe can report more', - 'ci-visibility/vitest-tests/test-visibility-passed-suite.mjs.context can report passed test', + 'ci-visibility/vitest-tests/test-visibility-failed-suite.mjs' + + '.test-visibility-failed-suite-second-describe can report passed test', 'ci-visibility/vitest-tests/test-visibility-passed-suite.mjs.context can report more', - 'ci-visibility/vitest-tests/test-visibility-passed-suite.mjs.other context can report passed test', + 'ci-visibility/vitest-tests/test-visibility-passed-suite.mjs.context can report passed test', + 'ci-visibility/vitest-tests/test-visibility-passed-suite.mjs.no suite', + 'ci-visibility/vitest-tests/test-visibility-passed-suite.mjs.other context can programmatic skip', 'ci-visibility/vitest-tests/test-visibility-passed-suite.mjs.other context can report more', + 'ci-visibility/vitest-tests/test-visibility-passed-suite.mjs.other context can report passed test', 'ci-visibility/vitest-tests/test-visibility-passed-suite.mjs.other context can skip', 'ci-visibility/vitest-tests/test-visibility-passed-suite.mjs.other context can todo', - 'ci-visibility/vitest-tests/test-visibility-failed-hooks.mjs.context can report failed test', - 'ci-visibility/vitest-tests/test-visibility-failed-hooks.mjs.context can report more', - 'ci-visibility/vitest-tests/test-visibility-failed-hooks.mjs.other context can report passed test', - 'ci-visibility/vitest-tests/test-visibility-failed-hooks.mjs.other context can report more', - 'ci-visibility/vitest-tests/test-visibility-passed-suite.mjs.no suite', + 'ci-visibility/vitest-tests/test-visibility-passed-suite.mjs.programmatic skip no suite', 'ci-visibility/vitest-tests/test-visibility-passed-suite.mjs.skip no suite', - 'ci-visibility/vitest-tests/test-visibility-passed-suite.mjs.programmatic skip no suite' ] ) const failedTests = testEvents.filter(test => test.content.meta[TEST_STATUS] === 'fail') - assert.includeMembers( - failedTests.map(test => test.content.resource), + assertObjectContains( + failedTests.map(test => test.content.resource).sort(), [ - 'ci-visibility/vitest-tests/test-visibility-failed-suite.mjs' + - '.test-visibility-failed-suite-first-describe can report failed test', 'ci-visibility/vitest-tests/test-visibility-failed-hooks.mjs.context can report failed test', 'ci-visibility/vitest-tests/test-visibility-failed-hooks.mjs.context can report more', + 'ci-visibility/vitest-tests/test-visibility-failed-hooks.mjs.other context can report more', 'ci-visibility/vitest-tests/test-visibility-failed-hooks.mjs.other context can report passed test', - 'ci-visibility/vitest-tests/test-visibility-failed-hooks.mjs.other context can report more' + 'ci-visibility/vitest-tests/test-visibility-failed-suite.mjs' + + '.test-visibility-failed-suite-first-describe can report failed test', ] ) const skippedTests = testEvents.filter(test => test.content.meta[TEST_STATUS] === 'skip') - assert.includeMembers( + assertObjectContains( skippedTests.map(test => test.content.resource), [ 'ci-visibility/vitest-tests/test-visibility-passed-suite.mjs.other context can skip', @@ -226,7 +227,10 @@ versions.forEach((version) => { assert.strictEqual(testSuite.content.meta[TEST_IS_TEST_FRAMEWORK_WORKER], 'true') } assert.strictEqual(testSuite.content.meta[TEST_COMMAND], 'vitest run') - assert.strictEqual(testSuite.content.meta[TEST_SOURCE_FILE].startsWith('ci-visibility/vitest-tests/test-visibility'), true) + assert.strictEqual( + testSuite.content.meta[TEST_SOURCE_FILE].startsWith('ci-visibility/vitest-tests/test-visibility'), + true + ) assert.strictEqual(testSuite.content.metrics[TEST_SOURCE_START], 1) assert.ok(testSuite.content.metrics[DD_HOST_CPU_COUNT] != null) }) @@ -252,17 +256,17 @@ versions.forEach((version) => { const testEvents = events.filter(event => event.type === 'test') assert.strictEqual(testEvents.length, 11) - assert.includeMembers(testEvents.map(test => test.content.resource), [ + assertObjectContains(testEvents.map(test => test.content.resource), [ 'ci-visibility/vitest-tests/flaky-test-retries.mjs.flaky test retries can retry tests that eventually pass', 'ci-visibility/vitest-tests/flaky-test-retries.mjs.flaky test retries can retry tests that eventually pass', 'ci-visibility/vitest-tests/flaky-test-retries.mjs.flaky test retries can retry tests that eventually pass', // passes at the third retry - 'ci-visibility/vitest-tests/flaky-test-retries.mjs.flaky test retries can retry tests that eventually pass', 'ci-visibility/vitest-tests/flaky-test-retries.mjs.flaky test retries can retry tests that never pass', 'ci-visibility/vitest-tests/flaky-test-retries.mjs.flaky test retries can retry tests that never pass', 'ci-visibility/vitest-tests/flaky-test-retries.mjs.flaky test retries can retry tests that never pass', 'ci-visibility/vitest-tests/flaky-test-retries.mjs.flaky test retries can retry tests that never pass', 'ci-visibility/vitest-tests/flaky-test-retries.mjs.flaky test retries can retry tests that never pass', + 'ci-visibility/vitest-tests/flaky-test-retries.mjs.flaky test retries can retry tests that eventually pass', // never passes 'ci-visibility/vitest-tests/flaky-test-retries.mjs.flaky test retries can retry tests that never pass', // passes on the first try @@ -275,7 +279,10 @@ versions.forEach((version) => { assert.strictEqual(eventuallyPassingTest.length, 4) assert.strictEqual(eventuallyPassingTest.filter(test => test.content.meta[TEST_STATUS] === 'fail').length, 3) assert.strictEqual(eventuallyPassingTest.filter(test => test.content.meta[TEST_STATUS] === 'pass').length, 1) - assert.strictEqual(eventuallyPassingTest.filter(test => test.content.meta[TEST_IS_RETRY] === 'true').length, 3) + assert.strictEqual( + eventuallyPassingTest.filter(test => test.content.meta[TEST_IS_RETRY] === 'true').length, + 3 + ) assert.strictEqual(eventuallyPassingTest.filter(test => test.content.meta[TEST_RETRY_REASON] === TEST_RETRY_REASON_TYPES.atr ).length, 3) @@ -323,7 +330,7 @@ versions.forEach((version) => { const testEvents = events.filter(event => event.type === 'test') assert.strictEqual(testEvents.length, 3) - assert.includeMembers(testEvents.map(test => test.content.resource), [ + assertObjectContains(testEvents.map(test => test.content.resource), [ 'ci-visibility/vitest-tests/flaky-test-retries.mjs.flaky test retries can retry tests that eventually pass', 'ci-visibility/vitest-tests/flaky-test-retries.mjs.flaky test retries can retry tests that never pass', 'ci-visibility/vitest-tests/flaky-test-retries.mjs.flaky test retries does not retry if unnecessary' @@ -364,10 +371,10 @@ versions.forEach((version) => { const testEvents = events.filter(event => event.type === 'test') assert.strictEqual(testEvents.length, 5) - assert.includeMembers(testEvents.map(test => test.content.resource), [ - 'ci-visibility/vitest-tests/flaky-test-retries.mjs.flaky test retries can retry tests that eventually pass', + assertObjectContains(testEvents.map(test => test.content.resource), [ 'ci-visibility/vitest-tests/flaky-test-retries.mjs.flaky test retries can retry tests that eventually pass', 'ci-visibility/vitest-tests/flaky-test-retries.mjs.flaky test retries can retry tests that never pass', + 'ci-visibility/vitest-tests/flaky-test-retries.mjs.flaky test retries can retry tests that eventually pass', 'ci-visibility/vitest-tests/flaky-test-retries.mjs.flaky test retries can retry tests that never pass', 'ci-visibility/vitest-tests/flaky-test-retries.mjs.flaky test retries does not retry if unnecessary' ]) @@ -564,21 +571,21 @@ versions.forEach((version) => { assert.strictEqual(tests.length, 14) - assert.includeMembers(tests.map(test => test.meta[TEST_NAME]), [ - 'early flake detection can retry tests that eventually pass', + assertObjectContains(tests.map(test => test.meta[TEST_NAME]), [ 'early flake detection can retry tests that eventually pass', 'early flake detection can retry tests that eventually pass', 'early flake detection can retry tests that eventually pass', - 'early flake detection can retry tests that eventually fail', - 'early flake detection can retry tests that eventually fail', - 'early flake detection can retry tests that eventually fail', - 'early flake detection can retry tests that eventually fail', 'early flake detection can retry tests that always pass', 'early flake detection can retry tests that always pass', 'early flake detection can retry tests that always pass', + 'early flake detection can retry tests that eventually fail', + 'early flake detection can retry tests that eventually fail', + 'early flake detection can retry tests that eventually fail', + 'early flake detection can retry tests that eventually pass', 'early flake detection can retry tests that always pass', 'early flake detection does not retry if it is not new', - 'early flake detection does not retry if the test is skipped' + 'early flake detection does not retry if the test is skipped', + 'early flake detection can retry tests that eventually fail', ]) const newTests = tests.filter(test => test.meta[TEST_IS_NEW] === 'true') // 4 executions of the 3 new tests + 1 new skipped test (not retried) @@ -652,14 +659,14 @@ versions.forEach((version) => { assert.strictEqual(tests.length, 10) - assert.includeMembers(tests.map(test => test.meta[TEST_NAME]), [ - 'early flake detection can retry tests that eventually pass', + assertObjectContains(tests.map(test => test.meta[TEST_NAME]), [ 'early flake detection can retry tests that eventually pass', 'early flake detection can retry tests that eventually pass', 'early flake detection can retry tests that eventually pass', 'early flake detection can retry tests that always pass', 'early flake detection can retry tests that always pass', 'early flake detection can retry tests that always pass', + 'early flake detection can retry tests that eventually pass', 'early flake detection can retry tests that always pass', 'early flake detection does not retry if it is not new', 'early flake detection does not retry if the test is skipped' @@ -786,7 +793,7 @@ versions.forEach((version) => { assert.strictEqual(tests.length, 4) - assert.includeMembers(tests.map(test => test.meta[TEST_NAME]), [ + assertObjectContains(tests.map(test => test.meta[TEST_NAME]), [ 'early flake detection can retry tests that eventually pass', 'early flake detection can retry tests that always pass', 'early flake detection does not retry if it is not new', @@ -850,7 +857,7 @@ versions.forEach((version) => { assert.strictEqual(tests.length, 4) - assert.includeMembers(tests.map(test => test.meta[TEST_NAME]), [ + assertObjectContains(tests.map(test => test.meta[TEST_NAME]), [ 'early flake detection can retry tests that eventually pass', 'early flake detection can retry tests that always pass', 'early flake detection does not retry if it is not new', @@ -919,7 +926,7 @@ versions.forEach((version) => { assert.strictEqual(tests[0].meta[TEST_SUITE], 'ci-visibility/subproject/vitest-test.mjs') // it's not considered new - assert.ok(!Object.hasOwn(tests[0].meta, TEST_IS_NEW)) + assert.ok(!('TEST_IS_NEW' in tests[0].meta)) }) childProcess = exec( @@ -971,12 +978,12 @@ versions.forEach((version) => { assert.strictEqual(tests.length, 8) - assert.includeMembers(tests.map(test => test.meta[TEST_NAME]), [ + assertObjectContains(tests.map(test => test.meta[TEST_NAME]), [ 'early flake detection can retry tests that eventually pass', 'early flake detection can retry tests that eventually pass', - 'early flake detection can retry tests that eventually pass', // repeated twice 'early flake detection can retry tests that always pass', 'early flake detection can retry tests that always pass', + 'early flake detection can retry tests that eventually pass', // repeated twice 'early flake detection can retry tests that always pass', // repeated twice 'early flake detection does not retry if it is not new', 'early flake detection does not retry if the test is skipped' @@ -995,7 +1002,7 @@ versions.forEach((version) => { const testSessionEvent = events.find(event => event.type === 'test_session_end').content assert.strictEqual(testSessionEvent.meta[TEST_STATUS], 'fail') - assert.ok(!Object.hasOwn(testSessionEvent.meta, TEST_EARLY_FLAKE_ENABLED)) + assert.ok(!('TEST_EARLY_FLAKE_ENABLED' in testSessionEvent.meta)) }) childProcess = exec( @@ -1050,7 +1057,7 @@ versions.forEach((version) => { assert.strictEqual(tests.length, 4) - assert.includeMembers(tests.map(test => test.meta[TEST_NAME]), [ + assertObjectContains(tests.map(test => test.meta[TEST_NAME]), [ 'early flake detection can retry tests that eventually pass', 'early flake detection can retry tests that always pass', 'early flake detection does not retry if it is not new', @@ -1278,7 +1285,7 @@ versions.forEach((version) => { const notRetriedTest = tests.find(test => test.meta[TEST_NAME].includes('is not retried')) - assert.ok(!Object.hasOwn(notRetriedTest.meta, DI_ERROR_DEBUG_INFO_CAPTURED)) + assert.ok(!('DI_ERROR_DEBUG_INFO_CAPTURED' in notRetriedTest.meta)) }) const logsPromise = receiver @@ -1288,10 +1295,10 @@ versions.forEach((version) => { ddsource: 'dd_debugger', level: 'error' }) - assert.ok(diLog.ddtags.includes('git.repository_url:')) - assert.ok(diLog.ddtags.includes('git.commit.sha:')) + assert.match(diLog.ddtags, /git.repository_url:/) + assert.match(diLog.ddtags, /git.commit.sha:/) assert.strictEqual(diLog.debugger.snapshot.language, 'javascript') - assert.deepInclude(diLog.debugger.snapshot.captures.lines['4'].locals, { + assertObjectContains(diLog.debugger.snapshot.captures.lines['4'].locals, { a: { type: 'number', value: '11' @@ -1414,7 +1421,7 @@ versions.forEach((version) => { assert.strictEqual(tests.length, 4) - assert.includeMembers(tests.map(test => test.meta[TEST_NAME]), [ + assertObjectContains(tests.map(test => test.meta[TEST_NAME]), [ 'early flake detection can retry tests that eventually pass', 'early flake detection can retry tests that always pass', 'early flake detection does not retry if it is not new', @@ -1432,7 +1439,7 @@ versions.forEach((version) => { const testSessionEvent = events.find(event => event.type === 'test_session_end').content assert.strictEqual(testSessionEvent.meta[TEST_STATUS], 'fail') - assert.ok(!Object.hasOwn(testSessionEvent.meta, TEST_EARLY_FLAKE_ENABLED)) + assert.ok(!('TEST_EARLY_FLAKE_ENABLED' in testSessionEvent.meta)) }) childProcess = exec( @@ -1527,12 +1534,12 @@ versions.forEach((version) => { if (isAttemptingToFix) { assert.strictEqual(testSession.meta[TEST_MANAGEMENT_ENABLED], 'true') } else { - assert.ok(!Object.hasOwn(testSession.meta, TEST_MANAGEMENT_ENABLED)) + assert.ok(!('TEST_MANAGEMENT_ENABLED' in testSession.meta)) } const resourceNames = tests.map(span => span.resource) - assert.includeMembers(resourceNames, + assertObjectContains(resourceNames, [ 'ci-visibility/vitest-tests/test-attempt-to-fix.mjs.attempt to fix tests can attempt to fix a test' ] @@ -1555,8 +1562,8 @@ versions.forEach((version) => { if (isAttemptingToFix) { assert.strictEqual(test.meta[TEST_MANAGEMENT_IS_ATTEMPT_TO_FIX], 'true') if (isFirstAttempt) { - assert.ok(!Object.hasOwn(test.meta, TEST_IS_RETRY)) - assert.ok(!Object.hasOwn(test.meta, TEST_RETRY_REASON)) + assert.ok(!('TEST_IS_RETRY' in test.meta)) + assert.ok(!('TEST_RETRY_REASON' in test.meta)) continue } assert.strictEqual(test.meta[TEST_IS_RETRY], 'true') @@ -1566,16 +1573,16 @@ versions.forEach((version) => { assert.strictEqual(test.meta[TEST_MANAGEMENT_ATTEMPT_TO_FIX_PASSED], 'true') } else if (shouldFailSometimes) { assert.strictEqual(test.meta[TEST_MANAGEMENT_ATTEMPT_TO_FIX_PASSED], 'false') - assert.ok(!Object.hasOwn(test.meta, TEST_HAS_FAILED_ALL_RETRIES)) + assert.ok(!('TEST_HAS_FAILED_ALL_RETRIES' in test.meta)) } else { assert.strictEqual(test.meta[TEST_HAS_FAILED_ALL_RETRIES], 'true') assert.strictEqual(test.meta[TEST_MANAGEMENT_ATTEMPT_TO_FIX_PASSED], 'false') } } } else { - assert.ok(!Object.hasOwn(test.meta, TEST_MANAGEMENT_IS_ATTEMPT_TO_FIX)) - assert.ok(!Object.hasOwn(test.meta, TEST_IS_RETRY)) - assert.ok(!Object.hasOwn(test.meta, TEST_RETRY_REASON)) + assert.ok(!('TEST_MANAGEMENT_IS_ATTEMPT_TO_FIX' in test.meta)) + assert.ok(!('TEST_IS_RETRY' in test.meta)) + assert.ok(!('TEST_RETRY_REASON' in test.meta)) } } }) @@ -1618,7 +1625,7 @@ versions.forEach((version) => { childProcess.on('exit', (exitCode) => { testAssertionsPromise.then(() => { - assert.ok(stdout.includes('I am running')) + assert.match(stdout, /I am running/) if (shouldAlwaysPass || (isAttemptingToFix && isQuarantining) || (isAttemptingToFix && isDisabling)) { assert.strictEqual(exitCode, 0) } else { @@ -1735,12 +1742,12 @@ versions.forEach((version) => { if (isDisabling) { assert.strictEqual(testSession.meta[TEST_MANAGEMENT_ENABLED], 'true') } else { - assert.ok(!Object.hasOwn(testSession.meta, TEST_MANAGEMENT_ENABLED)) + assert.ok(!('TEST_MANAGEMENT_ENABLED' in testSession.meta)) } const resourceNames = tests.map(span => span.resource) - assert.includeMembers(resourceNames, + assertObjectContains(resourceNames, [ 'ci-visibility/vitest-tests/test-disabled.mjs.disable tests can disable a test' ] @@ -1755,7 +1762,7 @@ versions.forEach((version) => { assert.strictEqual(skippedTest.meta[TEST_MANAGEMENT_IS_DISABLED], 'true') } else { assert.strictEqual(skippedTest.meta[TEST_STATUS], 'fail') - assert.ok(!Object.hasOwn(skippedTest.meta, TEST_MANAGEMENT_IS_DISABLED)) + assert.ok(!('TEST_MANAGEMENT_IS_DISABLED' in skippedTest.meta)) } }) @@ -1784,10 +1791,10 @@ versions.forEach((version) => { childProcess.on('exit', (exitCode) => { testAssertionsPromise.then(() => { if (isDisabling) { - assert.ok(!stdout.includes('I am running')) + assert.doesNotMatch(stdout, /I am running/) assert.strictEqual(exitCode, 0) } else { - assert.ok(stdout.includes('I am running')) + assert.match(stdout, /I am running/) assert.strictEqual(exitCode, 1) } done() @@ -1845,12 +1852,12 @@ versions.forEach((version) => { if (isQuarantining) { assert.strictEqual(testSession.meta[TEST_MANAGEMENT_ENABLED], 'true') } else { - assert.ok(!Object.hasOwn(testSession.meta, TEST_MANAGEMENT_ENABLED)) + assert.ok(!('TEST_MANAGEMENT_ENABLED' in testSession.meta)) } const resourceNames = tests.map(span => span.resource) - assert.includeMembers(resourceNames, + assertObjectContains(resourceNames, [ 'ci-visibility/vitest-tests/test-quarantine.mjs.quarantine tests can quarantine a test', 'ci-visibility/vitest-tests/test-quarantine.mjs.quarantine tests can pass normally' @@ -1867,7 +1874,7 @@ versions.forEach((version) => { assert.strictEqual(quarantinedTest.meta[TEST_MANAGEMENT_IS_QUARANTINED], 'true') } else { assert.strictEqual(quarantinedTest.meta[TEST_STATUS], 'fail') - assert.ok(!Object.hasOwn(quarantinedTest.meta, TEST_MANAGEMENT_IS_QUARANTINED)) + assert.ok(!('TEST_MANAGEMENT_IS_QUARANTINED' in quarantinedTest.meta)) } }) @@ -1896,7 +1903,7 @@ versions.forEach((version) => { childProcess.on('exit', (exitCode) => { testAssertionsPromise.then(() => { // it runs regardless of the quarantine status - assert.ok(stdout.includes('I am running when quarantined')) + assert.match(stdout, /I am running when quarantined/) if (isQuarantining) { // exit code 0 even though one of the tests failed assert.strictEqual(exitCode, 0) @@ -1939,7 +1946,7 @@ versions.forEach((version) => { .gatherPayloadsMaxTimeout(({ url }) => url.endsWith('/api/v2/citestcycle'), (payloads) => { const events = payloads.flatMap(({ payload }) => payload.events) const testSession = events.find(event => event.type === 'test_session_end').content - assert.ok(!Object.hasOwn(testSession.meta, TEST_MANAGEMENT_ENABLED)) + assert.ok(!('TEST_MANAGEMENT_ENABLED' in testSession.meta)) const tests = events.filter(event => event.type === 'test').map(event => event.content) // it is not retried assert.strictEqual(tests.length, 1) @@ -1972,7 +1979,7 @@ versions.forEach((version) => { once(childProcess.stderr, 'end'), eventsPromise ]) - assert.ok(testOutput.includes('Test management tests could not be fetched')) + assert.match(testOutput, /Test management tests could not be fetched/) }) }) } @@ -2061,12 +2068,12 @@ versions.forEach((version) => { if (isEfd) { assert.strictEqual(testSession.meta[TEST_EARLY_FLAKE_ENABLED], 'true') } else { - assert.ok(!Object.hasOwn(testSession.meta, TEST_EARLY_FLAKE_ENABLED)) + assert.ok(!('TEST_EARLY_FLAKE_ENABLED' in testSession.meta)) } const resourceNames = tests.map(span => span.resource) - assert.includeMembers(resourceNames, + assertObjectContains(resourceNames, [ 'ci-visibility/vitest-tests/impacted-test.mjs.impacted test can impacted test' ] @@ -2086,12 +2093,12 @@ versions.forEach((version) => { if (isModified) { assert.strictEqual(impactedTest.meta[TEST_IS_MODIFIED], 'true') } else { - assert.ok(!Object.hasOwn(impactedTest.meta, TEST_IS_MODIFIED)) + assert.ok(!('TEST_IS_MODIFIED' in impactedTest.meta)) } if (isNew) { assert.strictEqual(impactedTest.meta[TEST_IS_NEW], 'true') } else { - assert.ok(!Object.hasOwn(impactedTest.meta, TEST_IS_NEW)) + assert.ok(!('TEST_IS_NEW' in impactedTest.meta)) } } @@ -2197,7 +2204,7 @@ versions.forEach((version) => { testOutput += chunk.toString() }) childProcess.on('exit', (code) => { - assert.ok(testOutput.includes('result 10')) + assert.match(testOutput, /result 10/) assert.strictEqual(code, 0) done() }) diff --git a/packages/datadog-code-origin/test/helpers.js b/packages/datadog-code-origin/test/helpers.js index 9ab0be6248c..3cae531ae5f 100644 --- a/packages/datadog-code-origin/test/helpers.js +++ b/packages/datadog-code-origin/test/helpers.js @@ -19,15 +19,15 @@ module.exports = { if (frame.method) { assert.strictEqual(tags['_dd.code_origin.frames.0.method'], frame.method) } else { - assert.ok(!Object.hasOwn(tags, '_dd.code_origin.frames.0.method')) + assert.ok(!('_dd.code_origin.frames.0.method' in tags)) } if (frame.type) { assert.strictEqual(tags['_dd.code_origin.frames.0.type'], frame.type) } else { - assert.ok(!Object.hasOwn(tags, '_dd.code_origin.frames.0.type')) + assert.ok(!('_dd.code_origin.frames.0.type' in tags)) } // The second frame should not be present, because we only collect 1 frame for entry spans - assert.ok(!Object.hasOwn(tags, '_dd.code_origin.frames.1.file')) + assert.ok(!('_dd.code_origin.frames.1.file' in tags)) } } diff --git a/packages/datadog-core/test/storage.spec.js b/packages/datadog-core/test/storage.spec.js index d3790ce7e8e..259532fb099 100644 --- a/packages/datadog-core/test/storage.spec.js +++ b/packages/datadog-core/test/storage.spec.js @@ -58,7 +58,7 @@ describe('storage', () => { for (const sym of Object.getOwnPropertySymbols(resource)) { if (sym.toString() === 'Symbol(kResourceStore)' && resource[sym]) { - assert.ok(!Object.hasOwn(resource[sym], 'internal')) + assert.ok(!('internal' in resource[sym])) } } }) diff --git a/packages/datadog-instrumentations/test/express-mongo-sanitize.spec.js b/packages/datadog-instrumentations/test/express-mongo-sanitize.spec.js index babfbfbaafd..99692597bb8 100644 --- a/packages/datadog-instrumentations/test/express-mongo-sanitize.spec.js +++ b/packages/datadog-instrumentations/test/express-mongo-sanitize.spec.js @@ -103,7 +103,10 @@ describe('express-mongo-sanitize', () => { await axios.get(`http://localhost:${port}/?param=paramvalue`) sinon.assert.calledOnce(subscription) - assert.deepStrictEqual(subscription.firstCall.args[0].sanitizedProperties, ['body', 'params', 'headers', 'query']) + assert.deepStrictEqual( + subscription.firstCall.args[0].sanitizedProperties, + ['body', 'params', 'headers', 'query'], + ) assert.strictEqual(subscription.firstCall.args[0].req.query.param, 'paramvalue') }) @@ -113,7 +116,11 @@ describe('express-mongo-sanitize', () => { await axios.get(`http://localhost:${port}/?param[$eq]=paramvalue`) sinon.assert.calledOnce(subscription) - assert.deepStrictEqual(subscription.firstCall.args[0].sanitizedProperties, ['body', 'params', 'headers', 'query']) + assert.deepStrictEqual( + subscription.firstCall.args[0].sanitizedProperties, + ['body', 'params', 'headers', 'query'], + 'Sanitized properties should be called with expected parameters' + ) assert.strictEqual(subscription.firstCall.args[0].req.query.param.$eq, undefined) }) }) diff --git a/packages/datadog-instrumentations/test/helpers/check-require-cache.spec.js b/packages/datadog-instrumentations/test/helpers/check-require-cache.spec.js index e09615fa342..64618c4d3eb 100644 --- a/packages/datadog-instrumentations/test/helpers/check-require-cache.spec.js +++ b/packages/datadog-instrumentations/test/helpers/check-require-cache.spec.js @@ -5,7 +5,6 @@ const { exec } = require('node:child_process') const { expect } = require('chai') const { describe, it } = require('mocha') -const { assertObjectContains } = require('../../../../integration-tests/helpers') describe('check-require-cache', () => { const opts = { @@ -26,7 +25,7 @@ describe('check-require-cache', () => { it('should find warnings when tracer loaded late', (done) => { exec(`${process.execPath} ./check-require-cache/bad-order.js`, opts, (error, stdout, stderr) => { assert.strictEqual(error, null) - assertObjectContains(stderr, "Package 'express' was loaded") + assert.match(stderr, /Package 'express' was loaded/) done() }) }) diff --git a/packages/datadog-plugin-amqp10/test/index.spec.js b/packages/datadog-plugin-amqp10/test/index.spec.js index f63b4cd7ee4..ad59e1b66b5 100644 --- a/packages/datadog-plugin-amqp10/test/index.spec.js +++ b/packages/datadog-plugin-amqp10/test/index.spec.js @@ -84,7 +84,7 @@ describe('Plugin', () => { assert.strictEqual(span.name, expectedSchema.send.opName) assert.strictEqual(span.service, expectedSchema.send.serviceName) assert.strictEqual(span.resource, 'send amq.topic') - assert.ok(!Object.hasOwn(span, 'type')) + assert.ok(!('type' in span)) assert.strictEqual(span.meta['span.kind'], 'producer') assert.strictEqual(span.meta['out.host'], 'localhost') assert.strictEqual(span.meta['amqp.connection.host'], 'localhost') diff --git a/packages/datadog-plugin-amqplib/test/index.spec.js b/packages/datadog-plugin-amqplib/test/index.spec.js index 408efc892d8..741a23b4f9c 100644 --- a/packages/datadog-plugin-amqplib/test/index.spec.js +++ b/packages/datadog-plugin-amqplib/test/index.spec.js @@ -78,7 +78,7 @@ describe('Plugin', () => { assert.strictEqual(span.name, expectedSchema.controlPlane.opName) assert.strictEqual(span.service, expectedSchema.controlPlane.serviceName) assert.strictEqual(span.resource, `queue.declare ${queue}`) - assert.ok(!Object.hasOwn(span, 'type')) + assert.ok(!('type' in span)) assert.strictEqual(span.meta['span.kind'], 'client') assert.strictEqual(span.meta['out.host'], 'localhost') assert.strictEqual(span.meta.component, 'amqplib') @@ -99,7 +99,7 @@ describe('Plugin', () => { assert.strictEqual(span.name, expectedSchema.controlPlane.opName) assert.strictEqual(span.service, expectedSchema.controlPlane.serviceName) assert.strictEqual(span.resource, `queue.delete ${queue}`) - assert.ok(!Object.hasOwn(span, 'type')) + assert.ok(!('type' in span)) assert.strictEqual(span.meta['span.kind'], 'client') assert.strictEqual(span.meta['out.host'], 'localhost') assert.strictEqual(span.meta.component, 'amqplib') @@ -158,7 +158,7 @@ describe('Plugin', () => { assert.strictEqual(span.name, expectedSchema.send.opName) assert.strictEqual(span.service, expectedSchema.send.serviceName) assert.strictEqual(span.resource, 'basic.publish exchange routingKey') - assert.ok(!Object.hasOwn(span, 'type')) + assert.ok(!('type' in span)) assert.strictEqual(span.meta['out.host'], 'localhost') assert.strictEqual(span.meta['span.kind'], 'producer') assert.strictEqual(span.meta['amqp.routingKey'], 'routingKey') diff --git a/packages/datadog-plugin-apollo/test/index.spec.js b/packages/datadog-plugin-apollo/test/index.spec.js index c4c86d355ba..ab34fb5f276 100644 --- a/packages/datadog-plugin-apollo/test/index.spec.js +++ b/packages/datadog-plugin-apollo/test/index.spec.js @@ -148,7 +148,7 @@ describe('Plugin', () => { assert.strictEqual(traces[0][0].type, 'web') assert.strictEqual(traces[0][0].error, 0) assert.strictEqual(traces[0][0].meta['graphql.operation.name'], operationName) - assert.ok(!Object.hasOwn(traces[0][0].meta, 'graphql.source')) + assert.ok(!('graphql.source' in traces[0][0].meta)) assert.strictEqual(traces[0][0].meta['graphql.operation.type'], 'query') assert.strictEqual(traces[0][0].meta.component, 'apollo.gateway') assert.strictEqual(traces[0][0].meta['_dd.integration'], 'apollo.gateway') @@ -202,7 +202,7 @@ describe('Plugin', () => { assert.strictEqual(traces[0][0].resource, '{hello(name:"")}') assert.strictEqual(traces[0][0].type, 'web') assert.strictEqual(traces[0][0].error, 0) - assert.ok(!Object.hasOwn(traces[0][0].meta, 'graphql.source')) + assert.ok(!('graphql.source' in traces[0][0].meta)) assert.strictEqual(traces[0][0].meta['graphql.operation.type'], 'query') assert.strictEqual(traces[0][0].meta.component, 'apollo.gateway') }) @@ -234,7 +234,7 @@ describe('Plugin', () => { assert.strictEqual(traces[0][0].resource, '{human{address{civicNumber street}name}}') assert.strictEqual(traces[0][0].type, 'web') assert.strictEqual(traces[0][0].error, 0) - assert.ok(!Object.hasOwn(traces[0][0].meta, 'graphql.source')) + assert.ok(!('graphql.source' in traces[0][0].meta)) assert.strictEqual(traces[0][0].meta['graphql.operation.type'], 'query') assert.strictEqual(traces[0][0].meta.component, 'apollo.gateway') }) diff --git a/packages/datadog-plugin-aws-sdk/test/kinesis.spec.js b/packages/datadog-plugin-aws-sdk/test/kinesis.spec.js index 7dc7f3ae014..3baf4c8c6f4 100644 --- a/packages/datadog-plugin-aws-sdk/test/kinesis.spec.js +++ b/packages/datadog-plugin-aws-sdk/test/kinesis.spec.js @@ -148,7 +148,7 @@ describe('Kinesis', function () { helpers.getTestData(kinesis, streamName, data, (err, data) => { if (err) return done(err) - assert.ok(!Object.hasOwn(data, '_datadog')) + assert.ok(!('_datadog' in data)) done() }) @@ -186,7 +186,7 @@ describe('Kinesis', function () { helpers.getTestData(kinesis, streamName, data, (err, data) => { if (err) return done(err) - assert.ok(!Object.hasOwn(data, '_datadog')) + assert.ok(!('_datadog' in data)) done() }) diff --git a/packages/datadog-plugin-aws-sdk/test/sns.spec.js b/packages/datadog-plugin-aws-sdk/test/sns.spec.js index 9e5d2c5d450..3565c1495d5 100644 --- a/packages/datadog-plugin-aws-sdk/test/sns.spec.js +++ b/packages/datadog-plugin-aws-sdk/test/sns.spec.js @@ -459,7 +459,7 @@ describe('Sns', function () { if (err) return done(err) try { - assert.ok(!data.Messages[0].Body.includes('datadog')) + assert.doesNotMatch(data.Messages[0].Body, /datadog/) done() } catch (e) { done(e) diff --git a/packages/datadog-plugin-bunyan/test/index.spec.js b/packages/datadog-plugin-bunyan/test/index.spec.js index 25d0dc9de3b..ebf7234528b 100644 --- a/packages/datadog-plugin-bunyan/test/index.spec.js +++ b/packages/datadog-plugin-bunyan/test/index.spec.js @@ -92,7 +92,7 @@ describe('Plugin', () => { logger.info(record) sinon.assert.called(stream.write) - assert.ok(!Object.hasOwn(record, 'dd')) + assert.ok(!('dd' in record)) }) }) @@ -104,8 +104,8 @@ describe('Plugin', () => { const record = JSON.parse(stream.write.firstCall.args[0].toString()) assert.ok(Object.hasOwn(record, 'dd')) - assert.ok(!Object.hasOwn(record.dd, 'trace_id')) - assert.ok(!Object.hasOwn(record.dd, 'span_id')) + assert.ok(!('trace_id' in record.dd)) + assert.ok(!('span_id' in record.dd)) }) }) }) diff --git a/packages/datadog-plugin-child_process/test/index.spec.js b/packages/datadog-plugin-child_process/test/index.spec.js index 403c5b362b7..13fca709a84 100644 --- a/packages/datadog-plugin-child_process/test/index.spec.js +++ b/packages/datadog-plugin-child_process/test/index.spec.js @@ -9,7 +9,6 @@ const { storage } = require('../../datadog-core') const agent = require('../../dd-trace/test/plugins/agent') const { expectSomeSpan } = require('../../dd-trace/test/plugins/helpers') const ChildProcessPlugin = require('../src') -const { assertObjectContains } = require('../../../integration-tests/helpers') function noop () {} @@ -419,7 +418,7 @@ describe('Child process plugin', () => { const result = await execFileAsync('echo', ['bluebird-test']) assert.ok(result != null) - assertObjectContains(result.stdout, 'bluebird-test') + assert.strictEqual(result.stdout, 'bluebird-test\n') return expectedPromise }) @@ -432,7 +431,7 @@ describe('Child process plugin', () => { promises.push( execFileAsync('echo', [`concurrent-test-${i}`]) .then(result => { - assertObjectContains(result.stdout, `concurrent-test-${i}`) + assert.strictEqual(result.stdout, `concurrent-test-${i}\n`) return result }) ) @@ -480,7 +479,7 @@ describe('Child process plugin', () => { assert.ok(promise.constructor.version != null) const result = await promise - assertObjectContains(result.stdout, 'util-promisify-test') + assert.strictEqual(result.stdout, 'util-promisify-test\n') }) }) diff --git a/packages/datadog-plugin-child_process/test/scrub-cmd-params.spec.js b/packages/datadog-plugin-child_process/test/scrub-cmd-params.spec.js index b11f11de942..31add9c558c 100644 --- a/packages/datadog-plugin-child_process/test/scrub-cmd-params.spec.js +++ b/packages/datadog-plugin-child_process/test/scrub-cmd-params.spec.js @@ -37,9 +37,15 @@ describe('scrub cmds', () => { it('Should scrub secret values', () => { assert.deepStrictEqual(scrubCmdParams('cmd --pass abc --token=def'), ['cmd', '--pass', '?', '--token=?']) - assert.deepStrictEqual(scrubCmdParams('mysqladmin -u root password very_secret'), ['mysqladmin', '-u', 'root', 'password', '?']) - - assert.deepStrictEqual(scrubCmdParams('test -password very_secret -api_key 1234'), ['test', '-password', '?', '-api_key', '?']) + assert.deepStrictEqual( + scrubCmdParams('mysqladmin -u root password very_secret'), + ['mysqladmin', '-u', 'root', 'password', '?'] + ) + + assert.deepStrictEqual( + scrubCmdParams('test -password very_secret -api_key 1234'), + ['test', '-password', '?', '-api_key', '?'] + ) assert.deepStrictEqual(scrubCmdParams('test --address https://some.address.com --email testing@to.es --api-key 1234'), ['test', '--address', '?', '--email', '?', '--api-key', '?']) }) diff --git a/packages/datadog-plugin-elasticsearch/test/index.spec.js b/packages/datadog-plugin-elasticsearch/test/index.spec.js index 3852086de33..2a1c271a8d6 100644 --- a/packages/datadog-plugin-elasticsearch/test/index.spec.js +++ b/packages/datadog-plugin-elasticsearch/test/index.spec.js @@ -95,7 +95,10 @@ describe('Plugin', () => { assert.strictEqual(traces[0][0].meta['elasticsearch.params'], '{"sort":"name","size":100}') } else { assert.ok('elasticsearch.body' in traces[0][0].meta) - assert.strictEqual(traces[0][0].meta['elasticsearch.body'], '{"query":{"match_all":{}},"sort":"name","size":100}') + assert.strictEqual( + traces[0][0].meta['elasticsearch.body'], + '{"query":{"match_all":{}},"sort":"name","size":100}' + ) } }) .then(done) @@ -124,7 +127,10 @@ describe('Plugin', () => { assert.strictEqual(traces[0][0].meta['elasticsearch.method'], 'POST') assert.strictEqual(traces[0][0].meta['elasticsearch.url'], '/_msearch') assert.ok('elasticsearch.body' in traces[0][0].meta) - assert.strictEqual(traces[0][0].meta['elasticsearch.body'], '[{"index":"docs"},{"query":{"match_all":{}}},{"index":"docs2"},{"query":{"match_all":{}}}]') + assert.strictEqual( + traces[0][0].meta['elasticsearch.body'], + '[{"index":"docs"},{"query":{"match_all":{}}},{"index":"docs2"},{"query":{"match_all":{}}}]' + ) }) .then(done) .catch(done) @@ -150,7 +156,7 @@ describe('Plugin', () => { it('should skip tags for unavailable fields', done => { agent .assertSomeTraces(traces => { - assert.ok(!Object.hasOwn(traces[0][0].meta, 'elasticsearch.body')) + assert.ok(!('elasticsearch.body' in traces[0][0].meta)) }) .then(done) .catch(done) diff --git a/packages/datadog-plugin-express/test/code_origin.spec.js b/packages/datadog-plugin-express/test/code_origin.spec.js index 718658eb8c6..fa1b3440ca6 100644 --- a/packages/datadog-plugin-express/test/code_origin.spec.js +++ b/packages/datadog-plugin-express/test/code_origin.spec.js @@ -42,7 +42,7 @@ describe('Plugin', () => { agent.assertSomeTraces(traces => { const spans = traces[0] const tagNames = Object.keys(spans[0].meta) - assert.doesNotMatch(tagNames, /code_origin/) + assert.doesNotMatch(tagNames.join(','), /code_origin/) }), axios.get(`http://localhost:${listener.address().port}/user`) ]).then(() => done(), done) diff --git a/packages/datadog-plugin-express/test/index.spec.js b/packages/datadog-plugin-express/test/index.spec.js index 5c96381d22b..65305889bd8 100644 --- a/packages/datadog-plugin-express/test/index.spec.js +++ b/packages/datadog-plugin-express/test/index.spec.js @@ -1376,7 +1376,7 @@ describe('Plugin', () => { assert.strictEqual(spans[0].resource, 'GET') assert.strictEqual(spans[0].meta['http.status_code'], '404') assert.strictEqual(spans[0].meta.component, 'express') - assert.ok(!Object.hasOwn(spans[0].meta, 'http.route')) + assert.ok(!('http.route' in spans[0].meta)) }).then(done).catch(done) axios diff --git a/packages/datadog-plugin-fastify/test/code_origin.spec.js b/packages/datadog-plugin-fastify/test/code_origin.spec.js index 43412fcbceb..b91dea04a72 100644 --- a/packages/datadog-plugin-fastify/test/code_origin.spec.js +++ b/packages/datadog-plugin-fastify/test/code_origin.spec.js @@ -50,7 +50,7 @@ describe('Plugin', () => { agent.assertSomeTraces(traces => { const spans = traces[0] const tagNames = Object.keys(spans[0].meta) - assert.doesNotMatch(tagNames, /code_origin/) + assert.doesNotMatch(tagNames.join(','), /code_origin/) }), axios.get(`http://localhost:${app.server.address().port}/user`) ]) diff --git a/packages/datadog-plugin-fastify/test/tracing.spec.js b/packages/datadog-plugin-fastify/test/tracing.spec.js index 884833e136a..f8ef0df4981 100644 --- a/packages/datadog-plugin-fastify/test/tracing.spec.js +++ b/packages/datadog-plugin-fastify/test/tracing.spec.js @@ -488,9 +488,9 @@ describe('Plugin', () => { assert.strictEqual(spans[0].name, 'fastify.request') assert.strictEqual(spans[0].resource, 'GET /user') assert.strictEqual(spans[0].error, 0) - assert.ok(!Object.hasOwn(spans[0].meta, ERROR_TYPE)) - assert.ok(!Object.hasOwn(spans[0].meta, ERROR_MESSAGE)) - assert.ok(!Object.hasOwn(spans[0].meta, ERROR_STACK)) + assert.ok(!(ERROR_TYPE in spans[0].meta)) + assert.ok(!(ERROR_MESSAGE in spans[0].meta)) + assert.ok(!(ERROR_STACK in spans[0].meta)) assert.strictEqual(spans[0].meta.component, 'fastify') }) .then(done) diff --git a/packages/datadog-plugin-fetch/test/index.spec.js b/packages/datadog-plugin-fetch/test/index.spec.js index 809d47b2283..de67cebf267 100644 --- a/packages/datadog-plugin-fetch/test/index.spec.js +++ b/packages/datadog-plugin-fetch/test/index.spec.js @@ -284,7 +284,7 @@ describe('Plugin', function () { agent .assertSomeTraces(traces => { assert.strictEqual(traces[0][0].error, 0) - assert.ok(!Object.hasOwn(traces[0][0].meta, 'http.status_code')) + assert.ok(!('http.status_code' in traces[0][0].meta)) }) .then(done) .catch(done) diff --git a/packages/datadog-plugin-graphql/test/index.spec.js b/packages/datadog-plugin-graphql/test/index.spec.js index 759f106dad8..3bddf158e83 100644 --- a/packages/datadog-plugin-graphql/test/index.spec.js +++ b/packages/datadog-plugin-graphql/test/index.spec.js @@ -288,7 +288,7 @@ describe('Plugin', () => { assert.strictEqual(spans[0].resource, 'query MyQuery{hello(name:"")}') assert.strictEqual(spans[0].type, 'graphql') assert.strictEqual(spans[0].error, 0) - assert.ok(!Object.hasOwn(spans[0].meta, 'graphql.source')) + assert.ok(!('graphql.source' in spans[0].meta)) assert.strictEqual(spans[0].meta['graphql.operation.type'], 'query') assert.strictEqual(spans[0].meta['graphql.operation.name'], 'MyQuery') assert.strictEqual(spans[0].meta.component, 'graphql') @@ -351,7 +351,7 @@ describe('Plugin', () => { assert.strictEqual(span.resource, 'graphql.parse') assert.strictEqual(span.type, 'graphql') assert.strictEqual(span.error, 0) - assert.ok(!Object.hasOwn(span.meta, 'graphql.source')) + assert.ok(!('graphql.source' in span.meta)) assert.strictEqual(span.meta.component, 'graphql') }) .then(done) @@ -373,7 +373,7 @@ describe('Plugin', () => { assert.strictEqual(span.resource, 'graphql.validate') assert.strictEqual(span.type, 'graphql') assert.strictEqual(span.error, 0) - assert.ok(!Object.hasOwn(span.meta, 'graphql.source')) + assert.ok(!('graphql.source' in span.meta)) assert.strictEqual(span.meta.component, 'graphql') }) .then(done) @@ -395,7 +395,7 @@ describe('Plugin', () => { assert.strictEqual(spans[0].resource, 'query MyQuery{hello(name:"")}') assert.strictEqual(spans[0].type, 'graphql') assert.strictEqual(spans[0].error, 0) - assert.ok(!Object.hasOwn(spans[0].meta, 'graphql.source')) + assert.ok(!('graphql.source' in spans[0].meta)) assert.strictEqual(spans[0].meta['graphql.operation.type'], 'query') assert.strictEqual(spans[0].meta['graphql.operation.name'], 'MyQuery') assert.strictEqual(spans[0].meta.component, 'graphql') @@ -412,7 +412,7 @@ describe('Plugin', () => { agent .assertSomeTraces(traces => { const spans = sort(traces[0]) - assert.ok(!Object.hasOwn(spans[0].meta, 'graphql.variables')) + assert.ok(!('graphql.variables' in spans[0].meta)) }) .then(done) .catch(done) @@ -437,7 +437,7 @@ describe('Plugin', () => { assert.strictEqual(spans[1].meta['graphql.field.name'], 'hello') assert.strictEqual(spans[1].meta['graphql.field.path'], 'hello') assert.strictEqual(spans[1].meta['graphql.field.type'], 'String') - assert.ok(!Object.hasOwn(spans[1].meta, 'graphql.source')) + assert.ok(!('graphql.source' in spans[1].meta)) assert.strictEqual(spans[1].meta.component, 'graphql') }) .then(done) @@ -833,7 +833,7 @@ describe('Plugin', () => { return graphql.graphql({ schema, source }) .then(() => graphql.graphql({ schema, source: subscription })) .then(result => { - assert.ok(!Object.hasOwn(result, 'errors')) + assert.ok(!('errors' in result)) }) }) @@ -869,7 +869,7 @@ describe('Plugin', () => { const source = '{ human { oneTime } }' const result = await graphql.graphql({ schema, source }) - assert.ok(!Object.hasOwn(result, 'errors')) + assert.ok(!('errors' in result)) assert.strictEqual(result.data.human.oneTime, 'one-time result') }) @@ -885,7 +885,7 @@ describe('Plugin', () => { assert.strictEqual(spans[0].service, expectedSchema.server.serviceName) assert.strictEqual(spans[0].name, expectedSchema.server.opName) assert.strictEqual(spans[0].resource, 'query MyQuery{hello(name:"")}') - assert.ok(!Object.hasOwn(spans[0].meta, 'graphql.source')) + assert.ok(!('graphql.source' in spans[0].meta)) assert.strictEqual(spans[0].meta.component, 'graphql') }) .then(done) @@ -966,10 +966,10 @@ describe('Plugin', () => { const spanEvents = agent.unformatSpanEvents(spans[0]) assert.strictEqual(spanEvents.length, 1) - assert.ok(Object.hasOwn(spanEvents[0], 'startTime')) + assert.ok(('startTime' in spanEvents[0])) assert.strictEqual(spanEvents[0].name, 'dd.graphql.query.error') assert.strictEqual(spanEvents[0].attributes.type, 'GraphQLError') - assert.ok(Object.hasOwn(spanEvents[0].attributes, 'stacktrace')) + assert.ok(('stacktrace' in spanEvents[0].attributes)) assert.strictEqual(spanEvents[0].attributes.message, 'Field "address" of ' + 'type "Address" must have a selection of subfields. Did you mean "address { ... }"?') assert.strictEqual(spanEvents[0].attributes.locations.length, 1) @@ -1206,7 +1206,7 @@ describe('Plugin', () => { assert.strictEqual(spans[0].service, expectedSchema.server.serviceName) assert.strictEqual(spans[0].name, expectedSchema.server.opName) assert.strictEqual(spans[0].resource, 'query SecondQuery{hello(name:"")}') - assert.ok(!Object.hasOwn(spans[0].meta, 'graphql.source')) + assert.ok(!('graphql.source' in spans[0].meta)) assert.strictEqual(spans[0].meta['graphql.operation.type'], 'query') assert.strictEqual(spans[0].meta['graphql.operation.name'], 'SecondQuery') assert.strictEqual(spans[0].meta.component, 'graphql') @@ -1238,7 +1238,7 @@ describe('Plugin', () => { assert.strictEqual(spans[0].service, 'test') assert.strictEqual(spans[0].name, expectedSchema.server.opName) assert.strictEqual(spans[0].resource, resource) - assert.ok(!Object.hasOwn(spans[0].meta, 'graphql.source')) + assert.ok(!('graphql.source' in spans[0].meta)) assert.strictEqual(spans[0].meta['graphql.operation.type'], 'query') assert.strictEqual(spans[0].meta['graphql.operation.name'], 'WithFragments') assert.strictEqual(spans[0].meta.component, 'graphql') @@ -1263,9 +1263,9 @@ describe('Plugin', () => { assert.strictEqual(spans[0].service, 'test') assert.strictEqual(spans[0].name, 'graphql.parse') assert.strictEqual(spans[0].resource, 'graphql.parse') - assert.ok(!Object.hasOwn(spans[0].meta, 'graphql.source')) - assert.ok(!Object.hasOwn(spans[0].meta, 'graphql.operation.type')) - assert.ok(!Object.hasOwn(spans[0].meta, 'graphql.operation.name')) + assert.ok(!('graphql.source' in spans[0].meta)) + assert.ok(!('graphql.operation.type' in spans[0].meta)) + assert.ok(!('graphql.operation.name' in spans[0].meta)) assert.strictEqual(spans[0].meta.component, 'graphql') }) .then(done) @@ -1288,7 +1288,7 @@ describe('Plugin', () => { assert.strictEqual(spans[0].name, expectedSchema.server.opName) assert.strictEqual(spans[0].resource, 'query MyQuery{hello(name:"")}') assert.strictEqual(spans[0].type, 'graphql') - assert.ok(!Object.hasOwn(spans[0].meta, 'graphql.source')) + assert.ok(!('graphql.source' in spans[0].meta)) assert.strictEqual(spans[0].meta['graphql.operation.type'], 'query') assert.strictEqual(spans[0].meta['graphql.operation.name'], 'MyQuery') assert.strictEqual(spans[0].meta.component, 'graphql') @@ -1319,7 +1319,7 @@ describe('Plugin', () => { // assert.strictEqual(spans[0].service, 'test') // assert.strictEqual(spans[0].name, expectedSchema.server.opName) // assert.strictEqual(spans[0].resource, resource) - // assert.ok(!Object.hasOwn(spans[0].meta, 'graphql.source')) + // assert.ok(!('graphql.source' in spans[0].meta)) // assert.strictEqual(spans[0].meta['graphql.operation.type'], 'query') // assert.strictEqual(spans[0].meta['graphql.operation.name'], 'WithFragments') // }) @@ -1442,7 +1442,7 @@ describe('Plugin', () => { const spans = sort(traces[0]) assert.strictEqual(spans[0].meta['graphql.variables.title'], 'planet') - assert.ok(!Object.hasOwn(spans[0].meta, 'graphql.variables.who')) + assert.ok(!('graphql.variables.who' in spans[0].meta)) }) .then(done) .catch(done) @@ -1847,13 +1847,13 @@ describe('Plugin', () => { assert.strictEqual(spans[0].name, expectedSchema.server.opName) assert.strictEqual(spans[0].resource, 'query MyQuery{hello}') - assert.ok(!Object.hasOwn(spans[0].meta, 'graphql.source')) + assert.ok(!('graphql.source' in spans[0].meta)) assert.strictEqual(spans[1].name, 'graphql.resolve') assert.strictEqual(spans[1].resource, 'hello:String') assert.strictEqual(spans[2].name, 'graphql.validate') - assert.ok(!Object.hasOwn(spans[2].meta, 'graphql.source')) + assert.ok(!('graphql.source' in spans[2].meta)) }) .then(done) .catch(done) diff --git a/packages/datadog-plugin-grpc/test/server.spec.js b/packages/datadog-plugin-grpc/test/server.spec.js index ec17b0601a8..49f8bf6fb70 100644 --- a/packages/datadog-plugin-grpc/test/server.spec.js +++ b/packages/datadog-plugin-grpc/test/server.spec.js @@ -240,7 +240,7 @@ describe('Plugin', () => { assert.strictEqual(traces[0][0].error, 1) assert.strictEqual(traces[0][0].meta[ERROR_MESSAGE], 'foobar') assert.strictEqual(traces[0][0].meta[ERROR_TYPE], 'Error') - assert.ok(!Object.hasOwn(traces[0][0].meta, 'grpc.status.code')) + assert.ok(!('grpc.status.code' in traces[0][0].meta)) }) }) diff --git a/packages/datadog-plugin-hapi/test/index.spec.js b/packages/datadog-plugin-hapi/test/index.spec.js index a04bd686688..b7170029679 100644 --- a/packages/datadog-plugin-hapi/test/index.spec.js +++ b/packages/datadog-plugin-hapi/test/index.spec.js @@ -108,7 +108,10 @@ describe('Plugin', () => { assert.ok(Object.hasOwn(traces[0][0].meta, 'http.status_code')) assert.strictEqual(traces[0][0].meta.component, 'hapi') assert.strictEqual(traces[0][0].meta['_dd.integration'], 'hapi') - assert.ok(((Number(traces[0][0].meta['http.status_code'])) >= (200) && (Number(traces[0][0].meta['http.status_code'])) <= (299))) + assert.ok( + Number(traces[0][0].meta['http.status_code']) >= 200 && + Number(traces[0][0].meta['http.status_code']) <= 299 + ) }) .then(done) .catch(done) diff --git a/packages/datadog-plugin-http/test/client.spec.js b/packages/datadog-plugin-http/test/client.spec.js index e29b1ecabe3..e4b3e8216a4 100644 --- a/packages/datadog-plugin-http/test/client.spec.js +++ b/packages/datadog-plugin-http/test/client.spec.js @@ -627,7 +627,7 @@ describe('Plugin', () => { assert.strictEqual(traces[0][0].meta[ERROR_MESSAGE], error.message) assert.strictEqual(traces[0][0].meta[ERROR_TYPE], error.name) assert.strictEqual(traces[0][0].meta[ERROR_STACK], error.stack) - assert.ok(!Object.hasOwn(traces[0][0].meta, 'http.status_code')) + assert.ok(!('http.status_code' in traces[0][0].meta)) assert.strictEqual(traces[0][0].meta.component, 'http') }) .then(done) @@ -654,7 +654,7 @@ describe('Plugin', () => { agent .assertSomeTraces(traces => { assert.strictEqual(traces[0][0].error, 0) - assert.ok(!Object.hasOwn(traces[0][0].meta, 'http.status_code')) + assert.ok(!('http.status_code' in traces[0][0].meta)) }) .then(done) .catch(done) @@ -678,7 +678,7 @@ describe('Plugin', () => { agent .assertSomeTraces(traces => { assert.strictEqual(traces[0][0].error, 1) - assert.ok(!Object.hasOwn(traces[0][0].meta, 'http.status_code')) + assert.ok(!('http.status_code' in traces[0][0].meta)) }) .then(done) .catch(done) @@ -944,7 +944,7 @@ describe('Plugin', () => { agent .assertSomeTraces(traces => { assert.strictEqual(traces[0][0].error, 1) - assert.ok(!Object.hasOwn(traces[0][0].meta, 'http.status_code')) + assert.ok(!('http.status_code' in traces[0][0].meta)) }) .then(done) .catch(done) diff --git a/packages/datadog-plugin-jest/test/util.spec.js b/packages/datadog-plugin-jest/test/util.spec.js index b5759470455..e0c73b59a90 100644 --- a/packages/datadog-plugin-jest/test/util.spec.js +++ b/packages/datadog-plugin-jest/test/util.spec.js @@ -178,7 +178,13 @@ describe('getJestSuitesToRun', () => { const rootDir = __dirname getJestSuitesToRun(skippableSuites, tests, rootDir) - assert.deepStrictEqual(globalConfig.testEnvironmentOptions._ddUnskippable, JSON.stringify({ 'fixtures/test-unskippable.js': true })) - assert.deepStrictEqual(globalConfig.testEnvironmentOptions._ddForcedToRun, JSON.stringify({ 'fixtures/test-unskippable.js': true })) + assert.deepStrictEqual( + globalConfig.testEnvironmentOptions._ddUnskippable, + JSON.stringify({ 'fixtures/test-unskippable.js': true }) + ) + assert.deepStrictEqual( + globalConfig.testEnvironmentOptions._ddForcedToRun, + JSON.stringify({ 'fixtures/test-unskippable.js': true }) + ) }) }) diff --git a/packages/datadog-plugin-kafkajs/test/index.spec.js b/packages/datadog-plugin-kafkajs/test/index.spec.js index 6f3e7dd33cc..a6b02edeb52 100644 --- a/packages/datadog-plugin-kafkajs/test/index.spec.js +++ b/packages/datadog-plugin-kafkajs/test/index.spec.js @@ -1,6 +1,8 @@ 'use strict' -const { randomUUID } = require('crypto') +const assert = require('node:assert/strict') +const { randomUUID } = require('node:crypto') + const { expect } = require('chai') const dc = require('dc-polyfill') const { describe, it, beforeEach, afterEach, before } = require('mocha') @@ -16,6 +18,7 @@ const { expectedSchema, rawExpectedSchema } = require('./naming') const DataStreamsContext = require('../../dd-trace/src/datastreams/context') const { computePathwayHash } = require('../../dd-trace/src/datastreams/pathway') const { ENTRY_PARENT_HASH, DataStreamsProcessor } = require('../../dd-trace/src/datastreams/processor') +const { assertObjectContains } = require('../../../integration-tests/helpers') const testKafkaClusterId = '5L6g3nShT-eMCtK--X86sw' @@ -128,18 +131,17 @@ describe('Plugin', () => { const expectedSpanPromise = agent.assertSomeTraces(traces => { const span = traces[0][0] - expect(span).to.include({ + assertObjectContains(span, { name: resourceName, service: expectedSchema.send.serviceName, resource: resourceName, - error: 1 - }) - - expect(span.meta).to.include({ - [ERROR_TYPE]: error.name, - [ERROR_MESSAGE]: error.message, - [ERROR_STACK]: error.stack, - component: 'kafkajs' + error: 1, + meta: { + [ERROR_TYPE]: error.name, + [ERROR_MESSAGE]: error.message, + [ERROR_STACK]: error.stack, + component: 'kafkajs' + } }) }) @@ -213,20 +215,16 @@ describe('Plugin', () => { }) it('should hit an error for the first send and not inject headers in later sends', async () => { - try { - await producer.send({ topic: testTopic, messages }) - expect(true).to.be.false('First producer.send() should have thrown an error') - } catch (e) { - expect(e).to.equal(error) - } + await assert.rejects(producer.send({ topic: testTopic, messages }), error) + expect(messages[0].headers).to.have.property('x-datadog-trace-id') // restore the stub to allow the next send to succeed sendRequestStub.restore() const result2 = await producer.send({ topic: testTopic, messages: messages2 }) - expect(messages2[0].headers).to.be.undefined - expect(result2[0].errorCode).to.equal(0) + assert.strictEqual(messages2[0].headers, undefined) + assert.strictEqual(result2[0].errorCode, 0) }) }) @@ -278,8 +276,8 @@ describe('Plugin', () => { const currentSpan = tracer.scope().active() try { - expect(currentSpan).to.not.equal(firstSpan) - expect(currentSpan.context()._name).to.equal(expectedSchema.receive.opName) + assert.notDeepStrictEqual(currentSpan, firstSpan) + assert.strictEqual(currentSpan.context()._name, expectedSchema.receive.opName) done() } catch (e) { done(e) @@ -297,13 +295,13 @@ describe('Plugin', () => { const expectedSpanPromise = agent.assertSomeTraces(traces => { const span = traces[0][0] - expect(span).to.include({ + assertObjectContains(span, { name: 'kafka.consume', service: 'test-kafka', resource: testTopic }) - expect(parseInt(span.parent_id.toString())).to.be.gt(0) + assert.ok(parseInt(span.parent_id.toString()) > 0) }) await consumer.run({ eachMessage: () => {} }) @@ -342,7 +340,7 @@ describe('Plugin', () => { it('should run constructor even if no eachMessage supplied', (done) => { let eachBatch = async ({ batch }) => { try { - expect(batch.isEmpty()).to.be.false + assert.strictEqual(batch.isEmpty(), false) done() } catch (e) { done(e) @@ -366,25 +364,25 @@ describe('Plugin', () => { const afterStart = dc.channel('dd-trace:kafkajs:consumer:afterStart') const spy = sinon.spy((ctx) => { - expect(ctx.currentStore.span).to.not.be.null + assert.ok(ctx.currentStore.span) afterStart.unsubscribe(spy) }) afterStart.subscribe(spy) let eachMessage = async ({ topic, partition, message }) => { try { - expect(spy).to.have.been.calledOnce + assert.strictEqual(spy.callCount, 1) const channelMsg = spy.firstCall.args[0] - expect(channelMsg).to.not.undefined - expect(channelMsg.topic).to.eq(testTopic) - expect(channelMsg.message.key).to.not.undefined - expect(channelMsg.message.key.toString()).to.eq(messages[0].key) - expect(channelMsg.message.value).to.not.undefined - expect(channelMsg.message.value.toString()).to.eq(messages[0].value) + assert.ok(channelMsg) + assert.strictEqual(channelMsg.topic, testTopic) + assert.ok(channelMsg.message.key) + assert.strictEqual(channelMsg.message.key.toString(), messages[0].key) + assert.ok(channelMsg.message.value) + assert.strictEqual(channelMsg.message.value.toString(), messages[0].value) const name = spy.firstCall.args[1] - expect(name).to.eq(afterStart.name) + assert.strictEqual(name, afterStart.name) done() } catch (e) { @@ -402,7 +400,7 @@ describe('Plugin', () => { const beforeFinish = dc.channel('dd-trace:kafkajs:consumer:beforeFinish') const spy = sinon.spy(() => { - expect(tracer.scope().active()).to.not.be.null + assert.ok(tracer.scope().active()) beforeFinish.unsubscribe(spy) }) beforeFinish.subscribe(spy) @@ -469,7 +467,7 @@ describe('Plugin', () => { it('Should set a checkpoint on produce', async () => { const messages = [{ key: 'consumerDSM1', value: 'test2' }] await sendMessages(kafka, testTopic, messages) - expect(setDataStreamsContextSpy.args[0][0].hash).to.equal(expectedProducerHash) + assert.strictEqual(setDataStreamsContextSpy.args[0][0].hash, expectedProducerHash) }) it('Should set a checkpoint on consume (eachMessage)', async () => { @@ -482,7 +480,7 @@ describe('Plugin', () => { await sendMessages(kafka, testTopic, messages) await consumer.disconnect() for (const runArg of runArgs) { - expect(runArg.hash).to.equal(expectedConsumerHash) + assert.strictEqual(runArg.hash, expectedConsumerHash) } }) @@ -496,7 +494,7 @@ describe('Plugin', () => { await sendMessages(kafka, testTopic, messages) await consumer.disconnect() for (const runArg of runArgs) { - expect(runArg.hash).to.equal(expectedConsumerHash) + assert.strictEqual(runArg.hash, expectedConsumerHash) } }) @@ -507,7 +505,7 @@ describe('Plugin', () => { } const recordCheckpointSpy = sinon.spy(DataStreamsProcessor.prototype, 'recordCheckpoint') await sendMessages(kafka, testTopic, messages) - expect(recordCheckpointSpy.args[0][0].hasOwnProperty('payloadSize')) + assert.ok(Object.hasOwn(recordCheckpointSpy.args[0][0], 'payloadSize')) recordCheckpointSpy.restore() }) @@ -520,7 +518,7 @@ describe('Plugin', () => { await sendMessages(kafka, testTopic, messages) await consumer.run({ eachMessage: async () => { - expect(recordCheckpointSpy.args[0][0].hasOwnProperty('payloadSize')) + assert.ok(Object.hasOwn(recordCheckpointSpy.args[0][0], 'payloadSize')) recordCheckpointSpy.restore() } }) @@ -592,7 +590,7 @@ describe('Plugin', () => { await sendMessages(kafka, testTopic, messages) expect(setOffsetSpy).to.be.calledOnce const { topic } = setOffsetSpy.lastCall.args[0] - expect(topic).to.equal(testTopic) + assert.strictEqual(topic, testTopic) }) }) }) diff --git a/packages/datadog-plugin-koa/test/index.spec.js b/packages/datadog-plugin-koa/test/index.spec.js index 157a8d4ffad..02d8f2572a2 100644 --- a/packages/datadog-plugin-koa/test/index.spec.js +++ b/packages/datadog-plugin-koa/test/index.spec.js @@ -280,7 +280,7 @@ describe('Plugin', () => { agent .assertSomeTraces(traces => { const spans = sort(traces[0]) - assert.ok(!Object.hasOwn(spans[0].meta, 'http.client_ip')) + assert.ok(!('http.client_ip' in spans[0].meta)) }) .then(done) .catch(done) diff --git a/packages/datadog-plugin-langchain/test/index.spec.js b/packages/datadog-plugin-langchain/test/index.spec.js index 419067c989c..7f68d23cf3d 100644 --- a/packages/datadog-plugin-langchain/test/index.spec.js +++ b/packages/datadog-plugin-langchain/test/index.spec.js @@ -537,7 +537,7 @@ describe('Plugin', () => { const span = traces[0][0] - assert.ok(!Object.hasOwn(span.meta, 'langchain.response.outputs.embedding_length')) + assert.ok(!('langchain.response.outputs.embedding_length' in span.meta)) assert.ok(Object.hasOwn(span.meta, 'error.message')) assert.ok(Object.hasOwn(span.meta, 'error.type')) diff --git a/packages/datadog-plugin-memcached/test/index.spec.js b/packages/datadog-plugin-memcached/test/index.spec.js index dbe69643dfd..5004b5a7f0b 100644 --- a/packages/datadog-plugin-memcached/test/index.spec.js +++ b/packages/datadog-plugin-memcached/test/index.spec.js @@ -238,7 +238,7 @@ describe('Plugin', () => { it('trace should not contain memcached.command', done => { agent .assertSomeTraces(traces => { - assert.ok(!Object.hasOwn(traces[0][0].meta, 'memcached.command')) + assert.ok(!('memcached.command' in traces[0][0].meta)) }) .then(done) .catch(done) diff --git a/packages/datadog-plugin-mongodb-core/test/core.spec.js b/packages/datadog-plugin-mongodb-core/test/core.spec.js index 087e2b9fddf..928de310102 100644 --- a/packages/datadog-plugin-mongodb-core/test/core.spec.js +++ b/packages/datadog-plugin-mongodb-core/test/core.spec.js @@ -444,7 +444,7 @@ describe('Plugin', () => { .assertSomeTraces(traces => { assert.strictEqual(startSpy.called, true) const ops = startSpy.getCall(0).args[0].ops - assert.ok(!Object.hasOwn(ops, 'comment')) + assert.ok(!('comment' in ops)) }) .then(done) .catch(done) diff --git a/packages/datadog-plugin-openai/test/index.spec.js b/packages/datadog-plugin-openai/test/index.spec.js index 522edff7568..4c652562443 100644 --- a/packages/datadog-plugin-openai/test/index.spec.js +++ b/packages/datadog-plugin-openai/test/index.spec.js @@ -502,7 +502,10 @@ describe('Plugin', () => { assert.strictEqual(traces[0][0].metrics['openai.response.deleted'], 1) assert.ok('openai.response.id' in traces[0][0].meta) - assert.strictEqual(traces[0][0].meta['openai.response.id'], 'ft:gpt-4.1-mini-2025-04-14:datadog-staging::BkaILRSh') + assert.strictEqual( + traces[0][0].meta['openai.response.id'], + 'ft:gpt-4.1-mini-2025-04-14:datadog-staging::BkaILRSh' + ) }) if (semver.satisfies(realVersion, '>=4.0.0')) { diff --git a/packages/datadog-plugin-opensearch/test/index.spec.js b/packages/datadog-plugin-opensearch/test/index.spec.js index 327a90f244c..b9c67ec75e9 100644 --- a/packages/datadog-plugin-opensearch/test/index.spec.js +++ b/packages/datadog-plugin-opensearch/test/index.spec.js @@ -98,7 +98,10 @@ describe('Plugin', () => { assert.strictEqual(traces[0][0].meta['opensearch.method'], 'POST') assert.strictEqual(traces[0][0].meta['opensearch.url'], '/_msearch') assert.ok('opensearch.body' in traces[0][0].meta) - assert.strictEqual(traces[0][0].meta['opensearch.body'], '[{"index":"docs"},{"query":{"match_all":{}}},{"index":"docs2"},{"query":{"match_all":{}}}]') + assert.strictEqual( + traces[0][0].meta['opensearch.body'], + '[{"index":"docs"},{"query":{"match_all":{}}},{"index":"docs2"},{"query":{"match_all":{}}}]' + ) assert.strictEqual(traces[0][0].meta['opensearch.params'], '{"size":100}') assert.strictEqual(traces[0][0].meta.component, 'opensearch') assert.strictEqual(traces[0][0].meta['_dd.integration'], 'opensearch') @@ -128,7 +131,7 @@ describe('Plugin', () => { it('should skip tags for unavailable fields', done => { agent .assertSomeTraces(traces => { - assert.ok(!Object.hasOwn(traces[0][0].meta, 'opensearch.body')) + assert.ok(!('opensearch.body' in traces[0][0].meta)) }) .then(done) .catch(done) diff --git a/packages/datadog-plugin-pino/test/index.spec.js b/packages/datadog-plugin-pino/test/index.spec.js index c054f269a6f..06e5128b446 100644 --- a/packages/datadog-plugin-pino/test/index.spec.js +++ b/packages/datadog-plugin-pino/test/index.spec.js @@ -88,9 +88,9 @@ describe('Plugin', () => { const record = stream.write.firstCall.args[0].toString() - assertObjectContains(record, 'trace_id') - assertObjectContains(record, 'span_id') - assertObjectContains(record, 'message') + assert.match(record, new RegExp(`trace_id\\W+?${span.context().toTraceId(true)}`)) + assert.match(record, new RegExp(`span_id\\W+?${span.context().toSpanId()}`)) + assert.match(record, /message/) }) }) } @@ -228,7 +228,7 @@ describe('Plugin', () => { assert.match(record, new RegExp(`trace_id\\W+?${span.context().toTraceId(true)}`)) assert.match(record, new RegExp(`span_id\\W+?${span.context().toSpanId()}`)) - assertObjectContains(record, 'message') + assert.match(record, /message/) }) }) } diff --git a/packages/datadog-plugin-rhea/test/index.spec.js b/packages/datadog-plugin-rhea/test/index.spec.js index f8ebc215042..9f9c1727b5c 100644 --- a/packages/datadog-plugin-rhea/test/index.spec.js +++ b/packages/datadog-plugin-rhea/test/index.spec.js @@ -174,8 +174,7 @@ describe('Plugin', () => { it('should inject span context', (done) => { container.once('message', msg => { const keys = Object.keys(msg.message.delivery_annotations) - assertObjectContains(keys, 'x-datadog-trace-id') - assertObjectContains(keys, 'x-datadog-parent-id') + assertObjectContains(keys, ['x-datadog-trace-id', 'x-datadog-parent-id']) done() }) context.sender.send({ body: 'Hello World!' }) @@ -184,8 +183,7 @@ describe('Plugin', () => { it('should inject span context with encoded messages', (done) => { container.once('message', msg => { const keys = Object.keys(msg.message.delivery_annotations) - assertObjectContains(keys, 'x-datadog-trace-id') - assertObjectContains(keys, 'x-datadog-parent-id') + assertObjectContains(keys, ['x-datadog-trace-id', 'x-datadog-parent-id']) done() }) tracer.trace('web.request', () => { diff --git a/packages/datadog-plugin-sharedb/test/index.spec.js b/packages/datadog-plugin-sharedb/test/index.spec.js index 7f77b8b49db..2cb23e84636 100644 --- a/packages/datadog-plugin-sharedb/test/index.spec.js +++ b/packages/datadog-plugin-sharedb/test/index.spec.js @@ -96,7 +96,10 @@ describe('Plugin', () => { agent.assertSomeTraces(traces => { assert.strictEqual(traces[0][0].service, 'test') assert.ok('resource' in traces[0][0]) - assert.strictEqual(traces[0][0].resource, 'query-fetch some-collection {"randomValues":{"property":"?","one":"?"}}') + assert.strictEqual( + traces[0][0].resource, + 'query-fetch some-collection {"randomValues":{"property":"?","one":"?"}}' + ) assert.strictEqual(traces[0][0].meta['span.kind'], 'server') assert.strictEqual(traces[0][0].meta.service, 'test') assert.strictEqual(traces[0][0].meta['sharedb.action'], 'query-fetch') diff --git a/packages/datadog-plugin-undici/test/index.spec.js b/packages/datadog-plugin-undici/test/index.spec.js index 2fc4c654b9c..e66400b9c21 100644 --- a/packages/datadog-plugin-undici/test/index.spec.js +++ b/packages/datadog-plugin-undici/test/index.spec.js @@ -264,7 +264,7 @@ describe('Plugin', () => { agent .assertSomeTraces(traces => { assert.strictEqual(traces[0][0].error, 0) - assert.ok(!Object.hasOwn(traces[0][0].meta, 'http.status_code')) + assert.ok(!('http.status_code' in traces[0][0].meta)) }) .then(done) .catch(done) diff --git a/packages/datadog-plugin-winston/test/index.spec.js b/packages/datadog-plugin-winston/test/index.spec.js index 6eedc0afbaf..f29a54443df 100644 --- a/packages/datadog-plugin-winston/test/index.spec.js +++ b/packages/datadog-plugin-winston/test/index.spec.js @@ -386,8 +386,7 @@ describe('Plugin', () => { assert.ok('stack' in loggedInfo) assert.strictEqual(typeof loggedInfo.stack, 'string') - assertObjectContains(loggedInfo.stack, 'test error with stack') - assertObjectContains(loggedInfo.stack, 'Error:') + assert.match(loggedInfo.stack, /^Error: test error with stack\n/) assert.strictEqual(loggedInfo.message, 'test error with stack') diff --git a/packages/dd-trace/src/id.js b/packages/dd-trace/src/id.js index 98f370d52b7..c758917f043 100644 --- a/packages/dd-trace/src/id.js +++ b/packages/dd-trace/src/id.js @@ -14,26 +14,43 @@ let batch = 0 // Internal representation of a trace or span ID. class Identifier { + /** + * @param {string} value + * @param {number} [radix] + */ constructor (value, radix = 16) { this._buffer = radix === 16 ? createBuffer(value) : fromString(value, radix) } + /** + * @param {number} [radix] + * @returns {string} + */ toString (radix = 16) { return radix === 16 ? toHexString(this._buffer) : toNumberString(this._buffer, radix) } + /** + * @returns {bigint} + */ toBigInt () { return Buffer.from(this._buffer).readBigUInt64BE(0) } + /** + * @returns {number[] | Uint8Array} + */ toBuffer () { return this._buffer } + /** + * @returns {number[] | Uint8Array} + */ toArray () { if (this._buffer.length === 8) { return this._buffer @@ -41,10 +58,17 @@ class Identifier { return this._buffer.slice(-8) } + /** + * @returns {string} + */ toJSON () { return this.toString() } + /** + * @param {Identifier} other + * @returns {boolean} + */ equals (other) { const length = this._buffer.length const otherLength = other._buffer.length @@ -59,6 +83,10 @@ class Identifier { } // Create a buffer, using an optional hexadecimal value if provided. +/** + * @param {string} value + * @returns {number[] | Uint8Array} + */ function createBuffer (value) { if (value === '0') return zeroId if (!value) return pseudoRandom() @@ -77,6 +105,11 @@ function createBuffer (value) { } // Convert a numerical string to a buffer using the specified radix. +/** + * @param {string} str + * @param {number} raddix + * @returns {number[]} + */ function fromString (str, raddix) { const buffer = new Array(8) const len = str.length @@ -116,6 +149,11 @@ function fromString (str, raddix) { } // Convert a buffer to a numerical string. +/** + * @param {number[] | Uint8Array} buffer + * @param {number} [radix] + * @returns {string} + */ function toNumberString (buffer, radix) { let high = readInt32(buffer, buffer.length - 8) let low = readInt32(buffer, buffer.length - 4) @@ -137,11 +175,18 @@ function toNumberString (buffer, radix) { } // Convert a buffer to a hexadecimal string. +/** + * @param {number[] | Uint8Array} buffer + * @returns {string} + */ function toHexString (buffer) { return map.call(buffer, pad).join('') } // Simple pseudo-random 64-bit ID generator. +/** + * @returns {number[] | Uint8Array} + */ function pseudoRandom () { if (batch === 0) { randomFillSync(data) @@ -164,6 +209,11 @@ function pseudoRandom () { } // Read a buffer to unsigned integer bytes. +/** + * @param {number[] | Uint8Array} buffer + * @param {number} offset + * @returns {number} + */ function readInt32 (buffer, offset) { return (buffer[offset + 0] * 16_777_216) + (buffer[offset + 1] << 16) + @@ -172,6 +222,11 @@ function readInt32 (buffer, offset) { } // Write unsigned integer bytes to a buffer. +/** + * @param {number[] | Uint8Array} buffer + * @param {number} value + * @param {number} offset + */ function writeUInt32BE (buffer, value, offset) { buffer[3 + offset] = value & 255 value >>= 8 @@ -182,6 +237,11 @@ function writeUInt32BE (buffer, value, offset) { buffer[0 + offset] = value & 255 } +/** + * @param {string} value + * @param {number} [radix] + * @returns {Identifier} + */ module.exports = function createIdentifier (value, radix) { return new Identifier(value, radix) } diff --git a/packages/dd-trace/test/appsec/iast/analyzers/hardcoded-password-analyzer.spec.js b/packages/dd-trace/test/appsec/iast/analyzers/hardcoded-password-analyzer.spec.js index 9a595dfb7ec..d020d0e6cc8 100644 --- a/packages/dd-trace/test/appsec/iast/analyzers/hardcoded-password-analyzer.spec.js +++ b/packages/dd-trace/test/appsec/iast/analyzers/hardcoded-password-analyzer.spec.js @@ -1,20 +1,18 @@ -const assert = require('node:assert/strict') -const { assertObjectContains } = require('../../../../../../integration-tests/helpers') - /* eslint-disable @stylistic/max-len */ 'use strict' +const assert = require('node:assert/strict') +const fs = require('node:fs') +const os = require('node:os') +const path = require('node:path') + const { expect } = require('chai') const { after, afterEach, before, beforeEach, describe, it } = require('mocha') const sinon = require('sinon') -const path = require('node:path') -const fs = require('node:fs') -const os = require('node:os') - const agent = require('../../../plugins/agent') const { getConfigFresh } = require('../../../helpers/config') - +const { assertObjectContains } = require('../../../../../../integration-tests/helpers') const hardcodedPasswordAnalyzer = require('../../../../src/appsec/iast/analyzers/hardcoded-password-analyzer') const iast = require('../../../../src/appsec/iast') const vulnerabilityReporter = require('../../../../src/appsec/iast/vulnerability-reporter') @@ -154,8 +152,12 @@ describe('Hardcoded Password Analyzer', () => { it('should detect vulnerability', (done) => { agent .assertSomeTraces(traces => { - assertObjectContains(traces[0][0].meta['_dd.iast.json'], '"HARDCODED_PASSWORD"') - assertObjectContains(traces[0][0].meta['_dd.iast.json'], '"evidence":{"value":"pswd"}') + assertObjectContains( + JSON.parse(traces[0][0].meta['_dd.iast.json']), + { + vulnerabilities: [{ evidence: { value: 'pswd' }, type: 'HARDCODED_PASSWORD' }], + } + ) }) .then(done) .catch(done) diff --git a/packages/dd-trace/test/appsec/iast/analyzers/hardcoded-secret-analyzer.spec.js b/packages/dd-trace/test/appsec/iast/analyzers/hardcoded-secret-analyzer.spec.js index bd370e1c611..9a48dbd915c 100644 --- a/packages/dd-trace/test/appsec/iast/analyzers/hardcoded-secret-analyzer.spec.js +++ b/packages/dd-trace/test/appsec/iast/analyzers/hardcoded-secret-analyzer.spec.js @@ -122,7 +122,10 @@ describe('Hardcoded Secret Analyzer', () => { it('should detect vulnerability', (done) => { agent .assertSomeTraces(traces => { - assertObjectContains(traces[0][0].meta['_dd.iast.json'], '"HARDCODED_SECRET"') + assertObjectContains( + JSON.parse(traces[0][0].meta['_dd.iast.json']), + { vulnerabilities: [{ type: 'HARDCODED_SECRET' }] } + ) }) .then(done) .catch(done) diff --git a/packages/dd-trace/test/appsec/iast/analyzers/vulnerability-analyzer.spec.js b/packages/dd-trace/test/appsec/iast/analyzers/vulnerability-analyzer.spec.js index 7c5b615cd3c..1c36b3f5ae3 100644 --- a/packages/dd-trace/test/appsec/iast/analyzers/vulnerability-analyzer.spec.js +++ b/packages/dd-trace/test/appsec/iast/analyzers/vulnerability-analyzer.spec.js @@ -2,7 +2,6 @@ const assert = require('node:assert/strict') -const { expect } = require('chai') const { afterEach, beforeEach, describe, it } = require('mocha') const proxyquire = require('proxyquire') const sinon = require('sinon') @@ -258,7 +257,8 @@ describe('vulnerability-analyzer', () => { it('should not throw with undefined values', () => { const vulnerabilityAnalyzer = new VulnerabilityAnalyzer(ANALYZER_TYPE) - expect(() => vulnerabilityAnalyzer.analyzeAll(undefined, value1, undefined)).to.not.throw + // Should not throw + vulnerabilityAnalyzer.analyzeAll(undefined, value1, undefined) }) it('should analyze batch of values', () => { diff --git a/packages/dd-trace/test/appsec/iast/iast-plugin.spec.js b/packages/dd-trace/test/appsec/iast/iast-plugin.spec.js index 0e65bb669bb..e90d8a6bb3b 100644 --- a/packages/dd-trace/test/appsec/iast/iast-plugin.spec.js +++ b/packages/dd-trace/test/appsec/iast/iast-plugin.spec.js @@ -148,9 +148,10 @@ describe('IAST Plugin', () => { it('should exec handler and catch exception if any', () => { const handler = () => { throw new Error('error') } - expect(iastPlugin._execHandlerAndIncMetric({ + // Should not throw + iastPlugin._execHandlerAndIncMetric({ handler - })).to.not.throw + }) sinon.assert.calledOnce(logError) }) @@ -356,9 +357,10 @@ describe('IAST Plugin', () => { it('should exec handler and catch exception if any', () => { const handler = () => { throw new Error('error') } - expect(iastPlugin._execHandlerAndIncMetric({ + // Should not throw + iastPlugin._execHandlerAndIncMetric({ handler - })).to.not.throw + }) sinon.assert.calledOnce(logError) }) diff --git a/packages/dd-trace/test/appsec/iast/index.spec.js b/packages/dd-trace/test/appsec/iast/index.spec.js index 66c252a53ff..f56dac4a73d 100644 --- a/packages/dd-trace/test/appsec/iast/index.spec.js +++ b/packages/dd-trace/test/appsec/iast/index.spec.js @@ -70,7 +70,10 @@ describe('IAST Index', () => { it('should detect vulnerability', (done) => { agent .assertSomeTraces(traces => { - assertObjectContains(traces[0][0].meta['_dd.iast.json'], '"WEAK_HASH"') + assertObjectContains( + JSON.parse(traces[0][0].meta['_dd.iast.json']), + { vulnerabilities: [{ type: 'WEAK_HASH' }] } + ) }) .then(done) .catch(done) @@ -82,7 +85,10 @@ describe('IAST Index', () => { iastContextFunctions.cleanIastContext = mockedCleanIastContext agent .assertSomeTraces(traces => { - assertObjectContains(traces[0][0].meta['_dd.iast.json'], '"WEAK_HASH"') + assertObjectContains( + JSON.parse(traces[0][0].meta['_dd.iast.json']), + { vulnerabilities: [{ type: 'WEAK_HASH' }] } + ) sinon.assert.calledOnce(mockedCleanIastContext) }) .then(done) @@ -95,7 +101,10 @@ describe('IAST Index', () => { overheadController.releaseRequest = releaseRequest agent .assertSomeTraces(traces => { - assertObjectContains(traces[0][0].meta['_dd.iast.json'], '"WEAK_HASH"') + assertObjectContains( + JSON.parse(traces[0][0].meta['_dd.iast.json']), + { vulnerabilities: [{ type: 'WEAK_HASH' }] } + ) sinon.assert.calledOnce(releaseRequest) }) .then(done) diff --git a/packages/dd-trace/test/appsec/iast/overhead-controller.integration.spec.js b/packages/dd-trace/test/appsec/iast/overhead-controller.integration.spec.js index 68fe9a79f67..1a8e3019dfb 100644 --- a/packages/dd-trace/test/appsec/iast/overhead-controller.integration.spec.js +++ b/packages/dd-trace/test/appsec/iast/overhead-controller.integration.spec.js @@ -73,7 +73,7 @@ describe('IAST - overhead-controller - integration', () => { await agent.assertMessageReceived(({ payload }) => { assert.strictEqual(payload[0][0].type, 'web') assert.strictEqual(payload[0][0].metrics['_dd.iast.enabled'], 1) - assert.ok(!Object.hasOwn(payload[0][0].meta, '_dd.iast.json')) + assert.ok(!('_dd.iast.json' in payload[0][0].meta)) }, 1000, 1, true) } diff --git a/packages/dd-trace/test/appsec/iast/overhead-controller.spec.js b/packages/dd-trace/test/appsec/iast/overhead-controller.spec.js index 5d65a008d42..dfa4f518799 100644 --- a/packages/dd-trace/test/appsec/iast/overhead-controller.spec.js +++ b/packages/dd-trace/test/appsec/iast/overhead-controller.spec.js @@ -4,6 +4,7 @@ const assert = require('node:assert/strict') const { EventEmitter } = require('node:events') const axios = require('axios') +const { expect } = require('chai') const { after, afterEach, before, beforeEach, describe, it } = require('mocha') const proxyquire = require('proxyquire') const sinon = require('sinon') @@ -49,7 +50,7 @@ describe('Overhead controller', () => { it('should populate request context', () => { const iastContext = {} overheadController.initializeRequestContext(iastContext) - assert.ok(overheadController.OVERHEAD_CONTROLLER_CONTEXT_KEY in iastContext) + expect(iastContext).to.have.nested.property(overheadController.OVERHEAD_CONTROLLER_CONTEXT_KEY) }) }) }) @@ -229,15 +230,16 @@ describe('Overhead controller', () => { }) it('should populate initial context with available tokens', () => { - assert.ok(`tokens.${OPERATION.name}` in iastContext[oceContextKey]) - assert.strictEqual(iastContext[oceContextKey][`tokens.${OPERATION.name}`], OPERATION.initialTokenBucketSize()) + assert.strictEqual( + iastContext[oceContextKey].tokens[OPERATION.name], + OPERATION.initialTokenBucketSize() + ) }) it('should allow when available tokens', () => { iastContext[overheadController.OVERHEAD_CONTROLLER_CONTEXT_KEY].tokens[OPERATION.name] = 2 assert.strictEqual(overheadController.hasQuota(OPERATION, iastContext, vulnerabilities.SSRF), true) - assert.ok(`tokens.${OPERATION.name}` in iastContext[oceContextKey]) - assert.strictEqual(iastContext[oceContextKey][`tokens.${OPERATION.name}`], 1) + assert.strictEqual(iastContext[oceContextKey].tokens[OPERATION.name], 1) }) it('should detect the first vulnerability of the type ' + @@ -246,8 +248,7 @@ describe('Overhead controller', () => { iastContext[overheadController.OVERHEAD_CONTROLLER_CONTEXT_KEY].tokens[OPERATION.name] = 1 assert.strictEqual(overheadController.hasQuota(OPERATION, iastContext, vulnerabilities.SSRF), true) overheadController.consolidateVulnerabilities(iastContext) - assert.ok(`tokens.${OPERATION.name}` in iastContext[oceContextKey]) - assert.strictEqual(iastContext[oceContextKey][`tokens.${OPERATION.name}`], 0) + assert.strictEqual(iastContext[oceContextKey].tokens[OPERATION.name], 0) // Ignoring the first SSRF in the next request iastContext = { req } @@ -267,8 +268,7 @@ describe('Overhead controller', () => { iastContext[overheadController.OVERHEAD_CONTROLLER_CONTEXT_KEY].tokens[OPERATION.name] = 1 assert.strictEqual(overheadController.hasQuota(OPERATION, iastContext, vulnerabilities.SSRF), true) overheadController.consolidateVulnerabilities(iastContext) - assert.ok(`tokens.${OPERATION.name}` in iastContext[oceContextKey]) - assert.strictEqual(iastContext[oceContextKey][`tokens.${OPERATION.name}`], 0) + assert.strictEqual(iastContext[oceContextKey].tokens[OPERATION.name], 0) // Ignoring the first SSRF in the next request iastContext = { req } @@ -286,8 +286,7 @@ describe('Overhead controller', () => { iastContext[overheadController.OVERHEAD_CONTROLLER_CONTEXT_KEY].tokens[OPERATION.name] = 1 assert.strictEqual(overheadController.hasQuota(OPERATION, iastContext, vulnerabilities.SSRF), true) overheadController.consolidateVulnerabilities(iastContext) - assert.ok(`tokens.${OPERATION.name}` in iastContext[oceContextKey]) - assert.strictEqual(iastContext[oceContextKey][`tokens.${OPERATION.name}`], 0) + assert.strictEqual(iastContext[oceContextKey].tokens[OPERATION.name], 0) // Detecting the first CODE_INJECTION in the next request iastContext = { req } @@ -307,8 +306,7 @@ describe('Overhead controller', () => { iastContext[overheadController.OVERHEAD_CONTROLLER_CONTEXT_KEY].tokens[OPERATION.name] = 1 assert.strictEqual(overheadController.hasQuota(OPERATION, iastContext, vulnerabilities.SSRF), true) overheadController.consolidateVulnerabilities(iastContext) - assert.ok(`tokens.${OPERATION.name}` in iastContext[oceContextKey]) - assert.strictEqual(iastContext[oceContextKey][`tokens.${OPERATION.name}`], 0) + assert.strictEqual(iastContext[oceContextKey].tokens[OPERATION.name], 0) // Detecting the first CODE_INJECTION in the next request iastContext = { req } @@ -323,8 +321,7 @@ describe('Overhead controller', () => { iastContext[overheadController.OVERHEAD_CONTROLLER_CONTEXT_KEY].tokens[OPERATION.name] = 1 assert.strictEqual(overheadController.hasQuota(OPERATION, iastContext, vulnerabilities.SSRF), true) overheadController.consolidateVulnerabilities(iastContext) - assert.ok(`tokens.${OPERATION.name}` in iastContext[oceContextKey]) - assert.strictEqual(iastContext[oceContextKey][`tokens.${OPERATION.name}`], 0) + assert.strictEqual(iastContext[oceContextKey].tokens[OPERATION.name], 0) // Detecting the first CODE_INJECTION in the next request req.method = 'POST' @@ -340,8 +337,7 @@ describe('Overhead controller', () => { iastContext[overheadController.OVERHEAD_CONTROLLER_CONTEXT_KEY].tokens[OPERATION.name] = 2 assert.strictEqual(overheadController.hasQuota(OPERATION, iastContext, vulnerabilities.SSRF), true) overheadController.consolidateVulnerabilities(iastContext) - assert.ok(`tokens.${OPERATION.name}` in iastContext[oceContextKey]) - assert.strictEqual(iastContext[oceContextKey][`tokens.${OPERATION.name}`], 1) + assert.strictEqual(iastContext[oceContextKey].tokens[OPERATION.name], 1) // Detecting the first CODE_INJECTION in the next request iastContext = { req } @@ -355,8 +351,7 @@ describe('Overhead controller', () => { iastContext[overheadController.OVERHEAD_CONTROLLER_CONTEXT_KEY].tokens[OPERATION.name] = 1 assert.strictEqual(overheadController.hasQuota(OPERATION, iastContext, vulnerabilities.SSRF), true) overheadController.consolidateVulnerabilities(iastContext) - assert.ok(`tokens.${OPERATION.name}` in iastContext[oceContextKey]) - assert.strictEqual(iastContext[oceContextKey][`tokens.${OPERATION.name}`], 0) + assert.strictEqual(iastContext[oceContextKey].tokens[OPERATION.name], 0) // second request using the whole budget iastContext = { req } @@ -364,8 +359,7 @@ describe('Overhead controller', () => { iastContext[overheadController.OVERHEAD_CONTROLLER_CONTEXT_KEY].tokens[OPERATION.name] = 1 assert.strictEqual(overheadController.hasQuota(OPERATION, iastContext, vulnerabilities.SSRF), false) assert.strictEqual(overheadController.hasQuota(OPERATION, iastContext, vulnerabilities.SSRF), true) - assert.ok(`tokens.${OPERATION.name}` in iastContext[oceContextKey]) - assert.strictEqual(iastContext[oceContextKey][`tokens.${OPERATION.name}`], 0) + assert.strictEqual(iastContext[oceContextKey].tokens[OPERATION.name], 0) overheadController.consolidateVulnerabilities(iastContext) // third request detecting only the third SSRF @@ -380,8 +374,7 @@ describe('Overhead controller', () => { it('should not allow when no available tokens', () => { iastContext[overheadController.OVERHEAD_CONTROLLER_CONTEXT_KEY].tokens[OPERATION.name] = 0 assert.strictEqual(overheadController.hasQuota(OPERATION, iastContext), false) - assert.ok(`tokens.${OPERATION.name}` in iastContext[oceContextKey]) - assert.strictEqual(iastContext[oceContextKey][`tokens.${OPERATION.name}`], 0) + assert.strictEqual(iastContext[oceContextKey].tokens[OPERATION.name], 0) }) }) diff --git a/packages/dd-trace/test/appsec/iast/taint-tracking/taint-tracking-operations.spec.js b/packages/dd-trace/test/appsec/iast/taint-tracking/taint-tracking-operations.spec.js index bfbf2898e1a..40143c6bf29 100644 --- a/packages/dd-trace/test/appsec/iast/taint-tracking/taint-tracking-operations.spec.js +++ b/packages/dd-trace/test/appsec/iast/taint-tracking/taint-tracking-operations.spec.js @@ -13,6 +13,7 @@ const iastTelemetry = require('../../../../src/appsec/iast/telemetry') const { EXECUTED_PROPAGATION, REQUEST_TAINTED } = require('../../../../src/appsec/iast/telemetry/iast-metric') const { Verbosity } = require('../../../../src/appsec/iast/telemetry/verbosity') function getExpectedMethods () { + /** @type {Set} */ const set = new Set() for (const definition of csiMethods) { if (definition.dst) { @@ -565,16 +566,15 @@ describe('IAST TaintTracking Operations', () => { const tt = taintTrackingImpl.getTaintTrackingImpl() const noop = taintTrackingImpl.getTaintTrackingNoop() - assert.strictEqual(Object.keys(noop).length, ((Array.isArray(Object.keys(tt)) ? Object.keys(tt) : [Object.keys(tt)])).length) - assert.ok(((Array.isArray(Object.keys(tt)) ? Object.keys(tt) : [Object.keys(tt)])).every(k => Object.hasOwn(noop, k))) + assert.deepStrictEqual(Object.keys(noop).sort(), Object.keys(tt).sort()) }) it('should have the same properties as TaintTrackingDebug', () => { const ttDebug = taintTrackingImpl.getTaintTrackingImpl(Verbosity.DEBUG) const noop = taintTrackingImpl.getTaintTrackingNoop() - assert.strictEqual(Object.keys(noop).length, ((Array.isArray(Object.keys(ttDebug)) ? Object.keys(ttDebug) : [Object.keys(ttDebug)])).length) - assert.ok(((Array.isArray(Object.keys(ttDebug)) ? Object.keys(ttDebug) : [Object.keys(ttDebug)])).every(k => Object.hasOwn(noop, k))) + // TODO: Do we want the order to be identical? That is likely not needed. + assert.deepStrictEqual(Object.keys(noop).sort(), Object.keys(ttDebug).sort()) }) it('should have the same properties as csiMethods', () => { @@ -582,8 +582,8 @@ describe('IAST TaintTracking Operations', () => { const csiExpectedMethods = getExpectedMethods() - assert.strictEqual(Object.keys(tt).length, ((Array.isArray(csiExpectedMethods) ? csiExpectedMethods : [csiExpectedMethods])).length) - assert.ok(((Array.isArray(csiExpectedMethods) ? csiExpectedMethods : [csiExpectedMethods])).every(k => Object.hasOwn(tt, k))) + // TODO: Do we want the order to be identical? That is likely not needed. + assert.deepStrictEqual(Object.keys(tt).sort(), csiExpectedMethods.sort()) }) }) }) diff --git a/packages/dd-trace/test/appsec/iast/utils.js b/packages/dd-trace/test/appsec/iast/utils.js index 0e48c814634..93b376b1c5d 100644 --- a/packages/dd-trace/test/appsec/iast/utils.js +++ b/packages/dd-trace/test/appsec/iast/utils.js @@ -94,12 +94,15 @@ function testOutsideRequestHasVulnerability (fnToTest, vulnerability, plugins, t rewriter.disable() }) it(`should detect ${vulnerability} vulnerability out of request`, function (done) { - if (timeout) { - this.timeout(timeout) - } + this.timeout(timeout || 10000) agent .assertSomeTraces(traces => { - assertObjectContains(traces[0][0].meta['_dd.iast.json'], `"${vulnerability}"`) + assert.ok(traces[0][0].meta['_dd.iast.json']) + require('util').inspect.defaultOptions.depth = null + assertObjectContains( + JSON.parse(traces[0][0].meta['_dd.iast.json']), + { vulnerabilities: [{ type: vulnerability }] } + ) assert.strictEqual(traces[0][0].metrics['_dd.iast.enabled'], 1) }, { timeoutMs: 10000 }) .then(done) diff --git a/packages/dd-trace/test/appsec/iast/vulnerability-reporter.spec.js b/packages/dd-trace/test/appsec/iast/vulnerability-reporter.spec.js index bab27b643bc..141942f16e8 100644 --- a/packages/dd-trace/test/appsec/iast/vulnerability-reporter.spec.js +++ b/packages/dd-trace/test/appsec/iast/vulnerability-reporter.spec.js @@ -44,7 +44,7 @@ describe('vulnerability-reporter', () => { it('should not add null vulnerability', () => { addVulnerability(iastContext, null) - assert.ok(!Object.hasOwn(iastContext, 'vulnerabilities')) + assert.ok(!('vulnerabilities' in iastContext)) iastContext.vulnerabilities = [] addVulnerability(iastContext, undefined) assert.strictEqual(iastContext.vulnerabilities.length, 0) diff --git a/packages/dd-trace/test/appsec/index.express.plugin.spec.js b/packages/dd-trace/test/appsec/index.express.plugin.spec.js index f05da634fc8..5429333a6ae 100644 --- a/packages/dd-trace/test/appsec/index.express.plugin.spec.js +++ b/packages/dd-trace/test/appsec/index.express.plugin.spec.js @@ -332,7 +332,7 @@ withVersions('express', 'express', version => { await agent.assertSomeTraces((traces) => { const span = traces[0][0] assert.ok(Object.hasOwn(span.meta, '_dd.appsec.s.req.body')) - assert.ok(!Object.hasOwn(span.meta, '_dd.appsec.s.res.body')) + assert.ok(!('_dd.appsec.s.res.body' in span.meta)) assert.equal(span.meta['_dd.appsec.s.req.body'], expectedRequestBodySchema) }) diff --git a/packages/dd-trace/test/appsec/index.fastify.plugin.spec.js b/packages/dd-trace/test/appsec/index.fastify.plugin.spec.js index fbacea933bd..24f8b288153 100644 --- a/packages/dd-trace/test/appsec/index.fastify.plugin.spec.js +++ b/packages/dd-trace/test/appsec/index.fastify.plugin.spec.js @@ -735,7 +735,7 @@ describe('Api Security - Fastify', () => { const res = await axios.get('/') await agent.assertFirstTraceSpan(span => { - assert.ok(!Object.hasOwn(span.meta, '_dd.appsec.s.res.body')) + assert.ok(!('_dd.appsec.s.res.body' in span.meta)) }) assert.strictEqual(res.status, 200) @@ -747,7 +747,7 @@ describe('Api Security - Fastify', () => { await agent.assertFirstTraceSpan(span => { if (span.meta) { - assert.ok(!Object.hasOwn(span.meta, '_dd.appsec.s.res.body')) + assert.ok(!('_dd.appsec.s.res.body' in span.meta)) } }) @@ -760,7 +760,7 @@ describe('Api Security - Fastify', () => { await agent.assertFirstTraceSpan(span => { if (span.meta) { - assert.ok(!Object.hasOwn(span.meta, '_dd.appsec.s.res.body')) + assert.ok(!('_dd.appsec.s.res.body' in span.meta)) } }) @@ -772,7 +772,7 @@ describe('Api Security - Fastify', () => { await agent.assertFirstTraceSpan(span => { if (span.meta) { - assert.ok(!Object.hasOwn(span.meta, '_dd.appsec.s.res.body')) + assert.ok(!('_dd.appsec.s.res.body' in span.meta)) } }) diff --git a/packages/dd-trace/test/appsec/rasp/command_injection.integration.spec.js b/packages/dd-trace/test/appsec/rasp/command_injection.integration.spec.js index 9b83b42778a..ced35eff30a 100644 --- a/packages/dd-trace/test/appsec/rasp/command_injection.integration.spec.js +++ b/packages/dd-trace/test/appsec/rasp/command_injection.integration.spec.js @@ -58,7 +58,7 @@ describe('RASP - command_injection - integration', () => { const checkMessages = agent.assertMessageReceived(({ headers, payload }) => { assert.ok(Object.hasOwn(payload[0][0].meta, '_dd.appsec.json')) - assert.ok(payload[0][0].meta['_dd.appsec.json'].includes(`"rasp-command_injection-rule-id-${ruleId}"`)) + assert.match(payload[0][0].meta['_dd.appsec.json'], new RegExp(`"rasp-command_injection-rule-id-${ruleId}"`)) }) const checkTelemetry = agent.assertTelemetryReceived(({ headers, payload }) => { diff --git a/packages/dd-trace/test/appsec/rasp/fs-plugin.spec.js b/packages/dd-trace/test/appsec/rasp/fs-plugin.spec.js index 6f9ace71ad6..6feb4f69e41 100644 --- a/packages/dd-trace/test/appsec/rasp/fs-plugin.spec.js +++ b/packages/dd-trace/test/appsec/rasp/fs-plugin.spec.js @@ -110,7 +110,7 @@ describe('AppsecFsPlugin', () => { store = appsecFsPlugin._onFsOperationFinishOrRenderEnd() assert.strictEqual(store, origStore) - assert.ok(!Object.hasOwn(store, 'fs')) + assert.ok(!('fs' in store)) }) it('should mark fs children', () => { @@ -163,7 +163,7 @@ describe('AppsecFsPlugin', () => { store = appsecFsPlugin._onFsOperationFinishOrRenderEnd() assert.strictEqual(store, origStore) - assert.ok(!Object.hasOwn(store, 'fs')) + assert.ok(!('fs' in store)) }) }) diff --git a/packages/dd-trace/test/appsec/rasp/lfi.integration.express.plugin.spec.js b/packages/dd-trace/test/appsec/rasp/lfi.integration.express.plugin.spec.js index c52b407a407..9188e586ccf 100644 --- a/packages/dd-trace/test/appsec/rasp/lfi.integration.express.plugin.spec.js +++ b/packages/dd-trace/test/appsec/rasp/lfi.integration.express.plugin.spec.js @@ -48,7 +48,7 @@ describe('RASP - lfi - integration - sync', () => { assert.strictEqual(e.response.status, 403) return await agent.assertMessageReceived(({ headers, payload }) => { assert.ok(Object.hasOwn(payload[0][0].meta, '_dd.appsec.json')) - assert.ok(payload[0][0].meta['_dd.appsec.json'].includes('"rasp-lfi-rule-id-1"')) + assert.match(payload[0][0].meta['_dd.appsec.json'], /"rasp-lfi-rule-id-1"/) }) } diff --git a/packages/dd-trace/test/appsec/rasp/sql_injection.integration.pg.plugin.spec.js b/packages/dd-trace/test/appsec/rasp/sql_injection.integration.pg.plugin.spec.js index 1f97e4e00b6..978b6ef6fae 100644 --- a/packages/dd-trace/test/appsec/rasp/sql_injection.integration.pg.plugin.spec.js +++ b/packages/dd-trace/test/appsec/rasp/sql_injection.integration.pg.plugin.spec.js @@ -50,7 +50,7 @@ describe('RASP - sql_injection - integration', () => { assert.strictEqual(e.response.status, 403) return await agent.assertMessageReceived(({ headers, payload }) => { assert.ok(Object.hasOwn(payload[0][0].meta, '_dd.appsec.json')) - assert.ok(payload[0][0].meta['_dd.appsec.json'].includes('"rasp-sqli-rule-id-2"')) + assert.match(payload[0][0].meta['_dd.appsec.json'], /"rasp-sqli-rule-id-2"/) }) } @@ -68,7 +68,7 @@ describe('RASP - sql_injection - integration', () => { assert.strictEqual(e.response.status, 403) return await agent.assertMessageReceived(({ headers, payload }) => { assert.ok(Object.hasOwn(payload[0][0].meta, '_dd.appsec.json')) - assert.ok(payload[0][0].meta['_dd.appsec.json'].includes('"rasp-sqli-rule-id-2"')) + assert.match(payload[0][0].meta['_dd.appsec.json'], /"rasp-sqli-rule-id-2"/) }) } @@ -86,7 +86,7 @@ describe('RASP - sql_injection - integration', () => { assert.strictEqual(e.response.status, 403) return await agent.assertMessageReceived(({ headers, payload }) => { assert.ok(Object.hasOwn(payload[0][0].meta, '_dd.appsec.json')) - assert.ok(payload[0][0].meta['_dd.appsec.json'].includes('"rasp-sqli-rule-id-2"')) + assert.match(payload[0][0].meta['_dd.appsec.json'], /"rasp-sqli-rule-id-2"/) }) } diff --git a/packages/dd-trace/test/appsec/rasp/utils.js b/packages/dd-trace/test/appsec/rasp/utils.js index e6d1969ca2b..c261519fd8c 100644 --- a/packages/dd-trace/test/appsec/rasp/utils.js +++ b/packages/dd-trace/test/appsec/rasp/utils.js @@ -6,8 +6,8 @@ const { getWebSpan } = require('../utils') function checkRaspExecutedAndNotThreat (agent, checkRuleEval = true) { return agent.assertSomeTraces((traces) => { const span = getWebSpan(traces) - assert.ok(!Object.hasOwn(span.meta, '_dd.appsec.json')) - assert.ok(!Object.hasOwn(span.meta_struct || {}, '_dd.stack')) + assert.ok(!('_dd.appsec.json' in span.meta)) + assert.ok(!span.meta_struct || !('_dd.stack' in span.meta_struct)) if (checkRuleEval) { assert.strictEqual(span.metrics['_dd.appsec.rasp.rule.eval'], 1) } diff --git a/packages/dd-trace/test/appsec/reporter.spec.js b/packages/dd-trace/test/appsec/reporter.spec.js index c534875866a..8ebe06ad9e6 100644 --- a/packages/dd-trace/test/appsec/reporter.spec.js +++ b/packages/dd-trace/test/appsec/reporter.spec.js @@ -816,7 +816,7 @@ describe('reporter', () => { sinon.assert.calledOnceWithExactly(web.root, req) sinon.assert.calledWithExactly(span.addTags, { a: 1, b: 2 }) - assert.strictEqual(Reporter.metricsQueue.length, 0) + assert.strictEqual(Reporter.metricsQueue.size, 0) }) it('should only add mandatory headers when no attack or event was previously found', () => { diff --git a/packages/dd-trace/test/appsec/response_blocking.spec.js b/packages/dd-trace/test/appsec/response_blocking.spec.js index 5718758fce3..d8cf2db3e86 100644 --- a/packages/dd-trace/test/appsec/response_blocking.spec.js +++ b/packages/dd-trace/test/appsec/response_blocking.spec.js @@ -1,13 +1,13 @@ 'use strict' +const assert = require('node:assert') +const fs = require('node:fs') +const path = require('node:path') + const Axios = require('axios') -const { assert } = require('chai') const { describe, it, beforeEach, afterEach, before, after } = require('mocha') const sinon = require('sinon') -const path = require('node:path') -const fs = require('node:fs') - const agent = require('../plugins/agent') const appsec = require('../../src/appsec') const { getConfigFresh } = require('../helpers/config') @@ -128,14 +128,14 @@ describe('HTTP Response Blocking', () => { const res = await axios.get('/') assert.equal(res.status, 200) - assert.hasAllKeys(cloneHeaders(res.headers), [ + assert.deepStrictEqual([ 'a', 'b', 'bad3', - 'date', 'connection', - 'transfer-encoding' - ]) + 'date', + 'transfer-encoding', + ], Object.keys(cloneHeaders(res.headers)).sort()) assert.deepEqual(res.data, 'end') }) @@ -221,16 +221,16 @@ describe('HTTP Response Blocking', () => { const res = await axios.get('/') assert.equal(res.status, 201) - assert.hasAllKeys(cloneHeaders(res.headers), [ + assert.deepStrictEqual([ 'a', 'b', 'c', + 'connection', 'd', - 'e', 'date', - 'connection', - 'transfer-encoding' - ]) + 'e', + 'transfer-encoding', + ], Object.keys(cloneHeaders(res.headers)).sort()) assert.deepEqual(res.data, 'writefileend') }) @@ -264,12 +264,12 @@ function cloneHeaders (headers) { function assertBlocked (res) { assert.equal(res.status, 403) - assert.hasAllKeys(cloneHeaders(res.headers), [ - 'content-type', + assert.deepStrictEqual([ + 'connection', 'content-length', + 'content-type', 'date', - 'connection' - ]) + ], Object.keys(cloneHeaders(res.headers)).sort()) assert.deepEqual(res.data, blockingResponse) sinon.assert.callCount(WafContext.prototype.run, 2) diff --git a/packages/dd-trace/test/appsec/rule_manager.spec.js b/packages/dd-trace/test/appsec/rule_manager.spec.js index 7c632bbbd40..871e5fc8e3d 100644 --- a/packages/dd-trace/test/appsec/rule_manager.spec.js +++ b/packages/dd-trace/test/appsec/rule_manager.spec.js @@ -197,11 +197,11 @@ describe('AppSec Rule Manager', () => { RuleManager.updateWafFromRC(rcConfigsForNonAsmProducts) assert.strictEqual(rcConfigsForNonAsmProducts.toUnapply[0].apply_state, UNACKNOWLEDGED) - assert.ok(!Object.hasOwn(rcConfigsForNonAsmProducts.toUnapply[0], 'apply_error')) + assert.ok(!('apply_error' in rcConfigsForNonAsmProducts.toUnapply[0])) assert.strictEqual(rcConfigsForNonAsmProducts.toModify[0].apply_state, UNACKNOWLEDGED) - assert.ok(!Object.hasOwn(rcConfigsForNonAsmProducts.toModify[0], 'apply_error')) + assert.ok(!('apply_error' in rcConfigsForNonAsmProducts.toModify[0])) assert.strictEqual(rcConfigsForNonAsmProducts.toApply[0].apply_state, UNACKNOWLEDGED) - assert.ok(!Object.hasOwn(rcConfigsForNonAsmProducts.toApply[0], 'apply_error')) + assert.ok(!('apply_error' in rcConfigsForNonAsmProducts.toApply[0])) sinon.assert.notCalled(waf.updateConfig) sinon.assert.notCalled(waf.removeConfig) @@ -249,11 +249,11 @@ describe('AppSec Rule Manager', () => { RuleManager.updateWafFromRC(rcConfigs) assert.strictEqual(rcConfigs.toUnapply[0].apply_state, ACKNOWLEDGED) - assert.ok(!Object.hasOwn(rcConfigs.toUnapply[0], 'apply_error')) + assert.ok(!('apply_error' in rcConfigs.toUnapply[0])) assert.strictEqual(rcConfigs.toModify[0].apply_state, ACKNOWLEDGED) - assert.ok(!Object.hasOwn(rcConfigs.toModify[0], 'apply_error')) + assert.ok(!('apply_error' in rcConfigs.toModify[0])) assert.strictEqual(rcConfigs.toApply[0].apply_state, ACKNOWLEDGED) - assert.ok(!Object.hasOwn(rcConfigs.toApply[0], 'apply_error')) + assert.ok(!('apply_error' in rcConfigs.toApply[0])) }) it('should update apply_state and apply_error on failed config remove', () => { diff --git a/packages/dd-trace/test/appsec/sdk/set_user.spec.js b/packages/dd-trace/test/appsec/sdk/set_user.spec.js index 189de114916..c2d30631577 100644 --- a/packages/dd-trace/test/appsec/sdk/set_user.spec.js +++ b/packages/dd-trace/test/appsec/sdk/set_user.spec.js @@ -155,7 +155,7 @@ describe('set_user', () => { assert.strictEqual(traces[0][0].meta['usr.session_id'], '133769') assert.strictEqual(traces[0][0].meta['_dd.appsec.user.collection_mode'], 'sdk') assert.strictEqual(traces[0][0].meta['appsec.event'], 'true') - assert.ok(!Object.hasOwn(traces[0][0].meta, 'appsec.blocked')) + assert.ok(!('appsec.blocked' in traces[0][0].meta)) assert.strictEqual(traces[0][0].meta['http.status_code'], '200') }).then(done).catch(done) axios.get(`http://localhost:${port}/`) @@ -171,7 +171,7 @@ describe('set_user', () => { assert.strictEqual(traces[0][0].meta['usr.id'], 'blockedUser') assert.strictEqual(traces[0][0].meta['_dd.appsec.user.collection_mode'], 'sdk') assert.strictEqual(traces[0][0].meta['appsec.event'], 'true') - assert.ok(!Object.hasOwn(traces[0][0].meta, 'appsec.blocked')) + assert.ok(!('appsec.blocked' in traces[0][0].meta)) assert.strictEqual(traces[0][0].meta['http.status_code'], '200') }).then(done).catch(done) axios.get(`http://localhost:${port}/`) diff --git a/packages/dd-trace/test/appsec/sdk/track_event-integration.spec.js b/packages/dd-trace/test/appsec/sdk/track_event-integration.spec.js index cc757c5f629..81b57482dc5 100644 --- a/packages/dd-trace/test/appsec/sdk/track_event-integration.spec.js +++ b/packages/dd-trace/test/appsec/sdk/track_event-integration.spec.js @@ -63,7 +63,10 @@ describe('track_event - Integration with the tracer', () => { res.end() } agent.assertSomeTraces(traces => { - assert.ok(!('appsec.events.users.login.success.track' in traces[0][0].meta) || traces[0][0].meta['appsec.events.users.login.success.track'] !== 'true') + assert.ok( + !('appsec.events.users.login.success.track' in traces[0][0].meta) || + traces[0][0].meta['appsec.events.users.login.success.track'] !== 'true' + ) }).then(done).catch(done) axios.get(`http://localhost:${port}/`) }) @@ -73,7 +76,10 @@ describe('track_event - Integration with the tracer', () => { res.end() } agent.assertSomeTraces(traces => { - assert.ok(!('appsec.events.users.login.success.track' in traces[0][0].meta) || traces[0][0].meta['appsec.events.users.login.success.track'] !== 'true') + assert.ok( + !('appsec.events.users.login.success.track' in traces[0][0].meta) || + traces[0][0].meta['appsec.events.users.login.success.track'] !== 'true' + ) }).then(done).catch(done) axios.get(`http://localhost:${port}/`) }) @@ -116,7 +122,10 @@ describe('track_event - Integration with the tracer', () => { res.end() } agent.assertSomeTraces(traces => { - assert.ok(!('appsec.events.users.login.failure.track' in traces[0][0].meta) || traces[0][0].meta['appsec.events.users.login.failure.track'] !== 'true') + assert.ok( + !('appsec.events.users.login.failure.track' in traces[0][0].meta) || + traces[0][0].meta['appsec.events.users.login.failure.track'] !== 'true' + ) }).then(done).catch(done) axios.get(`http://localhost:${port}/`) }) @@ -126,7 +135,10 @@ describe('track_event - Integration with the tracer', () => { res.end() } agent.assertSomeTraces(traces => { - assert.ok(!('appsec.events.users.login.failure.track' in traces[0][0].meta) || traces[0][0].meta['appsec.events.users.login.failure.track'] !== 'true') + assert.ok( + !('appsec.events.users.login.failure.track' in traces[0][0].meta) || + traces[0][0].meta['appsec.events.users.login.failure.track'] !== 'true' + ) }).then(done).catch(done) axios.get(`http://localhost:${port}/`) }) @@ -153,7 +165,10 @@ describe('track_event - Integration with the tracer', () => { res.end() } agent.assertSomeTraces(traces => { - assert.ok(!('_sampling_priority_v1' in traces[0][0].metrics) || traces[0][0].metrics._sampling_priority_v1 !== USER_KEEP) + assert.ok( + !('_sampling_priority_v1' in traces[0][0].metrics) || + traces[0][0].metrics._sampling_priority_v1 !== USER_KEEP + ) }).then(done).catch(done) axios.get(`http://localhost:${port}/`) }) diff --git a/packages/dd-trace/test/appsec/stack_trace.spec.js b/packages/dd-trace/test/appsec/stack_trace.spec.js index b68d8945346..a3a7d9334bd 100644 --- a/packages/dd-trace/test/appsec/stack_trace.spec.js +++ b/packages/dd-trace/test/appsec/stack_trace.spec.js @@ -233,7 +233,7 @@ describe('Stack trace reporter', () => { const stackId = 'test_stack_id' reportStackTrace(rootSpan, stackId, undefined) assert.ok(Object.hasOwn(rootSpan.meta_struct, 'another_tag')) - assert.ok(!Object.hasOwn(rootSpan.meta_struct, '_dd.stack')) + assert.ok(!('_dd.stack' in rootSpan.meta_struct)) }) }) diff --git a/packages/dd-trace/test/appsec/telemetry/waf.spec.js b/packages/dd-trace/test/appsec/telemetry/waf.spec.js index 72f71f070d5..abc442bc99a 100644 --- a/packages/dd-trace/test/appsec/telemetry/waf.spec.js +++ b/packages/dd-trace/test/appsec/telemetry/waf.spec.js @@ -225,9 +225,10 @@ describe('Appsec Waf Telemetry metrics', () => { assert.strictEqual(metrics.series[0].metric, 'waf.init') assert.strictEqual(metrics.series[0].points.length, 1) assert.strictEqual(metrics.series[0].points[0][1], 3) - assertObjectContains(metrics.series[0].tags, 'waf_version:0.0.1') - assertObjectContains(metrics.series[0].tags, 'event_rules_version:0.0.2') - assertObjectContains(metrics.series[0].tags, 'success:true') + assertObjectContains( + metrics.series[0].tags, + ['waf_version:0.0.1', 'event_rules_version:0.0.2', 'success:true'] + ) }) it('should increment waf.init and waf.config_errors on failed init', () => { @@ -238,14 +239,16 @@ describe('Appsec Waf Telemetry metrics', () => { const { metrics } = appsecNamespace.toJSON() assert.strictEqual(metrics.series.length, 2) assert.strictEqual(metrics.series[0].metric, 'waf.init') - assertObjectContains(metrics.series[0].tags, 'waf_version:0.0.1') - assertObjectContains(metrics.series[0].tags, 'event_rules_version:0.0.2') - assertObjectContains(metrics.series[0].tags, 'success:false') + assertObjectContains( + metrics.series[0].tags, + ['waf_version:0.0.1', 'event_rules_version:0.0.2', 'success:false'] + ) assert.strictEqual(metrics.series[1].metric, 'waf.config_errors') - assertObjectContains(metrics.series[1].tags, 'waf_version:0.0.1') - assertObjectContains(metrics.series[1].tags, 'event_rules_version:0.0.2') - assertObjectContains(metrics.series[1].tags, 'action:init') + assertObjectContains( + metrics.series[1].tags, + ['waf_version:0.0.1', 'event_rules_version:0.0.2', 'action:init'] + ) }) }) @@ -273,9 +276,10 @@ describe('Appsec Waf Telemetry metrics', () => { assert.strictEqual(metrics.series[0].metric, 'waf.updates') assert.strictEqual(metrics.series[0].points.length, 1) assert.strictEqual(metrics.series[0].points[0][1], 3) - assertObjectContains(metrics.series[0].tags, 'waf_version:0.0.1') - assertObjectContains(metrics.series[0].tags, 'event_rules_version:0.0.2') - assertObjectContains(metrics.series[0].tags, 'success:true') + assertObjectContains( + metrics.series[0].tags, + ['waf_version:0.0.1', 'event_rules_version:0.0.2', 'success:true'] + ) }) }) @@ -303,9 +307,10 @@ describe('Appsec Waf Telemetry metrics', () => { assert.strictEqual(metrics.series[0].metric, 'waf.config_errors') assert.strictEqual(metrics.series[0].points.length, 1) assert.strictEqual(metrics.series[0].points[0][1], 3) - assertObjectContains(metrics.series[0].tags, 'waf_version:0.0.1') - assertObjectContains(metrics.series[0].tags, 'event_rules_version:0.0.2') - assertObjectContains(metrics.series[0].tags, 'action:update') + assertObjectContains( + metrics.series[0].tags, + ['waf_version:0.0.1', 'event_rules_version:0.0.2', 'action:update'] + ) }) }) diff --git a/packages/dd-trace/test/ci-visibility/exporters/agent-proxy/agent-proxy.spec.js b/packages/dd-trace/test/ci-visibility/exporters/agent-proxy/agent-proxy.spec.js index 7d6d088fc40..417ef63c1b0 100644 --- a/packages/dd-trace/test/ci-visibility/exporters/agent-proxy/agent-proxy.spec.js +++ b/packages/dd-trace/test/ci-visibility/exporters/agent-proxy/agent-proxy.spec.js @@ -56,8 +56,8 @@ describe('AgentProxyCiVisibilityExporter', () => { agentProxyCiVisibilityExporter.export(trace) agentProxyCiVisibilityExporter.exportCoverage(coverage) - assertObjectContains(agentProxyCiVisibilityExporter.getUncodedTraces(), trace) - assertObjectContains(agentProxyCiVisibilityExporter._coverageBuffer, coverage) + assertObjectContains(agentProxyCiVisibilityExporter.getUncodedTraces(), [trace]) + assertObjectContains(agentProxyCiVisibilityExporter._coverageBuffer, [coverage]) agentProxyCiVisibilityExporter.export = sinon.spy() agentProxyCiVisibilityExporter.exportCoverage = sinon.spy() diff --git a/packages/dd-trace/test/ci-visibility/exporters/agentless/exporter.spec.js b/packages/dd-trace/test/ci-visibility/exporters/agentless/exporter.spec.js index de497a62169..da7c903f8c1 100644 --- a/packages/dd-trace/test/ci-visibility/exporters/agentless/exporter.spec.js +++ b/packages/dd-trace/test/ci-visibility/exporters/agentless/exporter.spec.js @@ -1,7 +1,6 @@ 'use strict' const assert = require('node:assert/strict') -const { assertObjectContains } = require('../../../../../../integration-tests/helpers') const { describe, it, beforeEach, afterEach, before, after, context } = require('tap').mocha const sinon = require('sinon') @@ -171,7 +170,11 @@ describe('CI Visibility Agentless Exporter', () => { agentlessExporter.getLibraryConfiguration({}, (err) => { assert.notStrictEqual(scope.isDone(), true) - assertObjectContains(err.message, 'Request to settings endpoint was not done because Datadog API key is not defined') + assert.ok( + err.message.includes( + 'Request to settings endpoint was not done because Datadog API key is not defined' + ) + ) assert.strictEqual(agentlessExporter.shouldRequestSkippableSuites(), false) process.env.DD_API_KEY = '1' done() diff --git a/packages/dd-trace/test/ci-visibility/exporters/ci-visibility-exporter.spec.js b/packages/dd-trace/test/ci-visibility/exporters/ci-visibility-exporter.spec.js index 30987496ce4..c63f6000c6b 100644 --- a/packages/dd-trace/test/ci-visibility/exporters/ci-visibility-exporter.spec.js +++ b/packages/dd-trace/test/ci-visibility/exporters/ci-visibility-exporter.spec.js @@ -63,7 +63,7 @@ describe('CI Visibility Exporter', () => { const ciVisibilityExporter = new CiVisibilityExporter({ url: urlObj, isGitUploadEnabled: true }) ciVisibilityExporter._gitUploadPromise.then((err) => { - assertObjectContains(err.message, 'Error fetching commits to exclude') + assert.match(err.message, /Error fetching commits to exclude/) assert.strictEqual(scope.isDone(), true) done() }) @@ -601,7 +601,7 @@ describe('CI Visibility Exporter', () => { ciVisibilityExporter._isInitialized = true ciVisibilityExporter._writer = writer ciVisibilityExporter.export(trace) - expect(ciVisibilityExporter._traceBuffer).not.to.include(trace) + assert.ok(!ciVisibilityExporter._traceBuffer.includes(trace)) sinon.assert.called(ciVisibilityExporter._writer.append) }) }) @@ -619,7 +619,7 @@ describe('CI Visibility Exporter', () => { ciVisibilityExporter._isInitialized = true ciVisibilityExporter._writer = writer ciVisibilityExporter.export(trace) - expect(ciVisibilityExporter._traceBuffer).not.to.include(trace) + assert.ok(!ciVisibilityExporter._traceBuffer.includes(trace)) sinon.assert.notCalled(ciVisibilityExporter._writer.append) }) }) @@ -638,7 +638,7 @@ describe('CI Visibility Exporter', () => { ciVisibilityExporter._writer = writer ciVisibilityExporter._canUseCiVisProtocol = true ciVisibilityExporter.export(trace) - expect(ciVisibilityExporter._traceBuffer).not.to.include(trace) + assert.ok(!ciVisibilityExporter._traceBuffer.includes(trace)) sinon.assert.called(ciVisibilityExporter._writer.append) }) }) @@ -651,7 +651,7 @@ describe('CI Visibility Exporter', () => { const ciVisibilityExporter = new CiVisibilityExporter({ port }) ciVisibilityExporter.exportCoverage(coverage) ciVisibilityExporter._export = sinon.spy() - assertObjectContains(ciVisibilityExporter._coverageBuffer, coverage) + assertObjectContains(ciVisibilityExporter._coverageBuffer, [coverage]) sinon.assert.notCalled(ciVisibilityExporter._export) }) }) @@ -667,7 +667,7 @@ describe('CI Visibility Exporter', () => { ciVisibilityExporter._isInitialized = true ciVisibilityExporter._coverageWriter = writer ciVisibilityExporter.exportCoverage(coverage) - expect(ciVisibilityExporter._coverageBuffer).not.to.include(coverage) + assert.ok(!ciVisibilityExporter._coverageBuffer.includes(coverage)) sinon.assert.notCalled(ciVisibilityExporter._coverageWriter.append) }) }) @@ -689,7 +689,7 @@ describe('CI Visibility Exporter', () => { ciVisibilityExporter._canUseCiVisProtocol = true ciVisibilityExporter.exportCoverage(coverage) - expect(ciVisibilityExporter._coverageBuffer).not.to.include(coverage) + assert.ok(!ciVisibilityExporter._coverageBuffer.includes(coverage)) sinon.assert.called(ciVisibilityExporter._coverageWriter.append) }) }) diff --git a/packages/dd-trace/test/ci-visibility/exporters/git/git_metadata.spec.js b/packages/dd-trace/test/ci-visibility/exporters/git/git_metadata.spec.js index bcb1d6c088d..681c6b1276b 100644 --- a/packages/dd-trace/test/ci-visibility/exporters/git/git_metadata.spec.js +++ b/packages/dd-trace/test/ci-visibility/exporters/git/git_metadata.spec.js @@ -150,7 +150,7 @@ describe('git_metadata', () => { assert.strictEqual(err, null) // to check that it is not called assert.strictEqual(scope.isDone(), false) - assertObjectContains(scope.pendingMocks(), 'POST https://api.test.com:443/api/v2/git/repository/packfile') + assertObjectContains(scope.pendingMocks(), ['POST https://api.test.com:443/api/v2/git/repository/packfile']) done() }) }) @@ -166,7 +166,7 @@ describe('git_metadata', () => { assertObjectContains(err.message, 'Error fetching commits to exclude: Error from https://api.test.com/api/v2/git/repository/search_commits: 404 Not Found. Response from the endpoint: "Not found SHA"') // to check that it is not called assert.strictEqual(scope.isDone(), false) - assertObjectContains(scope.pendingMocks(), 'POST https://api.test.com:443/api/v2/git/repository/packfile') + assertObjectContains(scope.pendingMocks(), ['POST https://api.test.com:443/api/v2/git/repository/packfile']) done() }) }) @@ -182,7 +182,7 @@ describe('git_metadata', () => { assertObjectContains(err.message, "Can't parse commits to exclude response: Invalid commit type response") // to check that it is not called assert.strictEqual(scope.isDone(), false) - assertObjectContains(scope.pendingMocks(), 'POST https://api.test.com:443/api/v2/git/repository/packfile') + assertObjectContains(scope.pendingMocks(), ['POST https://api.test.com:443/api/v2/git/repository/packfile']) done() }) }) @@ -198,7 +198,7 @@ describe('git_metadata', () => { assertObjectContains(err.message, "Can't parse commits to exclude response: Invalid commit format") // to check that it is not called assert.strictEqual(scope.isDone(), false) - assertObjectContains(scope.pendingMocks(), 'POST https://api.test.com:443/api/v2/git/repository/packfile') + assertObjectContains(scope.pendingMocks(), ['POST https://api.test.com:443/api/v2/git/repository/packfile']) done() }) }) @@ -211,7 +211,7 @@ describe('git_metadata', () => { .reply(502) gitMetadata.sendGitMetadata(new URL('https://api.test.com'), { isEvpProxy: false }, '', (err) => { - assertObjectContains(err.message, 'Could not upload packfiles: status code 502') + assert.match(err.message, /Could not upload packfiles: status code 502/) assert.strictEqual(scope.isDone(), true) done() }) @@ -225,7 +225,7 @@ describe('git_metadata', () => { .reply(200, JSON.stringify({ data: [] })) gitMetadata.sendGitMetadata(new URL('https://api.test.com'), { isEvpProxy: false }, '', (err) => { - assertObjectContains(err.message, 'git rev-list failed') + assert.match(err.message, /git rev-list failed/) assert.strictEqual(scope.isDone(), true) done() }) @@ -327,7 +327,7 @@ describe('git_metadata', () => { ]) gitMetadata.sendGitMetadata(new URL('https://api.test.com'), { isEvpProxy: false }, '', (err) => { - assertObjectContains(err.message, 'Could not read "not-there"') + assert.match(err.message, /Could not read "not-there"/) assert.strictEqual(scope.isDone(), false) done() }) @@ -343,7 +343,7 @@ describe('git_metadata', () => { generatePackFilesForCommitsStub.returns([]) gitMetadata.sendGitMetadata(new URL('https://api.test.com'), { isEvpProxy: false }, '', (err) => { - assertObjectContains(err.message, 'Failed to generate packfiles') + assert.match(err.message, /Failed to generate packfiles/) assert.strictEqual(scope.isDone(), false) done() }) @@ -361,7 +361,7 @@ describe('git_metadata', () => { .reply(204) gitMetadata.sendGitMetadata(new URL('https://api.test.com'), { isEvpProxy: false }, '', (err) => { - assertObjectContains(err.message, 'Git is not available') + assert.match(err.message, /Git is not available/) assert.strictEqual(scope.isDone(), false) process.env.PATH = oldPath done() diff --git a/packages/dd-trace/test/config.spec.js b/packages/dd-trace/test/config.spec.js index 42dd9ff9250..83d6b6da389 100644 --- a/packages/dd-trace/test/config.spec.js +++ b/packages/dd-trace/test/config.spec.js @@ -2516,10 +2516,10 @@ describe('Config', () => { }) it('does not crash if git.properties is not available', () => { process.env.DD_GIT_PROPERTIES_FILE = '/does/not/exist' - expect(() => { - const config = getConfig({}) - expect(config).to.be.an('object') - }).to.not.throw() + + // Should not throw + const config = getConfig({}) + expect(config).to.be.an('object') }) it('does not read git.properties if env vars are passed', () => { process.env.DD_GIT_PROPERTIES_FILE = DD_GIT_PROPERTIES_FILE @@ -2556,10 +2556,10 @@ describe('Config', () => { }) it('does not crash if .git/ folder is not available', () => { process.env.DD_GIT_FOLDER_PATH = '/does/not/exist/' - expect(() => { - const config = getConfig({}) - expect(config).to.be.an('object') - }).to.not.throw() + + // Should not throw + const config = getConfig({}) + expect(config).to.be.an('object') }) it('does not read .git/ folder if env vars are passed', () => { process.env.DD_GIT_FOLDER_PATH = DD_GIT_FOLDER_PATH diff --git a/packages/dd-trace/test/datastreams/data_streams_checkpointer.spec.js b/packages/dd-trace/test/datastreams/data_streams_checkpointer.spec.js index 06a6e475427..3bd6dab4fce 100644 --- a/packages/dd-trace/test/datastreams/data_streams_checkpointer.spec.js +++ b/packages/dd-trace/test/datastreams/data_streams_checkpointer.spec.js @@ -2,9 +2,6 @@ const assert = require('node:assert/strict') -const { expect } = require('chai') -const { assertObjectContains } = require('../../../../integration-tests/helpers') - const { describe, it, before, after } = require('tap').mocha const sinon = require('sinon') @@ -88,7 +85,7 @@ describe('data streams checkpointer manual api', () => { tracer.dataStreamsCheckpointer.setConsumeCheckpoint('kinesis', 'stream-123', headers) const calledTags = mockSetCheckpoint.getCall(0).args[0] - assertObjectContains(calledTags, 'manual_checkpoint:true') + assert.deepStrictEqual(calledTags, ['type:kinesis', 'topic:stream-123', 'direction:in', 'manual_checkpoint:true']) }) it('should set an automatic checkpoint when setConsumeCheckpoint is called with manualCheckpoint:false', function () { @@ -99,6 +96,6 @@ describe('data streams checkpointer manual api', () => { tracer.dataStreamsCheckpointer.setConsumeCheckpoint('kinesis', 'stream-123', headers, false) const calledTags = mockSetCheckpoint.getCall(0).args[0] - expect(calledTags).to.not.include('manual_checkpoint:true') + assert.ok(!calledTags.includes('manual_checkpoint:true')) }) }) diff --git a/packages/dd-trace/test/debugger/devtools_client/snapshot/max-collection-size.spec.js b/packages/dd-trace/test/debugger/devtools_client/snapshot/max-collection-size.spec.js index caa0d1d4b7c..2421058edd6 100644 --- a/packages/dd-trace/test/debugger/devtools_client/snapshot/max-collection-size.spec.js +++ b/packages/dd-trace/test/debugger/devtools_client/snapshot/max-collection-size.spec.js @@ -54,8 +54,10 @@ describe('debugger -> devtools client -> snapshot.getLocalStateForCallFrame', fu }) it('should have expected number of elements in state', function () { - assert.strictEqual(Object.keys(state).length, ((Array.isArray(['arr', 'map', 'set', 'wmap', 'wset', 'typedArray']) ? ['arr', 'map', 'set', 'wmap', 'wset', 'typedArray'] : [['arr', 'map', 'set', 'wmap', 'wset', 'typedArray']])).length) - assert.ok(((Array.isArray(['arr', 'map', 'set', 'wmap', 'wset', 'typedArray']) ? ['arr', 'map', 'set', 'wmap', 'wset', 'typedArray'] : [['arr', 'map', 'set', 'wmap', 'wset', 'typedArray']])).every(k => Object.hasOwn(state, k))) + assert.deepStrictEqual( + Object.keys(state).sort(), + ['LARGE_SIZE', 'arr', 'map', 'set', 'typedArray', 'wmap', 'wset'] + ) }) it('Array', function () { diff --git a/packages/dd-trace/test/debugger/devtools_client/snapshot/max-field-count-scopes.spec.js b/packages/dd-trace/test/debugger/devtools_client/snapshot/max-field-count-scopes.spec.js index d17be63aa35..b55a9f386d1 100644 --- a/packages/dd-trace/test/debugger/devtools_client/snapshot/max-field-count-scopes.spec.js +++ b/packages/dd-trace/test/debugger/devtools_client/snapshot/max-field-count-scopes.spec.js @@ -28,8 +28,7 @@ describe('debugger -> devtools client -> snapshot.getLocalStateForCallFrame', fu it('should capture expected snapshot', function () { // Expect the snapshot to have captured the first 3 fields from each scope - assert.strictEqual(Object.keys(state).length, ((Array.isArray(['a1', 'b1', 'c1', 'a2', 'b2', 'c2']) ? ['a1', 'b1', 'c1', 'a2', 'b2', 'c2'] : [['a1', 'b1', 'c1', 'a2', 'b2', 'c2']])).length) - assert.ok(((Array.isArray(['a1', 'b1', 'c1', 'a2', 'b2', 'c2']) ? ['a1', 'b1', 'c1', 'a2', 'b2', 'c2'] : [['a1', 'b1', 'c1', 'a2', 'b2', 'c2']])).every(k => Object.hasOwn(state, k))) + assert.deepStrictEqual(Object.keys(state).sort(), ['a1', 'a2', 'b1', 'b2', 'c1', 'c2']) }) }) }) diff --git a/packages/dd-trace/test/debugger/devtools_client/snapshot/redaction.spec.js b/packages/dd-trace/test/debugger/devtools_client/snapshot/redaction.spec.js index 2b7b3aeef1f..013ef65bab9 100644 --- a/packages/dd-trace/test/debugger/devtools_client/snapshot/redaction.spec.js +++ b/packages/dd-trace/test/debugger/devtools_client/snapshot/redaction.spec.js @@ -16,8 +16,17 @@ describe('debugger -> devtools client -> snapshot.getLocalStateForCallFrame', fu // Non-default configuration is tested in the integration tests it('should replace PII in keys/properties/variables with expected notCapturedReason', function (done) { assertOnBreakpoint(done, (state) => { - assert.strictEqual(Object.keys(state).length, (['nonNormalizedSecretToken', 'foo', 'secret', 'Se_cret_$', 'weakMapKey', 'obj']).length) - assert.ok((['nonNormalizedSecretToken', 'foo', 'secret', 'Se_cret_$', 'weakMapKey', 'obj']).every(k => Object.hasOwn(state, k))) + assert.deepStrictEqual( + Object.keys(state).sort(), + [ + 'Se_cret_$', + 'foo', + 'nonNormalizedSecretToken', + 'obj', + 'secret', + 'weakMapKey' + ] + ) assert.ok('foo' in state) assert.deepStrictEqual(state.foo, { type: 'string', value: 'bar' }) @@ -34,8 +43,21 @@ describe('debugger -> devtools client -> snapshot.getLocalStateForCallFrame', fu assert.strictEqual(state.obj.type, 'Object') const { fields } = state.obj - assert.strictEqual(Object.keys(fields).length, (['foo', 'secret', '@Se-cret_$_', 'nested', 'arr', 'map', 'weakmap', 'password', 'Symbol(secret)', 'Symbol(@Se-cret_$_)']).length) - assert.ok((['foo', 'secret', '@Se-cret_$_', 'nested', 'arr', 'map', 'weakmap', 'password', 'Symbol(secret)', 'Symbol(@Se-cret_$_)']).every(k => Object.hasOwn(fields, k))) + assert.deepStrictEqual( + Object.keys(fields), + [ + 'foo', + 'secret', + '@Se-cret_$_', + 'nested', + 'arr', + 'map', + 'weakmap', + 'password', + 'Symbol(secret)', + 'Symbol(@Se-cret_$_)', + ] + ) assert.ok('foo' in fields) assert.deepStrictEqual(fields.foo, { type: 'string', value: 'bar' }) diff --git a/packages/dd-trace/test/encode/0.5.spec.js b/packages/dd-trace/test/encode/0.5.spec.js index 247ad422676..c46e0c8af66 100644 --- a/packages/dd-trace/test/encode/0.5.spec.js +++ b/packages/dd-trace/test/encode/0.5.spec.js @@ -92,8 +92,7 @@ describe('encode 0.5', () => { const decoded = msgpack.decode(buffer, { useBigInt64: true }) const stringMap = decoded[0] const trace = decoded[1][0] - assertObjectContains(stringMap, 'events') - assertObjectContains(stringMap, encodedLink) + assertObjectContains(stringMap, ['events', encodedLink]) assertObjectContains(trace[0][9], { [stringMap.indexOf('bar')]: stringMap.indexOf('baz'), [stringMap.indexOf('events')]: stringMap.indexOf(encodedLink) @@ -124,8 +123,7 @@ describe('encode 0.5', () => { assert.strictEqual(stringMap[trace[0][0]], data[0].service) assert.strictEqual(stringMap[trace[0][1]], data[0].name) assert.strictEqual(stringMap[trace[0][2]], data[0].resource) - assertObjectContains(stringMap, '_dd.span_links') - assertObjectContains(stringMap, encodedLink) + assertObjectContains(stringMap, ['_dd.span_links', encodedLink]) assert.strictEqual(trace[0][3].toString(16), data[0].trace_id.toString()) assert.strictEqual(trace[0][4].toString(16), data[0].span_id.toString()) assert.strictEqual(trace[0][5].toString(16), data[0].parent_id.toString()) @@ -158,8 +156,7 @@ describe('encode 0.5', () => { assert.strictEqual(stringMap[trace[0][0]], data[0].service) assert.strictEqual(stringMap[trace[0][1]], data[0].name) assert.strictEqual(stringMap[trace[0][2]], data[0].resource) - assertObjectContains(stringMap, '_dd.span_links') - assertObjectContains(stringMap, encodedLink) + assertObjectContains(stringMap, ['_dd.span_links', encodedLink]) assert.strictEqual(trace[0][3].toString(16), data[0].trace_id.toString()) assert.strictEqual(trace[0][4].toString(16), data[0].span_id.toString()) assert.strictEqual(trace[0][5].toString(16), data[0].parent_id.toString()) @@ -249,6 +246,7 @@ describe('encode 0.5', () => { assert.deepStrictEqual(trace[0][9], { [stringMap.indexOf('bar')]: stringMap.indexOf('baz') }) assert.deepStrictEqual(trace[0][10], { [stringMap.indexOf('example')]: 1 }) assert.strictEqual(stringMap[trace[0][11]], '') // unset - assert.strictEqual(trace[0][12], undefined) // Everything works the same as without meta_struct, and nothing else is added + // Everything works the same as without meta_struct, and nothing else is added + assert.strictEqual(trace[0][12], undefined) }) }) diff --git a/packages/dd-trace/test/encode/coverage-ci-visibility.spec.js b/packages/dd-trace/test/encode/coverage-ci-visibility.spec.js index a78098bc693..aa47ebd1fc4 100644 --- a/packages/dd-trace/test/encode/coverage-ci-visibility.spec.js +++ b/packages/dd-trace/test/encode/coverage-ci-visibility.spec.js @@ -12,6 +12,13 @@ require('../setup/core') const id = require('../../src/id') +/** + * @typedef {{ + * version: number, + * coverages: { test_session_id: number, test_suite_id: number, files: { filename: string }[] }[] } + * } CoverageObject + */ + describe('coverage-ci-visibility', () => { let encoder let logger @@ -50,10 +57,16 @@ describe('coverage-ci-visibility', () => { const form = encoder.makePayload() - assertObjectContains(form._data[1], 'Content-Disposition: form-data; name="coverage1"; filename="coverage1.msgpack"') - assertObjectContains(form._data[2], 'Content-Type: application/msgpack') - - const decodedCoverages = msgpack.decode(form._data[3]) + assert.ok(form._data[0].startsWith('--')) + assertObjectContains( + form._data, + [ + 'Content-Disposition: form-data; name="coverage1"; filename="coverage1.msgpack"\r\n', + // TODO: The double line breaks seem to be a mistake + 'Content-Type: application/msgpack\r\n\r\n' + ] + ) + const decodedCoverages = /** @type {CoverageObject} */ (msgpack.decode(form._data[3])) assert.strictEqual(decodedCoverages.version, 2) assert.strictEqual(decodedCoverages.coverages.length, 2) @@ -87,14 +100,14 @@ describe('coverage-ci-visibility', () => { let form, decodedCoverages encoder.encode(formattedCoverage) form = encoder.makePayload() - decodedCoverages = msgpack.decode(form._data[3]) + decodedCoverages = /** @type {CoverageObject} */ (msgpack.decode(form._data[3])) assert.strictEqual(decodedCoverages.version, 2) assert.strictEqual(decodedCoverages.coverages.length, 1) assertObjectContains(decodedCoverages.coverages[0], { test_session_id: 1, test_suite_id: 2 }) encoder.encode(formattedCoverage2) form = encoder.makePayload() - decodedCoverages = msgpack.decode(form._data[3]) + decodedCoverages = /** @type {CoverageObject} */ (msgpack.decode(form._data[3])) assert.strictEqual(decodedCoverages.version, 2) assert.strictEqual(decodedCoverages.coverages.length, 1) assertObjectContains(decodedCoverages.coverages[0], { test_session_id: 3, test_suite_id: 4 }) @@ -105,10 +118,16 @@ describe('coverage-ci-visibility', () => { const form = encoder.makePayload() - assertObjectContains(form._data[1], 'Content-Disposition: form-data; name="coverage1"; filename="coverage1.msgpack"') - assertObjectContains(form._data[2], 'Content-Type: application/msgpack') + assert.ok(form._data[0].startsWith('--')) + assertObjectContains( + form._data, + [ + 'Content-Disposition: form-data; name="coverage1"; filename="coverage1.msgpack"\r\n', + 'Content-Type: application/msgpack\r\n\r\n' + ] + ) - const decodedCoverages = msgpack.decode(form._data[3]) + const decodedCoverages = /** @type {CoverageObject} */ (msgpack.decode(form._data[3])) assert.strictEqual(decodedCoverages.version, 2) assert.strictEqual(decodedCoverages.coverages.length, 1) diff --git a/packages/dd-trace/test/encode/span-stats.spec.js b/packages/dd-trace/test/encode/span-stats.spec.js index 63c3e0b2fcf..d53584477dd 100644 --- a/packages/dd-trace/test/encode/span-stats.spec.js +++ b/packages/dd-trace/test/encode/span-stats.spec.js @@ -2,7 +2,6 @@ const assert = require('node:assert/strict') -const { expect } = require('chai') const { describe, it, beforeEach } = require('tap').mocha const msgpack = require('@msgpack/msgpack') const sinon = require('sinon') @@ -129,7 +128,7 @@ describe('span-stats-encode', () => { const buffer = encoder.makePayload() const decoded = msgpack.decode(buffer) - expect(decoded) + assert.ok(decoded) const decodedStat = decoded.Stats[0].Stats[0] assert.strictEqual(decodedStat.Type.length, MAX_TYPE_LENGTH) assert.strictEqual(decodedStat.Name.length, MAX_NAME_LENGTH) @@ -158,10 +157,10 @@ describe('span-stats-encode', () => { const buffer = encoder.makePayload() const decodedStats = msgpack.decode(buffer) - expect(decodedStats) + assert.ok(decodedStats) const decodedStat = decodedStats.Stats[0].Stats[0] - expect(decodedStat) + assert.ok(decodedStat) assert.strictEqual(decodedStat.Service, DEFAULT_SERVICE_NAME) assert.strictEqual(decodedStat.Name, DEFAULT_SPAN_NAME) }) @@ -173,7 +172,7 @@ describe('span-stats-encode', () => { const decoded = msgpack.decode(buffer) const decodedStat = decoded.Stats[0].Stats[0] - expect(decodedStat.HTTPMethod).to.equal('GET') - expect(decodedStat.HTTPEndpoint).to.equal('/users/:id') + assert.strictEqual(decodedStat.HTTPMethod, 'GET') + assert.strictEqual(decodedStat.HTTPEndpoint, '/users/:id') }) }) diff --git a/packages/dd-trace/test/exporters/common/agent-info-exporter.spec.js b/packages/dd-trace/test/exporters/common/agent-info-exporter.spec.js index c6330a56cc1..bffd57612e8 100644 --- a/packages/dd-trace/test/exporters/common/agent-info-exporter.spec.js +++ b/packages/dd-trace/test/exporters/common/agent-info-exporter.spec.js @@ -3,7 +3,6 @@ const assert = require('node:assert/strict') const { expect } = require('chai') -const { assertObjectContains } = require('../../../../../integration-tests/helpers') const { describe, it } = require('tap').mocha const sinon = require('sinon') @@ -32,9 +31,9 @@ describe('AgentInfoExporter', () => { const agentInfoExporter = new AgentInfoExporter({ port }) assert.notStrictEqual(scope.isDone(), true) - agentInfoExporter.getAgentInfo((err, { endpoints }) => { + agentInfoExporter.getAgentInfo((err, response) => { assert.strictEqual(err, null) - assertObjectContains(endpoints, '/evp_proxy/v2') + assert.deepStrictEqual(response.endpoints, ['/evp_proxy/v2']) assert.strictEqual(scope.isDone(), true) done() }) @@ -51,10 +50,10 @@ describe('AgentInfoExporter', () => { agentInfoExporter.export(trace) - assertObjectContains(agentInfoExporter.getUncodedTraces(), trace) + assert.deepStrictEqual(agentInfoExporter.getUncodedTraces(), [trace]) agentInfoExporter.getAgentInfo(() => { - assertObjectContains(agentInfoExporter.getUncodedTraces(), trace) + assert.deepStrictEqual(agentInfoExporter.getUncodedTraces(), [trace]) done() }) }) diff --git a/packages/dd-trace/test/llmobs/sdk/index.spec.js b/packages/dd-trace/test/llmobs/sdk/index.spec.js index 9d463104b3d..40df3a4979f 100644 --- a/packages/dd-trace/test/llmobs/sdk/index.spec.js +++ b/packages/dd-trace/test/llmobs/sdk/index.spec.js @@ -2,7 +2,6 @@ const assert = require('node:assert') -const { expect } = require('chai') const { channel } = require('dc-polyfill') const { after, afterEach, before, beforeEach, describe, it } = require('mocha') const sinon = require('sinon') diff --git a/packages/dd-trace/test/llmobs/span_processor.spec.js b/packages/dd-trace/test/llmobs/span_processor.spec.js index cf343598297..f406eafe194 100644 --- a/packages/dd-trace/test/llmobs/span_processor.spec.js +++ b/packages/dd-trace/test/llmobs/span_processor.spec.js @@ -255,7 +255,7 @@ describe('span processor', () => { assert.strictEqual(payload.meta['error.stack'], 'error stack') assert.strictEqual(payload.status, 'error') - assertObjectContains(payload.tags, 'error_type:error type') + assertObjectContains(payload.tags, ['error_type:error type']) }) it('uses the error itself if the span does not have specific error fields', () => { @@ -283,7 +283,7 @@ describe('span processor', () => { assert.ok(payload.meta['error.stack'] != null) assert.strictEqual(payload.status, 'error') - assertObjectContains(payload.tags, 'error_type:Error') + assertObjectContains(payload.tags, ['error_type:Error']) }) it('uses the span name from the tag if provided', () => { @@ -329,7 +329,7 @@ describe('span processor', () => { const payload = writer.append.getCall(0).firstArg assert.strictEqual(payload.session_id, '1234') - assertObjectContains(payload.tags, 'session_id:1234') + assertObjectContains(payload.tags, ['session_id:1234']) }) it('sets span tags appropriately', () => { @@ -351,9 +351,7 @@ describe('span processor', () => { processor.process(span) const payload = writer.append.getCall(0).firstArg - assertObjectContains(payload.tags, 'foo:bar') - assertObjectContains(payload.tags, 'source:mySource') - assertObjectContains(payload.tags, 'hostname:localhost') + assertObjectContains(payload.tags, ['source:mySource', 'hostname:localhost', 'foo:bar']) }) }) }) diff --git a/packages/dd-trace/test/llmobs/tagger.spec.js b/packages/dd-trace/test/llmobs/tagger.spec.js index 818e531fd32..dee69040356 100644 --- a/packages/dd-trace/test/llmobs/tagger.spec.js +++ b/packages/dd-trace/test/llmobs/tagger.spec.js @@ -511,7 +511,7 @@ describe('tagger', () => { tagger.tagLLMIO(span, messages, undefined) const messageTags = Tagger.tagMap.get(span)['_ml_obs.meta.input.messages'] - assert.ok(!Object.hasOwn(messageTags[0], 'tool_id')) + assert.ok(!('tool_id' in messageTags[0])) sinon.assert.calledOnce(logger.warn) }) diff --git a/packages/dd-trace/test/llmobs/util.spec.js b/packages/dd-trace/test/llmobs/util.spec.js index ecb13186eca..e15038b225f 100644 --- a/packages/dd-trace/test/llmobs/util.spec.js +++ b/packages/dd-trace/test/llmobs/util.spec.js @@ -60,7 +60,10 @@ describe('util', () => { }) it('should capture spread arguments', () => { - assert.deepStrictEqual(getFunctionArguments((foo, bar, ...args) => {}, ['foo', 'bar', 1, 2, 3]), { foo: 'foo', bar: 'bar', args: [1, 2, 3] }) + assert.deepStrictEqual( + getFunctionArguments((foo, bar, ...args) => {}, ['foo', 'bar', 1, 2, 3]), + { foo: 'foo', bar: 'bar', args: [1, 2, 3] } + ) }) }) diff --git a/packages/dd-trace/test/openfeature/flagging_provider_timeout.spec.js b/packages/dd-trace/test/openfeature/flagging_provider_timeout.spec.js index d5d25541b4f..adeec79c0ba 100644 --- a/packages/dd-trace/test/openfeature/flagging_provider_timeout.spec.js +++ b/packages/dd-trace/test/openfeature/flagging_provider_timeout.spec.js @@ -6,7 +6,6 @@ const { ProviderEvents } = require('@openfeature/server-sdk') const { afterEach, beforeEach, describe, it } = require('mocha') const proxyquire = require('proxyquire') const sinon = require('sinon') -const { assertObjectContains } = require('../../../../integration-tests/helpers') require('../setup/mocha') @@ -146,8 +145,7 @@ describe('FlaggingProvider Initialization Timeout', () => { sinon.assert.calledOnce(setErrorSpy) const errorArg = setErrorSpy.firstCall.args[0] assert.ok(errorArg instanceof Error) - assertObjectContains(errorArg.message, 'Initialization timeout') - assertObjectContains(errorArg.message, '30000ms') + assert.strictEqual(errorArg.message, 'Initialization timeout after 30000ms') }) it('should allow recovery if configuration is set after timeout', async () => { @@ -254,8 +252,7 @@ describe('FlaggingProvider Initialization Timeout', () => { sinon.assert.calledOnce(setErrorSpy) const errorArg = setErrorSpy.firstCall.args[0] assert.ok(errorArg instanceof Error) - assertObjectContains(errorArg.message, 'Initialization timeout') - assertObjectContains(errorArg.message, '10000ms') + assert.strictEqual(errorArg.message, 'Initialization timeout after 10000ms') }) }) }) diff --git a/packages/dd-trace/test/opentelemetry/span.spec.js b/packages/dd-trace/test/opentelemetry/span.spec.js index 52bd9c4c885..541f1db0806 100644 --- a/packages/dd-trace/test/opentelemetry/span.spec.js +++ b/packages/dd-trace/test/opentelemetry/span.spec.js @@ -367,13 +367,13 @@ describe('OTel Span', () => { const unset = makeSpan('name') const unsetCtx = unset._ddSpan.context() unset.setStatus({ code: 0, message: 'unset' }) - assert.ok(!Object.hasOwn(unsetCtx._tags, ERROR_MESSAGE)) + assert.ok(!(ERROR_MESSAGE in unsetCtx._tags)) const ok = makeSpan('name') const okCtx = ok._ddSpan.context() ok.setStatus({ code: 1, message: 'ok' }) - assert.ok(!Object.hasOwn(okCtx._tags, ERROR_MESSAGE)) - assert.ok(!Object.hasOwn(okCtx._tags, IGNORE_OTEL_ERROR)) + assert.ok(!(ERROR_MESSAGE in okCtx._tags)) + assert.ok(!(IGNORE_OTEL_ERROR in okCtx._tags)) const error = makeSpan('name') const errorCtx = error._ddSpan.context() @@ -410,7 +410,7 @@ describe('OTel Span', () => { let formatted = spanFormat(span._ddSpan) assert.strictEqual(formatted.error, 0) - assert.ok(!Object.hasOwn(formatted.meta, 'doNotSetTraceError')) + assert.ok(!('doNotSetTraceError' in formatted.meta)) // Set error code span.setStatus({ code: 2, message: 'error' }) diff --git a/packages/dd-trace/test/opentracing/propagation/text_map.spec.js b/packages/dd-trace/test/opentracing/propagation/text_map.spec.js index 32e701b5ccf..9c8fab6151e 100644 --- a/packages/dd-trace/test/opentracing/propagation/text_map.spec.js +++ b/packages/dd-trace/test/opentracing/propagation/text_map.spec.js @@ -353,7 +353,10 @@ describe('TextMapPropagator', () => { assert.ok('traceparent' in carrier) assert.strictEqual(carrier.traceparent, '00-1111aaaa2222bbbb3333cccc4444dddd-5555eeee6666ffff-01') assert.ok('tracestate' in carrier) - assert.strictEqual(carrier.tracestate, 'dd=t.foo_bar_baz_:abc_!@#$%^&*()_+`-~;p:5555eeee6666ffff;s:2;o:foo_bar~;t.dm:-4,other=bleh') + assert.strictEqual( + carrier.tracestate, + 'dd=t.foo_bar_baz_:abc_!@#$%^&*()_+`-~;p:5555eeee6666ffff;s:2;o:foo_bar~;t.dm:-4,other=bleh' + ) }) it('should skip injection of B3 headers without the feature flag', () => { @@ -1054,8 +1057,10 @@ describe('TextMapPropagator', () => { const spanContext = propagator.extract(carrier) const idExpr = /^[0-9a-f]{16}$/ - assert.match(spanContext._traceId, idExpr) - assert.notStrictEqual(spanContext._traceId.toString(), '0000000000000000') + const traceId = spanContext._traceId + assert.strictEqual(typeof traceId, 'object') + assert.match(traceId.toString(), idExpr) + assert.notStrictEqual(traceId.toString(), '0000000000000000') assert.strictEqual(spanContext._spanId, null) assert.strictEqual(spanContext._sampling.priority, AUTO_REJECT) }) @@ -1067,8 +1072,10 @@ describe('TextMapPropagator', () => { const spanContext = propagator.extract(carrier) const idExpr = /^[0-9a-f]{16}$/ - assert.match(spanContext._traceId, idExpr) - assert.notStrictEqual(spanContext._traceId.toString(), '0000000000000000') + const traceId = spanContext._traceId + assert.strictEqual(typeof traceId, 'object') + assert.match(traceId.toString(), idExpr) + assert.notStrictEqual(traceId.toString(), '0000000000000000') assert.strictEqual(spanContext._spanId, null) assert.strictEqual(spanContext._sampling.priority, AUTO_KEEP) }) @@ -1080,8 +1087,10 @@ describe('TextMapPropagator', () => { const spanContext = propagator.extract(carrier) const idExpr = /^[0-9a-f]{16}$/ - assert.match(spanContext._traceId, idExpr) - assert.notStrictEqual(spanContext._traceId.toString(), '0000000000000000') + const traceId = spanContext._traceId + assert.strictEqual(typeof traceId, 'object') + assert.match(traceId.toString(), idExpr) + assert.notStrictEqual(traceId.toString(), '0000000000000000') assert.strictEqual(spanContext._spanId, null) assert.strictEqual(spanContext._sampling.priority, USER_KEEP) }) @@ -1169,8 +1178,10 @@ describe('TextMapPropagator', () => { const spanContext = propagator.extract(carrier) const idExpr = /^[0-9a-f]{16}$/ - assert.match(spanContext._traceId, idExpr) - assert.notStrictEqual(spanContext._traceId.toString(), '0000000000000000') + const traceId = spanContext._traceId + assert.strictEqual(typeof traceId, 'object') + assert.match(traceId.toString(), idExpr) + assert.notStrictEqual(traceId.toString(), '0000000000000000') assert.strictEqual(spanContext._spanId, null) assert.strictEqual(spanContext._sampling.priority, AUTO_REJECT) }) @@ -1182,8 +1193,10 @@ describe('TextMapPropagator', () => { const spanContext = propagator.extract(carrier) const idExpr = /^[0-9a-f]{16}$/ - assert.match(spanContext._traceId, idExpr) - assert.notStrictEqual(spanContext._traceId.toString(), '0000000000000000') + const traceId = spanContext._traceId + assert.strictEqual(typeof traceId, 'object') + assert.match(traceId.toString(), idExpr) + assert.notStrictEqual(traceId.toString(), '0000000000000000') assert.strictEqual(spanContext._spanId, null) assert.strictEqual(spanContext._sampling.priority, AUTO_KEEP) }) @@ -1195,8 +1208,10 @@ describe('TextMapPropagator', () => { const spanContext = propagator.extract(carrier) const idExpr = /^[0-9a-f]{16}$/ - assert.match(spanContext._traceId, idExpr) - assert.notStrictEqual(spanContext._traceId.toString(), '0000000000000000') + const traceId = spanContext._traceId + assert.strictEqual(typeof traceId, 'object') + assert.match(traceId.toString(), idExpr) + assert.notStrictEqual(traceId.toString(), '0000000000000000') assert.strictEqual(spanContext._spanId, null) assert.strictEqual(spanContext._sampling.priority, USER_KEEP) }) @@ -1251,7 +1266,10 @@ describe('TextMapPropagator', () => { propagator.extract(textMap) sinon.assert.called(log.debug) - assert.strictEqual(log.debug.firstCall.args[0](), `Extract from carrier (b3 single header): {"b3":"${textMap.b3}"}.`) + assert.strictEqual( + log.debug.firstCall.args[0](), + `Extract from carrier (b3 single header): {"b3":"${textMap.b3}"}.` + ) }) }) @@ -1321,7 +1339,7 @@ describe('TextMapPropagator', () => { propagator.inject(spanContext, carrier) assert.match(carrier.traceparent, /^01/) - assertObjectContains(carrier['x-datadog-tags'], '_dd.p.dm=-4') + assert.match(carrier['x-datadog-tags'], /_dd.p.dm=-4/) assert.deepStrictEqual(spanContext._trace.tags['_dd.p.dm'], '-4') }) @@ -1335,7 +1353,7 @@ describe('TextMapPropagator', () => { propagator.inject(spanContext, carrier) - assertObjectContains(carrier.tracestate, 'other=bleh') + assert.match(carrier.tracestate, /other=bleh/) }) it('should propagate last datadog id', () => { @@ -1350,7 +1368,7 @@ describe('TextMapPropagator', () => { propagator.inject(spanContext, carrier) - assertObjectContains(carrier.tracestate, 'p:4444eeee6666aaaa') + assert.match(carrier.tracestate, /p:4444eeee6666aaaa/) }) it('should fix _dd.p.dm if invalid (non-hyphenated) input is received', () => { @@ -1363,7 +1381,7 @@ describe('TextMapPropagator', () => { propagator.inject(spanContext, carrier) - assertObjectContains(carrier['x-datadog-tags'], '_dd.p.dm=-4') + assert.match(carrier['x-datadog-tags'], /_dd.p.dm=-4/) assert.deepStrictEqual(spanContext._trace.tags['_dd.p.dm'], '-4') }) @@ -1377,7 +1395,7 @@ describe('TextMapPropagator', () => { propagator.inject(spanContext, carrier) - assertObjectContains(carrier['x-datadog-tags'], '_dd.p.dm=-0') + assert.match(carrier['x-datadog-tags'], /_dd.p.dm=-0/) assert.deepStrictEqual(spanContext._trace.tags['_dd.p.dm'], '-0') }) diff --git a/packages/dd-trace/test/plugins/agent.js b/packages/dd-trace/test/plugins/agent.js index 21669ea2ef1..8f4d443d90a 100644 --- a/packages/dd-trace/test/plugins/agent.js +++ b/packages/dd-trace/test/plugins/agent.js @@ -323,6 +323,7 @@ let availableEndpoints = DEFAULT_AVAILABLE_ENDPOINTS * @returns {Promise} A promise resolving if expectations are met */ function runCallbackAgainstTraces (callback, options = {}, handlers) { + /** @type {Error[]} */ const errors = [] let resolve let reject @@ -333,11 +334,14 @@ function runCallbackAgainstTraces (callback, options = {}, handlers) { const rejectionTimeout = setTimeout(() => { if (errors.length) { - const error = new AggregateError(errors, 'Asserting traces failed. No result matched the expected one.') - // Mark errors enumerable for older Node.js versions to be visible. - Object.defineProperty(error, 'errors', { - enumerable: true - }) + let error = errors[0] + if (errors.length > 1) { + error = new AggregateError(errors, 'Asserting traces failed. No result matched the expected one.') + // Mark errors enumerable for older Node.js versions to be visible. + Object.defineProperty(error, 'errors', { + enumerable: true + }) + } // Hack for the information to be fully visible. error.message = util.inspect(error, { depth: null }) reject(error) diff --git a/packages/dd-trace/test/plugins/log_plugin.spec.js b/packages/dd-trace/test/plugins/log_plugin.spec.js index ccdaa79d76d..8e2147c1738 100644 --- a/packages/dd-trace/test/plugins/log_plugin.spec.js +++ b/packages/dd-trace/test/plugins/log_plugin.spec.js @@ -47,8 +47,8 @@ describe('LogPlugin', () => { assert.deepStrictEqual(message.dd, config) // Should not have trace/span data when none is active - assert.ok(!Object.hasOwn(message.dd, 'trace_id')) - assert.ok(!Object.hasOwn(message.dd, 'span_id')) + assert.ok(!('trace_id' in message.dd)) + assert.ok(!('span_id' in message.dd)) }) it('should include trace_id and span_id when a span is active', () => { diff --git a/packages/dd-trace/test/plugins/outbound.spec.js b/packages/dd-trace/test/plugins/outbound.spec.js index a19332feae4..d726e387ee3 100644 --- a/packages/dd-trace/test/plugins/outbound.spec.js +++ b/packages/dd-trace/test/plugins/outbound.spec.js @@ -209,7 +209,7 @@ describe('OuboundPlugin', () => { assert.strictEqual(args.length, 1) const tags = parseTags(args[0]) - assertObjectContains(tags, { '_dd.code_origin.type': 'exit' }) + assertObjectContains(tags, { _dd: { code_origin: { type: 'exit' } } }) assert.ok(Array.isArray(tags._dd.code_origin.frames)) assert.ok(tags._dd.code_origin.frames.length > 0) diff --git a/packages/dd-trace/test/plugins/util/llm.spec.js b/packages/dd-trace/test/plugins/util/llm.spec.js index eb71dbb3817..13ab2846e9d 100644 --- a/packages/dd-trace/test/plugins/util/llm.spec.js +++ b/packages/dd-trace/test/plugins/util/llm.spec.js @@ -56,11 +56,18 @@ describe('llm utils', () => { describe('with sampling rate 0.6', () => { it('should not sample prompt completion', () => { - assert.strictEqual(utils.isPromptCompletionSampled(new SpanContext({ traceId: id('8081965455359722133', 10) })), false) + assert.strictEqual( + utils.isPromptCompletionSampled(new SpanContext({ traceId: id('8081965455359722133', 10) })), + false, + 'should not sample prompt completion' + ) }) it('should sample prompt completion', () => { - assert.strictEqual(utils.isPromptCompletionSampled(new SpanContext({ traceId: id('5533085789307409170', 10) })), true) + assert.strictEqual( + utils.isPromptCompletionSampled(new SpanContext({ traceId: id('5533085789307409170', 10) })), true, + 'should sample prompt completion' + ) }) }) }) diff --git a/packages/dd-trace/test/plugins/util/test-environment.spec.js b/packages/dd-trace/test/plugins/util/test-environment.spec.js index c752c21be97..234131c8a1a 100644 --- a/packages/dd-trace/test/plugins/util/test-environment.spec.js +++ b/packages/dd-trace/test/plugins/util/test-environment.spec.js @@ -97,14 +97,16 @@ describe('test environment data', () => { ...restOfExpectedTags } = expectedSpanTags - assertObjectContains(restOfTags, restOfExpectedTags) - // `CI_ENV_VARS` key contains a dictionary, so we do a `eql` comparison + const msg = testCaseName ?? `${testCaseName} Failed` + + assertObjectContains(restOfTags, restOfExpectedTags, msg) + // `CI_ENV_VARS` key contains a dictionary if (envVars && expectedEnvVars) { - assert.deepStrictEqual(JSON.parse(envVars), JSON.parse(expectedEnvVars)) + assert.deepStrictEqual(JSON.parse(envVars), JSON.parse(expectedEnvVars), msg) } - // `CI_NODE_LABELS` key contains an array, so we do a `to.have.same.members` comparison + // `CI_NODE_LABELS` key contains an array if (nodeLabels && expectedNodeLabels) { - assertObjectContains(JSON.parse(nodeLabels), JSON.parse(expectedNodeLabels)) + assertObjectContains(JSON.parse(nodeLabels).sort(), JSON.parse(expectedNodeLabels).sort(), msg) } }) }) diff --git a/packages/dd-trace/test/plugins/util/web.spec.js b/packages/dd-trace/test/plugins/util/web.spec.js index dc65aa98dba..f0195d7817e 100644 --- a/packages/dd-trace/test/plugins/util/web.spec.js +++ b/packages/dd-trace/test/plugins/util/web.spec.js @@ -243,7 +243,7 @@ describe('plugins/util/web', () => { res.end() - assert.ok(!Object.hasOwn(tags, HTTP_CLIENT_IP)) + assert.ok(!(HTTP_CLIENT_IP in tags)) }) }) @@ -258,7 +258,7 @@ describe('plugins/util/web', () => { res.end() - assert.ok(!Object.hasOwn(tags, HTTP_CLIENT_IP)) + assert.ok(!(HTTP_CLIENT_IP in tags)) }) }) @@ -288,7 +288,7 @@ describe('plugins/util/web', () => { res.end() - assert.ok(!Object.hasOwn(tags, HTTP_CLIENT_IP)) + assert.ok(!(HTTP_CLIENT_IP in tags)) }) }) @@ -684,7 +684,7 @@ describe('plugins/util/web', () => { res.end() assert.strictEqual(tags[RESOURCE_NAME], 'GET') - assert.ok(!Object.hasOwn(tags, HTTP_ROUTE)) + assert.ok(!(HTTP_ROUTE in tags)) }) }) @@ -866,7 +866,7 @@ describe('plugins/util/web', () => { web.addStatusError(req, 500) - assert.ok(!Object.hasOwn(tags, ERROR)) + assert.ok(!(ERROR in tags)) }) }) diff --git a/packages/dd-trace/test/priority_sampler.spec.js b/packages/dd-trace/test/priority_sampler.spec.js index 6add282d70e..bb80dce4e6a 100644 --- a/packages/dd-trace/test/priority_sampler.spec.js +++ b/packages/dd-trace/test/priority_sampler.spec.js @@ -248,7 +248,8 @@ describe('PrioritySampler', () => { } }) - expect(prioritySampler.sample(context)).to.not.throw + // Should not throw + prioritySampler.sample(context) assert.strictEqual(context._sampling.priority, USER_REJECT) }) @@ -257,7 +258,8 @@ describe('PrioritySampler', () => { rules: 5 }) - expect(prioritySampler.sample(context)).to.not.throw + // Should not throw + prioritySampler.sample(context) assert.strictEqual(context._sampling.priority, AUTO_KEEP) }) @@ -355,7 +357,7 @@ describe('PrioritySampler', () => { prioritySampler.sample(span) assert.strictEqual(context._trace['_dd.rule_psr'], 0) - assert.ok(!Object.hasOwn(context._trace, '_dd.limit_psr')) + assert.ok(!('_dd.limit_psr' in context._trace)) }) it('should add metrics for rate limiter sample rate', () => { diff --git a/packages/dd-trace/test/remote_config/manager.spec.js b/packages/dd-trace/test/remote_config/manager.spec.js index 1daf60eed7b..6b94cec5dd3 100644 --- a/packages/dd-trace/test/remote_config/manager.spec.js +++ b/packages/dd-trace/test/remote_config/manager.spec.js @@ -695,7 +695,7 @@ describe('RemoteConfigManager', () => { rc.dispatch([rc.appliedConfigs.get('datadog/42/ASM_FEATURES/confId/config')], 'unapply') sinon.assert.calledOnceWithExactly(handler, 'unapply', { asm: { enabled: true } }, 'asm_data') - assert.strictEqual(rc.appliedConfigs.length, 0) + assert.strictEqual(rc.appliedConfigs.size, 0) }) }) }) diff --git a/packages/dd-trace/test/span_format.spec.js b/packages/dd-trace/test/span_format.spec.js index ae31580bf8b..b2badbfee9a 100644 --- a/packages/dd-trace/test/span_format.spec.js +++ b/packages/dd-trace/test/span_format.spec.js @@ -206,7 +206,9 @@ describe('spanFormat', () => { trace = spanFormat(span) - assert.ok(!(([SAMPLING_AGENT_DECISION, SAMPLING_LIMIT_DECISION, SAMPLING_RULE_DECISION]).some(k => Object.hasOwn(trace.metrics, k)))) + assert.ok( + !([SAMPLING_AGENT_DECISION, SAMPLING_LIMIT_DECISION, SAMPLING_RULE_DECISION] + .some(k => Object.hasOwn(trace.metrics, k)))) }) it('should always add single span ingestion tags from options if present', () => { @@ -226,7 +228,9 @@ describe('spanFormat', () => { it('should not add single span ingestion tags if options not present', () => { trace = spanFormat(span) - assert.ok(!(([SPAN_SAMPLING_MECHANISM, SPAN_SAMPLING_MAX_PER_SECOND, SPAN_SAMPLING_RULE_RATE]).some(k => Object.hasOwn(trace.metrics, k)))) + assert.ok( + !([SPAN_SAMPLING_MECHANISM, SPAN_SAMPLING_MAX_PER_SECOND, SPAN_SAMPLING_RULE_RATE] + .some(k => Object.hasOwn(trace.metrics, k)))) }) it('should format span links', () => { @@ -384,7 +388,7 @@ describe('spanFormat', () => { trace = spanFormat(span) - assert.ok(!Object.hasOwn(trace.metrics, 'metric')) + assert.ok(!('metric' in trace.metrics)) }) it('should ignore metrics that are not a number', () => { @@ -392,7 +396,7 @@ describe('spanFormat', () => { trace = spanFormat(span) - assert.ok(!Object.hasOwn(trace.metrics, 'metric')) + assert.ok(!('metric' in trace.metrics)) }) it('should extract errors', () => { @@ -415,8 +419,8 @@ describe('spanFormat', () => { trace = spanFormat(span) assert.strictEqual(trace.meta[ERROR_MESSAGE], error.message) - assert.ok(!Object.hasOwn(trace.meta, ERROR_TYPE)) - assert.ok(!Object.hasOwn(trace.meta, ERROR_STACK)) + assert.ok(!(ERROR_TYPE in trace.meta)) + assert.ok(!(ERROR_STACK in trace.meta)) }) it('should extract the origin', () => { @@ -519,8 +523,8 @@ describe('spanFormat', () => { assert.strictEqual(trace.name, 'null') assert.strictEqual(trace.resource, 'null') - assert.ok(!Object.hasOwn(trace.meta, 'foo.bar')) - assert.ok(!Object.hasOwn(trace.meta, 'baz.qux')) + assert.ok(!('foo.bar' in trace.meta)) + assert.ok(!('baz.qux' in trace.meta)) assert.strictEqual(typeof trace.start, 'number') assert.strictEqual(typeof trace.duration, 'number') }) @@ -570,12 +574,12 @@ describe('spanFormat', () => { it('should not measure internal spans', () => { spanContext._tags['span.kind'] = 'internal' trace = spanFormat(span) - assert.ok(!Object.hasOwn(trace.metrics, MEASURED)) + assert.ok(!(MEASURED in trace.metrics)) }) it('should not measure unknown spans', () => { trace = spanFormat(span) - assert.ok(!Object.hasOwn(trace.metrics, MEASURED)) + assert.ok(!(MEASURED in trace.metrics)) }) it('should measure non-internal spans', () => { diff --git a/packages/dd-trace/test/span_processor.spec.js b/packages/dd-trace/test/span_processor.spec.js index cda79fcd4a1..994daea461a 100644 --- a/packages/dd-trace/test/span_processor.spec.js +++ b/packages/dd-trace/test/span_processor.spec.js @@ -200,15 +200,15 @@ describe('SpanProcessor', () => { tags.split(',').forEach(tag => { const [key, value] = tag.split(':') if (key !== 'entrypoint.basedir') return - expect(value).to.equal('test') + assert.strictEqual(value, 'test') foundATag = true }) - expect(foundATag).to.be.true + assert.ok(foundATag) } - expect(spanFormat.getCall(0)).to.have.been.calledWith(finishedSpan, true, processor._processTags) - expect(spanFormat.getCall(1)).to.have.been.calledWith(finishedSpan, false, processor._processTags) - expect(spanFormat.getCall(2)).to.have.been.calledWith(finishedSpan, false, processor._processTags) - expect(spanFormat.getCall(3)).to.have.been.calledWith(finishedSpan, false, processor._processTags) + sinon.assert.calledWith(spanFormat.getCall(0), finishedSpan, true, processor._processTags) + sinon.assert.calledWith(spanFormat.getCall(1), finishedSpan, false, processor._processTags) + sinon.assert.calledWith(spanFormat.getCall(2), finishedSpan, false, processor._processTags) + sinon.assert.calledWith(spanFormat.getCall(3), finishedSpan, false, processor._processTags) }) }) diff --git a/packages/dd-trace/test/standalone/index.spec.js b/packages/dd-trace/test/standalone/index.spec.js index 3198317d3bb..b4d610828a4 100644 --- a/packages/dd-trace/test/standalone/index.spec.js +++ b/packages/dd-trace/test/standalone/index.spec.js @@ -133,7 +133,7 @@ describe('Disabled APM Tracing or Standalone', () => { operationName: 'operation' }) - assert.ok(!Object.hasOwn(span.context()._tags, APM_TRACING_ENABLED_KEY)) + assert.ok(!(APM_TRACING_ENABLED_KEY in span.context()._tags)) }) it('should add _dd.apm.enabled tag when standalone is enabled', () => { @@ -160,7 +160,7 @@ describe('Disabled APM Tracing or Standalone', () => { parent }) - assert.ok(!Object.hasOwn(child.context()._tags, APM_TRACING_ENABLED_KEY)) + assert.ok(!(APM_TRACING_ENABLED_KEY in child.context()._tags)) }) it('should add _dd.apm.enabled tag in child spans with remote parent', () => { @@ -280,12 +280,12 @@ describe('Disabled APM Tracing or Standalone', () => { const propagator = new TextMapPropagator(config) propagator.inject(span._spanContext, carrier) - assert.ok(!Object.hasOwn(carrier, 'x-datadog-trace-id')) - assert.ok(!Object.hasOwn(carrier, 'x-datadog-parent-id')) - assert.ok(!Object.hasOwn(carrier, 'x-datadog-sampling-priority')) + assert.ok(!('x-datadog-trace-id' in carrier)) + assert.ok(!('x-datadog-parent-id' in carrier)) + assert.ok(!('x-datadog-sampling-priority' in carrier)) - assert.ok(!Object.hasOwn(carrier, 'x-b3-traceid')) - assert.ok(!Object.hasOwn(carrier, 'x-b3-spanid')) + assert.ok(!('x-b3-traceid' in carrier)) + assert.ok(!('x-b3-spanid' in carrier)) }) it('should keep priority if apm tracing is disabled and there is an appsec event', () => { @@ -359,7 +359,7 @@ describe('Disabled APM Tracing or Standalone', () => { propagator.inject(span._spanContext, carrier) assert.strictEqual(carrier.tracestate, 'other=id:0xC0FFEE') - assert.ok(!Object.hasOwn(carrier, 'traceparent')) + assert.ok(!('traceparent' in carrier)) }) }) }) diff --git a/packages/dd-trace/test/standalone/tracesource.spec.js b/packages/dd-trace/test/standalone/tracesource.spec.js index 8132f23ca66..35228a9af66 100644 --- a/packages/dd-trace/test/standalone/tracesource.spec.js +++ b/packages/dd-trace/test/standalone/tracesource.spec.js @@ -18,7 +18,7 @@ describe('Disabled APM Tracing or Standalone - Tracesource propagation tag', () describe('addTraceSourceTag', () => { it('should not fail', () => { - assert.ok(!Object.hasOwn(addTraceSourceTag(tags), TRACE_SOURCE_PROPAGATION_KEY)) + assert.ok(!(TRACE_SOURCE_PROPAGATION_KEY in addTraceSourceTag(tags))) }) it('should not modify original tag value', () => { diff --git a/packages/dd-trace/test/tagger.spec.js b/packages/dd-trace/test/tagger.spec.js index 2db165a43e3..50a2de4d042 100644 --- a/packages/dd-trace/test/tagger.spec.js +++ b/packages/dd-trace/test/tagger.spec.js @@ -31,28 +31,28 @@ describe('tagger', () => { assert.strictEqual(carrier.baz, 'qux:quxx') assert.strictEqual(carrier.def, '') assert.strictEqual(carrier.abc, '') - assert.ok(!Object.hasOwn(carrier, '')) + assert.ok(!('' in carrier)) assert.strictEqual(carrier.valid, '') tagger.add(carrier, ':') - assert.ok(!Object.hasOwn(carrier, '')) + assert.ok(!('' in carrier)) }) it('should not add empty tags', () => { tagger.add(carrier, ' ') - assert.ok(!Object.hasOwn(carrier, '')) + assert.ok(!('' in carrier)) tagger.add(carrier, 'a:true,\t') assert.strictEqual(carrier.a, 'true') - assert.ok(!Object.hasOwn(carrier, '')) + assert.ok(!('' in carrier)) tagger.add(carrier, 'a:true,') assert.strictEqual(carrier.a, 'true') - assert.ok(!Object.hasOwn(carrier, '')) + assert.ok(!('' in carrier)) }) it('should add tags as an array', () => { @@ -88,7 +88,7 @@ describe('tagger', () => { assert.strictEqual(carrier[ERROR_MESSAGE], 'foo') assert.strictEqual(carrier[ERROR_STACK], 'foo') assert.strictEqual(carrier.doNotSetTraceError, true) - assert.ok(!Object.hasOwn(carrier, 'setTraceError')) + assert.ok(!('setTraceError' in carrier)) tagger.add(carrier, { [ERROR_TYPE]: 'foo', @@ -99,6 +99,6 @@ describe('tagger', () => { assert.strictEqual(carrier[ERROR_TYPE], 'foo') assert.strictEqual(carrier[ERROR_MESSAGE], 'foo') assert.strictEqual(carrier[ERROR_STACK], 'foo') - assert.ok(!Object.hasOwn(carrier, 'setTraceError')) + assert.ok(!('setTraceError' in carrier)) }) }) diff --git a/packages/dd-trace/test/telemetry/endpoints.spec.js b/packages/dd-trace/test/telemetry/endpoints.spec.js index 2cfa805e313..2fdaa8f1bf0 100644 --- a/packages/dd-trace/test/telemetry/endpoints.spec.js +++ b/packages/dd-trace/test/telemetry/endpoints.spec.js @@ -167,8 +167,7 @@ describe('endpoints telemetry', () => { sinon.assert.calledOnce(sendData) const payload = sendData.firstCall.args[4] const resources = payload.endpoints.map(e => e.resource_name) - assertObjectContains(resources, 'GET /test') - assertObjectContains(resources, 'HEAD /test') + assert.deepStrictEqual(resources, ['GET /test', 'HEAD /test']) }) it('should record express wildcard and ignore subsequent specific methods for same path', () => { @@ -192,8 +191,7 @@ describe('endpoints telemetry', () => { sinon.assert.calledOnce(sendData) const payload = sendData.firstCall.args[4] const resources = payload.endpoints.map(e => e.resource_name) - assertObjectContains(resources, 'GET /router-test') - assertObjectContains(resources, 'HEAD /router-test') + assert.deepStrictEqual(resources, ['GET /router-test', 'HEAD /router-test']) }) describe('on failed request', () => { diff --git a/packages/dd-trace/test/telemetry/index.spec.js b/packages/dd-trace/test/telemetry/index.spec.js index dfd3222d5e8..c495e1aaf31 100644 --- a/packages/dd-trace/test/telemetry/index.spec.js +++ b/packages/dd-trace/test/telemetry/index.spec.js @@ -2,8 +2,6 @@ const assert = require('node:assert/strict') -const { expect } = require('chai') - const { assertObjectContains } = require('../../../../integration-tests/helpers') const { describe, it, beforeEach, afterEach, before, after } = require('tap').mocha const sinon = require('sinon') @@ -215,7 +213,7 @@ describe('telemetry', () => { telemetry.stop() const server = http.createServer(() => { - expect.fail('server should not be called') + assert.fail('server should not be called') }).listen(0, () => { telemetry.start({ telemetry: { enabled: false, heartbeatInterval: 60000 }, @@ -859,12 +857,13 @@ describe('Telemetry retry', () => { // Skip forward a day clock.tick(86400000) assert.strictEqual(extendedHeartbeatRequest, 'app-extended-heartbeat') - expect(extendedHeartbeatPayload).to.haveOwnProperty('integrations') - assertObjectContains(extendedHeartbeatPayload.integrations, { - integrations: [ - { name: 'foo2', enabled: true, auto_enabled: true }, - { name: 'bar2', enabled: false, auto_enabled: true } - ] + assertObjectContains(extendedHeartbeatPayload, { + integrations: [{ + integrations: [ + { name: 'foo2', enabled: true, auto_enabled: true }, + { name: 'bar2', enabled: false, auto_enabled: true } + ] + }] }) }) }) diff --git a/packages/dd-trace/test/tracer.spec.js b/packages/dd-trace/test/tracer.spec.js index c14d7b9afcc..77af3fe79f9 100644 --- a/packages/dd-trace/test/tracer.spec.js +++ b/packages/dd-trace/test/tracer.spec.js @@ -91,14 +91,14 @@ describe('Tracer', () => { tracer.trace('name', {}, () => {}) const trace = tracer._exporter.export.getCall(0).args[0][0] assert.strictEqual(trace[EXPORT_SERVICE_NAME], 'service') - assert.ok(!Object.hasOwn(trace.meta, BASE_SERVICE)) + assert.ok(!(BASE_SERVICE in trace.meta)) }) it('should not be set when tracer.trace service matched configured service', () => { tracer.trace('name', { service: 'service' }, () => {}) const trace = tracer._exporter.export.getCall(0).args[0][0] assert.strictEqual(trace[EXPORT_SERVICE_NAME], 'service') - assert.ok(!Object.hasOwn(trace.meta, BASE_SERVICE)) + assert.ok(!(BASE_SERVICE in trace.meta)) }) }) diff --git a/scripts/codemods/chai-to-assert.js b/scripts/codemods/chai-to-assert.js index 3ddbd807994..40ca89fb2b2 100644 --- a/scripts/codemods/chai-to-assert.js +++ b/scripts/codemods/chai-to-assert.js @@ -22,7 +22,10 @@ function read (file) { return fs.readFileSync(file, 'utf8') } -/** @param {string} file @param {string} content */ +/** + * @param {string} file + * @param {string} content + */ function write (file, content) { fs.writeFileSync(file, content) }