diff --git a/.eslintignore b/.eslintignore index 09b31fe73..c6588fc18 100644 --- a/.eslintignore +++ b/.eslintignore @@ -1,5 +1,6 @@ **/node_modules -src/**/doc/* build/ docs/ protos/ +test/fixtures +src/plugins/types diff --git a/.eslintrc.yml b/.eslintrc.yml deleted file mode 100644 index 73eeec276..000000000 --- a/.eslintrc.yml +++ /dev/null @@ -1,15 +0,0 @@ ---- -extends: - - 'eslint:recommended' - - 'plugin:node/recommended' - - prettier -plugins: - - node - - prettier -rules: - prettier/prettier: error - block-scoped-var: error - eqeqeq: error - no-warning-comments: warn - no-var: error - prefer-const: error diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index 716c72273..afff7c23d 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -9,7 +9,7 @@ jobs: runs-on: ubuntu-latest strategy: matrix: - node: [8, 10, 12, 13] + node: [10, 12, 13] # Docker containers to run for database RPC tracing integration tests. services: mongo: diff --git a/.prettierignore b/.prettierignore index f6fac98b0..c6588fc18 100644 --- a/.prettierignore +++ b/.prettierignore @@ -1,3 +1,6 @@ -node_modules/* -samples/node_modules/* -src/**/doc/* +**/node_modules +build/ +docs/ +protos/ +test/fixtures +src/plugins/types diff --git a/.prettierrc b/.prettierrc deleted file mode 100644 index df6eac074..000000000 --- a/.prettierrc +++ /dev/null @@ -1,8 +0,0 @@ ---- -bracketSpacing: false -printWidth: 80 -semi: true -singleQuote: true -tabWidth: 2 -trailingComma: es5 -useTabs: false diff --git a/AUTHORS b/AUTHORS deleted file mode 100644 index 77f24a3e8..000000000 --- a/AUTHORS +++ /dev/null @@ -1,17 +0,0 @@ -# Authors ordered by first contribution. - -Ali Ijaz Sheikh -Matt Loring -Jon Wayne Parrott -Brad Abrams -Michael Diarmid -Justin Beckwith -misterpoe -Jerry Jalava -Zach Bjornson -June Rhodes -Michael Prentice -Kelvin Jin -Steren -Dominic Kramer -Adri Van Houdt diff --git a/appveyor.yml b/appveyor.yml deleted file mode 100644 index 22c5e2f0d..000000000 --- a/appveyor.yml +++ /dev/null @@ -1,36 +0,0 @@ -# Test against this version of Node.js -environment: - matrix: - # node.js - - nodejs_version: "6" - - nodejs_version: "8" - - nodejs_version: "10" - -cache: - - src/plugins/types -> src/plugins/types/index.d.ts - - node_modules -> package-lock.json, package.json - -# Install scripts. (runs after repo cloning) -install: - # Get the latest stable version of Node.js or io.js - - ps: Install-Product node $env:nodejs_version - - SET GCLOUD_PROJECT=0 - - SET TRACE_TEST_EXCLUDE_INTEGRATION=1 - -# Post-install test scripts. -test_script: - # install modules - - npm install - # check code style and linting - - npm run check - # compile the code - - npm run compile - # check that installing this module is OK - - npm run check-install - # initialize test fixtures - - npm run init-test-fixtures - # run tests - - npm run unit-test - -# Don't actually build using MSBuild -build: off diff --git a/codecov.yml b/codecov.yml deleted file mode 100644 index 56a4b3e1e..000000000 --- a/codecov.yml +++ /dev/null @@ -1,2 +0,0 @@ -fixes: - - "root/project::" diff --git a/package.json b/package.json index 1c07ab3ef..06e25df6f 100644 --- a/package.json +++ b/package.json @@ -7,7 +7,7 @@ "repository": "googleapis/cloud-trace-nodejs", "scripts": { "init-test-fixtures": "npm run script init-test-fixtures", - "test": "npm run script npm-check npm-compile npm-init-test-fixtures npm-unit-test npm-license-check", + "test": "npm run script npm-compile npm-init-test-fixtures npm-unit-test npm-license-check", "unit-test": "npm run script run-unit-tests", "non-interference": "npm run script test-non-interference", "presystem-test": "npm run compile", @@ -15,7 +15,6 @@ "check-install": "npm run script check-install", "get-plugin-types": "npm run script get-plugin-types", "coverage": "npm run script run-unit-tests-with-coverage report-coverage", - "check": "gts check", "lint": "gts check", "clean": "rimraf build/src", "compile-all": "npm run script compile-auto", @@ -51,7 +50,7 @@ "author": "Google Inc.", "license": "Apache-2.0", "engines": { - "node": ">=8.10.0" + "node": ">=10" }, "devDependencies": { "@compodoc/compodoc": "1.1.11", @@ -85,7 +84,7 @@ "gaxios": "^3.0.2", "glob": "^7.0.3", "grpc": "1.24.2", - "gts": "^1.0.0", + "gts": "^2.0.0", "js-green-licenses": "^1.0.0", "linkinator": "^2.0.0", "mocha": "^7.0.0", @@ -108,6 +107,7 @@ "continuation-local-storage": "^3.2.1", "extend": "^3.0.2", "gcp-metadata": "^4.0.0", + "google-auth-library": "^6.0.0", "hex2dec": "^1.0.1", "is": "^3.2.0", "methods": "^1.1.1", diff --git a/samples/app.js b/samples/app.js index abb032c94..810e81b44 100644 --- a/samples/app.js +++ b/samples/app.js @@ -31,18 +31,12 @@ const DISCOVERY_URL = 'https://www.googleapis.com/discovery/v1/apis'; app.get('/', async (req, res) => { // This outgoing HTTP request should be captured by Trace try { - const { body } = await got(DISCOVERY_URL, { json: true }); - const names = body.items.map((item) => item.name); - res - .status(200) - .send(names.join('\n')) - .end(); - } - catch (err) { + const {body} = await got(DISCOVERY_URL, {json: true}); + const names = body.items.map(item => item.name); + res.status(200).send(names.join('\n')).end(); + } catch (err) { console.error(err); - res - .status(500) - .end(); + res.status(500).end(); } }); diff --git a/samples/package.json b/samples/package.json index 9cb57ea2f..8087ec91d 100644 --- a/samples/package.json +++ b/samples/package.json @@ -9,8 +9,11 @@ "type": "git", "url": "https://github.com/googleapis/cloud-trace-nodejs.git" }, + "files": [ + "*.js" + ], "engines": { - "node": ">=8" + "node": ">=10" }, "scripts": { "deploy": "gcloud app deploy", diff --git a/samples/snippets.js b/samples/snippets.js index d8df69d79..d3966cf1c 100644 --- a/samples/snippets.js +++ b/samples/snippets.js @@ -17,6 +17,6 @@ // [START trace_setup_nodejs_explicit] require('@google-cloud/trace-agent').start({ projectId: 'your-project-id', - keyFilename: '/path/to/key.json' + keyFilename: '/path/to/key.json', }); // [END trace_setup_nodejs_explicit] diff --git a/samples/test/test.js b/samples/test/test.js index 5bab55156..95ed91db2 100644 --- a/samples/test/test.js +++ b/samples/test/test.js @@ -15,16 +15,16 @@ 'use strict'; const execa = require('execa'); +const {describe, it} = require('mocha'); describe('trace samples', () => { - it('should run the quickstart', done => { // select a random port between 49152 and 65535 - const PORT = Math.floor((Math.random() * (65535-49152))) + 49152; + const PORT = Math.floor(Math.random() * (65535 - 49152)) + 49152; const proc = execa('node', ['app.js'], { env: { - PORT - } + PORT, + }, }); proc.stdout.on('data', message => { // Listen to stdout and look for messages. If we get a `Press CTRL+...` @@ -37,11 +37,10 @@ describe('trace samples', () => { done(); }, 1000); } - }) + }); proc.stderr.on('data', message => { // if anything comes through stderr, assume a bug done(new Error(message.toString('utf8'))); }); }); - }); diff --git a/scripts/check-install.ts b/scripts/check-install.ts index 2d82b0509..00f8bc778 100644 --- a/scripts/check-install.ts +++ b/scripts/check-install.ts @@ -1,6 +1,20 @@ +// Copyright 2017 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + import * as cpy from 'cpy'; import * as path from 'path'; -import { globP, spawnP, tmpDirP } from './utils'; +import {globP, spawnP, tmpDirP} from './utils'; /** * Get the major version number of the current Node process. @@ -25,31 +39,45 @@ export async function checkInstall() { // in your current working directory. const tgz = await globP(`${process.cwd()}/*.tgz`); if (tgz.length !== 1) { - throw new Error(`Expected 1 tgz file in current directory, but found ${tgz.length}`); + throw new Error( + `Expected 1 tgz file in current directory, but found ${tgz.length}` + ); } // Initialize a new npm package.json in the temp directory. await spawnP('npm', ['init', '-y'], { - cwd: installDir + cwd: installDir, }); // Install the tgz file as a package, along with necessities. // @types/node version should match the current process version, but clamped // at >=9 (because of http2 types) and <11 (because Node 11 doesn't yet have // type definitions). const nodeTypesVersion = Math.min(Math.max(getNodeMajorVersion(), 9), 10); - await spawnP('npm', ['install', 'typescript', `@types/node@${nodeTypesVersion}`, tgz[0]], { - cwd: installDir - }); + await spawnP( + 'npm', + ['install', 'typescript', `@types/node@${nodeTypesVersion}`, tgz[0]], + { + cwd: installDir, + } + ); // Create an entry point for the package created in the temp directory // use-module.ts is a fixture that imports the Trace Agent - await cpy('./test/fixtures/use-module.ts', installDir, { rename: 'index.ts' }); + await cpy('./test/fixtures/use-module.ts', installDir, {rename: 'index.ts'}); // Compile it - await spawnP(`node_modules${path.sep}.bin${path.sep}tsc`, ['index.ts', '--lib', 'es2015'], { - cwd: installDir - }); + await spawnP( + `node_modules${path.sep}.bin${path.sep}tsc`, + ['index.ts', '--lib', 'es2015'], + { + cwd: installDir, + } + ); console.log('`npm install` + `tsc` test was successful.'); // Evaluate require('..').start() in Node. - await spawnP(`node`, ['-e', `"require('@google-cloud/trace-agent').start()"`], { - cwd: installDir - }); + await spawnP( + 'node', + ['-e', '"require(\'@google-cloud/trace-agent\').start()"'], + { + cwd: installDir, + } + ); console.log('require + start test was successful.'); } diff --git a/scripts/compile.ts b/scripts/compile.ts index 6df3b8550..4645656f8 100644 --- a/scripts/compile.ts +++ b/scripts/compile.ts @@ -1,6 +1,18 @@ -import * as path from 'path'; -import { forkP } from './utils'; -import * as ts from 'typescript'; +// Copyright 2017 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import {forkP} from './utils'; import * as semver from 'semver'; export interface CompileOptions { @@ -9,14 +21,16 @@ export interface CompileOptions { } export async function compile(options: CompileOptions) { - let { strict, languageLevel } = options; + let {languageLevel} = options; if (languageLevel === 'auto') { - languageLevel = semver.satisfies(process.version, '>=7.5') ? 'es2017' : 'es2015'; + languageLevel = semver.satisfies(process.version, '>=7.5') + ? 'es2017' + : 'es2015'; } - await forkP(`node_modules/typescript/lib/tsc`, [ + await forkP('node_modules/typescript/lib/tsc', [ '-p', - strict ? '.' : './tsconfig.full.json', + options.strict ? '.' : './tsconfig.full.json', '--target', - languageLevel + languageLevel, ]); } diff --git a/scripts/credentials.ts b/scripts/credentials.ts index 3bf597ef3..44b7b2fc8 100644 --- a/scripts/credentials.ts +++ b/scripts/credentials.ts @@ -1,5 +1,19 @@ -import { createCipheriv, createDecipheriv, randomBytes } from 'crypto'; -import { createReadStream, createWriteStream } from 'fs'; +// Copyright 2017 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import {createCipheriv, createDecipheriv, randomBytes} from 'crypto'; +import {createReadStream, createWriteStream} from 'fs'; export interface KeyAndIV { key: string; @@ -28,10 +42,13 @@ export async function encryptCredentials(filename: string): Promise { .on('error', reject) .on('finish', resolve); }); - return { key, iv }; + return {key, iv}; } -export async function decryptCredentials({ key, iv }: KeyAndIV, filename: string) { +export async function decryptCredentials( + {key, iv}: KeyAndIV, + filename: string +) { const decipher = createDecipheriv( 'aes-256-cbc', Buffer.from(key, 'hex'), diff --git a/scripts/get-plugin-types.ts b/scripts/get-plugin-types.ts index db68ed399..c8afbdb31 100644 --- a/scripts/get-plugin-types.ts +++ b/scripts/get-plugin-types.ts @@ -1,4 +1,18 @@ -import { mkdirP, readFileP, spawnP, writeFileP } from './utils'; +// Copyright 2017 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import {mkdirP, readFileP, spawnP, writeFileP} from './utils'; const TYPES_DIRECTORY = 'src/plugins/types'; @@ -17,10 +31,14 @@ async function mkdirSafeP(dir: string) { export async function getPluginTypes() { await mkdirSafeP(TYPES_DIRECTORY); - const indexTs = (await readFileP(`${TYPES_DIRECTORY}/index.d.ts`, 'utf8') as string) - .split('\n'); + const indexTs = ((await readFileP( + `${TYPES_DIRECTORY}/index.d.ts`, + 'utf8' + )) as string).split('\n'); for (const line of indexTs) { - const matches = line.match(/^import \* as .* from '\.\/(.+)';\s*\/\/\s*(.+)@(.+)/); + const matches = line.match( + /^import \* as .* from '\.\/(.+)';\s*\/\/\s*(.+)@(.+)/ + ); if (!matches) { continue; } @@ -28,13 +46,16 @@ export async function getPluginTypes() { const installDir = `${TYPES_DIRECTORY}/${packageName}`; if (await mkdirSafeP(installDir)) { await spawnP('npm', ['init', '-y'], { - cwd: installDir + cwd: installDir, }); await spawnP('npm', ['install', `@types/${name}@${version}`], { - cwd: installDir + cwd: installDir, }); - await writeFileP(`${installDir}/index.ts`, - `import * as _ from '${name}'; export = _;\n`, 'utf8'); + await writeFileP( + `${installDir}/index.ts`, + `import * as _ from '${name}'; export = _;\n`, + 'utf8' + ); } } } diff --git a/scripts/index.ts b/scripts/index.ts index a0fade2cb..ecaa51649 100644 --- a/scripts/index.ts +++ b/scripts/index.ts @@ -1,3 +1,17 @@ +// Copyright 2017 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + /** * The main entry point for cross-platform build scripts. * Usage (in repository root directory): @@ -10,35 +24,37 @@ const [, , ...steps] = process.argv; const { TRACE_TEST_EXCLUDE_INTEGRATION, TRACE_SYSTEM_TEST_ENCRYPTED_CREDENTIALS_KEY, - TRACE_SYSTEM_TEST_ENCRYPTED_CREDENTIALS_IV + TRACE_SYSTEM_TEST_ENCRYPTED_CREDENTIALS_IV, } = process.env; -import { checkInstall } from './check-install'; -import { compile } from './compile'; -import { encryptCredentials, decryptCredentials } from './credentials'; -import { getPluginTypes } from './get-plugin-types'; -import { initTestFixtures } from './init-test-fixtures'; -import { reportCoverage } from './report-coverage'; -import { runTests } from './run-tests'; -import { testNonInterference } from './test-non-interference'; -import { BUILD_DIRECTORY, spawnP } from './utils'; +import {checkInstall} from './check-install'; +import {compile} from './compile'; +import {encryptCredentials, decryptCredentials} from './credentials'; +import {getPluginTypes} from './get-plugin-types'; +import {initTestFixtures} from './init-test-fixtures'; +import {reportCoverage} from './report-coverage'; +import {runTests} from './run-tests'; +import {testNonInterference} from './test-non-interference'; +import {BUILD_DIRECTORY, spawnP} from './utils'; // The identifying components in the service account credentials file path. const projectID = 'long-door-651'; const keyID = 'a179efbeda21'; // Globs to exclude when running unit tests only. -const unitTestExcludeGlobs: string[] = TRACE_TEST_EXCLUDE_INTEGRATION ? [ - `${BUILD_DIRECTORY}/test/plugins/test-*`, - `${BUILD_DIRECTORY}/test/test-agent-stopped.js`, - `${BUILD_DIRECTORY}/test/test-grpc-async-handler.js`, - `${BUILD_DIRECTORY}/test/test-grpc-context.js`, - `${BUILD_DIRECTORY}/test/test-mysql-pool.js`, - `${BUILD_DIRECTORY}/test/test-plugins-*`, - `${BUILD_DIRECTORY}/test/test-trace-hapi-tails.js`, - `${BUILD_DIRECTORY}/test/test-trace-web-frameworks.js`, - `${BUILD_DIRECTORY}/test/test-unpatch.js` -] : []; +const unitTestExcludeGlobs: string[] = TRACE_TEST_EXCLUDE_INTEGRATION + ? [ + `${BUILD_DIRECTORY}/test/plugins/test-*`, + `${BUILD_DIRECTORY}/test/test-agent-stopped.js`, + `${BUILD_DIRECTORY}/test/test-grpc-async-handler.js`, + `${BUILD_DIRECTORY}/test/test-grpc-context.js`, + `${BUILD_DIRECTORY}/test/test-mysql-pool.js`, + `${BUILD_DIRECTORY}/test/test-plugins-*`, + `${BUILD_DIRECTORY}/test/test-trace-hapi-tails.js`, + `${BUILD_DIRECTORY}/test/test-trace-web-frameworks.js`, + `${BUILD_DIRECTORY}/test/test-unpatch.js`, + ] + : []; /** * Sequentially runs a list of commands. @@ -50,40 +66,39 @@ async function run(steps: string[]) { // command, and then short-circuit. if (step.indexOf('npm-') === 0) { const moduleAndArgs = step.split('-'); - await spawnP( - 'npm', - [ - 'run', - moduleAndArgs.slice(1).join('-') - ] - ); + await spawnP('npm', ['run', moduleAndArgs.slice(1).join('-')]); continue; } else if (step.startsWith('compile-')) { const [, languageLevel, strict] = step.split('-'); - await compile({ strict: !!strict, languageLevel }); + await compile({strict: !!strict, languageLevel}); continue; } else { switch (step) { case 'check-install': await checkInstall(); break; - case 'encrypt-service-account-credentials': - const keyAndIV = await encryptCredentials(`${projectID}-${keyID}.json`); - console.log([ - `key: ${keyAndIV.key}`, - `iv: ${keyAndIV.iv}` - ].join('\n')); + case 'encrypt-service-account-credentials': { + const keyAndIV = await encryptCredentials( + `${projectID}-${keyID}.json` + ); + console.log( + [`key: ${keyAndIV.key}`, `iv: ${keyAndIV.iv}`].join('\n') + ); break; - case 'decrypt-service-account-credentials': + } + case 'decrypt-service-account-credentials': { const key = TRACE_SYSTEM_TEST_ENCRYPTED_CREDENTIALS_KEY; const iv = TRACE_SYSTEM_TEST_ENCRYPTED_CREDENTIALS_IV; if (!key || !iv) { - console.log('> Environment insufficient to decrypt service account credentials'); + console.log( + '> Environment insufficient to decrypt service account credentials' + ); break; } - await decryptCredentials({ key, iv }, `${projectID}-${keyID}.json`); + await decryptCredentials({key, iv}, `${projectID}-${keyID}.json`); break; + } case 'get-plugin-types': await getPluginTypes(); break; @@ -94,24 +109,24 @@ async function run(steps: string[]) { await runTests({ includeGlobs: [ `${BUILD_DIRECTORY}/test/test-*.js`, - `${BUILD_DIRECTORY}/test/plugins/test-*.js` + `${BUILD_DIRECTORY}/test/plugins/test-*.js`, ], excludeGlobs: unitTestExcludeGlobs, rootDir: BUILD_DIRECTORY, coverage: false, - timeout: 4000 + timeout: 4000, }); break; case 'run-unit-tests-with-coverage': await runTests({ includeGlobs: [ `${BUILD_DIRECTORY}/test/test-*.js`, - `${BUILD_DIRECTORY}/test/plugins/test-*.js` + `${BUILD_DIRECTORY}/test/plugins/test-*.js`, ], excludeGlobs: unitTestExcludeGlobs, rootDir: BUILD_DIRECTORY, coverage: true, - timeout: 4000 + timeout: 4000, }); break; case 'report-coverage': @@ -128,7 +143,8 @@ async function run(steps: string[]) { } } -run(steps).catch((err) => { +run(steps).catch(err => { console.error(err); + // eslint-disable-next-line no-process-exit process.exit(1); }); diff --git a/scripts/init-test-fixtures.ts b/scripts/init-test-fixtures.ts index 4cae8792d..37a4259e1 100644 --- a/scripts/init-test-fixtures.ts +++ b/scripts/init-test-fixtures.ts @@ -1,7 +1,27 @@ +// Copyright 2017 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + import * as cpy from 'cpy'; -import * as path from 'path'; -import { BUILD_DIRECTORY, statP, spawnP, readFileP, writeFileP, mkdirP } from './utils'; -import { readdir } from 'fs'; +import { + BUILD_DIRECTORY, + statP, + spawnP, + readFileP, + writeFileP, + mkdirP, +} from './utils'; +import {readdir} from 'fs'; import {promisify} from 'util'; import * as semver from 'semver'; @@ -11,19 +31,20 @@ export async function initTestFixtures(installPlugins: boolean) { // Copy fixtures to build directory const fixtureDirectories = ['./test/fixtures']; for (const fixtureDirectory of fixtureDirectories) { - const newLocation = `${BUILD_DIRECTORY}/${path.relative('.', fixtureDirectory)}`; await cpy(`${fixtureDirectory}/**`, BUILD_DIRECTORY, { - parents: true + parents: true, }); - }; + } if (!installPlugins) { return; } // Run `npm install` for package fixtures - const packageFixtures = JSON.parse(await readFileP('./test/fixtures/plugin-fixtures.json', 'utf8') as string); - await mkdirP('./build/test/plugins/fixtures').catch((e: { code?: string }) => { + const packageFixtures = JSON.parse( + (await readFileP('./test/fixtures/plugin-fixtures.json', 'utf8')) as string + ); + await mkdirP('./build/test/plugins/fixtures').catch((e: {code?: string}) => { // it's OK if this directory already exists if (e.code !== 'EEXIST') { throw e; @@ -53,20 +74,36 @@ export async function initTestFixtures(installPlugins: boolean) { * skip install */ const packageFixture = packageFixtures[packageName]; - const supportedNodeVersions = (packageFixture.engines && packageFixture.engines.node) || '*'; + const supportedNodeVersions = + (packageFixture.engines && packageFixture.engines.node) || '*'; if (semver.satisfies(process.version, supportedNodeVersions)) { if (!fixtureExists) { await mkdirP(packageDirectory); - await writeFileP(`${packageDirectory}/package.json`, JSON.stringify(Object.assign({ - name: packageName, - version: '1.0.0', - main: 'index.js' - }, packageFixture), null, 2)); - const mainModule = packageFixture._mainModule || Object.keys(packageFixture.dependencies)[0]; - await writeFileP(`${packageDirectory}/index.js`, `module.exports = require('${mainModule}');\n`); + await writeFileP( + `${packageDirectory}/package.json`, + JSON.stringify( + Object.assign( + { + name: packageName, + version: '1.0.0', + main: 'index.js', + }, + packageFixture + ), + null, + 2 + ) + ); + const mainModule = + packageFixture._mainModule || + Object.keys(packageFixture.dependencies)[0]; + await writeFileP( + `${packageDirectory}/index.js`, + `module.exports = require('${mainModule}');\n` + ); console.log(`npm install in ${packageDirectory}`); await spawnP('npm', ['install', '--reinstall'], { - cwd: packageDirectory + cwd: packageDirectory, }); } else { // Conditionally re-install if gRPC module binary exists but for a different Node version @@ -75,23 +112,43 @@ export async function initTestFixtures(installPlugins: boolean) { try { await statP(extBinDirectory); const files = await readdirP(extBinDirectory); - const modulesVersions = files.map(file => file.match(/^node-v([0-9]+)-/)).filter(x => x).map(matches => matches![1]); - if (!modulesVersions.some(version => version === process.versions.modules)) { + const modulesVersions = files + .map(file => file.match(/^node-v([0-9]+)-/)) + .filter(x => x) + .map(matches => matches![1]); + if ( + !modulesVersions.some( + version => version === process.versions.modules + ) + ) { reinstallGrpc = true; } - } catch {} + } catch { + // 🤷‍♂️ + } if (reinstallGrpc) { - console.log(`Re-installing gRPC in ${packageDirectory} because of stale gRPC binary`); - const grpcPackageJson = JSON.parse(await readFileP(`${packageDirectory}/node_modules/grpc/package.json`, 'utf8') as string); + console.log( + `Re-installing gRPC in ${packageDirectory} because of stale gRPC binary` + ); + const grpcPackageJson = JSON.parse( + (await readFileP( + `${packageDirectory}/node_modules/grpc/package.json`, + 'utf8' + )) as string + ); await spawnP('npm', ['install', `grpc@${grpcPackageJson.version}`], { - cwd: packageDirectory + cwd: packageDirectory, }); } else { - console.log(`Skipping npm install in ${packageDirectory} since node_modules already exists`); + console.log( + `Skipping npm install in ${packageDirectory} since node_modules already exists` + ); } } } else { - console.log(`Skipping npm install in ${packageDirectory} since package not supported in Node ${process.version}`); + console.log( + `Skipping npm install in ${packageDirectory} since package not supported in Node ${process.version}` + ); } - }; + } } diff --git a/scripts/report-coverage.ts b/scripts/report-coverage.ts index f2f34fa14..986230555 100644 --- a/scripts/report-coverage.ts +++ b/scripts/report-coverage.ts @@ -1,8 +1,26 @@ -import { BUILD_DIRECTORY, nodule, forkP } from './utils'; +// Copyright 2017 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import {BUILD_DIRECTORY, nodule, forkP} from './utils'; import * as path from 'path'; export async function reportCoverage() { - await forkP(nodule('.bin/codecov'), [`--root=${path.resolve(BUILD_DIRECTORY, '..')}`], { - cwd: BUILD_DIRECTORY - }); + await forkP( + nodule('.bin/codecov'), + [`--root=${path.resolve(BUILD_DIRECTORY, '..')}`], + { + cwd: BUILD_DIRECTORY, + } + ); } diff --git a/scripts/run-tests.ts b/scripts/run-tests.ts index fb9704ca8..dfbb3fb1e 100644 --- a/scripts/run-tests.ts +++ b/scripts/run-tests.ts @@ -1,57 +1,66 @@ +// Copyright 2017 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + import * as path from 'path'; -import { globP, forkP, BUILD_DIRECTORY } from './utils'; +import {globP, forkP} from './utils'; export interface Options { - includeGlobs: string[], - excludeGlobs?: string[], - rootDir: string, - coverage?: boolean, - timeout?: number + includeGlobs: string[]; + excludeGlobs?: string[]; + rootDir: string; + coverage?: boolean; + timeout?: number; } export async function runTests(options: Options) { - const { includeGlobs, excludeGlobs, rootDir, coverage, timeout } = options; + const {includeGlobs, excludeGlobs, rootDir, coverage, timeout} = options; function nodule(nodule: string) { return path.relative(rootDir, `node_modules/${nodule}`); } let testNum = 0; - const excludedFiles = ([] as string[]) - .concat(...await Promise.all((excludeGlobs || []).map(glob => globP(glob)))); - const includedFiles = ([] as string[]) - .concat(...await Promise.all(includeGlobs.map(glob => globP(glob)))); + const excludedFiles = ([] as string[]).concat( + ...(await Promise.all((excludeGlobs || []).map(glob => globP(glob)))) + ); + const includedFiles = ([] as string[]).concat( + ...(await Promise.all(includeGlobs.map(glob => globP(glob)))) + ); // Take the difference const files = includedFiles.filter(i => excludedFiles.indexOf(i) < 0); for (const file of files) { const moduleAndArgs = [ - ...coverage ? [ - nodule('.bin/nyc'), - '--reporter', - 'lcov', - '--report-dir', - `./.coverage/${testNum++}`, - '--exclude', - 'build/test/fixtures/**', - '--exclude', - 'build/test/plugins/fixtures/**', - '--exclude-after-remap', - 'false', - ] : [], + ...(coverage + ? [ + nodule('.bin/nyc'), + '--reporter', + 'lcov', + '--report-dir', + `./.coverage/${testNum++}`, + '--exclude', + 'build/test/fixtures/**', + '--exclude', + 'build/test/plugins/fixtures/**', + '--exclude-after-remap', + 'false', + ] + : []), nodule('mocha/bin/_mocha'), '--require', 'source-map-support/register', path.relative(rootDir, file), - ...timeout ? [ - '--timeout', - `${timeout}` - ] : [ - '--no-timeouts' - ] + ...(timeout ? ['--timeout', `${timeout}`] : ['--no-timeouts']), ]; - await forkP( - moduleAndArgs[0], - moduleAndArgs.slice(1), - { cwd: rootDir } - ); + await forkP(moduleAndArgs[0], moduleAndArgs.slice(1), {cwd: rootDir}); } } diff --git a/scripts/test-non-interference.ts b/scripts/test-non-interference.ts index 4df90a3f5..e548d0079 100644 --- a/scripts/test-non-interference.ts +++ b/scripts/test-non-interference.ts @@ -1,4 +1,16 @@ -import { forkP, globP } from './utils'; +// Copyright 2017 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. export async function testNonInterference() { // TODO(kjin): Re-enable non-interference tests when we can be sure their diff --git a/scripts/utils.ts b/scripts/utils.ts index c33245258..fddff6137 100644 --- a/scripts/utils.ts +++ b/scripts/utils.ts @@ -1,8 +1,28 @@ -import { mkdir, stat, readFile, writeFile } from 'fs'; +// Copyright 2017 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import {mkdir, stat, readFile, writeFile} from 'fs'; import * as glob from 'glob'; import * as path from 'path'; import {promisify} from 'util'; -import { ChildProcess, ForkOptions, fork, SpawnOptions, spawn } from 'child_process'; +import { + ChildProcess, + ForkOptions, + fork, + SpawnOptions, + spawn, +} from 'child_process'; import * as once from 'once'; import * as tmp from 'tmp'; @@ -32,32 +52,64 @@ export function existsP(path: string): Promise { function promisifyChildProcess(childProcess: ChildProcess): Promise { return new Promise((resolve, reject) => { - const exit = (err?: Error) => once(() => err ? reject(err) : resolve())(); + const exit = (err?: Error) => once(() => (err ? reject(err) : resolve()))(); childProcess.on('error', exit); - childProcess.on('close', (code) => { + childProcess.on('close', code => { if (code === 0) { exit(); } else { - exit(new Error(`Process ${childProcess.pid} exited with code ${code}.`)); + exit( + new Error(`Process ${childProcess.pid} exited with code ${code}.`) + ); } }); }); } -export function spawnP(command: string, args: string[] = [], options: SpawnOptions = {}): Promise { - const stringifiedCommand = `\`${command}${args ? (' ' + args.join(' ')) : ''}\``; +export function spawnP( + command: string, + args: string[] = [], + options: SpawnOptions = {} +): Promise { + const stringifiedCommand = `\`${command}${ + args ? ' ' + args.join(' ') : '' + }\``; console.log(`> Running: ${stringifiedCommand}`); - return promisifyChildProcess(spawn(command, args, Object.assign({ - stdio: 'inherit', - shell: true - }, options))); + return promisifyChildProcess( + spawn( + command, + args, + Object.assign( + { + stdio: 'inherit', + shell: true, + }, + options + ) + ) + ); } -export function forkP(moduleName: string, args: string[] = [], options: ForkOptions = {}): Promise { - const stringifiedCommand = `\`${moduleName}${args ? (' ' + args.join(' ')) : ''}\``; +export function forkP( + moduleName: string, + args: string[] = [], + options: ForkOptions = {} +): Promise { + const stringifiedCommand = `\`${moduleName}${ + args ? ' ' + args.join(' ') : '' + }\``; console.log(`> Running: ${stringifiedCommand}`); - return promisifyChildProcess(fork(moduleName, args, Object.assign({ - stdio: 'inherit', - execArgv: [] - }, options))); + return promisifyChildProcess( + fork( + moduleName, + args, + Object.assign( + { + stdio: 'inherit', + execArgv: [], + }, + options + ) + ) + ); } diff --git a/src/.jshintrc b/src/.jshintrc deleted file mode 100644 index 3d121028c..000000000 --- a/src/.jshintrc +++ /dev/null @@ -1,4 +0,0 @@ -{ - "extends": "../.jshintrc", - "predef": ["-console"] -} \ No newline at end of file diff --git a/src/cls/async-hooks.ts b/src/cls/async-hooks.ts index 89f9d1e28..369ce917e 100644 --- a/src/cls/async-hooks.ts +++ b/src/cls/async-hooks.ts @@ -57,7 +57,7 @@ export class AsyncHooksCLS implements CLS { // Create the hook. this.hook = this.ah.createHook({ - init: (id: number, type: string, triggerId: number, resource: {}) => { + init: (id: number, type: string, triggerId: number) => { // init is called when a new AsyncResource is created. We want code // that runs within the scope of this new AsyncResource to see the same // context as its "parent" AsyncResource. The criteria for the parent @@ -161,11 +161,13 @@ export class AsyncHooksCLS implements CLS { if (!boundContext) { return fn; } + // eslint-disable-next-line @typescript-eslint/no-this-alias const that = this; // Wrap fn so that any AsyncResource objects that are created in fn will // share context with that of the AsyncResource with the given ID. - const contextWrapper: ContextWrapped> = function(this: {}) { + const contextWrapper: ContextWrapped> = function (this: {}) { return that.runWithContext( + // eslint-disable-next-line prefer-rest-params () => fn.apply(this, arguments) as T, boundContext ); @@ -184,11 +186,12 @@ export class AsyncHooksCLS implements CLS { } patchEmitterToPropagateContext(ee: EventEmitter): void { + // eslint-disable-next-line @typescript-eslint/no-this-alias const that = this; EVENT_EMITTER_METHODS.forEach(method => { if (ee[method]) { shimmer.wrap(ee, method, oldMethod => { - return function(this: {}, event: string, cb: Func) { + return function (this: {}, event: string, cb: Func) { return oldMethod.call(this, event, that.bindWithCurrentContext(cb)); }; }); diff --git a/src/cls/base.ts b/src/cls/base.ts index 64dfb7f0a..2f078dcf6 100644 --- a/src/cls/base.ts +++ b/src/cls/base.ts @@ -14,7 +14,7 @@ import {EventEmitter} from 'events'; -// tslint:disable-next-line:no-any +// eslint-disable-next-line @typescript-eslint/no-explicit-any export type Func = (...args: any[]) => T; /** diff --git a/src/cls/null.ts b/src/cls/null.ts index b63e84d0f..a16012761 100644 --- a/src/cls/null.ts +++ b/src/cls/null.ts @@ -49,5 +49,6 @@ export class NullCLS implements CLS { return fn; } + // eslint-disable-next-line @typescript-eslint/no-unused-vars patchEmitterToPropagateContext(ee: EventEmitter): void {} } diff --git a/src/cls/singular.ts b/src/cls/singular.ts index 6fde5dca8..e8611cc0f 100644 --- a/src/cls/singular.ts +++ b/src/cls/singular.ts @@ -55,5 +55,6 @@ export class SingularCLS implements CLS { return fn; } + // eslint-disable-next-line @typescript-eslint/no-unused-vars patchEmitterToPropagateContext(ee: EventEmitter): void {} } diff --git a/src/index.ts b/src/index.ts index 10421d606..60486548d 100644 --- a/src/index.ts +++ b/src/index.ts @@ -17,7 +17,7 @@ const filesLoadedBeforeTrace = Object.keys(require.cache); // This file's top-level imports must not transitively depend on modules that // do I/O, or continuation-local-storage will not work. import * as semver from 'semver'; -import {Config, defaultConfig, TracePolicy} from './config'; +import {Config, defaultConfig} from './config'; import * as extend from 'extend'; import * as path from 'path'; import * as PluginTypes from './plugin-types'; @@ -41,7 +41,7 @@ let traceAgent: StackdriverTracer; */ function initConfig(userConfig: Forceable): TopLevelConfig { let envSetConfig = {}; - if (!!process.env.GCLOUD_TRACE_CONFIG) { + if (process.env.GCLOUD_TRACE_CONFIG) { envSetConfig = require(path.resolve( process.env.GCLOUD_TRACE_CONFIG! )) as Config; diff --git a/src/plugin-types.ts b/src/plugin-types.ts index ec34fb963..424076a72 100644 --- a/src/plugin-types.ts +++ b/src/plugin-types.ts @@ -13,7 +13,7 @@ // limitations under the License. // This file only describes public-facing interfaces. -// tslint:disable:no-any +// eslint-disable-next-line @typescript-eslint/no-explicit-any import {EventEmitter} from 'events'; @@ -24,6 +24,7 @@ import {TraceContext} from './util'; export {TraceContext}; +// eslint-disable-next-line @typescript-eslint/no-explicit-any export type Func = (...args: any[]) => T; // Defines an interface for storing Trace-Agent related data on patched modules. @@ -48,6 +49,7 @@ export interface Span { * @param key The label's key. * @param value The label's value. */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any addLabel(key: string, value: any): void; /** @@ -267,4 +269,5 @@ export interface Intercept { export type Patch = Monkeypatch | Intercept; +// eslint-disable-next-line @typescript-eslint/no-explicit-any export type Plugin = Array>; diff --git a/src/plugins/plugin-bluebird.ts b/src/plugins/plugin-bluebird.ts index 5d11b0e44..582fa1a38 100644 --- a/src/plugins/plugin-bluebird.ts +++ b/src/plugins/plugin-bluebird.ts @@ -27,12 +27,13 @@ const plugin: PluginTypes.Plugin = [ patch: (Bluebird, tracer) => { // any is a type arg; args are type checked when read directly, otherwise // passed through to a function with the same type signature. - // tslint:disable:no-any + // eslint-disable-next-line @typescript-eslint/no-explicit-any const wrapIfFunction = (fn: any) => typeof fn === 'function' ? tracer.wrap(fn) : fn; shimmer.wrap(Bluebird.prototype, '_then', (thenFn: Function) => { // Inherit context from the call site of .then(). - return function(this: bluebird_3, ...args: any[]) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return function (this: bluebird_3, ...args: any[]) { return thenFn.apply(this, [ wrapIfFunction(args[0]), wrapIfFunction(args[1]), diff --git a/src/plugins/plugin-connect.ts b/src/plugins/plugin-connect.ts index b58eaedc9..b6b6aac06 100644 --- a/src/plugins/plugin-connect.ts +++ b/src/plugins/plugin-connect.ts @@ -13,6 +13,7 @@ // limitations under the License. import {IncomingMessage, ServerResponse} from 'http'; +// eslint-disable-next-line node/no-deprecated-api import {parse as urlParse} from 'url'; import {PluginTypes} from '..'; @@ -69,8 +70,9 @@ function createMiddleware( // wrap end const originalEnd = res.end; - res.end = function(this: ServerResponse) { + res.end = function (this: ServerResponse) { res.end = originalEnd; + // eslint-disable-next-line prefer-rest-params const returned = res.end.apply(this, arguments); root.addLabel('connect/request.route.path', req.originalUrl); @@ -90,7 +92,7 @@ const plugin: PluginTypes.Plugin = [ file: '', versions: SUPPORTED_VERSIONS, intercept: (connect, api) => { - return function(this: {}) { + return function (this: {}) { const app = connect(); app.use(createMiddleware(api)); return app; diff --git a/src/plugins/plugin-express.ts b/src/plugins/plugin-express.ts index 5696874de..c31a10f70 100644 --- a/src/plugins/plugin-express.ts +++ b/src/plugins/plugin-express.ts @@ -14,7 +14,6 @@ import * as httpMethods from 'methods'; import * as shimmer from 'shimmer'; - import {PluginTypes} from '..'; import {express_4} from './types'; @@ -70,8 +69,9 @@ function patchModuleRoot(express: Express4Module, api: PluginTypes.Tracer) { // wrap end const originalEnd = res.end; - res.end = function(this: express_4.Response) { + res.end = function (this: express_4.Response) { res.end = originalEnd; + // eslint-disable-next-line prefer-rest-params const returned = res.end.apply(this, arguments); if (req.route && req.route.path) { @@ -94,6 +94,7 @@ function patchModuleRoot(express: Express4Module, api: PluginTypes.Tracer) { this._google_trace_patched = true; this.use(middleware); } + // eslint-disable-next-line prefer-rest-params return method.apply(this, arguments); }; } diff --git a/src/plugins/plugin-generic-pool.ts b/src/plugins/plugin-generic-pool.ts index 95640576d..2752fe2f3 100644 --- a/src/plugins/plugin-generic-pool.ts +++ b/src/plugins/plugin-generic-pool.ts @@ -11,13 +11,12 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. -'use strict'; -var shimmer = require('shimmer'); +import * as shimmer from 'shimmer'; function wrapModuleRoot2(Pool, api) { - shimmer.wrap(Pool.Pool.prototype, 'acquire', function(original) { - return function(callback, priority) { + shimmer.wrap(Pool.Pool.prototype, 'acquire', original => { + return function (callback, priority) { return original.call(this, api.wrap(callback), priority); }; }); @@ -27,8 +26,8 @@ module.exports = [ { file: '', versions: '2', - patch: wrapModuleRoot2 - } + patch: wrapModuleRoot2, + }, ]; export default {}; diff --git a/src/plugins/plugin-grpc.ts b/src/plugins/plugin-grpc.ts index 3bb54b31c..f2fb009aa 100644 --- a/src/plugins/plugin-grpc.ts +++ b/src/plugins/plugin-grpc.ts @@ -128,7 +128,7 @@ const SKIP_FRAMES = 1; // tslint:disable-next-line:variable-name let MetadataModuleValue: MetadataModule; -function patchMetadata(metadata: MetadataModule, api: Tracer) { +function patchMetadata(metadata: MetadataModule) { // metadata is the value of module.exports of src/node/src/metadata.js MetadataModuleValue = metadata; } @@ -200,10 +200,12 @@ function patchClient(client: ClientModule, api: Tracer) { if (!api.isRealSpan(span)) { // Span couldn't be created, either by policy or because a root span // doesn't exist. + // eslint-disable-next-line prefer-rest-params return method.apply(this, arguments); } const args: Array< Metadata | Callback | undefined | never + // eslint-disable-next-line prefer-rest-params > = Array.prototype.slice.call(arguments); // Check if the response is through a stream or a callback. if (!method.responseStream) { @@ -290,7 +292,7 @@ function patchClient(client: ClientModule, api: Tracer) { } // TODO(kjin): Investigate whether we need to copy properties of // method onto clientMethodTrace. - // tslint:disable-next-line:no-any + // eslint-disable-next-line @typescript-eslint/no-explicit-any return (clientMethodTrace as any) as ClientMethod; } @@ -304,6 +306,7 @@ function patchClient(client: ClientModule, api: Tracer) { return function makeClientConstructorTrace(this: never, methods) { // Client is a class. // tslint:disable-next-line:variable-name + // eslint-disable-next-line prefer-rest-params const Client = makeClientConstructor.apply(this, arguments); const methodsToWrap = [ ...Object.keys(methods), @@ -311,6 +314,7 @@ function patchClient(client: ClientModule, api: Tracer) { .map(methodName => methods[methodName].originalName) .filter( originalName => + // eslint-disable-next-line no-prototype-builtins !!originalName && Client.prototype.hasOwnProperty(originalName) ) as string[]), ]; @@ -365,6 +369,7 @@ function patchServer(server: ServerModule, api: Tracer) { 'metadata', JSON.stringify(responseMetadata.getMap()) ); + // eslint-disable-next-line prefer-rest-params return sendMetadata.apply(this, arguments); }; }; @@ -658,6 +663,7 @@ function patchServer(server: ServerModule, api: Tracer) { // method. Its role is to assign the serialize, deserialize, and user // logic handlers for each exposed service method. Here, we wrap these // functions depending on the method type. + // eslint-disable-next-line prefer-rest-params const result = register.apply(this, arguments); const handlerSet = this.handlers[name] as ServerHandlerFunctions< ServerHandler diff --git a/src/plugins/plugin-hapi.ts b/src/plugins/plugin-hapi.ts index d2671a877..a594ed935 100644 --- a/src/plugins/plugin-hapi.ts +++ b/src/plugins/plugin-hapi.ts @@ -12,8 +12,9 @@ // See the License for the specific language governing permissions and // limitations under the License. -import {IncomingMessage, ServerResponse} from 'http'; +import {ServerResponse} from 'http'; import * as shimmer from 'shimmer'; +// eslint-disable-next-line node/no-deprecated-api import {parse as urlParse} from 'url'; import {PluginTypes} from '..'; @@ -80,8 +81,9 @@ function instrument( root.addLabel(api.labels.HTTP_SOURCE_IP, req.connection.remoteAddress); // wrap end - res.end = function(this: ServerResponse) { + res.end = function (this: ServerResponse) { res.end = originalEnd; + // eslint-disable-next-line prefer-rest-params const returned = res.end.apply(this, arguments); if (request.route && request.route.path) { @@ -113,6 +115,7 @@ const plugin: PluginTypes.Plugin = [ patch: (hapi, api) => { shimmer.wrap(hapi.Server.prototype, 'connection', connection => { return function connectionTrace(this: hapi_16.Server) { + // eslint-disable-next-line prefer-rest-params const server = connection.apply(this, arguments); server.ext('onRequest', function handler(request, reply) { return instrument(api, request, () => reply.continue()); @@ -142,6 +145,7 @@ const plugin: PluginTypes.Plugin = [ Request.prototype._execute = Object.assign( function _executeWrap(this: hapi_17.Request) { return instrument(api, this, () => { + // eslint-disable-next-line prefer-rest-params return origExecute.apply(this, arguments); }); }, diff --git a/src/plugins/plugin-http.ts b/src/plugins/plugin-http.ts index 6c36b930a..1cbd5becb 100644 --- a/src/plugins/plugin-http.ts +++ b/src/plugins/plugin-http.ts @@ -17,6 +17,7 @@ import {Agent, ClientRequest, ClientRequestArgs, request} from 'http'; import * as httpsModule from 'https'; import * as semver from 'semver'; import * as shimmer from 'shimmer'; +// eslint-disable-next-line node/no-deprecated-api import {URL, parse as urlParse} from 'url'; import {Plugin, Tracer} from '../plugin-types'; @@ -30,10 +31,12 @@ const ERR_HTTP_HEADERS_SENT_MSG = "Can't set headers after they are sent."; // URL is used for type checking, but doesn't exist in Node <7. // This function works around that. -// tslint:disable:no-any +// eslint-disable-next-line @typescript-eslint/no-explicit-any const isURL = semver.satisfies(process.version, '>=7') - ? (value: any): value is URL => value instanceof URL - : (value: any): value is URL => false; + ? // eslint-disable-next-line @typescript-eslint/no-explicit-any + (value: any): value is URL => value instanceof URL + : // eslint-disable-next-line + (value: any): value is URL => false; // tslint:enable:no-any function getSpanName(options: ClientRequestArgs | URL) { @@ -83,7 +86,7 @@ function extractUrl( return `${protocol}//${host}${portString}${path}`; } -// tslint:disable-next-line:no-any +// eslint-disable-next-line @typescript-eslint/no-explicit-any function isTraceAgentRequest(options: httpModule.RequestOptions, api: Tracer) { return ( options && @@ -109,6 +112,7 @@ function makeRequestTrace( ): ClientRequest { // These are error conditions; defer to http.request and don't trace. if (!url || (typeof url === 'object' && typeof options === 'object')) { + // eslint-disable-next-line prefer-rest-params return request.apply(this, arguments); } @@ -130,11 +134,13 @@ function makeRequestTrace( // of trace api calls. If there is no buffering then each trace is // an http call which will get a trace which will be an http call if (isTraceAgentRequest(options, api)) { + // eslint-disable-next-line prefer-rest-params return request.apply(this, arguments); } const span = api.createChildSpan({name: getSpanName(options)}); if (!api.isRealSpan(span)) { + // eslint-disable-next-line prefer-rest-params return request.apply(this, arguments); } @@ -188,6 +194,7 @@ function makeRequestTrace( numBytes += chunk.length; }); } + // eslint-disable-next-line prefer-rest-params return on.apply(this, arguments); }; }); @@ -250,6 +257,7 @@ function patchHttp(http: HttpModule, api: Tracer) { // Ref: // https://nodejs.org/dist/latest/docs/api/http.html#http_http_get_options_callback return function getTrace(this: never) { + // eslint-disable-next-line prefer-rest-params const req = http.request.apply(this, arguments); req.end(); return req; @@ -264,8 +272,9 @@ function patchHttps(https: HttpsModule, api: Tracer) { shimmer.wrap(https, 'request', request => { return makeRequestTrace('https:', request, api); }); - shimmer.wrap(https, 'get', function getWrap(): typeof httpsModule.get { + shimmer.wrap(https, 'get', () => { return function getTrace(this: never) { + // eslint-disable-next-line prefer-rest-params const req = https.request.apply(this, arguments); req.end(); return req; diff --git a/src/plugins/plugin-http2.ts b/src/plugins/plugin-http2.ts index 7b6b5b9e6..0a629ad4f 100644 --- a/src/plugins/plugin-http2.ts +++ b/src/plugins/plugin-http2.ts @@ -1,3 +1,4 @@ +/* eslint-disable @typescript-eslint/no-unused-vars */ // Copyright 2017 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); @@ -12,9 +13,9 @@ // See the License for the specific language governing permissions and // limitations under the License. -import {EventEmitter} from 'events'; // This is imported only for types. Generated .js file should NOT load 'http2'. // `http2` must be used only in type annotations, not in expressions. +// eslint-disable-next-line node/no-unsupported-features/node-builtins import * as http2 from 'http2'; import * as shimmer from 'shimmer'; import {URL} from 'url'; @@ -73,7 +74,7 @@ function makeRequestTrace( authority: string | URL, api: Tracer ): Http2SessionRequestFunction { - return function( + return function ( this: http2.Http2Session, headers?: http2.OutgoingHttpHeaders ): http2.ClientHttp2Stream { @@ -93,6 +94,7 @@ function makeRequestTrace( // add the check anyway for the potential migration to http2 in the // future. if (isTraceAgentRequest(newHeaders, api)) { + // eslint-disable-next-line prefer-rest-params return request.apply(this, arguments); } @@ -100,6 +102,7 @@ function makeRequestTrace( name: getSpanName(authority), }); if (!api.isRealSpan(requestLifecycleSpan)) { + // eslint-disable-next-line prefer-rest-params return request.apply(this, arguments); } // Node sets the :method pseudo-header to GET if not set by client. @@ -118,6 +121,7 @@ function makeRequestTrace( const stream: http2.ClientHttp2Stream = request.call( this, newHeaders, + // eslint-disable-next-line prefer-rest-params ...Array.prototype.slice.call(arguments, 1) ); api.wrapEmitter(stream); @@ -160,7 +164,7 @@ function makeRequestTrace( // request. We expect this to be very uncommon as it is not mentioned in // any of the official documentation. shimmer.wrap(stream, 'on', on => { - return function( + return function ( this: http2.ClientHttp2Stream, eventName: {}, cb: Function @@ -171,6 +175,7 @@ function makeRequestTrace( numBytes += chunk.length; }); } + // eslint-disable-next-line prefer-rest-params return on.apply(this, arguments); }; }); @@ -194,9 +199,10 @@ function patchHttp2(h2: Http2Module, api: Tracer): void { h2, 'connect', connect => - function(this: Http2Module, authority: string | URL) { + function (this: Http2Module, authority: string | URL) { const session: http2.ClientHttp2Session = connect.apply( this, + // eslint-disable-next-line prefer-rest-params arguments ); patchHttp2Session(session, authority, api); diff --git a/src/plugins/plugin-koa.ts b/src/plugins/plugin-koa.ts index d2419572f..02a339c8a 100644 --- a/src/plugins/plugin-koa.ts +++ b/src/plugins/plugin-koa.ts @@ -12,8 +12,9 @@ // See the License for the specific language governing permissions and // limitations under the License. -import {IncomingMessage, ServerResponse} from 'http'; +import {ServerResponse} from 'http'; import * as shimmer from 'shimmer'; +// eslint-disable-next-line node/no-deprecated-api import {parse as urlParse} from 'url'; import {PluginTypes} from '..'; @@ -29,7 +30,7 @@ type KoaContext = (koa_1.Context | koa_2.Context) & { interface KoaModule { // TypeScript isn't expressive enough, but KoaModule#use should return `this`. - // tslint:disable-next-line:no-any + // eslint-disable-next-line @typescript-eslint/no-explicit-any readonly prototype: {use: (m: T) => any}; } @@ -88,8 +89,9 @@ function startSpanForRequest( root.addLabel(api.labels.HTTP_SOURCE_IP, ctx.request.ip); // wrap end - res.end = function(this: ServerResponse) { + res.end = function (this: ServerResponse) { res.end = originalEnd; + // eslint-disable-next-line prefer-rest-params const returned = res.end.apply(this, arguments); if (ctx.routePath) { @@ -121,7 +123,7 @@ function createMiddleware(api: PluginTypes.Tracer): koa_1.Middleware { if (propagateContext) { // TS Iterator definition clashes with @types/node. // For some reason, this causes the next line to not pass type check. - // tslint:disable-next-line:no-any + // eslint-disable-next-line @typescript-eslint/no-explicit-any next.next = api.wrap(next.next as any); } return next; @@ -152,6 +154,7 @@ function patchUse( this._google_trace_patched = true; this.use(createMiddlewareFunction(api)); } + // eslint-disable-next-line prefer-rest-params return use.apply(this, arguments); }; }); diff --git a/src/plugins/plugin-mongodb-core.ts b/src/plugins/plugin-mongodb-core.ts index 2cf639c00..338fdec1e 100644 --- a/src/plugins/plugin-mongodb-core.ts +++ b/src/plugins/plugin-mongodb-core.ts @@ -11,17 +11,17 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. -'use strict'; -var shimmer = require('shimmer'); +import * as shimmer from 'shimmer'; -var SUPPORTED_VERSIONS = '1 - 3'; +const SUPPORTED_VERSIONS = '1 - 3'; function createNextWrap(api) { return function nextWrap(next) { return function next_trace(cb) { - var span = api.createChildSpan({ name: 'mongo-cursor' }); + const span = api.createChildSpan({name: 'mongo-cursor'}); if (!api.isRealSpan(span)) { + // eslint-disable-next-line prefer-rest-params return next.apply(this, arguments); } span.addLabel('db', this.ns); @@ -34,10 +34,11 @@ function createNextWrap(api) { } function wrapWithLabel(api, label) { - return function(original) { + return function (original) { return function mongo_operation_trace(ns, ops, options, callback) { - var span = api.createChildSpan({ name: label }); + const span = api.createChildSpan({name: label}); if (!api.isRealSpan(span)) { + // eslint-disable-next-line prefer-rest-params return original.apply(this, arguments); } span.addLabel('db', ns); @@ -45,11 +46,15 @@ function wrapWithLabel(api, label) { span.addLabel('operations', JSON.stringify(ops)); } if (typeof options === 'function') { - return original.call(this, ns, ops, - wrapCallback(api, span, options)); + return original.call(this, ns, ops, wrapCallback(api, span, options)); } else { - return original.call(this, ns, ops, options, - wrapCallback(api, span, callback)); + return original.call( + this, + ns, + ops, + options, + wrapCallback(api, span, callback) + ); } }; }; @@ -64,14 +69,14 @@ function wrapWithLabel(api, label) { * @return {Function} The wrapped function. */ function wrapCallback(api, span, done) { - var fn = function(err, res) { + const fn = function (err, res) { if (api.enhancedDatabaseReportingEnabled()) { if (err) { // Errors may contain sensitive query parameters. span.addLabel('mongoError', err); } if (res) { - var result = res.result ? res.result : res; + const result = res.result ? res.result : res; span.addLabel('result', result); } } @@ -95,31 +100,47 @@ module.exports = [ { file: 'lib/connection/pool.js', versions: SUPPORTED_VERSIONS, - patch: function(pool, api) { + patch: function (pool, api) { shimmer.wrap(pool.prototype, 'once', createOnceWrap(api)); }, - unpatch: function(pool) { + unpatch: function (pool) { shimmer.unwrap(pool.prototype, 'once'); - } + }, }, { file: '', versions: SUPPORTED_VERSIONS, - patch: function(mongo, api) { - shimmer.wrap(mongo.Server.prototype, 'command', wrapWithLabel(api, 'mongo-command')); - shimmer.wrap(mongo.Server.prototype, 'insert', wrapWithLabel(api, 'mongo-insert')); - shimmer.wrap(mongo.Server.prototype, 'update', wrapWithLabel(api, 'mongo-update')); - shimmer.wrap(mongo.Server.prototype, 'remove', wrapWithLabel(api, 'mongo-remove')); + patch: function (mongo, api) { + shimmer.wrap( + mongo.Server.prototype, + 'command', + wrapWithLabel(api, 'mongo-command') + ); + shimmer.wrap( + mongo.Server.prototype, + 'insert', + wrapWithLabel(api, 'mongo-insert') + ); + shimmer.wrap( + mongo.Server.prototype, + 'update', + wrapWithLabel(api, 'mongo-update') + ); + shimmer.wrap( + mongo.Server.prototype, + 'remove', + wrapWithLabel(api, 'mongo-remove') + ); shimmer.wrap(mongo.Cursor.prototype, 'next', createNextWrap(api)); }, - unpatch: function(mongo) { + unpatch: function (mongo) { shimmer.unwrap(mongo.Server.prototype, 'command'); shimmer.unwrap(mongo.Server.prototype, 'insert'); shimmer.unwrap(mongo.Server.prototype, 'update'); shimmer.unwrap(mongo.Server.prototype, 'remove'); shimmer.unwrap(mongo.Cursor.prototype, 'next'); - } - } + }, + }, ]; export default {}; diff --git a/src/plugins/plugin-mongodb.ts b/src/plugins/plugin-mongodb.ts index 2e401cc9d..77a6095e2 100644 --- a/src/plugins/plugin-mongodb.ts +++ b/src/plugins/plugin-mongodb.ts @@ -11,7 +11,6 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. -'use strict'; /** * NOTE: This file is almost completely cloned from the mongodb-core plugin, as @@ -21,15 +20,16 @@ * Any changes here might need to go in there as well. */ -var shimmer = require('shimmer'); +import * as shimmer from 'shimmer'; -var SUPPORTED_VERSIONS = '>=3.3'; +const SUPPORTED_VERSIONS = '>=3.3'; function createNextWrap(api) { return function nextWrap(next) { return function next_trace(cb) { - var span = api.createChildSpan({ name: 'mongo-cursor' }); + const span = api.createChildSpan({name: 'mongo-cursor'}); if (!api.isRealSpan(span)) { + // eslint-disable-next-line prefer-rest-params return next.apply(this, arguments); } span.addLabel('db', this.ns); @@ -42,10 +42,11 @@ function createNextWrap(api) { } function wrapWithLabel(api, label) { - return function(original) { + return function (original) { return function mongo_operation_trace(ns, ops, options, callback) { - var span = api.createChildSpan({ name: label }); + const span = api.createChildSpan({name: label}); if (!api.isRealSpan(span)) { + // eslint-disable-next-line prefer-rest-params return original.apply(this, arguments); } span.addLabel('db', ns); @@ -53,11 +54,15 @@ function wrapWithLabel(api, label) { span.addLabel('operations', JSON.stringify(ops)); } if (typeof options === 'function') { - return original.call(this, ns, ops, - wrapCallback(api, span, options)); + return original.call(this, ns, ops, wrapCallback(api, span, options)); } else { - return original.call(this, ns, ops, options, - wrapCallback(api, span, callback)); + return original.call( + this, + ns, + ops, + options, + wrapCallback(api, span, callback) + ); } }; }; @@ -72,14 +77,14 @@ function wrapWithLabel(api, label) { * @return {Function} The wrapped function. */ function wrapCallback(api, span, done) { - var fn = function(err, res) { + const fn = function (err, res) { if (api.enhancedDatabaseReportingEnabled()) { if (err) { // Errors may contain sensitive query parameters. span.addLabel('mongoError', err); } if (res) { - var result = res.result ? res.result : res; + const result = res.result ? res.result : res; span.addLabel('result', result); } } @@ -103,31 +108,47 @@ module.exports = [ { file: 'lib/core/connection/pool.js', versions: SUPPORTED_VERSIONS, - patch: function(pool, api) { + patch: function (pool, api) { shimmer.wrap(pool.prototype, 'once', createOnceWrap(api)); }, - unpatch: function(pool) { + unpatch: function (pool) { shimmer.unwrap(pool.prototype, 'once'); - } + }, }, { file: 'lib/core/index.js', versions: SUPPORTED_VERSIONS, - patch: function(mongo, api) { - shimmer.wrap(mongo.Server.prototype, 'command', wrapWithLabel(api, 'mongo-command')); - shimmer.wrap(mongo.Server.prototype, 'insert', wrapWithLabel(api, 'mongo-insert')); - shimmer.wrap(mongo.Server.prototype, 'update', wrapWithLabel(api, 'mongo-update')); - shimmer.wrap(mongo.Server.prototype, 'remove', wrapWithLabel(api, 'mongo-remove')); + patch: function (mongo, api) { + shimmer.wrap( + mongo.Server.prototype, + 'command', + wrapWithLabel(api, 'mongo-command') + ); + shimmer.wrap( + mongo.Server.prototype, + 'insert', + wrapWithLabel(api, 'mongo-insert') + ); + shimmer.wrap( + mongo.Server.prototype, + 'update', + wrapWithLabel(api, 'mongo-update') + ); + shimmer.wrap( + mongo.Server.prototype, + 'remove', + wrapWithLabel(api, 'mongo-remove') + ); shimmer.wrap(mongo.Cursor.prototype, '_next', createNextWrap(api)); }, - unpatch: function(mongo) { + unpatch: function (mongo) { shimmer.unwrap(mongo.Server.prototype, 'command'); shimmer.unwrap(mongo.Server.prototype, 'insert'); shimmer.unwrap(mongo.Server.prototype, 'update'); shimmer.unwrap(mongo.Server.prototype, 'remove'); shimmer.unwrap(mongo.Cursor.prototype, '_next'); - } - } + }, + }, ]; export default {}; diff --git a/src/plugins/plugin-mongoose.ts b/src/plugins/plugin-mongoose.ts index 59e9860c0..ee8ce4740 100644 --- a/src/plugins/plugin-mongoose.ts +++ b/src/plugins/plugin-mongoose.ts @@ -13,7 +13,7 @@ // limitations under the License. import * as mongooseTypes from 'mongoose'; -import { PluginTypes } from '..'; +import {PluginTypes} from '..'; const plugin: PluginTypes.Plugin = [ { @@ -30,10 +30,10 @@ const plugin: PluginTypes.Plugin = [ const result = target.apply(thisArg, args); thisArg.exec = api.wrap(thisArg.exec); return result; - } + }, }); - } - } + }, + }, ]; export = plugin; diff --git a/src/plugins/plugin-mysql.ts b/src/plugins/plugin-mysql.ts index 576a5bdc5..7ed3d4a5e 100644 --- a/src/plugins/plugin-mysql.ts +++ b/src/plugins/plugin-mysql.ts @@ -11,19 +11,20 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. -'use strict'; -var shimmer = require('shimmer'); +import * as shimmer from 'shimmer'; -var SUPPORTED_VERSIONS = '^2.9.x'; +const SUPPORTED_VERSIONS = '^2.9.x'; function createCreateQueryWrap(api) { return function createQueryWrap(createQuery) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars return function createQuery_trace(sql, values, cb) { - var span = api.createChildSpan({ - name: 'mysql-query' + const span = api.createChildSpan({ + name: 'mysql-query', }); - var query = createQuery.apply(this, arguments); + // eslint-disable-next-line prefer-rest-params + const query = createQuery.apply(this, arguments); if (!api.isRealSpan(span)) { return query; } @@ -37,7 +38,7 @@ function createCreateQueryWrap(api) { if (query._callback) { query._callback = wrapCallback(api, span, query._callback); } else { - query.on('end', function() { + query.on('end', () => { span.endSpan(); }); } @@ -47,7 +48,7 @@ function createCreateQueryWrap(api) { } function wrapCallback(api, span, done) { - var fn = function(err, res) { + const fn = function (err, res) { if (api.enhancedDatabaseReportingEnabled()) { if (err) { span.addLabel('error', err); @@ -76,24 +77,27 @@ module.exports = [ { file: 'lib/Connection.js', versions: SUPPORTED_VERSIONS, - patch: function(Connection, api) { + patch: function (Connection, api) { shimmer.wrap(Connection, 'createQuery', createCreateQueryWrap(api)); }, - unpatch: function(Connection) { + unpatch: function (Connection) { shimmer.unwrap(Connection, 'createQuery'); - } + }, }, { file: 'lib/Pool.js', versions: SUPPORTED_VERSIONS, - patch: function(Pool, api) { - shimmer.wrap(Pool.prototype, 'getConnection', - createWrapGetConnection(api)); + patch: function (Pool, api) { + shimmer.wrap( + Pool.prototype, + 'getConnection', + createWrapGetConnection(api) + ); }, - unpatch: function(Pool) { + unpatch: function (Pool) { shimmer.unwrap(Pool.prototype, 'getConnection'); - } - } + }, + }, ]; export default {}; diff --git a/src/plugins/plugin-mysql2.ts b/src/plugins/plugin-mysql2.ts index 57fdb75a4..95b1926c2 100644 --- a/src/plugins/plugin-mysql2.ts +++ b/src/plugins/plugin-mysql2.ts @@ -11,19 +11,20 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. -'use strict'; -var shimmer = require('shimmer'); +import * as shimmer from 'shimmer'; -var SUPPORTED_VERSIONS = '^1.0.0'; +const SUPPORTED_VERSIONS = '^1.0.0'; function createCreateQueryWrap(api) { return function createQueryWrap(createQuery) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars return function createQuery_trace(sql, values, cb, config) { - var span = api.createChildSpan({ - name: 'mysql-query' + const span = api.createChildSpan({ + name: 'mysql-query', }); - var query = createQuery.apply(this, arguments); + // eslint-disable-next-line prefer-rest-params + const query = createQuery.apply(this, arguments); if (!api.isRealSpan(span)) { return query; } @@ -37,7 +38,7 @@ function createCreateQueryWrap(api) { if (query.onResult) { query.onResult = wrapCallback(api, span, query.onResult); } else { - query.on('end', function() { + query.on('end', () => { span.endSpan(); }); } @@ -47,7 +48,7 @@ function createCreateQueryWrap(api) { } function wrapCallback(api, span, done) { - var fn = function(err, res) { + const fn = function (err, res) { if (api.enhancedDatabaseReportingEnabled()) { if (err) { span.addLabel('error', err); @@ -76,24 +77,27 @@ module.exports = [ { file: 'lib/connection.js', versions: SUPPORTED_VERSIONS, - patch: function(Connection, api) { + patch: function (Connection, api) { shimmer.wrap(Connection, 'createQuery', createCreateQueryWrap(api)); }, - unpatch: function(Connection) { + unpatch: function (Connection) { shimmer.unwrap(Connection, 'createQuery'); - } + }, }, { file: 'index.js', versions: SUPPORTED_VERSIONS, - patch: function(mysql2, api) { - shimmer.wrap(mysql2.Pool.prototype, 'getConnection', - createWrapGetConnection(api)); + patch: function (mysql2, api) { + shimmer.wrap( + mysql2.Pool.prototype, + 'getConnection', + createWrapGetConnection(api) + ); }, - unpatch: function(mysql2) { + unpatch: function (mysql2) { shimmer.unwrap(mysql2.Pool.prototype, 'getConnection'); - } - } + }, + }, ]; export default {}; diff --git a/src/plugins/plugin-pg.ts b/src/plugins/plugin-pg.ts index bef4cb058..20e6e9fcc 100644 --- a/src/plugins/plugin-pg.ts +++ b/src/plugins/plugin-pg.ts @@ -98,12 +98,13 @@ class PostgresPatchUtility { patchSubmittable(pgQuery: Submittable, span: Span): Submittable { let spanEnded = false; const {maybePopulateLabelsFromOutputs} = this; - if (pgQuery.handleError) { + if (pgQuery.handleError!) { shimmer.wrap(pgQuery, 'handleError', origCallback => { // Elements of args are not individually accessed. - // tslint:disable:no-any - return this.tracer.wrap(function( + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return this.tracer.wrap(function ( this: Submittable, + // eslint-disable-next-line @typescript-eslint/no-explicit-any ...args: any[] ): void { // tslint:enable:no-any @@ -119,12 +120,13 @@ class PostgresPatchUtility { }); }); } - if (pgQuery.handleReadyForQuery) { + if (pgQuery.handleReadyForQuery!) { shimmer.wrap(pgQuery, 'handleReadyForQuery', origCallback => { // Elements of args are not individually accessed. - // tslint:disable:no-any - return this.tracer.wrap(function( + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return this.tracer.wrap(function ( this: Submittable, + // eslint-disable-next-line @typescript-eslint/no-explicit-any ...args: any[] ): void { // tslint:enable:no-any @@ -239,6 +241,7 @@ const plugin: Plugin = [ return function query_trace(this: pg_7.Client) { const span = api.createChildSpan({name: 'pg-query'}); if (!api.isRealSpan(span)) { + // eslint-disable-next-line prefer-rest-params return query.apply(this, arguments); } @@ -256,6 +259,7 @@ const plugin: Plugin = [ const argLength = arguments.length; if (argLength >= 1) { const args: ClientQueryArguments = Array.prototype.slice.call( + // eslint-disable-next-line prefer-rest-params arguments, 0 ); @@ -276,6 +280,7 @@ const plugin: Plugin = [ } pgQuery = query.apply(this, args); } else { + // eslint-disable-next-line prefer-rest-params pgQuery = query.apply(this, arguments); } diff --git a/src/plugins/plugin-redis.ts b/src/plugins/plugin-redis.ts index 6a772d066..916d3b54b 100644 --- a/src/plugins/plugin-redis.ts +++ b/src/plugins/plugin-redis.ts @@ -12,14 +12,13 @@ // See the License for the specific language governing permissions and // limitations under the License. -'use strict'; - -var shimmer = require('shimmer'); +import * as shimmer from 'shimmer'; function createCreateClientWrap(api) { return function createClientWrap(createClient) { return function createClientTrace() { - var client = createClient.apply(this, arguments); + // eslint-disable-next-line prefer-rest-params + const client = createClient.apply(this, arguments); api.wrapEmitter(client); return client; }; @@ -32,13 +31,16 @@ function createCreateStreamWrap(api) { return function create_stream_trace() { if (!this.stream) { Object.defineProperty(this, 'stream', { - get: function () { return this._google_trace_stream; }, + get: function () { + return this._google_trace_stream; + }, set: function (val) { api.wrapEmitter(val); this._google_trace_stream = val; - } + }, }); } + // eslint-disable-next-line prefer-rest-params return create_stream.apply(this, arguments); }; }; @@ -49,15 +51,16 @@ function createStreamListenersWrap(api) { return function streamListenersWrap(install_stream_listeners) { return function install_stream_listeners_trace() { api.wrapEmitter(this.stream); + // eslint-disable-next-line prefer-rest-params return install_stream_listeners.apply(this, arguments); }; }; } function setupSpan(api, cmd, args, skipped_frames) { - var span = api.createChildSpan({ + const span = api.createChildSpan({ name: 'redis-' + cmd, - skipFrames: skipped_frames + 1 + skipFrames: skipped_frames + 1, }); span.addLabel('command', cmd); if (api.enhancedDatabaseReportingEnabled()) { @@ -70,17 +73,24 @@ function startSpanFromArguments(api, cmd, args, cb, send_command) { // If the arguments cannot be processed in this plugin, let redis process // them so that if they are incorrect, redis reports an error instead of // this plugin. - if (!cmd || !args || typeof cmd !== 'string' || !Array.isArray(args) || - (cb && typeof cb !== 'function')) { + if ( + !cmd || + !args || + typeof cmd !== 'string' || + !Array.isArray(args) || + (cb && typeof cb !== 'function') + ) { return send_command(cmd, args, cb); } if (!cb) { - if (typeof args[args.length - 1] === 'function' || - typeof args[args.length - 1] === 'undefined') { + if ( + typeof args[args.length - 1] === 'function' || + typeof args[args.length - 1] === 'undefined' + ) { cb = args.pop(); } } - var span = setupSpan(api, cmd, args, 1); + const span = setupSpan(api, cmd, args, 1); if (!api.isRealSpan(span)) { return send_command(cmd, args, cb); } @@ -93,14 +103,20 @@ function createInternalSendCommandWrap(api) { if (arguments.length === 1 && typeof cmd === 'object') { // New versions of redis (2.4+) use a single options object instead // of separate named arguments. - var span = setupSpan(api, cmd.command, cmd.args, 0); + const span = setupSpan(api, cmd.command, cmd.args, 0); if (!api.isRealSpan(span)) { return internal_send_command.call(this, cmd); } cmd.callback = wrapCallback(api, span, cmd.callback); return internal_send_command.call(this, cmd); } - return startSpanFromArguments(api, cmd, args, cb, internal_send_command.bind(this)); + return startSpanFromArguments( + api, + cmd, + args, + cb, + internal_send_command.bind(this) + ); }; }; } @@ -108,13 +124,19 @@ function createInternalSendCommandWrap(api) { function createSendCommandWrap(api) { return function sendCommandWrap(send_command) { return function send_command_trace(cmd, args, cb) { - return startSpanFromArguments(api, cmd, args, cb, send_command.bind(this)); + return startSpanFromArguments( + api, + cmd, + args, + cb, + send_command.bind(this) + ); }; }; } function wrapCallback(api, span, done) { - var fn = function(err, res) { + const fn = function (err, res) { if (api.enhancedDatabaseReportingEnabled()) { if (err) { span.addLabel('error', err); @@ -132,8 +154,11 @@ function wrapCallback(api, span, done) { } function wrapInternalSendCommand(redis, api) { - shimmer.wrap(redis.RedisClient.prototype, 'internal_send_command', - createInternalSendCommandWrap(api)); + shimmer.wrap( + redis.RedisClient.prototype, + 'internal_send_command', + createInternalSendCommandWrap(api) + ); } function unwrapInternalSendCommand(redis) { @@ -149,8 +174,11 @@ function unwrapCreateClient(redis) { } function wrapCreateStream(redis, api) { - shimmer.wrap(redis.RedisClient.prototype, 'create_stream', - createCreateStreamWrap(api)); + shimmer.wrap( + redis.RedisClient.prototype, + 'create_stream', + createCreateStreamWrap(api) + ); } function unwrapCreateStream(redis) { @@ -158,8 +186,11 @@ function unwrapCreateStream(redis) { } function wrapSendCommand(redis, api) { - shimmer.wrap(redis.RedisClient.prototype, 'send_command', - createSendCommandWrap(api)); + shimmer.wrap( + redis.RedisClient.prototype, + 'send_command', + createSendCommandWrap(api) + ); } function unwrapSendCommand(redis) { @@ -167,8 +198,11 @@ function unwrapSendCommand(redis) { } function wrapInstallStreamListeners(redis, api) { - shimmer.wrap(redis.RedisClient.prototype, 'install_stream_listeners', - createStreamListenersWrap(api)); + shimmer.wrap( + redis.RedisClient.prototype, + 'install_stream_listeners', + createStreamListenersWrap(api) + ); } function unwrapInstallStreamListeners(redis) { @@ -179,45 +213,45 @@ module.exports = [ { file: '', versions: '>=2.6', - patch: function(redis, api) { + patch: function (redis, api) { wrapCreateStream(redis, api); wrapInternalSendCommand(redis, api); wrapCreateClient(redis, api); }, - unpatch: function(redis) { + unpatch: function (redis) { unwrapCreateStream(redis); unwrapInternalSendCommand(redis); unwrapCreateClient(redis); - } + }, }, { file: '', versions: '>2.3 <2.6', - patch: function(redis, api) { + patch: function (redis, api) { wrapSendCommand(redis, api); wrapCreateStream(redis, api); wrapCreateClient(redis, api); }, - unpatch: function(redis) { + unpatch: function (redis) { unwrapSendCommand(redis); unwrapCreateStream(redis); unwrapCreateClient(redis); - } + }, }, { file: '', versions: '<=2.3', - patch: function(redis, api) { + patch: function (redis, api) { wrapSendCommand(redis, api); wrapInstallStreamListeners(redis, api); wrapCreateClient(redis, api); }, - unpatch: function(redis) { + unpatch: function (redis) { unwrapSendCommand(redis); unwrapInstallStreamListeners(redis); unwrapCreateClient(redis); - } - } + }, + }, ]; export default {}; diff --git a/src/plugins/plugin-restify.ts b/src/plugins/plugin-restify.ts index 840eaa6cf..4e2393fc7 100644 --- a/src/plugins/plugin-restify.ts +++ b/src/plugins/plugin-restify.ts @@ -14,7 +14,6 @@ import {ServerResponse} from 'http'; import * as shimmer from 'shimmer'; -import {parse as urlParse} from 'url'; import {PluginTypes} from '..'; @@ -37,6 +36,7 @@ function patchRestify(restify: Restify5, api: PluginTypes.Tracer) { function createServerWrap(createServer: CreateServerFn): CreateServerFn { return function createServerTrace(this: {}) { + // eslint-disable-next-line prefer-rest-params const server = createServer.apply(this, arguments) as restify_5.Server; server.use(middleware); return server; @@ -86,8 +86,9 @@ function patchRestify(restify: Restify5, api: PluginTypes.Tracer) { ); const originalEnd = res.end; - res.end = function(this: ServerResponse) { + res.end = function (this: ServerResponse) { res.end = originalEnd; + // eslint-disable-next-line prefer-rest-params const returned = res.end.apply(this, arguments); if (req.route && req.route.path) { diff --git a/src/plugins/types/index.d.ts b/src/plugins/types/index.d.ts index 6ddb08249..f8884ba55 100644 --- a/src/plugins/types/index.d.ts +++ b/src/plugins/types/index.d.ts @@ -36,9 +36,9 @@ import * as restify_5 from './restify_5'; // restify@5 //---other imports---// -import { EventEmitter } from 'events'; -import { Server } from 'http'; -import { Readable } from 'stream'; +import {EventEmitter} from 'events'; +import {Server} from 'http'; +import {Readable} from 'stream'; //---koa@1---// @@ -58,7 +58,7 @@ declare namespace koa_1 { // References: // https://github.com/koajs/koa/issues/533 // https://github.com/koajs/koa/blob/master/History.md#200-alpha1--2015-10-22 - interface Context extends koa_2.Context {} + type Context = koa_2.Context; } //---pg@6---// @@ -72,10 +72,10 @@ declare namespace pg_6 { // References: // https://node-postgres.com/guides/upgrading#client-query-on // https://github.com/brianc/node-postgres/blob/v6.4.2/lib/client.js#L355 - type QueryReturnValue = ( - pg_7.QueryConfig & - { callback?: (err: Error|null, res?: pg_7.QueryResult) => void } - ) & (({ submit: Function } & Readable) | (pg_7.Query & PromiseLike)); + type QueryReturnValue = (pg_7.QueryConfig & { + callback?: (err: Error | null, res?: pg_7.QueryResult) => void; + }) & + (({submit: Function} & Readable) | (pg_7.Query & PromiseLike)); class Client { query(...args: any[]): QueryReturnValue; @@ -94,5 +94,5 @@ export { koa_2, pg_6, pg_7, - restify_5 + restify_5, }; diff --git a/src/span-data.ts b/src/span-data.ts index e5baf725f..36a2d4441 100644 --- a/src/span-data.ts +++ b/src/span-data.ts @@ -100,7 +100,7 @@ export abstract class BaseSpanData implements Span { }; } - // tslint:disable-next-line:no-any + // eslint-disable-next-line @typescript-eslint/no-explicit-any addLabel(key: string, value: any) { const k = traceUtil.truncate(key, Constants.TRACE_SERVICE_LABEL_KEY_LIMIT); const stringValue = typeof value === 'string' ? value : util.inspect(value); @@ -112,7 +112,7 @@ export abstract class BaseSpanData implements Span { } endSpan(timestamp?: Date) { - if (!!this.span.endTime) { + if (this.span.endTime) { return; } timestamp = timestamp || new Date(); @@ -153,7 +153,7 @@ export class RootSpanData extends BaseSpanData implements RootSpan { } endSpan(timestamp?: Date) { - if (!!this.span.endTime) { + if (this.span.endTime) { return; } super.endSpan(timestamp); @@ -190,7 +190,7 @@ export class ChildSpanData extends BaseSpanData { } endSpan(timestamp?: Date) { - if (!!this.span.endTime) { + if (this.span.endTime) { return; } super.endSpan(timestamp); @@ -215,7 +215,7 @@ function createPhantomSpanData( getTraceContext() { return null; }, - // tslint:disable-next-line:no-any + // eslint-disable-next-line addLabel(key: string, value: any) {}, endSpan() {}, }, diff --git a/src/trace-api.ts b/src/trace-api.ts index 32d5b209a..d001501a9 100644 --- a/src/trace-api.ts +++ b/src/trace-api.ts @@ -233,10 +233,7 @@ export class StackdriverTracer implements Tracer { const traceId = traceContext ? traceContext.traceId - : uuid - .v4() - .split('-') - .join(''); + : uuid.v4().split('-').join(''); let rootContext: RootSpan & RootContext; // Create an "untraced" root span (one that won't be published) if the @@ -306,7 +303,7 @@ export class StackdriverTracer implements Tracer { options = options || {name: ''}; const rootSpan = cls.get().getContext(); if (rootSpan.type === SpanType.ROOT) { - if (!!rootSpan.span.endTime) { + if (rootSpan.span.endTime) { // A closed root span suggests that we either have context confusion or // some work is being done after the root request has been completed. // The first case could lead to a memory leak, if somehow all spans end diff --git a/src/trace-plugin-loader.ts b/src/trace-plugin-loader.ts index e0aa190d1..c381b2229 100644 --- a/src/trace-plugin-loader.ts +++ b/src/trace-plugin-loader.ts @@ -16,8 +16,6 @@ import * as builtinModules from 'builtin-modules'; import * as path from 'path'; import * as hook from 'require-in-the-middle'; import * as semver from 'semver'; - -import {TracePolicy} from './config'; import {Logger} from './logger'; import {Intercept, Monkeypatch, Plugin} from './plugin-types'; import { @@ -373,7 +371,7 @@ export class PluginLoader { */ activate(): PluginLoader { if (this.internalState === PluginLoaderState.NO_HOOK) { - this.logger.info(`PluginLoader#activate: Adding require hook.`); + this.logger.info('PluginLoader#activate: Adding require hook.'); // Enable the require hook. this.enableRequireHook((exportedValue, moduleStr, baseDir) => { if (this.internalState === PluginLoaderState.ACTIVATED) { @@ -403,7 +401,7 @@ export class PluginLoader { let version = this.getVersion(baseDir); if (version) { // Warn for pre-releases. - if (!!semver.prerelease(version)) { + if (semver.prerelease(version)) { if (isMainModule) { this.logger.warn( `PluginLoader#onRequire: [${name}@${version}] This module is in pre-release. Applying plugin anyways.` @@ -438,7 +436,7 @@ export class PluginLoader { return exportedValue; }); this.internalState = PluginLoaderState.ACTIVATED; - this.logger.info(`PluginLoader#activate: Activated.`); + this.logger.info('PluginLoader#activate: Activated.'); } else if (this.internalState === PluginLoaderState.DEACTIVATED) { throw new Error('Currently cannot re-activate plugin loader.'); } else { @@ -459,7 +457,7 @@ export class PluginLoader { pluginWrapper.unapplyAll(); } this.internalState = PluginLoaderState.DEACTIVATED; - this.logger.info(`PluginLoader#deactivate: Deactivated.`); + this.logger.info('PluginLoader#deactivate: Deactivated.'); } return this; } diff --git a/src/trace-writer.ts b/src/trace-writer.ts index f059be914..67ae1486f 100644 --- a/src/trace-writer.ts +++ b/src/trace-writer.ts @@ -27,6 +27,7 @@ import { Service, } from '@google-cloud/common'; +// eslint-disable-next-line @typescript-eslint/no-var-requires const pjson = require('../../package.json'); // TODO(kjin): This value should be exported from @g-c/c. @@ -150,6 +151,7 @@ export class TraceWriter extends Service { this.flushBuffer(); if (onUncaughtException === 'flushAndExit') { setTimeout(() => { + // eslint-disable-next-line no-process-exit process.exit(1); }, 2000); } @@ -198,12 +200,12 @@ export class TraceWriter extends Service { TraceLabels.AGENT_DATA, `node ${pjson.name} v${pjson.version}` ); - addDefaultLabel(TraceLabels.GCE_HOSTNAME, hostname); + addDefaultLabel(TraceLabels.GCE_HOSTNAME, hostname!); if (instanceId) { addDefaultLabel(TraceLabels.GCE_INSTANCE_ID, instanceId); } const moduleName = this.config.serviceContext.service || hostname; - addDefaultLabel(TraceLabels.GAE_MODULE_NAME, moduleName); + addDefaultLabel(TraceLabels.GAE_MODULE_NAME, moduleName!); const moduleVersion = this.config.serviceContext.version; if (moduleVersion) { @@ -341,7 +343,7 @@ export class TraceWriter extends Service { if (this.projectId !== NO_PROJECT_ID_TOKEN) { afterProjectId(this.projectId); } else { - this.getProjectId().then(afterProjectId, (err: Error) => { + this.getProjectId().then(afterProjectId, () => { // Because failing to get a project ID means that the trace agent will // get disabled, there is a very small window for this code path to be // taken. For this reason we don't do anything more complex than just diff --git a/src/types.d.ts b/src/types.d.ts index 4ea61622a..40a7006d0 100644 --- a/src/types.d.ts +++ b/src/types.d.ts @@ -1,5 +1,20 @@ +// Copyright 2017 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + declare namespace NodeJS { export interface Global { + // eslint-disable-next-line @typescript-eslint/no-explicit-any _google_trace_agent: any; } export interface Process { @@ -10,9 +25,20 @@ declare namespace NodeJS { // NodeModule will be removed in favor of NodeJS.Module. // Currently, neither depends on the other, though NodeJS.Module's interface is // a superset of NodeModule. - function _resolveFilename(request: string, parent?: Module | NodeModule): string; - function _load(request: string, parent?: Module | NodeModule, isMain?: boolean): any; - function _resolveLookupPaths(request: string, parent?: Module | NodeModule): string; + function _resolveFilename( + request: string, + parent?: Module | NodeModule + ): string; + function _load( + request: string, + parent?: Module | NodeModule, + isMain?: boolean + // eslint-disable-next-line @typescript-eslint/no-explicit-any + ): any; + function _resolveLookupPaths( + request: string, + parent?: Module | NodeModule + ): string; } } @@ -23,8 +49,12 @@ declare module 'require-in-the-middle' { }; type OnRequireFn = (exports: T, name: string, basedir?: string) => T; } - function hook(modules: string[]|null, options: hook.Options|null, onRequire: hook.OnRequireFn): void; - function hook(modules: string[]|null, onRequire: hook.OnRequireFn): void; + function hook( + modules: string[] | null, + options: hook.Options | null, + onRequire: hook.OnRequireFn + ): void; + function hook(modules: string[] | null, onRequire: hook.OnRequireFn): void; function hook(onRequire: hook.OnRequireFn): void; export = hook; } diff --git a/src/util.ts b/src/util.ts index 4dfc0d2d0..0c2305554 100644 --- a/src/util.ts +++ b/src/util.ts @@ -17,7 +17,8 @@ import * as sourceMapSupport from 'source-map-support'; const { hexToDec, decToHex, -}: {[key: string]: (input: string) => string} = require('hex2dec'); +}: // eslint-disable-next-line @typescript-eslint/no-var-requires +{[key: string]: (input: string) => string} = require('hex2dec'); export {hexToDec, decToHex}; @@ -105,10 +106,11 @@ export function lastOf( ...otherValues: Array ): T { for (let i = otherValues.length - 1; i >= 0; i--) { - // tslint:disable:no-any + // eslint-disable-next-line @typescript-eslint/no-explicit-any if ( otherValues[i] !== null && otherValues[i] !== undefined && + // eslint-disable-next-line @typescript-eslint/no-explicit-any (typeof otherValues[i] !== 'number' || !isNaN(otherValues[i] as any)) ) { return otherValues[i] as T; diff --git a/system-test/trace-express.ts b/system-test/trace-express.ts index 079618d6c..5e670ce94 100644 --- a/system-test/trace-express.ts +++ b/system-test/trace-express.ts @@ -68,11 +68,12 @@ describe('express + datastore', () => { it('should be able to trace datastore (grpc) calls', async () => { // Build a unique path so that we get unique trace span names. const testPath = `/test-${uuid.v4()}`; + // eslint-disable-next-line @typescript-eslint/no-var-requires const express = require('express'); const datastore = new Datastore(); const app = express(); - // tslint:disable-next-line no-any + // eslint-disable-next-line @typescript-eslint/no-explicit-any app.get(testPath, async (_: {}, res: any) => { // Make a query to a non-existent datastore entity. This will get traced // regardless. @@ -82,7 +83,7 @@ describe('express + datastore', () => { res.status(200).send('hello\n'); }); - // tslint:disable-next-line no-any + // eslint-disable-next-line @typescript-eslint/no-explicit-any let server: any; await new Promise((resolve, reject) => { server = app.listen(8080, async () => { @@ -104,7 +105,7 @@ describe('express + datastore', () => { }); }); - // tslint:disable-next-line no-any + // eslint-disable-next-line @typescript-eslint/no-explicit-any function verifyTraces(traces: any[]) { assert.strictEqual(traces.length, 1, 'there should be exactly one trace'); const trace = traces[0]; @@ -113,7 +114,7 @@ describe('express + datastore', () => { 'should be at least 2 spans: parent, child' ); const parent = trace.spans[0]; - // tslint:disable-next-line no-any + // eslint-disable-next-line @typescript-eslint/no-explicit-any const child = trace.spans.find((span: any) => { const urlLabelValue = span.labels[tracer.labels.HTTP_URL_LABEL_KEY]; return ( diff --git a/test/logger.ts b/test/logger.ts index 3fa370756..00e7f69e8 100644 --- a/test/logger.ts +++ b/test/logger.ts @@ -20,7 +20,7 @@ const PASS_THROUGH_LOG_LEVEL = Number(process.env.GCLOUD_TEST_LOG_LEVEL || 0); // tslint:disable-next-line:variable-name const OriginalLogger = Logger; -// tslint:disable-next-line:no-any +// eslint-disable-next-line @typescript-eslint/no-explicit-any type LoggerFunction = (message: any, ...args: any[]) => R; export class TestLogger extends Logger { @@ -40,8 +40,10 @@ export class TestLogger extends Logger { private makeLoggerFn(logLevel: keyof Logger): LoggerFunction { // TODO(kjin): When we drop support for Node 4, use spread args. + // eslint-disable-next-line @typescript-eslint/no-this-alias const that = this; - return function(this: null) { + return function (this: null) { + // eslint-disable-next-line prefer-rest-params const args = Array.prototype.slice.call(arguments, 0); that.logs[logLevel].push(args.join(' ')); that.innerLogger[logLevel].apply(this, args); diff --git a/test/mysql-config.ts b/test/mysql-config.ts index f481202d8..838cded50 100644 --- a/test/mysql-config.ts +++ b/test/mysql-config.ts @@ -16,5 +16,5 @@ export = { host: 'localhost', user: 'root', password: 'Password12!', - database: 'test' + database: 'test', }; diff --git a/test/non-interference/express-e2e.js b/test/non-interference/express-e2e.js index 2e53d85e0..38b606f6a 100644 --- a/test/non-interference/express-e2e.js +++ b/test/non-interference/express-e2e.js @@ -14,20 +14,27 @@ 'use strict'; -var assert = require('assert'); -var cp = require('child_process'); -var glob = require('glob'); -var path = require('path'); -var tmp = require('tmp'); +const assert = require('assert'); +const cp = require('child_process'); +const glob = require('glob'); +const path = require('path'); +const tmp = require('tmp'); -var expressVersion = '4.15.3'; +const expressVersion = '4.15.3'; // Setup -var express_dir = tmp.dirSync().name; -cp.execFileSync('git', ['clone', '--branch', expressVersion, - 'https://github.com/strongloop/express.git', '--depth', '1', express_dir]); -var test_glob = path.join(express_dir, 'test', '*.js'); -var error; +const express_dir = tmp.dirSync().name; +cp.execFileSync('git', [ + 'clone', + '--branch', + expressVersion, + 'https://github.com/strongloop/express.git', + '--depth', + '1', + express_dir, +]); +const test_glob = path.join(express_dir, 'test', '*.js'); +let error; process.chdir(express_dir); // Remove name to allow for cyclic dependency @@ -36,24 +43,27 @@ cp.execFileSync('sed', ['-i.bak', 's/"express"/"e"/', 'package.json']); // Install express as its own dependency console.log('Installing express dependencies'); -cp.execFileSync('npm', ['--version'], { stdio: 'inherit' }); +cp.execFileSync('npm', ['--version'], {stdio: 'inherit'}); cp.execFileSync('npm', ['install']); cp.execFileSync('npm', ['install', 'express@' + expressVersion]); // Reformat tests to use newly installed express console.log('Reformatting tests'); -glob(test_glob, function(err, files) { +glob(test_glob, (err, files) => { error = error || err; - for (var i = 0; i < files.length; i++) { - cp.execFileSync('sed', ['-i', 's#require(\'\\.\\./\\?\')#require(\'express\')#', - files[i]]); + for (let i = 0; i < files.length; i++) { + cp.execFileSync('sed', [ + '-i', + "s#require('\\.\\./\\?')#require('express')#", + files[i], + ]); } // Run tests console.log('Running tests'); - var results = cp.spawnSync('mocha', [ + const results = cp.spawnSync('mocha', [ '--require', path.join(__dirname, 'start-agent.js'), - test_glob + test_glob, ]); console.log(results.output[1].toString() || results.output[2].toString()); error = error || results.status; diff --git a/test/non-interference/http-e2e.js b/test/non-interference/http-e2e.js index 4c08b9d34..33602945a 100644 --- a/test/non-interference/http-e2e.js +++ b/test/non-interference/http-e2e.js @@ -14,63 +14,82 @@ 'use strict'; -var assert = require('assert'); -var cp = require('child_process'); -var fs = require('fs'); -var glob = require('glob'); -var path = require('path'); -var tmp = require('tmp'); +const assert = require('assert'); +const cp = require('child_process'); +const fs = require('fs'); +const glob = require('glob'); +const path = require('path'); +const tmp = require('tmp'); // Setup -var node_dir = tmp.dirSync().name; -cp.execFileSync('git', ['clone', '--branch', process.version, - 'https://github.com/nodejs/node.git', '--depth', '1', node_dir]); +const node_dir = tmp.dirSync().name; +cp.execFileSync('git', [ + 'clone', + '--branch', + process.version, + 'https://github.com/nodejs/node.git', + '--depth', + '1', + node_dir, +]); fs.mkdirSync(path.join(node_dir, 'test', 'tmp')); console.log('Turning off global checks'); // The use of the -i flag as '-i.bak' to specify a backup extension of '.bak' // is needed to ensure that the command works on both Linux and OS X -var testCommonPath = [ - path.join(node_dir, 'test', 'common', 'index.js'), - path.join(node_dir, 'test', 'common.js') -].find(function(candidatePath) { - return fs.existsSync(candidatePath); +const testCommonPath = [ + path.join(node_dir, 'test', 'common', 'index.js'), + path.join(node_dir, 'test', 'common.js'), +].find(candidatePath => { + return fs.existsSync(candidatePath); }); if (!testCommonPath) { - console.error('No common.js or common/index.js found in test directory'); - process.exit(1); + console.error('No common.js or common/index.js found in test directory'); + // eslint-disable-next-line no-process-exit + process.exit(1); } -cp.execFileSync('sed', ['-i.bak', 's/exports.globalCheck = true/' + - 'exports.globalCheck = false/g', testCommonPath]); +cp.execFileSync('sed', [ + '-i.bak', + 's/exports.globalCheck = true/' + 'exports.globalCheck = false/g', + testCommonPath, +]); // Test files for http, https, and http2. -var test_glob = path.join(node_dir, 'test', 'parallel', 'test-http?(s|2)-*.js'); +const test_glob = path.join( + node_dir, + 'test', + 'parallel', + 'test-http?(s|2)-*.js' +); // Run tests console.log('Running tests'); -var gcloud_require = - 'var proxyquire = require(\'' + - path.join(__dirname, '../../node_modules/proxyquire') + - '\');' + - 'proxyquire(\'' + - path.join(__dirname, '../../node_modules/gcp-metadata') + - '\', { \'retry-request\': require(\'' + - path.join(__dirname, '../../node_modules/request') + - '\')});' + - 'require(\'' + path.join(__dirname, '../..') + - '\').start();'; -glob(test_glob, function(err, files) { - var errors = 0; - var testCount; +const gcloud_require = + "var proxyquire = require('" + + path.join(__dirname, '../../node_modules/proxyquire') + + "');" + + "proxyquire('" + + path.join(__dirname, '../../node_modules/gcp-metadata') + + "', { 'retry-request': require('" + + path.join(__dirname, '../../node_modules/request') + + "')});" + + "require('" + + path.join(__dirname, '../..') + + "').start();"; +glob(test_glob, (err, files) => { + let errors = 0; + let testCount; for (testCount = 0; testCount < files.length; testCount++) { // parser-bad-ref: Relies on valgrind gc // max-headers-count: Breaks because we introduce new headers // parser-free: Breaks because we send outgoing http on startup // response-splitting: Breaks because we introduce new headers // http-chunk-problem: Relies on shasum of own file - if (files[testCount].indexOf('parser-bad-ref') !== -1 || - files[testCount].indexOf('max-headers-count') !== -1 || - files[testCount].indexOf('parser-free') !== -1 || - files[testCount].indexOf('response-splitting') !== -1 || - files[testCount].indexOf('http-chunk-problem') !== -1) { + if ( + files[testCount].indexOf('parser-bad-ref') !== -1 || + files[testCount].indexOf('max-headers-count') !== -1 || + files[testCount].indexOf('parser-free') !== -1 || + files[testCount].indexOf('response-splitting') !== -1 || + files[testCount].indexOf('http-chunk-problem') !== -1 + ) { console.log('Skipped: ' + files[testCount]); continue; } @@ -82,18 +101,32 @@ glob(test_glob, function(err, files) { // The use of the -i flag as '-i.bak' to specify a backup extension of // '.bak' is needed to ensure that the command works on both Linux and OS X - cp.execFileSync('sed', ['-i.bak', 's#\'use strict\';#' + - '\'use strict\';' + gcloud_require + '#g', files[testCount]]); + cp.execFileSync('sed', [ + '-i.bak', + "s#'use strict';#" + "'use strict';" + gcloud_require + '#g', + files[testCount], + ]); if (cp.spawnSync('grep', ['-q', gcloud_require, files[testCount]]).status) { - cp.execSync('echo "' + gcloud_require + '" | cat - ' + files[testCount] + - ' >' + files[testCount] + '.instru.js' + '&& mv ' + files[testCount] + - '.instru.js' + ' ' + files[testCount]); + cp.execSync( + 'echo "' + + gcloud_require + + '" | cat - ' + + files[testCount] + + ' >' + + files[testCount] + + '.instru.js' + + '&& mv ' + + files[testCount] + + '.instru.js' + + ' ' + + files[testCount] + ); } - var results = cp.spawnSync('node', [flags, files[testCount]]); + const results = cp.spawnSync('node', [flags, files[testCount]]); if (results.status) { console.log('Failed: ' + files[testCount]); - errors ++; + errors++; console.log(results.stderr.toString()); } else { console.log('Passed: ' + files[testCount]); diff --git a/test/non-interference/restify-e2e.js b/test/non-interference/restify-e2e.js index 5accccdb5..fb2388cfd 100644 --- a/test/non-interference/restify-e2e.js +++ b/test/non-interference/restify-e2e.js @@ -14,20 +14,27 @@ 'use strict'; -var assert = require('assert'); -var cp = require('child_process'); -var glob = require('glob'); -var path = require('path'); -var tmp = require('tmp'); +const assert = require('assert'); +const cp = require('child_process'); +const glob = require('glob'); +const path = require('path'); +const tmp = require('tmp'); -var branchVersion = '4.x'; -var restifyVersion = branchVersion; +const branchVersion = '4.x'; +const restifyVersion = branchVersion; // Setup -var restify_dir = tmp.dirSync().name; -cp.execFileSync('git', ['clone', '--branch', branchVersion, - 'https://github.com/restify/node-restify.git', '--depth', '1', restify_dir]); -var test_glob = path.join(restify_dir, 'test', '*.test.js'); +const restify_dir = tmp.dirSync().name; +cp.execFileSync('git', [ + 'clone', + '--branch', + branchVersion, + 'https://github.com/restify/node-restify.git', + '--depth', + '1', + restify_dir, +]); +const test_glob = path.join(restify_dir, 'test', '*.test.js'); process.chdir(restify_dir); // Remove name to allow for cyclic dependency @@ -41,26 +48,45 @@ cp.execFileSync('npm', ['install', 'restify@' + restifyVersion]); // Reformat tests to use newly installed restify console.log('Reformatting tests'); -var gcloud_require = 'require(\'' + path.join(__dirname, '..', '..') + - '\').start({ forceNewAgent_: true, samplingRate: 0, projectId: \'0\', logLevel: 1 });'; -glob(test_glob, function(err, files) { - for (var i = 0; i < files.length; i++) { +const gcloud_require = + "require('" + + path.join(__dirname, '..', '..') + + "').start({ forceNewAgent_: true, samplingRate: 0, projectId: '0', logLevel: 1 });"; +glob(test_glob, (err, files) => { + for (let i = 0; i < files.length; i++) { if (i === 0) { - cp.execFileSync('sed', ['-i.bak', 's#\'use strict\';#' + - '\'use strict\'; ' + gcloud_require + '#g', files[i]]); + cp.execFileSync('sed', [ + '-i.bak', + "s#'use strict';#" + "'use strict'; " + gcloud_require + '#g', + files[i], + ]); if (cp.spawnSync('grep', ['-q', gcloud_require, files[i]]).status) { - cp.execSync('echo "' + gcloud_require + '" | cat - ' + files[i] + - ' >' + files[i] + '.instru.js' + '&& mv ' + files[i] + - '.instru.js' + ' ' + files[i]); + cp.execSync( + 'echo "' + + gcloud_require + + '" | cat - ' + + files[i] + + ' >' + + files[i] + + '.instru.js' + + '&& mv ' + + files[i] + + '.instru.js' + + ' ' + + files[i] + ); } } - cp.execFileSync('sed', ['-i.bak', 's#require(\'\\.\\./lib\')#require(\'restify\')#', - files[i]]); + cp.execFileSync('sed', [ + '-i.bak', + "s#require('\\.\\./lib')#require('restify')#", + files[i], + ]); } // Run tests console.log('Running tests'); - var results = cp.spawnSync('make', ['test']); - var output = results.output[1].toString() || results.output[2].toString(); + const results = cp.spawnSync('make', ['test']); + const output = results.output[1].toString() || results.output[2].toString(); console.log(output); assert(output.indexOf('FAILURES:') === -1); assert(output.indexOf('OK:') !== -1); diff --git a/test/non-interference/start-agent.js b/test/non-interference/start-agent.js index 0fce603d8..759535683 100644 --- a/test/non-interference/start-agent.js +++ b/test/non-interference/start-agent.js @@ -11,10 +11,11 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. + 'use strict'; -var shimmer = require('shimmer'); -var util = require('../../build/src/util.js'); +const shimmer = require('shimmer'); +const util = require('../../build/src/util.js'); // Stub generateTraceContext so that it always returns the same thing. // This is because web framework unit tests check that similar/identical // incoming requests yield the same outgoing headers (for example, express @@ -22,13 +23,13 @@ var util = require('../../build/src/util.js'); // same response headers). // This problem doesn't manifest when samplingRate is set to default, because // traces are almost never generated. -shimmer.wrap(util, 'generateTraceContext', function() { - return function() { +shimmer.wrap(util, 'generateTraceContext', () => { + return function () { return 'ffeeddccbbaa99887766554433221100/0?o=1'; }; }); require('../..').start({ projectId: '0', logLevel: 1, - samplingRate: 0 + samplingRate: 0, }); diff --git a/test/override-gcp-metadata.ts b/test/override-gcp-metadata.ts index 5997f0d0c..91f137d57 100644 --- a/test/override-gcp-metadata.ts +++ b/test/override-gcp-metadata.ts @@ -16,18 +16,18 @@ import * as rax from 'retry-axios'; import * as shimmer from 'shimmer'; -import { AxiosRequestConfig } from 'axios'; +import {AxiosRequestConfig} from 'axios'; shimmer.wrap(rax, 'attach', attach => { - return (arg) => { + return arg => { if (arg) { shimmer.wrap(arg, 'request', request => { return (config: AxiosRequestConfig) => { delete config['raxConfig']; return request(config); - } + }; }); } return attach(arg); - } + }; }); diff --git a/test/pg-config.ts b/test/pg-config.ts index 65ac77817..ab47d3a68 100644 --- a/test/pg-config.ts +++ b/test/pg-config.ts @@ -15,5 +15,5 @@ export = { user: 'postgres', password: 'Password12!', - database: 'test' + database: 'test', }; diff --git a/test/plugins/common.ts b/test/plugins/common.ts index 9c5b82d72..0639203c6 100644 --- a/test/plugins/common.ts +++ b/test/plugins/common.ts @@ -11,24 +11,23 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. -'use strict'; import '../override-gcp-metadata'; import {v1 as stackdriverPropagation} from '@opencensus/propagation-stackdriver'; -import { cls, TraceCLS } from '../../src/cls'; -import { StackdriverTracer } from '../../src/trace-api'; -import { traceWriter } from '../../src/trace-writer'; -import { SpanType } from '../../src/constants'; -import { TestLogger } from '../logger'; -import { getBaseConfig } from '../utils'; -import { alwaysTrace } from '../../src/tracing-policy'; +import {cls, TraceCLS} from '../../src/cls'; +import {StackdriverTracer} from '../../src/trace-api'; +import {traceWriter} from '../../src/trace-writer'; +import {SpanType} from '../../src/constants'; +import {TestLogger} from '../logger'; +import {getBaseConfig} from '../utils'; +import {alwaysTrace} from '../../src/tracing-policy'; -var semver = require('semver'); +import * as semver from 'semver'; +import * as trace from '../../src'; -var trace = require('../../..'); if (semver.satisfies(process.version, '>=8')) { // Monkeypatch Mocha's it() to create a fresh context with each test case. - var oldIt = global.it; + const oldIt = global.it; global.it = Object.assign(function it(title, fn) { // it.skip calls it without a function argument if (!fn) { @@ -36,54 +35,59 @@ if (semver.satisfies(process.version, '>=8')) { } function wrappedFn() { if (cls.exists()) { - return cls.get().runWithContext(() => fn.apply(this, arguments), TraceCLS.UNCORRELATED); + return cls.get().runWithContext( + // eslint-disable-next-line prefer-rest-params + () => fn.apply(this, arguments), + TraceCLS.UNCORRELATED + ); } else { + // eslint-disable-next-line prefer-rest-params return fn.apply(this, arguments); } - }; + } // Mocha uses a function's length property to determine whether the // test case is async or not. Object.defineProperty(wrappedFn, 'length', { enumerable: false, configurable: true, writable: false, - value: fn.length + value: fn.length, }); return oldIt.call(this, title, wrappedFn); }, oldIt); } -var assert = require('assert'); -var fs = require('fs'); -var path = require('path'); -var { teenyRequest: request } = require('teeny-request'); -var shimmer = require('shimmer'); +import * as assert from 'assert'; +import * as shimmer from 'shimmer'; +import {teenyRequest} from 'teeny-request'; -var testTraceAgent: StackdriverTracer; -shimmer.wrap(trace, 'start', function(original) { - return function() { - var result = original.apply(this, arguments); +let testTraceAgent: StackdriverTracer; +shimmer.wrap(trace, 'start', original => { + return function () { + // eslint-disable-next-line prefer-rest-params + const result = original.apply(this, arguments); testTraceAgent = new StackdriverTracer('test'); testTraceAgent.enable(getBaseConfig(), { tracePolicy: alwaysTrace(), logger: new TestLogger(), - propagation: stackdriverPropagation + propagation: stackdriverPropagation, }); return result; }; }); -var SERVER_PORT = 9042; +const SERVER_PORT = 9042; function replaceFunction(target, prop, fn) { - var old = target[prop]; + const old = target[prop]; target[prop] = fn; return old; } function replaceWarnLogger(fn) { - var agent = trace.get(); - return replaceFunction(agent.logger, 'warn', fn); + const agent = trace.get(); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return replaceFunction((agent as any).logger, 'warn', fn); } /** @@ -98,16 +102,20 @@ function getTraces() { } function getMatchingSpan(predicate) { - var spans = getMatchingSpans(predicate); - assert.strictEqual(spans.length, 1, - 'predicate did not isolate a single span'); + const spans = getMatchingSpans(predicate); + assert.strictEqual( + spans.length, + 1, + 'predicate did not isolate a single span' + ); return spans[0]; } function getMatchingSpans(predicate) { - var list: any[] = []; - getTraces().forEach(function(trace) { - trace.spans.forEach(function(span) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const list: any[] = []; + getTraces().forEach(trace => { + trace.spans.forEach(span => { if (predicate(span)) { list.push(span); } @@ -117,8 +125,8 @@ function getMatchingSpans(predicate) { } function runInTransaction(fn) { - testTraceAgent.runInRootSpan({ name: 'outer' }, function(span) { - return fn(function() { + testTraceAgent.runInRootSpan({name: 'outer'}, span => { + return fn(() => { assert.strictEqual(span.type, SpanType.ROOT); span.endSpan(); }); @@ -130,16 +138,16 @@ function runInTransaction(fn) { // Returns a method which, when called, closes the child span // right away and cancels callback from being called after the duration. function createChildSpan(cb, duration) { - var span = testTraceAgent.createChildSpan({ name: 'inner' }); + const span = testTraceAgent.createChildSpan({name: 'inner'}); assert.ok(span); - var t = setTimeout(function() { + const t = setTimeout(() => { assert.strictEqual(span.type, SpanType.CHILD); span.endSpan(); if (cb) { cb(); } }, duration); - return function() { + return function () { assert.strictEqual(span.type, SpanType.CHILD); span.endSpan(); clearTimeout(t); @@ -147,11 +155,11 @@ function createChildSpan(cb, duration) { } function installNoopTraceWriter() { - traceWriter.get().writeTrace = function() {}; + traceWriter.get().writeTrace = function () {}; } function avoidTraceWriterAuth() { - traceWriter.get().request = request; + traceWriter.get().request = teenyRequest; } function hasContext() { diff --git a/test/plugins/test-cls-bluebird.ts b/test/plugins/test-cls-bluebird.ts index 61471754d..fe98f5486 100644 --- a/test/plugins/test-cls-bluebird.ts +++ b/test/plugins/test-cls-bluebird.ts @@ -13,7 +13,7 @@ // limitations under the License. import * as assert from 'assert'; -import {describe, it} from 'mocha'; +import {describe, it, before, after} from 'mocha'; import {bluebird_3 as BluebirdPromise} from '../../src/plugins/types'; import {Trace} from '../../src/trace'; @@ -160,7 +160,7 @@ describe('Patch plugin for bluebird', () => { } as TestCase, ]; - // tslint:disable-next-line:no-any + // eslint-disable-next-line @typescript-eslint/no-explicit-any testCases.forEach((testCase: TestCase) => { it(`enables context propagation in the same way as native promises for test case: ${testCase.description}`, async () => { const actual = ( diff --git a/test/plugins/test-plugins-interop-mongo-express.ts b/test/plugins/test-plugins-interop-mongo-express.ts index 7da4c8602..196ed684c 100644 --- a/test/plugins/test-plugins-interop-mongo-express.ts +++ b/test/plugins/test-plugins-interop-mongo-express.ts @@ -11,48 +11,49 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. -'use strict'; // Prereqs: // Start docker daemon // ex) docker -d // Run a mongo image binding the mongo port // ex) docker run -p 27017:27017 -d mongo -var common = require('./common'/*.js*/); +// eslint-disable-next-line @typescript-eslint/no-var-requires +const common = require('./common' /*.js*/); -var assert = require('assert'); -var http = require('http'); +import * as assert from 'assert'; +import * as http from 'http'; +import {describe, it, before} from 'mocha'; -var server; +let server; -describe('mongodb + express', function() { - var agent; - var oldWarn; - var mongoose; - var express; - before(function() { - agent = require('../../..').start({ projectId: '0' }); +describe('mongodb + express', () => { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + let agent; + let oldWarn; + let mongoose; + let express; + before(() => { + agent = require('../../..').start({projectId: '0'}); express = require('./fixtures/express4'); mongoose = require('./fixtures/mongoose4'); - oldWarn = common.replaceWarnLogger( - function(error) { - assert(error.indexOf('mongo') === -1, error); + oldWarn = common.replaceWarnLogger(error => { + assert(error.indexOf('mongo') === -1, error); }); }); - it('should not lose context on startup', function(done) { - var app = express(); - app.get('/', function (req, res) { - mongoose.connect('mongodb://localhost:27017/testdb', function(err) { + it('should not lose context on startup', done => { + const app = express(); + app.get('/', (req, res) => { + mongoose.connect('mongodb://localhost:27017/testdb', err => { assert(!err, 'Skipping: no mongo server found at localhost:27017.'); - mongoose.connection.close(function(err) { + mongoose.connection.close(err => { assert(!err); res.sendStatus(200); }); }); }); - server = app.listen(common.serverPort, function() { - http.get({port: common.serverPort}, function(res) { + server = app.listen(common.serverPort, () => { + http.get({port: common.serverPort}, () => { server.close(); common.cleanTraces(); common.replaceWarnLogger(oldWarn); diff --git a/test/plugins/test-plugins-multi-version.ts b/test/plugins/test-plugins-multi-version.ts index 965918fd9..fec8306e2 100644 --- a/test/plugins/test-plugins-multi-version.ts +++ b/test/plugins/test-plugins-multi-version.ts @@ -11,51 +11,55 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. -'use strict'; // Prereqs: // Start docker daemon // ex) docker -d // Run a redis image binding the redis port // ex) docker run -p 6379:6379 -d redis -var assert = require('assert'); -var common = require('./common'/*.js*/); +import * as assert from 'assert'; +import {describe, it, before, after} from 'mocha'; +// eslint-disable-next-line @typescript-eslint/no-var-requires +const common = require('./common' /*.js*/); -describe('multiple instrumentations of the same module', function() { - var agent; - var clientv0; - var clientv2; +describe('multiple instrumentations of the same module', () => { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + let agent; + let clientv0; + let clientv2; - before(function() { + before(() => { agent = require('../../..').start({ projectId: '0', enhancedDatabaseReporting: true, - samplingRate: 0 + samplingRate: 0, }); clientv0 = require('./fixtures/redis0.12').createClient(); - clientv0.on('error', function(err) { + clientv0.on('error', err => { assert(false, 'redisv0 error ' + err); }); clientv2 = require('./fixtures/redis2.x').createClient(); - clientv2.on('error', function(err) { + clientv2.on('error', err => { assert(false, 'redisv2 error ' + err); }); }); - after(function(done) { - clientv0.quit(function() { - clientv2.quit(function() { + after(done => { + clientv0.quit(() => { + clientv2.quit(() => { done(); }); }); }); - it('should record spans', function(done) { - common.runInTransaction(function(endTransaction) { - clientv0.get('v0', function(err, n) { - clientv2.get('v2', function(err, n) { + it('should record spans', done => { + common.runInTransaction(endTransaction => { + clientv0.get('v0', () => { + clientv2.get('v2', () => { endTransaction(); - var spans = common.getMatchingSpans(redisPredicate.bind(null, 'redis-get')); + const spans = common.getMatchingSpans( + redisPredicate.bind(null, 'redis-get') + ); assert.strictEqual(spans.length, 2); assert.strictEqual(spans[0].labels.arguments, '["v0"]'); assert.strictEqual(spans[0].labels.command, 'get'); @@ -69,8 +73,7 @@ describe('multiple instrumentations of the same module', function() { }); function redisPredicate(id, span) { - return span.name.length >= id.length && - span.name.substr(0, id.length) === id; + return span.name.length >= id.length && span.name.substr(0, id.length) === id; } export default {}; diff --git a/test/plugins/test-trace-generic-pool.ts b/test/plugins/test-trace-generic-pool.ts index f88d0a4c4..4f4f026cf 100644 --- a/test/plugins/test-trace-generic-pool.ts +++ b/test/plugins/test-trace-generic-pool.ts @@ -11,59 +11,59 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. -'use strict'; import {FORCE_NEW} from '../../src/util'; - -var assert = require('assert'); -var common = require('./common'); -var semver = require('semver'); - -describe('generic-pool2', function() { - var ROOT_SPAN = 'root-span'; - var CHILD_SPAN_1 = 'child-span-1'; - var CHILD_SPAN_2 = 'child-span-2'; - - var api; - var genericPool; - before(function() { +import * as assert from 'assert'; +import * as common from './common'; +import * as semver from 'semver'; +import {describe, it, before, after} from 'mocha'; + +describe('generic-pool2', () => { + const ROOT_SPAN = 'root-span'; + const CHILD_SPAN_1 = 'child-span-1'; + const CHILD_SPAN_2 = 'child-span-2'; + + let api; + let genericPool; + before(() => { api = require('../../..').start({ projectId: '0', samplingRate: 0, - [FORCE_NEW]: true + [FORCE_NEW]: true, }); genericPool = require('./fixtures/generic-pool2'); }); - after(function() { - common.cleanTraces(); + after(() => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (common as any).cleanTraces(); }); - it('preserves context', function(done) { - var config = { + it('preserves context', done => { + const config = { name: 'generic-pool2 test', - create: function(callback) { - callback(function() { - var childSpan = api.createChildSpan({ name: CHILD_SPAN_2 }); + create: function (callback) { + callback(() => { + const childSpan = api.createChildSpan({name: CHILD_SPAN_2}); assert.ok(childSpan); childSpan.endSpan(); }); }, - destroy: function(fn) { - } + destroy: function () {}, }; - var pool = new genericPool.Pool(config); - api.runInRootSpan({ name: ROOT_SPAN }, function(span) { - pool.acquire(function(err, fn) { + const pool = new genericPool.Pool(config); + api.runInRootSpan({name: ROOT_SPAN}, span => { + pool.acquire((err, fn) => { assert.ifError(err); - var childSpan = api.createChildSpan({ name: CHILD_SPAN_1 }); + const childSpan = api.createChildSpan({name: CHILD_SPAN_1}); assert.ok(childSpan); fn(); childSpan.endSpan(); span.endSpan(); - var spans = common.getTraces(api)[0].spans; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const spans = (common as any).getTraces(api)[0].spans; assert.ok(spans); assert.strictEqual(spans.length, 3); assert.strictEqual(spans[0].name, ROOT_SPAN); @@ -76,81 +76,89 @@ describe('generic-pool2', function() { }); }); -describe('generic-pool3', function() { - var agent; - var genericPool; +describe('generic-pool3', () => { + let agent; + let genericPool; if (semver.satisfies(process.version, '<4')) { - console.log('Skipping testing generic-pool@3 on Node.js version ' + - process.version + ' that predates version 4.'); + console.log( + 'Skipping testing generic-pool@3 on Node.js version ' + + process.version + + ' that predates version 4.' + ); return; } - before(function() { + before(() => { agent = require('../../..').start({ projectId: '0', samplingRate: 0, - [FORCE_NEW]: true + [FORCE_NEW]: true, }); genericPool = require('./fixtures/generic-pool3'); }); - after(function() { - common.cleanTraces(); + after(() => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (common as any).cleanTraces(); }); - it ('preserves context', function() { - var ROOT_SPAN = 'root-span'; - var CHILD_SPAN_1 = 'child-span-1'; - var CHILD_SPAN_2 = 'child-span-2'; - var CHILD_SPAN_3 = 'child-span-3'; + it('preserves context', () => { + const ROOT_SPAN = 'root-span'; + const CHILD_SPAN_1 = 'child-span-1'; + const CHILD_SPAN_2 = 'child-span-2'; + const CHILD_SPAN_3 = 'child-span-3'; - var factory = { - create: function() { - return new Promise(function(resolve, reject) { - resolve(function(input) { + const factory = { + create: function () { + return new Promise(resolve => { + resolve(input => { assert.strictEqual(input, 'SomeInput'); - var childSpan = agent.createChildSpan({ name: CHILD_SPAN_2 }); + const childSpan = agent.createChildSpan({name: CHILD_SPAN_2}); assert.ok(childSpan); childSpan.endSpan(); }); }); }, - destroy: function(fn) { - return new Promise(function(resolve) { + destroy: function () { + return new Promise(resolve => { resolve(); }); - } + }, }; - var opts = { + const opts = { max: 1, - min: 1 + min: 1, }; - var pool = genericPool.createPool(factory, opts); - - var promise; - agent.runInRootSpan({ name: ROOT_SPAN }, function(rootSpan) { - promise = pool.acquire().then(function(fn) { - var childSpan = agent.createChildSpan({ name: CHILD_SPAN_1 }); - assert.ok(childSpan); - fn('SomeInput'); - childSpan.endSpan(); - }).then(function() { - var childSpan = agent.createChildSpan({ name: CHILD_SPAN_3 }); - assert.ok(childSpan); - childSpan.endSpan(); - rootSpan.endSpan(); + const pool = genericPool.createPool(factory, opts); - var spans = common.getTraces()[0].spans; - assert.ok(spans); - assert.strictEqual(spans.length, 4); - assert.strictEqual(spans[0].name, ROOT_SPAN); - assert.strictEqual(spans[1].name, CHILD_SPAN_1); - assert.strictEqual(spans[2].name, CHILD_SPAN_2); - assert.strictEqual(spans[3].name, CHILD_SPAN_3); - }); + let promise; + agent.runInRootSpan({name: ROOT_SPAN}, rootSpan => { + promise = pool + .acquire() + .then(fn => { + const childSpan = agent.createChildSpan({name: CHILD_SPAN_1}); + assert.ok(childSpan); + fn('SomeInput'); + childSpan.endSpan(); + }) + .then(() => { + const childSpan = agent.createChildSpan({name: CHILD_SPAN_3}); + assert.ok(childSpan); + childSpan.endSpan(); + rootSpan.endSpan(); + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const spans = (common as any).getTraces()[0].spans; + assert.ok(spans); + assert.strictEqual(spans.length, 4); + assert.strictEqual(spans[0].name, ROOT_SPAN); + assert.strictEqual(spans[1].name, CHILD_SPAN_1); + assert.strictEqual(spans[2].name, CHILD_SPAN_2); + assert.strictEqual(spans[3].name, CHILD_SPAN_3); + }); }); return promise; diff --git a/test/plugins/test-trace-google-gax.ts b/test/plugins/test-trace-google-gax.ts index ed758673c..ce1408514 100644 --- a/test/plugins/test-trace-google-gax.ts +++ b/test/plugins/test-trace-google-gax.ts @@ -34,7 +34,7 @@ */ import * as assert from 'assert'; -import {describe, it} from 'mocha'; +import {it, before, after} from 'mocha'; import * as testTraceModule from '../trace'; import {describeInterop} from '../utils'; @@ -78,13 +78,10 @@ describeInterop('google-gax', fixture => { testTraceModule.setPluginLoaderForTest(testTraceModule.TestPluginLoader); }); - it(`doesn't break context`, done => { + it("doesn't break context", done => { const authPromise = Promise.resolve(((args, metadata, opts, cb) => { // Simulate an RPC. - testTraceModule - .get() - .createChildSpan({name: 'in-request'}) - .endSpan(); + testTraceModule.get().createChildSpan({name: 'in-request'}).endSpan(); setImmediate(() => cb(null, {})); }) as InnerApiCall<{}, {}>); const apiCall = googleGax.createApiCall(authPromise, { @@ -94,10 +91,7 @@ describeInterop('google-gax', fixture => { testTraceModule.get().runInRootSpan({name: 'root'}, root => { apiCall({}, {timeout: 20}, err => { assert.ifError(err); - testTraceModule - .get() - .createChildSpan({name: 'in-callback'}) - .endSpan(); + testTraceModule.get().createChildSpan({name: 'in-callback'}).endSpan(); root.endSpan(); // Both children should be nested under the root span where the API call diff --git a/test/plugins/test-trace-grpc.ts b/test/plugins/test-trace-grpc.ts index 0cfb174c6..433c080c4 100644 --- a/test/plugins/test-trace-grpc.ts +++ b/test/plugins/test-trace-grpc.ts @@ -11,36 +11,41 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. -'use strict'; -import { cls } from '../../src/cls'; -import { Constants } from '../../src/constants'; -import { TraceLabels } from '../../src/trace-labels'; +import {cls} from '../../src/cls'; +import {Constants} from '../../src/constants'; +import {TraceLabels} from '../../src/trace-labels'; import * as TracingPolicy from '../../src/tracing-policy'; import * as util from '../../src/util'; import * as assert from 'assert'; -import {describe, it} from 'mocha'; -import { asRootSpanData, describeInterop, DEFAULT_SPAN_DURATION, assertSpanDuration } from '../utils'; -import { Span } from '../../src/plugin-types'; -import { FORCE_NEW } from '../../src/util'; - -var shimmer = require('shimmer'); -var common = require('./common'/*.js*/); - -var protoFile = __dirname + '/../fixtures/test-grpc.proto'; -var grpcPort = 50051; +import {it, before, after, afterEach} from 'mocha'; +import { + asRootSpanData, + describeInterop, + DEFAULT_SPAN_DURATION, + assertSpanDuration, +} from '../utils'; +import {Span} from '../../src/plugin-types'; +import {FORCE_NEW} from '../../src/util'; + +import * as shimmer from 'shimmer'; +// eslint-disable-next-line @typescript-eslint/no-var-requires +const common = require('./common' /*.js*/); + +const protoFile = __dirname + '/../fixtures/test-grpc.proto'; +const grpcPort = 50051; // When received in the 'n' field, the server should perform the appropriate action // (For client streaming methods, this would be the total sum of all requests) -var SEND_METADATA = 131; -var EMIT_ERROR = 13412; +const SEND_METADATA = 131; +const EMIT_ERROR = 13412; // Regular expression matching client-side metadata labels -var metadataRegExp = /"a":"b"/; +const metadataRegExp = /"a":"b"/; // Whether asserts in checkServerMetadata should be run // Turned on only for the test that checks propagated trace context -var checkMetadata; +let checkMetadata; // When trace IDs are checked in checkServerMetadata, they should have this // exact value. This only applies in the test "should support distributed @@ -49,10 +54,12 @@ const COMMON_TRACE_ID = 'ffeeddccbbaa99887766554433221100'; function checkServerMetadata(metadata) { if (checkMetadata) { - var traceContext = metadata.getMap()[Constants.TRACE_CONTEXT_GRPC_METADATA_NAME]; - var parsedContext = util.deserializeTraceContext(traceContext); + const traceContext = metadata.getMap()[ + Constants.TRACE_CONTEXT_GRPC_METADATA_NAME + ]; + const parsedContext = util.deserializeTraceContext(traceContext); assert.ok(parsedContext); - var root = asRootSpanData(cls.get().getContext() as Span); + const root = asRootSpanData(cls.get().getContext() as Span); // Check that we were able to propagate trace context. assert.strictEqual(parsedContext!.traceId, COMMON_TRACE_ID); assert.strictEqual(root.trace.traceId, COMMON_TRACE_ID); @@ -63,45 +70,45 @@ function checkServerMetadata(metadata) { } function startServer(proto, grpc, agent, metadata, trailing_metadata) { - var _server = new grpc.Server(); + const _server = new grpc.Server(); _server.addProtoService(proto.Tester.service, { - testUnary: function(call, cb) { + testUnary: function (call, cb) { checkServerMetadata(call.metadata); if (call.request.n === EMIT_ERROR) { - common.createChildSpan(function () { + common.createChildSpan(() => { cb(new Error('test')); }, DEFAULT_SPAN_DURATION); } else if (call.request.n === SEND_METADATA) { call.sendMetadata(metadata); - setTimeout(function() { + setTimeout(() => { cb(null, {n: call.request.n}, trailing_metadata); }, DEFAULT_SPAN_DURATION); } else { - common.createChildSpan(function () { + common.createChildSpan(() => { cb(null, {n: call.request.n}); }, DEFAULT_SPAN_DURATION); } }, - testClientStream: function(call, cb) { + testClientStream: function (call, cb) { checkServerMetadata(call.metadata); - var sum = 0; - var triggerCb = function () { + let sum = 0; + let triggerCb = function () { cb(null, {n: sum}); }; - var stopChildSpan; - call.on('data', function(data) { + let stopChildSpan; + call.on('data', data => { // Creating child span in stream event handler to ensure that // context is propagated correctly if (!stopChildSpan) { - stopChildSpan = common.createChildSpan(function () { + stopChildSpan = common.createChildSpan(() => { triggerCb(); }, DEFAULT_SPAN_DURATION); } sum += data.n; }); - call.on('end', function() { + call.on('end', () => { if (sum === EMIT_ERROR) { - triggerCb = function() { + triggerCb = function () { if (stopChildSpan) { stopChildSpan(); } @@ -109,38 +116,38 @@ function startServer(proto, grpc, agent, metadata, trailing_metadata) { }; } else if (sum === SEND_METADATA) { call.sendMetadata(metadata); - triggerCb = function() { + triggerCb = function () { cb(null, {n: sum}, trailing_metadata); }; } }); }, - testServerStream: function(stream) { + testServerStream: function (stream) { checkServerMetadata(stream.metadata); if (stream.request.n === EMIT_ERROR) { - common.createChildSpan(function () { + common.createChildSpan(() => { stream.emit('error', new Error('test')); }, DEFAULT_SPAN_DURATION); } else { if (stream.request.n === SEND_METADATA) { stream.sendMetadata(metadata); } - for (var i = 0; i < 10; ++i) { + for (let i = 0; i < 10; ++i) { stream.write({n: i}); } - common.createChildSpan(function () { + common.createChildSpan(() => { stream.end(); }, DEFAULT_SPAN_DURATION); } }, - testBidiStream: function(stream) { + testBidiStream: function (stream) { checkServerMetadata(stream.metadata); - var sum = 0; - var stopChildSpan; - var t = setTimeout(function() { + let sum = 0; + let stopChildSpan; + const t = setTimeout(() => { stream.end(); }, DEFAULT_SPAN_DURATION); - stream.on('data', function(data) { + stream.on('data', data => { // Creating child span in stream event handler to ensure that // context is propagated correctly if (!stopChildSpan) { @@ -149,11 +156,11 @@ function startServer(proto, grpc, agent, metadata, trailing_metadata) { sum += data.n; stream.write({n: data.n}); }); - stream.on('end', function() { + stream.on('end', () => { stopChildSpan(); if (sum === EMIT_ERROR) { clearTimeout(t); - setTimeout(function() { + setTimeout(() => { if (stopChildSpan) { stopChildSpan(); } @@ -163,73 +170,82 @@ function startServer(proto, grpc, agent, metadata, trailing_metadata) { stream.sendMetadata(metadata); } }); - } + }, }); - _server.bind('localhost:' + grpcPort, - grpc.ServerCredentials.createInsecure()); + _server.bind( + 'localhost:' + grpcPort, + grpc.ServerCredentials.createInsecure() + ); _server.start(); return _server; } function createClient(proto, grpc) { - return new proto.Tester('localhost:' + grpcPort, - grpc.credentials.createInsecure()); + return new proto.Tester( + 'localhost:' + grpcPort, + grpc.credentials.createInsecure() + ); } function callUnary(client, grpc, metadata, cb) { - var args = [ + const args = [ {n: 42}, - function(err, result) { + function (err, result) { assert.ifError(err); assert.strictEqual(result.n, 42); cb(); - } + }, ]; if (Object.keys(metadata).length > 0) { - var m = new grpc.Metadata(); - for (var key in metadata) { + const m = new grpc.Metadata(); + for (const key in metadata) { m.add(key, metadata[key]); } args.splice(1, 0, m); } + // eslint-disable-next-line prefer-spread client.testUnary.apply(client, args); } function callClientStream(client, grpc, metadata, cb) { - var args = [function(err, result) { - assert.ifError(err); - assert.strictEqual(result.n, 45); - cb(); - }]; + const args = [ + function (err, result) { + assert.ifError(err); + assert.strictEqual(result.n, 45); + cb(); + }, + ]; if (Object.keys(metadata).length > 0) { - var m = new grpc.Metadata(); - for (var key in metadata) { + const m = new grpc.Metadata(); + for (const key in metadata) { m.add(key, metadata[key]); } args.unshift(m); } - var stream = client.testClientStream.apply(client, args); - for (var i = 0; i < 10; ++i) { + // eslint-disable-next-line prefer-spread + const stream = client.testClientStream.apply(client, args); + for (let i = 0; i < 10; ++i) { stream.write({n: i}); } stream.end(); } function callServerStream(client, grpc, metadata, cb) { - var args = [ {n: 42} ]; + const args = [{n: 42}]; if (Object.keys(metadata).length > 0) { - var m = new grpc.Metadata(); - for (var key in metadata) { + const m = new grpc.Metadata(); + for (const key in metadata) { m.add(key, metadata[key]); } args.push(m); } - var stream = client.testServerStream.apply(client, args); - var sum = 0; - stream.on('data', function(data) { + // eslint-disable-next-line prefer-spread + const stream = client.testServerStream.apply(client, args); + let sum = 0; + stream.on('data', data => { sum += data.n; }); - stream.on('status', function(status) { + stream.on('status', status => { assert.strictEqual(status.code, grpc.status.OK); assert.strictEqual(sum, 45); cb(); @@ -237,24 +253,26 @@ function callServerStream(client, grpc, metadata, cb) { } function callBidi(client, grpc, metadata, cb) { - var args: any[] = []; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const args: any[] = []; if (Object.keys(metadata).length > 0) { - var m = new grpc.Metadata(); - for (var key in metadata) { + const m = new grpc.Metadata(); + for (const key in metadata) { m.add(key, metadata[key]); } args.push(m); } - var stream = client.testBidiStream.apply(client, args); - var sum = 0; - stream.on('data', function(data) { + // eslint-disable-next-line prefer-spread + const stream = client.testBidiStream.apply(client, args); + let sum = 0; + stream.on('data', data => { sum += data.n; }); - for (var i = 0; i < 10; ++i) { + for (let i = 0; i < 10; ++i) { stream.write({n: i}); } stream.end(); - stream.on('status', function(status) { + stream.on('status', status => { assert.strictEqual(status.code, grpc.status.OK); assert.strictEqual(sum, 45); cb(); @@ -262,36 +280,43 @@ function callBidi(client, grpc, metadata, cb) { } describeInterop('grpc', fixture => { - var agent; - var grpc; - var metadata; - var server; - var client; - var shouldTraceArgs: any[] = []; - before(function() { + let agent; + let grpc; + let metadata; + let server; + let client; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let shouldTraceArgs: any[] = []; + before(() => { // Set up to record invocations of shouldTrace - shimmer.wrap(TracingPolicy.BuiltinTracePolicy.prototype, 'shouldTrace', function(original) { - return function(options) { - shouldTraceArgs.push(options); - return original.apply(this, arguments); - }; - }); + shimmer.wrap( + TracingPolicy.BuiltinTracePolicy.prototype, + 'shouldTrace', + original => { + return function (options) { + shouldTraceArgs.push(options); + // eslint-disable-next-line prefer-rest-params + return original.apply(this, arguments); + }; + } + ); // It is necessary for the samplingRate to be 0 for the tests to succeed agent = require('../../..').start({ projectId: '0', samplingRate: 0, enhancedDatabaseReporting: true, - [FORCE_NEW]: true + [FORCE_NEW]: true, }); grpc = fixture.require(); - var oldRegister = grpc.Server.prototype.register; + const oldRegister = grpc.Server.prototype.register; grpc.Server.prototype.register = function register(n, h, s, d, m) { - var result = oldRegister.call(this, n, h, s, d, m); - var oldFunc = this.handlers[n].func; - this.handlers[n].func = function() { + const result = oldRegister.call(this, n, h, s, d, m); + const oldFunc = this.handlers[n].func; + this.handlers[n].func = function () { + // eslint-disable-next-line prefer-rest-params return oldFunc.apply(this, arguments); }; return result; @@ -302,34 +327,36 @@ describeInterop('grpc', fixture => { metadata.set('a', 'b'); // Trailing metadata can be sent by unary and client stream requests. - var trailing_metadata = new grpc.Metadata(); + const trailing_metadata = new grpc.Metadata(); trailing_metadata.set('c', 'd'); - var proto = grpc.load(protoFile).nodetest; + const proto = grpc.load(protoFile).nodetest; server = startServer(proto, grpc, agent, metadata, trailing_metadata); client = createClient(proto, grpc); }); - after(function() { + after(() => { server.forceShutdown(); }); - afterEach(function() { + afterEach(() => { shouldTraceArgs = []; common.cleanTraces(); checkMetadata = false; }); - it('should accurately measure time for unary requests', function(done) { - var start = Date.now(); - common.runInTransaction(function(endTransaction) { - callUnary(client, grpc, {}, function() { + it('should accurately measure time for unary requests', done => { + const start = Date.now(); + common.runInTransaction(endTransaction => { + callUnary(client, grpc, {}, () => { endTransaction(); - var assertTraceProperties = function(predicate) { - var trace = common.getMatchingSpan(predicate); + const assertTraceProperties = function (predicate) { + const trace = common.getMatchingSpan(predicate); assert(trace); - assertSpanDuration(common.getMatchingSpan(predicate), - [DEFAULT_SPAN_DURATION, Date.now() - start]); + assertSpanDuration(common.getMatchingSpan(predicate), [ + DEFAULT_SPAN_DURATION, + Date.now() - start, + ]); assert.strictEqual(trace.labels.argument, '{"n":42}'); assert.strictEqual(trace.labels.result, '{"n":42}'); }; @@ -342,16 +369,18 @@ describeInterop('grpc', fixture => { }); }); - it('should accurately measure time for client streaming requests', function(done) { - var start = Date.now(); - common.runInTransaction(function(endTransaction) { - callClientStream(client, grpc, {}, function() { + it('should accurately measure time for client streaming requests', done => { + const start = Date.now(); + common.runInTransaction(endTransaction => { + callClientStream(client, grpc, {}, () => { endTransaction(); - var assertTraceProperties = function(predicate) { - var trace = common.getMatchingSpan(predicate); + const assertTraceProperties = function (predicate) { + const trace = common.getMatchingSpan(predicate); assert(trace); - assertSpanDuration(common.getMatchingSpan(predicate), - [DEFAULT_SPAN_DURATION, Date.now() - start]); + assertSpanDuration(common.getMatchingSpan(predicate), [ + DEFAULT_SPAN_DURATION, + Date.now() - start, + ]); assert.strictEqual(trace.labels.result, '{"n":45}'); }; assertTraceProperties(grpcClientPredicate); @@ -363,22 +392,26 @@ describeInterop('grpc', fixture => { }); }); - it('should accurately measure time for server streaming requests', function(done) { - var start = Date.now(); - common.runInTransaction(function(endTransaction) { - callServerStream(client, grpc, {}, function() { + it('should accurately measure time for server streaming requests', done => { + const start = Date.now(); + common.runInTransaction(endTransaction => { + callServerStream(client, grpc, {}, () => { endTransaction(); - var assertTraceProperties = function(predicate) { - var trace = common.getMatchingSpan(predicate); + const assertTraceProperties = function (predicate) { + const trace = common.getMatchingSpan(predicate); assert(trace); - assertSpanDuration(common.getMatchingSpan(predicate), - [DEFAULT_SPAN_DURATION, Date.now() - start]); + assertSpanDuration(common.getMatchingSpan(predicate), [ + DEFAULT_SPAN_DURATION, + Date.now() - start, + ]); assert.strictEqual(trace.labels.argument, '{"n":42}'); return trace; }; - var clientTrace = assertTraceProperties(grpcClientPredicate); - assert.strictEqual(clientTrace.labels.status, - '{"code":0,"details":"OK","metadata":{"_internal_repr":{},"flags":0}}'); + const clientTrace = assertTraceProperties(grpcClientPredicate); + assert.strictEqual( + clientTrace.labels.status, + '{"code":0,"details":"OK","metadata":{"_internal_repr":{},"flags":0}}' + ); assertTraceProperties(grpcServerOuterPredicate); // Check that a child span was created in gRPC root span assert(common.getMatchingSpan(grpcServerInnerPredicate)); @@ -387,21 +420,25 @@ describeInterop('grpc', fixture => { }); }); - it('should accurately measure time for bidi streaming requests', function(done) { - var start = Date.now(); - common.runInTransaction(function(endTransaction) { - callBidi(client, grpc, {}, function() { + it('should accurately measure time for bidi streaming requests', done => { + const start = Date.now(); + common.runInTransaction(endTransaction => { + callBidi(client, grpc, {}, () => { endTransaction(); - var assertTraceProperties = function(predicate) { - var trace = common.getMatchingSpan(predicate); + const assertTraceProperties = function (predicate) { + const trace = common.getMatchingSpan(predicate); assert(trace); - assertSpanDuration(common.getMatchingSpan(predicate), - [DEFAULT_SPAN_DURATION, Date.now() - start]); + assertSpanDuration(common.getMatchingSpan(predicate), [ + DEFAULT_SPAN_DURATION, + Date.now() - start, + ]); return trace; }; - var clientTrace = assertTraceProperties(grpcClientPredicate); - assert.strictEqual(clientTrace.labels.status, - '{"code":0,"details":"OK","metadata":{"_internal_repr":{},"flags":0}}'); + const clientTrace = assertTraceProperties(grpcClientPredicate); + assert.strictEqual( + clientTrace.labels.status, + '{"code":0,"details":"OK","metadata":{"_internal_repr":{},"flags":0}}' + ); assertTraceProperties(grpcServerOuterPredicate); // Check that a child span was created in gRPC root span assert(common.getMatchingSpan(grpcServerInnerPredicate)); @@ -411,31 +448,34 @@ describeInterop('grpc', fixture => { }); // Older versions of gRPC (<1.7) do not add original names. - fixture.skip(it, '1.6')('should trace client requests using the original method name', (done) => { - common.runInTransaction((endTransaction) => { - // The original method name is TestUnary. - client.TestUnary({n: 10}, (err, result) => { - assert.ifError(err); - assert.strictEqual(result.n, 10); - endTransaction(); - var assertTraceProperties = function(predicate) { - var trace = common.getMatchingSpan(predicate); - assert.ok(trace); - assert.strictEqual(trace.labels.argument, '{"n":10}'); - assert.strictEqual(trace.labels.result, '{"n":10}'); - }; - assertTraceProperties(grpcClientPredicate); - assertTraceProperties(grpcServerOuterPredicate); - // Check that a child span was created in gRPC root span - assert.ok(common.getMatchingSpan(grpcServerInnerPredicate)); - done(); + fixture.skip(it, '1.6')( + 'should trace client requests using the original method name', + done => { + common.runInTransaction(endTransaction => { + // The original method name is TestUnary. + client.TestUnary({n: 10}, (err, result) => { + assert.ifError(err); + assert.strictEqual(result.n, 10); + endTransaction(); + const assertTraceProperties = function (predicate) { + const trace = common.getMatchingSpan(predicate); + assert.ok(trace); + assert.strictEqual(trace.labels.argument, '{"n":10}'); + assert.strictEqual(trace.labels.result, '{"n":10}'); + }; + assertTraceProperties(grpcClientPredicate); + assertTraceProperties(grpcServerOuterPredicate); + // Check that a child span was created in gRPC root span + assert.ok(common.getMatchingSpan(grpcServerInnerPredicate)); + done(); + }); }); - }); - }); + } + ); - it('should propagate context', function(done) { - common.runInTransaction(function(endTransaction) { - callUnary(client, grpc, {}, function() { + it('should propagate context', done => { + common.runInTransaction(endTransaction => { + callUnary(client, grpc, {}, () => { assert.ok(common.hasContext()); endTransaction(); done(); @@ -443,19 +483,26 @@ describeInterop('grpc', fixture => { }); }); - it('should not break if no parent transaction', function(done) { - callUnary(client, grpc, {}, function() { - assert.strictEqual(common.getMatchingSpans(grpcClientPredicate).length, 0); + it('should not break if no parent transaction', done => { + callUnary(client, grpc, {}, () => { + assert.strictEqual( + common.getMatchingSpans(grpcClientPredicate).length, + 0 + ); done(); }); }); - it('should respect the tracing policy', function(done) { - var next = function() { - assert.strictEqual(shouldTraceArgs.length, 4, + it('should respect the tracing policy', done => { + let next = function () { + assert.strictEqual( + shouldTraceArgs.length, + 4, 'expected one call for each of four gRPC method types but got ' + - shouldTraceArgs.length + ' instead'); - var prefix = 'grpc:/nodetest.Tester/Test'; + shouldTraceArgs.length + + ' instead' + ); + const prefix = 'grpc:/nodetest.Tester/Test'; // calls to shouldTrace should be in the order which the client method // of each type was called. assert.strictEqual(shouldTraceArgs[3].url, prefix + 'Unary'); @@ -471,27 +518,33 @@ describeInterop('grpc', fixture => { next(); }); - it('should support distributed trace context', function(done) { + it('should support distributed trace context', done => { function makeLink(fn, meta, next) { - return function() { - agent.runInRootSpan({ name: '', traceContext: { - traceId: COMMON_TRACE_ID, - spanId: '0', - options: 1 - }}, function(span) { - assert.strictEqual(span.type, agent.spanTypes.ROOT); - fn(client, grpc, meta, function() { - span.endSpan(); - next(); - }); - }); + return function () { + agent.runInRootSpan( + { + name: '', + traceContext: { + traceId: COMMON_TRACE_ID, + spanId: '0', + options: 1, + }, + }, + span => { + assert.strictEqual(span.type, agent.spanTypes.ROOT); + fn(client, grpc, meta, () => { + span.endSpan(); + next(); + }); + } + ); }; } // Enable asserting properties of the metdata on the grpc server. checkMetadata = true; - var next; - var metadata = { a: 'b' }; - next = function() { + let next; + const metadata = {a: 'b'}; + next = function () { checkMetadata = false; done(); }; @@ -512,40 +565,44 @@ describeInterop('grpc', fixture => { next(); }); - it('should not let root spans interfere with one another', function(done) { + it('should not let root spans interfere with one another', function (done) { this.timeout(8000); - var next = done; + let next = done; // Calling queueCallTogether builds a call chain, with each link // testing interference between two gRPC calls spaced apart by half // of DEFAULT_SPAN_DURATION (to interleave them). // This chain is kicked off with an initial call to next(). - var queueCallTogether = function(first, second) { - var prevNext = next; - next = function() { - var startFirst, startSecond, endFirst; - common.runInTransaction(function(endTransaction) { - var num = 0; + const queueCallTogether = function (first, second) { + const prevNext = next; + next = function () { + let startFirst, startSecond, endFirst; + common.runInTransaction(endTransaction => { + let num = 0; common.cleanTraces(); - var callback = function() { + const callback = function () { if (num === 0) { endFirst = Date.now(); } if (++num === 2) { endTransaction(); - var spans = common.getMatchingSpans(grpcServerOuterPredicate); + const spans = common.getMatchingSpans(grpcServerOuterPredicate); assert(spans.length === 2); assert(spans[0].spanId !== spans[1].spanId); assert(spans[0].startTime !== spans[1].startTime); - assertSpanDuration(spans[0], - [DEFAULT_SPAN_DURATION, endFirst - startFirst]); - assertSpanDuration(spans[1], - [DEFAULT_SPAN_DURATION, Date.now() - startSecond]); + assertSpanDuration(spans[0], [ + DEFAULT_SPAN_DURATION, + endFirst - startFirst, + ]); + assertSpanDuration(spans[1], [ + DEFAULT_SPAN_DURATION, + Date.now() - startSecond, + ]); setImmediate(prevNext); } }; startFirst = Date.now(); first(callback); - setTimeout(function() { + setTimeout(() => { startSecond = Date.now(); second(callback); }, DEFAULT_SPAN_DURATION / 2); @@ -554,12 +611,14 @@ describeInterop('grpc', fixture => { }; // Call queueCallTogether with every possible pair of gRPC calls. - var methods = [ callUnary.bind(null, client, grpc, {}), - callClientStream.bind(null, client, grpc, {}), - callServerStream.bind(null, client, grpc, {}), - callBidi.bind(null, client, grpc, {}) ]; - for (var m of methods) { - for (var n of methods) { + const methods = [ + callUnary.bind(null, client, grpc, {}), + callClientStream.bind(null, client, grpc, {}), + callServerStream.bind(null, client, grpc, {}), + callBidi.bind(null, client, grpc, {}), + ]; + for (const m of methods) { + for (const n of methods) { queueCallTogether(m, n); } } @@ -568,34 +627,38 @@ describeInterop('grpc', fixture => { next(); }); - it('should remove trace frames from stack', function(done) { - common.runInTransaction(function(endTransaction) { - client.testUnary({n: 42}, function(err, result) { + it('should remove trace frames from stack', done => { + common.runInTransaction(endTransaction => { + client.testUnary({n: 42}, (err, result) => { endTransaction(); assert.ifError(err); assert.strictEqual(result.n, 42); function getMethodName(predicate) { - var trace = common.getMatchingSpan(predicate); - var labels = trace.labels; - var stack = JSON.parse(labels[TraceLabels.STACK_TRACE_DETAILS_KEY]); + const trace = common.getMatchingSpan(predicate); + const labels = trace.labels; + const stack = JSON.parse(labels[TraceLabels.STACK_TRACE_DETAILS_KEY]); return stack.stack_frame[0].method_name; } - assert.notStrictEqual(-1, getMethodName(grpcClientPredicate) - .indexOf('clientMethodTrace')); - assert.notStrictEqual(-1, getMethodName(grpcServerOuterPredicate) - .indexOf('serverMethodTrace')); + assert.notStrictEqual( + -1, + getMethodName(grpcClientPredicate).indexOf('clientMethodTrace') + ); + assert.notStrictEqual( + -1, + getMethodName(grpcServerOuterPredicate).indexOf('serverMethodTrace') + ); done(); }); }); }); - it('should trace errors for unary requests', function(done) { - common.runInTransaction(function(endTransaction) { - client.testUnary({n: EMIT_ERROR}, function(err, result) { + it('should trace errors for unary requests', done => { + common.runInTransaction(endTransaction => { + client.testUnary({n: EMIT_ERROR}, err => { endTransaction(); assert(err); - var assertTraceProperties = function(predicate) { - var trace = common.getMatchingSpan(predicate); + const assertTraceProperties = function (predicate) { + const trace = common.getMatchingSpan(predicate); assert.ok(trace); assert.strictEqual(trace.labels.argument, '{"n":' + EMIT_ERROR + '}'); assert.ok(trace.labels.error.indexOf('test') !== -1); @@ -609,13 +672,13 @@ describeInterop('grpc', fixture => { }); }); - it('should trace errors for client streaming requests', function(done) { - common.runInTransaction(function(endTransaction) { - var stream = client.testClientStream(function(err, result) { + it('should trace errors for client streaming requests', done => { + common.runInTransaction(endTransaction => { + const stream = client.testClientStream(err => { endTransaction(); assert(err); - var assertTraceProperties = function(predicate) { - var trace = common.getMatchingSpan(predicate); + const assertTraceProperties = function (predicate) { + const trace = common.getMatchingSpan(predicate); assert.ok(trace); assert.ok(trace.labels.error.indexOf('test') !== -1); }; @@ -630,14 +693,14 @@ describeInterop('grpc', fixture => { }); }); - it('should trace errors for server streaming requests', function(done) { - common.runInTransaction(function(endTransaction) { - var stream = client.testServerStream({n: EMIT_ERROR}, metadata); - stream.on('data', function(data) {}); - stream.on('error', function (err) { + it('should trace errors for server streaming requests', done => { + common.runInTransaction(endTransaction => { + const stream = client.testServerStream({n: EMIT_ERROR}, metadata); + stream.on('data', () => {}); + stream.on('error', () => { endTransaction(); - var assertTraceProperties = function(predicate) { - var trace = common.getMatchingSpan(predicate); + const assertTraceProperties = function (predicate) { + const trace = common.getMatchingSpan(predicate); assert.ok(trace); assert.ok(trace.labels.error.indexOf('test') !== -1); }; @@ -650,16 +713,16 @@ describeInterop('grpc', fixture => { }); }); - it('should trace errors for bidi streaming requests', function(done) { - common.runInTransaction(function(endTransaction) { - var stream = client.testBidiStream(metadata); - stream.on('data', function(data) {}); + it('should trace errors for bidi streaming requests', done => { + common.runInTransaction(endTransaction => { + const stream = client.testBidiStream(metadata); + stream.on('data', () => {}); stream.write({n: EMIT_ERROR}); stream.end(); - stream.on('error', function(err) { + stream.on('error', () => { endTransaction(); - var assertTraceProperties = function(predicate) { - var trace = common.getMatchingSpan(predicate); + const assertTraceProperties = function (predicate) { + const trace = common.getMatchingSpan(predicate); assert.ok(trace); assert.ok(trace.labels.error.indexOf('test') !== -1); }; @@ -672,19 +735,21 @@ describeInterop('grpc', fixture => { }); }); - it('should trace metadata for server streaming requests', function(done) { - var start = Date.now(); - common.runInTransaction(function(endTransaction) { - var stream = client.testServerStream({n: SEND_METADATA}, metadata); - stream.on('data', function(data) {}); - stream.on('status', function(status) { + it('should trace metadata for server streaming requests', done => { + const start = Date.now(); + common.runInTransaction(endTransaction => { + const stream = client.testServerStream({n: SEND_METADATA}, metadata); + stream.on('data', () => {}); + stream.on('status', status => { endTransaction(); assert.strictEqual(status.code, grpc.status.OK); - var assertTraceProperties = function(predicate) { - var trace = common.getMatchingSpan(predicate); + const assertTraceProperties = function (predicate) { + const trace = common.getMatchingSpan(predicate); assert(trace); - assertSpanDuration(common.getMatchingSpan(predicate), - [DEFAULT_SPAN_DURATION, Date.now() - start]); + assertSpanDuration(common.getMatchingSpan(predicate), [ + DEFAULT_SPAN_DURATION, + Date.now() - start, + ]); assert.ok(metadataRegExp.test(trace.labels.metadata)); }; assertTraceProperties(grpcClientPredicate); @@ -694,21 +759,23 @@ describeInterop('grpc', fixture => { }); }); - it('should trace metadata for bidi streaming requests', function(done) { - var start = Date.now(); - common.runInTransaction(function(endTransaction) { - var stream = client.testBidiStream(metadata); - stream.on('data', function(data) {}); + it('should trace metadata for bidi streaming requests', done => { + const start = Date.now(); + common.runInTransaction(endTransaction => { + const stream = client.testBidiStream(metadata); + stream.on('data', () => {}); stream.write({n: SEND_METADATA}); stream.end(); - stream.on('status', function(status) { + stream.on('status', status => { endTransaction(); assert.strictEqual(status.code, grpc.status.OK); - var assertTraceProperties = function(predicate) { - var trace = common.getMatchingSpan(predicate); + const assertTraceProperties = function (predicate) { + const trace = common.getMatchingSpan(predicate); assert(trace); - assertSpanDuration(common.getMatchingSpan(predicate), - [DEFAULT_SPAN_DURATION, Date.now() - start]); + assertSpanDuration(common.getMatchingSpan(predicate), [ + DEFAULT_SPAN_DURATION, + Date.now() - start, + ]); assert.ok(metadataRegExp.test(trace.labels.metadata)); }; assertTraceProperties(grpcClientPredicate); diff --git a/test/plugins/test-trace-http.ts b/test/plugins/test-trace-http.ts index 0702838f2..4ac473de7 100644 --- a/test/plugins/test-trace-http.ts +++ b/test/plugins/test-trace-http.ts @@ -13,7 +13,7 @@ // limitations under the License. import * as assert from 'assert'; -import {describe, it} from 'mocha'; +import {describe, it, before, afterEach, beforeEach} from 'mocha'; import {EventEmitter} from 'events'; import * as httpModule from 'http'; import * as httpsModule from 'https'; @@ -155,6 +155,7 @@ for (const nodule of Object.keys(servers) as Array) { fn: async () => { const waitForResponse = new WaitForResponse(); http.get({port, rejectUnauthorized: false}, res => { + // eslint-disable-next-line @typescript-eslint/no-unused-vars let result = ''; const writable = new stream.Writable(); writable._write = (chunk, encoding, next) => { @@ -447,7 +448,7 @@ for (const nodule of Object.keys(servers) as Array) { .get() .runInRootSpan({name: 'outer'}, async rootSpan => { await Promise.all( - [0, 1, 2, 3, 4].map(async i => { + [0, 1, 2, 3, 4].map(async () => { assert.ok(testTraceModule.get().isRealSpan(rootSpan)); const waitForResponse = new WaitForResponse(); http.get( diff --git a/test/plugins/test-trace-http2.ts b/test/plugins/test-trace-http2.ts index ce087df2b..ceeec876a 100644 --- a/test/plugins/test-trace-http2.ts +++ b/test/plugins/test-trace-http2.ts @@ -13,9 +13,10 @@ // limitations under the License. import * as assert from 'assert'; -import {describe, it} from 'mocha'; +import {describe, it, after, afterEach, before} from 'mocha'; // This is imported only for types. Generated .js file should NOT load 'http2' // in this place. It is dynamically loaded later from each test suite below. +// eslint-disable-next-line node/no-unsupported-features/node-builtins import * as http2Types from 'http2'; import * as semver from 'semver'; import * as stream from 'stream'; @@ -45,6 +46,7 @@ maybeSkipHttp2('Trace Agent integration with http2', () => { traceTestModule.setPluginLoaderForTest(); traceTestModule.setCLSForTest(); traceTestModule.start(); + // eslint-disable-next-line node/no-unsupported-features/node-builtins http2 = require('http2'); }); @@ -158,6 +160,7 @@ maybeSkipHttp2('Trace Agent integration with http2', () => { // `headers` are not passed const s = session.request(); s.setEncoding('utf8'); + // eslint-disable-next-line @typescript-eslint/no-unused-vars s.on('data', (data: string) => {}).on('end', () => { rootSpan.endSpan(); const traces = traceTestModule.getTraces(); @@ -349,7 +352,7 @@ maybeSkipHttp2('Trace Agent integration with http2', () => { }); }); - it('should handle concurrent requests', function(done) { + it('should handle concurrent requests', function (done) { this.timeout(10000); // this test takes a long time let count = 200; const slowServer: http2Types.Http2Server = http2.createServer(); diff --git a/test/plugins/test-trace-knex.ts b/test/plugins/test-trace-knex.ts index 29e62c11e..7feb31632 100644 --- a/test/plugins/test-trace-knex.ts +++ b/test/plugins/test-trace-knex.ts @@ -13,7 +13,7 @@ // limitations under the License. import * as assert from 'assert'; -import {describe, it} from 'mocha'; +import {it, before, beforeEach, after, afterEach} from 'mocha'; import * as knexTypes from 'knex'; import {Tracer} from '../../src/plugin-types'; @@ -107,7 +107,7 @@ describeInterop('knex', fixture => { return knex .select() .from(TABLE_NAME) - .then(res => { + .then(() => { assert.ok(hasContext()); rootSpan.endSpan(); }); @@ -119,7 +119,7 @@ describeInterop('knex', fixture => { return knex .select() .from(TABLE_NAME) - .then(res => { + .then(() => { rootSpan.endSpan(); const spans = traceTestModule.getSpans(span => { return span.name === 'mysql-query'; @@ -140,55 +140,61 @@ describeInterop('knex', fixture => { it('should work with events using ' + version, () => { return tracer.runInRootSpan({name: 'outer'}, rootSpan => { - return knex - .select() - .from(TABLE_NAME) - .on('query-response', (response, obj, builder) => { - const row = response[0]; - assert.ok(row); - assert.strictEqual(row.k, 1); - assert.strictEqual(row.v, 'obj'); - }) - .on('query-error', (err, obj) => { - assert.ifError(err); - }) - .then(res => { - rootSpan.endSpan(); - const spans = traceTestModule.getSpans(span => { - return span.name === 'mysql-query'; - }); - if (parsedVersion.minor === 11) { - assert.strictEqual(spans.length, 2); - assert.strictEqual(spans[0].labels.sql, 'SELECT 1'); - assert.strictEqual(spans[1].labels.sql, 'select * from `t`'); - } else { - assert.strictEqual(spans.length, 1); - assert.strictEqual(spans[0].labels.sql, 'select * from `t`'); - } - }); + return ( + knex + .select() + .from(TABLE_NAME) + // eslint-disable-next-line @typescript-eslint/no-unused-vars + .on('query-response', (response, obj, builder) => { + const row = response[0]; + assert.ok(row); + assert.strictEqual(row.k, 1); + assert.strictEqual(row.v, 'obj'); + }) + .on('query-error', err => { + assert.ifError(err); + }) + .then(() => { + rootSpan.endSpan(); + const spans = traceTestModule.getSpans(span => { + return span.name === 'mysql-query'; + }); + if (parsedVersion.minor === 11) { + assert.strictEqual(spans.length, 2); + assert.strictEqual(spans[0].labels.sql, 'SELECT 1'); + assert.strictEqual(spans[1].labels.sql, 'select * from `t`'); + } else { + assert.strictEqual(spans.length, 1); + assert.strictEqual(spans[0].labels.sql, 'select * from `t`'); + } + }) + ); }); }); it('should work without events or callback using ' + version, () => { return tracer.runInRootSpan({name: 'outer'}, rootSpan => { - return knex - .select() - .from(TABLE_NAME) - .then(async result => { - await wait(50); - rootSpan.endSpan(); - const spans = traceTestModule.getSpans(span => { - return span.name === 'mysql-query'; - }); - if (parsedVersion.minor === 11) { - assert.strictEqual(spans.length, 2); - assert.strictEqual(spans[0].labels.sql, 'SELECT 1'); - assert.strictEqual(spans[1].labels.sql, 'select * from `t`'); - } else { - assert.strictEqual(spans.length, 1); - assert.strictEqual(spans[0].labels.sql, 'select * from `t`'); - } - }); + return ( + knex + .select() + .from(TABLE_NAME) + // eslint-disable-next-line @typescript-eslint/no-unused-vars + .then(async result => { + await wait(50); + rootSpan.endSpan(); + const spans = traceTestModule.getSpans(span => { + return span.name === 'mysql-query'; + }); + if (parsedVersion.minor === 11) { + assert.strictEqual(spans.length, 2); + assert.strictEqual(spans[0].labels.sql, 'SELECT 1'); + assert.strictEqual(spans[1].labels.sql, 'select * from `t`'); + } else { + assert.strictEqual(spans.length, 1); + assert.strictEqual(spans[0].labels.sql, 'select * from `t`'); + } + }) + ); }); }); @@ -201,7 +207,7 @@ describeInterop('knex', fixture => { .insert(obj2) .into(TABLE_NAME) .transacting(trx) - .then(res => { + .then(() => { return trx .select() .from(TABLE_NAME) diff --git a/test/plugins/test-trace-mongodb.ts b/test/plugins/test-trace-mongodb.ts index 4b2608a51..684886e43 100644 --- a/test/plugins/test-trace-mongodb.ts +++ b/test/plugins/test-trace-mongodb.ts @@ -11,57 +11,58 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. -'use strict'; -import { TraceLabels } from '../../src/trace-labels'; +import {TraceLabels} from '../../src/trace-labels'; // Prereqs: // Start docker daemon // ex) docker -d // Run a mongo image binding the mongo port // ex) docker run -p 27017:27017 -d mongo -var common = require('./common'/*.js*/); -var assert = require('assert'); +// eslint-disable-next-line @typescript-eslint/no-var-requires +const common = require('./common' /*.js*/); +import * as assert from 'assert'; +import {describe, it, before, beforeEach, afterEach} from 'mocha'; -var RESULT_SIZE = 5; +const RESULT_SIZE = 5; -var versions = { +const versions = { mongodb1: './fixtures/mongodb-core1', mongodb2: './fixtures/mongodb-core2', mongodb3: './fixtures/mongodb-core3', }; -describe('mongodb', function() { - before(function() { +describe('mongodb', () => { + before(() => { require('../../..').start({ projectId: '0', samplingRate: 0, enhancedDatabaseReporting: true, - databaseResultReportingSize: RESULT_SIZE + databaseResultReportingSize: RESULT_SIZE, }); }); - Object.keys(versions).forEach(function(version) { - describe(version, function() { - var mongodb; - var server; + Object.keys(versions).forEach(version => { + describe(version, () => { + let mongodb; + let server; - before(function() { + before(() => { mongodb = require(versions[version]); }); - beforeEach(function(done) { + beforeEach(done => { server = new mongodb.Server({ host: 'localhost', - port: 27017 + port: 27017, }); - var sim = { + const sim = { f1: 'sim', f2: true, - f3: 42 + f3: 42, }; - server.on('connect', function(_server) { - server.insert('testdb.simples', [sim], function(err, res) { + server.on('connect', () => { + server.insert('testdb.simples', [sim], (err, res) => { assert.ifError(err); assert.strictEqual(res.result.n, 1); done(); @@ -70,9 +71,9 @@ describe('mongodb', function() { server.connect(); }); - afterEach(function(done) { + afterEach(done => { common.cleanTraces(); - server.command('testdb.$cmd', {dropDatabase: 1}, function(err, res) { + server.command('testdb.$cmd', {dropDatabase: 1}, (err, res) => { assert.ifError(err); assert.strictEqual(res.result.dropped, 'testdb'); server.destroy(); @@ -80,131 +81,165 @@ describe('mongodb', function() { }); }); - it('should trace an insert', function(done) { - var data = { + it('should trace an insert', done => { + const data = { f1: 'val', f2: false, - f3: 1729 + f3: 1729, }; - common.runInTransaction(function(endTransaction) { - server.insert('testdb.simples', [data], function(err, res) { + common.runInTransaction(endTransaction => { + server.insert('testdb.simples', [data], (err, res) => { endTransaction(); assert.ifError(err); assert.strictEqual(res.result.n, 1); - var trace = common.getMatchingSpan( - mongoPredicate.bind(null, 'mongo-insert')); + const trace = common.getMatchingSpan( + mongoPredicate.bind(null, 'mongo-insert') + ); assert(trace); done(); }); }); }); - it('should trace an update', function(done) { - common.runInTransaction(function(endTransaction) { - server.update('testdb.simples', [{ - q: {f1: 'sim'}, - u: {'$set': {f2: false}} - }], function(err, res) { - endTransaction(); - assert.ifError(err); - assert.strictEqual(res.result.n, 1); - var trace = common.getMatchingSpan( - mongoPredicate.bind(null, 'mongo-update')); - assert(trace); - done(); - }); + it('should trace an update', done => { + common.runInTransaction(endTransaction => { + server.update( + 'testdb.simples', + [ + { + q: {f1: 'sim'}, + u: {$set: {f2: false}}, + }, + ], + (err, res) => { + endTransaction(); + assert.ifError(err); + assert.strictEqual(res.result.n, 1); + const trace = common.getMatchingSpan( + mongoPredicate.bind(null, 'mongo-update') + ); + assert(trace); + done(); + } + ); }); }); - it('should propagate context', function(done) { - common.runInTransaction(function(endTransaction) { - server.update('testdb.simples', [{ - q: {f1: 'sim'}, - u: {'$set': {f2: false}} - }], function(err, res) { - assert.ok(common.hasContext()); - endTransaction(); - done(); - }); + it('should propagate context', done => { + common.runInTransaction(endTransaction => { + server.update( + 'testdb.simples', + [ + { + q: {f1: 'sim'}, + u: {$set: {f2: false}}, + }, + ], + () => { + assert.ok(common.hasContext()); + endTransaction(); + done(); + } + ); }); }); - it('should trace a query', function(done) { - common.runInTransaction(function(endTransaction) { - server.cursor('testdb.simples', { - find: 'testdb.simples', - query: {f1: 'sim'} - }).next(function(err, doc) { - endTransaction(); - assert.ifError(err); - assert.strictEqual(doc.f3, 42); - var trace = common.getMatchingSpan( - mongoPredicate.bind(null, 'mongo-cursor')); - assert(trace); - done(); - }); + it('should trace a query', done => { + common.runInTransaction(endTransaction => { + server + .cursor('testdb.simples', { + find: 'testdb.simples', + query: {f1: 'sim'}, + }) + .next((err, doc) => { + endTransaction(); + assert.ifError(err); + assert.strictEqual(doc.f3, 42); + const trace = common.getMatchingSpan( + mongoPredicate.bind(null, 'mongo-cursor') + ); + assert(trace); + done(); + }); }); }); - it('should trace a remove', function(done) { - common.runInTransaction(function(endTransaction) { - server.remove('testdb.simples', [{ - q: {f1: 'sim'}, - limit: 0 - }], function(err, res) { - endTransaction(); - assert.ifError(err); - assert.strictEqual(res.result.n, 1); - var trace = common.getMatchingSpan( - mongoPredicate.bind(null, 'mongo-remove')); - assert(trace); - done(); - }); + it('should trace a remove', done => { + common.runInTransaction(endTransaction => { + server.remove( + 'testdb.simples', + [ + { + q: {f1: 'sim'}, + limit: 0, + }, + ], + (err, res) => { + endTransaction(); + assert.ifError(err); + assert.strictEqual(res.result.n, 1); + const trace = common.getMatchingSpan( + mongoPredicate.bind(null, 'mongo-remove') + ); + assert(trace); + done(); + } + ); }); }); - it('should trace a command', function(done) { - common.runInTransaction(function(endTransaction) { - server.command('admin.$cmd', {ismaster: true}, function(err, res) { + it('should trace a command', done => { + common.runInTransaction(endTransaction => { + server.command('admin.$cmd', {ismaster: true}, err => { endTransaction(); assert.ifError(err); - var trace = common.getMatchingSpan( - mongoPredicate.bind(null, 'mongo-comman')); + const trace = common.getMatchingSpan( + mongoPredicate.bind(null, 'mongo-comman') + ); assert(trace); done(); }); }); }); - it('should not break if no parent transaction', function(done) { - server.cursor('testdb.simples', { - find: 'testdb.simples', - query: {f1: 'sim'} - }).next(function(err, doc) { - assert.ifError(err); - assert.strictEqual(doc.f3, 42); - assert.strictEqual(common.getTraces().length, 0); - done(); - }); - }); - - it('should remove trace frames from stack', function(done) { - common.runInTransaction(function(endTransaction) { - server.cursor('testdb.simples', { + it('should not break if no parent transaction', done => { + server + .cursor('testdb.simples', { find: 'testdb.simples', - query: {f1: 'sim'} - }).next(function(err, doc) { - endTransaction(); + query: {f1: 'sim'}, + }) + .next((err, doc) => { assert.ifError(err); assert.strictEqual(doc.f3, 42); - var trace = common.getMatchingSpan( - mongoPredicate.bind(null, 'mongo-cursor')); - var labels = trace.labels; - var stack = JSON.parse(labels[TraceLabels.STACK_TRACE_DETAILS_KEY]); - assert.notStrictEqual(-1, - stack.stack_frame[0].method_name.indexOf('next_trace')); + assert.strictEqual(common.getTraces().length, 0); done(); }); + }); + + it('should remove trace frames from stack', done => { + common.runInTransaction(endTransaction => { + server + .cursor('testdb.simples', { + find: 'testdb.simples', + query: {f1: 'sim'}, + }) + .next((err, doc) => { + endTransaction(); + assert.ifError(err); + assert.strictEqual(doc.f3, 42); + const trace = common.getMatchingSpan( + mongoPredicate.bind(null, 'mongo-cursor') + ); + const labels = trace.labels; + const stack = JSON.parse( + labels[TraceLabels.STACK_TRACE_DETAILS_KEY] + ); + assert.notStrictEqual( + -1, + stack.stack_frame[0].method_name.indexOf('next_trace') + ); + done(); + }); }); }); }); diff --git a/test/plugins/test-trace-mongoose-async-await.ts b/test/plugins/test-trace-mongoose-async-await.ts index be4d66add..b36a789df 100644 --- a/test/plugins/test-trace-mongoose-async-await.ts +++ b/test/plugins/test-trace-mongoose-async-await.ts @@ -13,7 +13,7 @@ // limitations under the License. import * as assert from 'assert'; -import {describe, it} from 'mocha'; +import {it, before, after, afterEach} from 'mocha'; import * as mongooseTypes from 'mongoose'; import * as traceTestModule from '../trace'; diff --git a/test/plugins/test-trace-mongoose.ts b/test/plugins/test-trace-mongoose.ts index 518dfcb4e..3c9c5640e 100644 --- a/test/plugins/test-trace-mongoose.ts +++ b/test/plugins/test-trace-mongoose.ts @@ -11,26 +11,28 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. -'use strict'; -import { TraceLabels } from '../../src/trace-labels'; +import {TraceLabels} from '../../src/trace-labels'; // Prereqs: // Start docker daemon // ex) docker -d // Run a mongo image binding the mongo port // ex) docker run -p 27017:27017 -d mongo -var common = require('./common'/*.js*/); +// eslint-disable-next-line @typescript-eslint/no-var-requires +const common = require('./common' /*.js*/); -var assert = require('assert'); +import {describe, it, before, beforeEach, afterEach} from 'mocha'; +import * as assert from 'assert'; -describe('mongoose integration tests', function() { - var agent; - var Simple; - before(function() { +describe('mongoose integration tests', () => { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + let agent; + let Simple; + before(() => { agent = require('../../..').start({ projectId: '0', - samplingRate: 0 + samplingRate: 0, }); }); @@ -43,25 +45,28 @@ describe('mongoose integration tests', function() { mongoose = require(`./fixtures/mongoose${version}`); mongoose.Promise = global.Promise; - var Schema = mongoose.Schema; - var simpleSchema = new Schema({ + const Schema = mongoose.Schema; + const simpleSchema = new Schema({ f1: String, f2: Boolean, - f3: Number + f3: Number, }); Simple = mongoose.model('Simple', simpleSchema); }); - beforeEach(function(done) { - var sim = new Simple({ + beforeEach(done => { + const sim = new Simple({ f1: 'sim', f2: true, - f3: 42 + f3: 42, }); - mongoose.connect('mongodb://localhost:27017/testdb', function(err) { - assert(!err, 'Skipping: error connecting to mongo at localhost:27017.'); - sim.save(function(err) { + mongoose.connect('mongodb://localhost:27017/testdb', err => { + assert( + !err, + 'Skipping: error connecting to mongo at localhost:27017.' + ); + sim.save(err => { assert(!err); common.cleanTraces(); done(); @@ -69,10 +74,10 @@ describe('mongoose integration tests', function() { }); }); - afterEach(function(done) { - mongoose.connection.db.dropDatabase(function(err) { + afterEach(done => { + mongoose.connection.db.dropDatabase(err => { assert(!err); - mongoose.connection.close(function(err) { + mongoose.connection.close(err => { assert(!err); common.cleanTraces(); done(); @@ -80,32 +85,36 @@ describe('mongoose integration tests', function() { }); }); - it('should accurately measure create time', function(done) { - var data = new Simple({ + it('should accurately measure create time', done => { + const data = new Simple({ f1: 'val', f2: false, - f3: 1729 + f3: 1729, }); - common.runInTransaction(function(endTransaction) { - data.save(function(err) { + common.runInTransaction(endTransaction => { + data.save(err => { endTransaction(); assert(!err); - var trace = common.getMatchingSpan(mongoPredicate.bind(null, 'mongo-insert')); + const trace = common.getMatchingSpan( + mongoPredicate.bind(null, 'mongo-insert') + ); assert(trace); done(); }); }); }); - it('should accurately measure update time', function(done) { - common.runInTransaction(function(endTransaction) { - Simple.findOne({f1: 'sim'}, function(err, res) { + it('should accurately measure update time', done => { + common.runInTransaction(endTransaction => { + Simple.findOne({f1: 'sim'}, (err, res) => { assert(!err); res.f2 = false; - res.save(function(err) { + res.save(err => { endTransaction(); assert(!err); - var trace = common.getMatchingSpan(mongoPredicate.bind(null, 'mongo-update')); + const trace = common.getMatchingSpan( + mongoPredicate.bind(null, 'mongo-update') + ); assert(trace); done(); }); @@ -113,49 +122,58 @@ describe('mongoose integration tests', function() { }); }); - it('should accurately measure retrieval time', function(done) { - common.runInTransaction(function(endTransaction) { - Simple.findOne({f1: 'sim'}, function(err, res) { + it('should accurately measure retrieval time', done => { + common.runInTransaction(endTransaction => { + Simple.findOne({f1: 'sim'}, err => { endTransaction(); assert(!err); - var trace = common.getMatchingSpan(mongoPredicate.bind(null, 'mongo-cursor')); + const trace = common.getMatchingSpan( + mongoPredicate.bind(null, 'mongo-cursor') + ); assert(trace); done(); }); }); }); - it('should accurately measure delete time', function(done) { - common.runInTransaction(function(endTransaction) { - Simple.remove({f1: 'sim'}, function(err, res) { + it('should accurately measure delete time', done => { + common.runInTransaction(endTransaction => { + Simple.remove({f1: 'sim'}, err => { endTransaction(); assert(!err); - var trace = common.getMatchingSpan(mongoPredicate.bind(null, 'mongo-remove')); + const trace = common.getMatchingSpan( + mongoPredicate.bind(null, 'mongo-remove') + ); assert(trace); done(); }); }); }); - it('should not break if no parent transaction', function(done) { - Simple.findOne({f1: 'sim'}, function(err, res) { + it('should not break if no parent transaction', done => { + Simple.findOne({f1: 'sim'}, (err, res) => { assert(!err); assert(res); done(); }); }); - it('should remove trace frames from stack', function(done) { - common.runInTransaction(function(endTransaction) { - Simple.findOne({f1: 'sim'}, function(err, res) { + it('should remove trace frames from stack', done => { + common.runInTransaction(endTransaction => { + Simple.findOne({f1: 'sim'}, err => { endTransaction(); assert(!err); - var trace = common.getMatchingSpan(mongoPredicate.bind(null, 'mongo-cursor')); - var labels = trace.labels; - var stackTrace = JSON.parse(labels[TraceLabels.STACK_TRACE_DETAILS_KEY]); + const trace = common.getMatchingSpan( + mongoPredicate.bind(null, 'mongo-cursor') + ); + const labels = trace.labels; + const stackTrace = JSON.parse( + labels[TraceLabels.STACK_TRACE_DETAILS_KEY] + ); // Ensure that our patch is on top of the stack assert( - stackTrace.stack_frame[0].method_name.indexOf('next_trace') !== -1); + stackTrace.stack_frame[0].method_name.indexOf('next_trace') !== -1 + ); done(); }); }); diff --git a/test/plugins/test-trace-mysql.ts b/test/plugins/test-trace-mysql.ts index a8671f4e6..47230fdbd 100644 --- a/test/plugins/test-trace-mysql.ts +++ b/test/plugins/test-trace-mysql.ts @@ -11,46 +11,49 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. -'use strict'; -import { TraceLabels } from '../../src/trace-labels'; -var common = require('./common'/*.js*/); -var assert = require('assert'); +import {TraceLabels} from '../../src/trace-labels'; +// eslint-disable-next-line @typescript-eslint/no-var-requires +const common = require('./common' /*.js*/); +import * as assert from 'assert'; +import {describe, it, before, beforeEach, after, afterEach} from 'mocha'; -var RESULT_SIZE = 5; +const RESULT_SIZE = 5; -var obj = { +const obj = { k: 1, - v: 'obj' + v: 'obj', }; -var agent = require('../../..').start({ +// eslint-disable-next-line @typescript-eslint/no-unused-vars +const agent = require('../../..').start({ projectId: '0', enhancedDatabaseReporting: true, - databaseResultReportingSize: RESULT_SIZE + databaseResultReportingSize: RESULT_SIZE, }); -var fixtures = [ "mysql-2", "mysql2-1"] -fixtures.forEach(function(fixture) { - describe('test-trace-' + fixture, function() { - var connection; - var mysql; - var pool; - before(function() { +const fixtures = ['mysql-2', 'mysql2-1']; +fixtures.forEach(fixture => { + describe('test-trace-' + fixture, () => { + let connection; + let mysql; + let pool; + before(() => { mysql = require('./fixtures/' + fixture); - pool = mysql.createPool(require('../mysql-config'/*.js*/)); + // eslint-disable-next-line @typescript-eslint/no-var-requires + pool = mysql.createPool(require('../mysql-config' /*.js*/)); }); - after(function() { + after(() => { pool.end(); }); - beforeEach(function(done) { - pool.getConnection(function(err, conn) { + beforeEach(done => { + pool.getConnection((err, conn) => { assert(!err, 'Skipping: Failed to connect to mysql.'); - conn.query('CREATE TABLE t (k int(10), v varchar(10))', function(err) { + conn.query('CREATE TABLE t (k int(10), v varchar(10))', err => { assert(!err, err); - conn.query('INSERT INTO t SET ?', obj, function(err, res) { + conn.query('INSERT INTO t SET ?', obj, (err, res) => { connection = conn; assert(!err); assert.strictEqual(res.affectedRows, 1); @@ -61,8 +64,8 @@ fixtures.forEach(function(fixture) { }); }); - afterEach(function(done) { - connection.query('DROP TABLE t', function(err) { + afterEach(done => { + connection.query('DROP TABLE t', err => { assert(!err); connection.release(); common.cleanTraces(); @@ -70,15 +73,15 @@ fixtures.forEach(function(fixture) { }); }); - it('should perform basic operations', function(done) { - common.runInTransaction(function(endRootSpan) { - connection.query('SELECT * FROM t', function(err, res) { + it('should perform basic operations', done => { + common.runInTransaction(endRootSpan => { + connection.query('SELECT * FROM t', (err, res) => { endRootSpan(); assert(!err); assert.strictEqual(res.length, 1); assert.strictEqual(res[0].k, 1); assert.strictEqual(res[0].v, 'obj'); - var spans = common.getMatchingSpans(function (span) { + const spans = common.getMatchingSpans(span => { return span.name === 'mysql-query'; }); assert.strictEqual(spans.length, 1); @@ -88,9 +91,9 @@ fixtures.forEach(function(fixture) { }); }); - it('should propagate context', function(done) { - common.runInTransaction(function(endRootSpan) { - connection.query('SELECT * FROM t', function(err, res) { + it('should propagate context', done => { + common.runInTransaction(endRootSpan => { + connection.query('SELECT * FROM t', () => { assert.ok(common.hasContext()); endRootSpan(); done(); @@ -98,34 +101,39 @@ fixtures.forEach(function(fixture) { }); }); - it('should remove trace frames from stack', function(done) { - common.runInTransaction(function(endRootSpan) { - connection.query('SELECT * FROM t', function(err, res) { + it('should remove trace frames from stack', done => { + common.runInTransaction(endRootSpan => { + connection.query('SELECT * FROM t', err => { endRootSpan(); assert(!err); - var spans = common.getMatchingSpans(function (span) { + const spans = common.getMatchingSpans(span => { return span.name === 'mysql-query'; }); - var labels = spans[0].labels; - var stackTrace = JSON.parse(labels[TraceLabels.STACK_TRACE_DETAILS_KEY]); + const labels = spans[0].labels; + const stackTrace = JSON.parse( + labels[TraceLabels.STACK_TRACE_DETAILS_KEY] + ); // Ensure that our patch is on top of the stack assert( - stackTrace.stack_frame[0].method_name.indexOf('createQuery_trace') !== -1); + stackTrace.stack_frame[0].method_name.indexOf( + 'createQuery_trace' + ) !== -1 + ); done(); }); }); }); - it('should work with events', function(done) { - common.runInTransaction(function(endRootSpan) { - var query = connection.query('SELECT * FROM t'); - query.on('result', function(row) { + it('should work with events', done => { + common.runInTransaction(endRootSpan => { + const query = connection.query('SELECT * FROM t'); + query.on('result', row => { assert.strictEqual(row.k, 1); assert.strictEqual(row.v, 'obj'); }); - query.on('end', function() { + query.on('end', () => { endRootSpan(); - var spans = common.getMatchingSpans(function (span) { + const spans = common.getMatchingSpans(span => { return span.name === 'mysql-query'; }); assert.strictEqual(spans.length, 1); @@ -135,12 +143,12 @@ fixtures.forEach(function(fixture) { }); }); - it('should work without events or callback', function(done) { - common.runInTransaction(function(endRootSpan) { + it('should work without events or callback', done => { + common.runInTransaction(endRootSpan => { connection.query('SELECT * FROM t'); - setTimeout(function() { + setTimeout(() => { endRootSpan(); - var spans = common.getMatchingSpans(function (span) { + const spans = common.getMatchingSpans(span => { return span.name === 'mysql-query'; }); assert.strictEqual(spans.length, 1); @@ -150,40 +158,46 @@ fixtures.forEach(function(fixture) { }); }); - it('should perform basic transaction', function(done) { - var obj2 = { + it('should perform basic transaction', done => { + const obj2 = { k: 2, - v: 'obj2' + v: 'obj2', }; - common.runInTransaction(function(endRootSpan) { - connection.beginTransaction(function(err) { + common.runInTransaction(endRootSpan => { + connection.beginTransaction(err => { assert(!err); - connection.query('INSERT INTO t SET ?', obj2, function(err, res) { + connection.query('INSERT INTO t SET ?', obj2, err => { assert(!err); - connection.query('SELECT * FROM t', function(err, res) { + connection.query('SELECT * FROM t', (err, res) => { assert(!err); assert.strictEqual(res.length, 2); assert.strictEqual(res[0].k, 1); assert.strictEqual(res[0].v, 'obj'); assert.strictEqual(res[1].k, 2); assert.strictEqual(res[1].v, 'obj2'); - connection.rollback(function(err) { + connection.rollback(err => { assert(!err); - connection.query('SELECT * FROM t', function(err, res) { + connection.query('SELECT * FROM t', (err, res) => { assert(!err); - connection.commit(function(err) { + connection.commit(err => { endRootSpan(); assert(!err); assert.strictEqual(res.length, 1); assert.strictEqual(res[0].k, 1); assert.strictEqual(res[0].v, 'obj'); - var spans = common.getMatchingSpans(function (span) { + const spans = common.getMatchingSpans(span => { return span.name === 'mysql-query'; }); - var expectedCmds = ['START TRANSACTION', 'INSERT INTO t SET ?', - 'SELECT * FROM t', 'ROLLBACK', 'SELECT * FROM t', 'COMMIT']; + const expectedCmds = [ + 'START TRANSACTION', + 'INSERT INTO t SET ?', + 'SELECT * FROM t', + 'ROLLBACK', + 'SELECT * FROM t', + 'COMMIT', + ]; assert.strictEqual(expectedCmds.length, spans.length); - for (var i = 0; i < spans.length; i++) { + for (let i = 0; i < spans.length; i++) { assert.strictEqual(spans[i].labels.sql, expectedCmds[i]); } done(); diff --git a/test/plugins/test-trace-node-fetch.ts b/test/plugins/test-trace-node-fetch.ts index 3e5d5a534..2380fe500 100644 --- a/test/plugins/test-trace-node-fetch.ts +++ b/test/plugins/test-trace-node-fetch.ts @@ -12,10 +12,11 @@ // See the License for the specific language governing permissions and // limitations under the License. +// eslint-disable-next-line node/no-extraneous-import import * as fetchTypes from 'node-fetch'; // For types only. import * as testTraceModule from '../trace'; import * as assert from 'assert'; -import {describe, it} from 'mocha'; +import {it, before, after, beforeEach} from 'mocha'; import {describeInterop} from '../utils'; import {Express4} from '../web-frameworks/express'; import {Express4Secure} from '../web-frameworks/express-secure'; diff --git a/test/plugins/test-trace-pg.ts b/test/plugins/test-trace-pg.ts index a8e9ed8df..11ea6a78b 100644 --- a/test/plugins/test-trace-pg.ts +++ b/test/plugins/test-trace-pg.ts @@ -11,46 +11,51 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. -'use strict'; -import { TraceLabels } from '../../src/trace-labels'; -import { FORCE_NEW } from '../../src/util'; +import {TraceLabels} from '../../src/trace-labels'; +import {FORCE_NEW} from '../../src/util'; -var common = require('./common'/*.js*/); -var assert = require('assert'); +// eslint-disable-next-line @typescript-eslint/no-var-requires +const common = require('./common' /*.js*/); +import * as assert from 'assert'; +import {describe, it, before, beforeEach, afterEach} from 'mocha'; -var pgVersions = ['6', '7']; +const pgVersions = ['6', '7']; pgVersions.forEach(pgVersion => { - describe(`test-trace-pg (v${pgVersion})`, function() { - var pg; - var traceApi; - var pool; - var client; - var releaseClient; - before(function() { + describe(`test-trace-pg (v${pgVersion})`, () => { + let pg; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + let traceApi; + let pool; + let client; + let releaseClient; + before(() => { traceApi = require('../../..').start({ projectId: '0', samplingRate: 0, enhancedDatabaseReporting: true, - [FORCE_NEW]: true + [FORCE_NEW]: true, }); pg = require(`./fixtures/pg${pgVersion}`); - pool = new pg.Pool(require('../pg-config'/*.js*/)); + pool = new pg.Pool(require('../pg-config' /*.js*/)); }); - beforeEach(function(done) { - pool.connect(function(err, c, release) { + beforeEach(done => { + pool.connect((err, c, release) => { client = c; releaseClient = release; assert(!err); - client.query('DROP TABLE t', [], function(err, res) { - assert(!err || err.code == '42P01'); // table "t" does not exist - client.query('CREATE TABLE t (name text NOT NULL, id text NOT NULL)', [], - function(err, res) { - assert(!err); - done(); - }); + client.query('DROP TABLE t', [], err => { + assert(!err || err.code === '42P01'); // table "t" does not exist + client.query( + 'CREATE TABLE t (name text NOT NULL, id text NOT NULL)', + [], + err => { + assert(!err); + done(); + } + ); }); }); }); @@ -60,64 +65,91 @@ pgVersions.forEach(pgVersion => { common.cleanTraces(); }); - it('should perform basic operations', function(done) { - common.runInTransaction(function(endRootSpan) { - client.query('INSERT INTO t (name, id) VALUES($1, $2)', - ['test_name', 'test_id'], function(err, res) { - endRootSpan(); - assert(!err); - var span = common.getMatchingSpan(function (span) { - return span.name === 'pg-query'; - }); - assert.strictEqual(span.labels.query, 'INSERT INTO t (name, id) VALUES($1, $2)'); - assert.strictEqual(span.labels.values, '[ \'test_name\', \'test_id\' ]'); - assert.strictEqual(span.labels.row_count, '1'); - assert.strictEqual(span.labels.oid, '0'); - assert.strictEqual(span.labels.rows, '[]'); - assert.strictEqual(span.labels.fields, '[]'); - done(); - }); - }); - }); - - it('should perform basic operations with promises', function(done) { - common.runInTransaction(function(endRootSpan) { - client.query('INSERT INTO t (name, id) VALUES($1, $2)', - ['test_name', 'test_id']) - .then((res) => { + it('should perform basic operations', done => { + common.runInTransaction(endRootSpan => { + client.query( + 'INSERT INTO t (name, id) VALUES($1, $2)', + ['test_name', 'test_id'], + err => { endRootSpan(); - var span = common.getMatchingSpan(function (span) { + assert(!err); + const span = common.getMatchingSpan(span => { return span.name === 'pg-query'; }); - assert.strictEqual(span.labels.query, 'INSERT INTO t (name, id) VALUES($1, $2)'); - assert.strictEqual(span.labels.values, '[ \'test_name\', \'test_id\' ]'); + assert.strictEqual( + span.labels.query, + 'INSERT INTO t (name, id) VALUES($1, $2)' + ); + assert.strictEqual( + span.labels.values, + "[ 'test_name', 'test_id' ]" + ); assert.strictEqual(span.labels.row_count, '1'); assert.strictEqual(span.labels.oid, '0'); assert.strictEqual(span.labels.rows, '[]'); assert.strictEqual(span.labels.fields, '[]'); done(); - }, (err) => { - assert.fail('Error not expected'); - }); + } + ); }); }); - it('should propagate context', function(done) { - common.runInTransaction(function(endRootSpan) { - client.query('INSERT INTO t (name, id) VALUES($1, $2)', - ['test_name', 'test_id'], function(err, res) { - assert.ok(common.hasContext()); - endRootSpan(); - done(); - }); + it('should perform basic operations with promises', done => { + common.runInTransaction(endRootSpan => { + client + .query('INSERT INTO t (name, id) VALUES($1, $2)', [ + 'test_name', + 'test_id', + ]) + .then( + () => { + endRootSpan(); + const span = common.getMatchingSpan(span => { + return span.name === 'pg-query'; + }); + assert.strictEqual( + span.labels.query, + 'INSERT INTO t (name, id) VALUES($1, $2)' + ); + assert.strictEqual( + span.labels.values, + "[ 'test_name', 'test_id' ]" + ); + assert.strictEqual(span.labels.row_count, '1'); + assert.strictEqual(span.labels.oid, '0'); + assert.strictEqual(span.labels.rows, '[]'); + assert.strictEqual(span.labels.fields, '[]'); + done(); + }, + () => { + assert.fail('Error not expected'); + } + ); }); }); - it('should propagate context with promises', function(done) { - common.runInTransaction(function(endRootSpan) { - client.query('INSERT INTO t (name, id) VALUES($1, $2)', - ['test_name', 'test_id']) - .then((res) => { + it('should propagate context', done => { + common.runInTransaction(endRootSpan => { + client.query( + 'INSERT INTO t (name, id) VALUES($1, $2)', + ['test_name', 'test_id'], + () => { + assert.ok(common.hasContext()); + endRootSpan(); + done(); + } + ); + }); + }); + + it('should propagate context with promises', done => { + common.runInTransaction(endRootSpan => { + client + .query('INSERT INTO t (name, id) VALUES($1, $2)', [ + 'test_name', + 'test_id', + ]) + .then(() => { assert.ok(common.hasContext()); endRootSpan(); done(); @@ -125,33 +157,38 @@ pgVersions.forEach(pgVersion => { }); }); - it('should remove trace frames from stack', function(done) { - common.runInTransaction(function(endRootSpan) { - client.query('SELECT $1::int AS number', [1], function(err, res) { + it('should remove trace frames from stack', done => { + common.runInTransaction(endRootSpan => { + client.query('SELECT $1::int AS number', [1], err => { endRootSpan(); assert(!err); - var span = common.getMatchingSpan(function (span) { + const span = common.getMatchingSpan(span => { return span.name === 'pg-query'; }); - var labels = span.labels; - var stackTrace = JSON.parse(labels[TraceLabels.STACK_TRACE_DETAILS_KEY]); + const labels = span.labels; + const stackTrace = JSON.parse( + labels[TraceLabels.STACK_TRACE_DETAILS_KEY] + ); // Ensure that our patch is on top of the stack assert( - stackTrace.stack_frame[0].method_name.indexOf('query_trace') !== -1); + stackTrace.stack_frame[0].method_name.indexOf('query_trace') !== -1 + ); done(); }); }); }); - it('should work with events', function(done) { - common.runInTransaction(function(endRootSpan) { - var query = client.query(new pg.Query('SELECT $1::int AS number', [1])); - query.on('row', function(row) { + it('should work with events', done => { + common.runInTransaction(endRootSpan => { + const query = client.query( + new pg.Query('SELECT $1::int AS number', [1]) + ); + query.on('row', row => { assert.strictEqual(row.number, 1); }); - query.on('end', function() { + query.on('end', () => { endRootSpan(); - var span = common.getMatchingSpan(function (span) { + const span = common.getMatchingSpan(span => { return span.name === 'pg-query'; }); assert.strictEqual(span.labels.query, 'SELECT $1::int AS number'); @@ -161,30 +198,30 @@ pgVersions.forEach(pgVersion => { }); }); - it('should work with generic Submittables', function(done) { - common.runInTransaction(function(endRootSpan) { + it('should work with generic Submittables', done => { + common.runInTransaction(endRootSpan => { client.query({ - submit: (connection) => { + submit: connection => { // Indicate that the next item may be processed. connection.emit('readyForQuery'); }, handleReadyForQuery: () => { endRootSpan(); - common.getMatchingSpan(function (span) { + common.getMatchingSpan(span => { return span.name === 'pg-query'; }); done(); - } + }, }); }); }); - it('should work without events or callback', function(done) { - common.runInTransaction(function(endRootSpan) { + it('should work without events or callback', done => { + common.runInTransaction(endRootSpan => { client.query('SELECT $1::int AS number', [1]); - setTimeout(function() { + setTimeout(() => { endRootSpan(); - var span = common.getMatchingSpan(function (span) { + const span = common.getMatchingSpan(span => { return span.name === 'pg-query'; }); assert.strictEqual(span.labels.query, 'SELECT $1::int AS number'); diff --git a/test/plugins/test-trace-redis.ts b/test/plugins/test-trace-redis.ts index a7a83d953..9a740a0b3 100644 --- a/test/plugins/test-trace-redis.ts +++ b/test/plugins/test-trace-redis.ts @@ -11,74 +11,78 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. -'use strict'; -import { TraceLabels } from '../../src/trace-labels'; -import { describeInterop } from '../utils'; +import {TraceLabels} from '../../src/trace-labels'; +import {describeInterop} from '../utils'; // Prereqs: // Start docker daemon // ex) docker -d // Run a redis image binding the redis port // ex) docker run -p 6379:6379 -d redis -var common = require('./common'/*.js*/); +// eslint-disable-next-line @typescript-eslint/no-var-requires +const common = require('./common' /*.js*/); -var RESULT_SIZE = 5; +const RESULT_SIZE = 5; -var assert = require('assert'); +import * as assert from 'assert'; +import {describe, it, before, beforeEach, afterEach} from 'mocha'; -describe('redis', function() { - var agent; +describe('redis', () => { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + let agent; - before(function() { + before(() => { agent = require('../../..').start({ projectId: '0', samplingRate: 0, enhancedDatabaseReporting: true, - databaseResultReportingSize: RESULT_SIZE + databaseResultReportingSize: RESULT_SIZE, }); }); - var client; - describeInterop('redis', function(fixture) { - var redis; - before(function() { + let client; + describeInterop('redis', fixture => { + let redis; + before(() => { redis = fixture.require(); }); - beforeEach(function(done) { + beforeEach(done => { client = redis.createClient(); - client.on('error', function(err) { + client.on('error', err => { assert(false, 'redis error ' + err); }); - client.set('beforeEach', 42, function() { + client.set('beforeEach', 42, () => { common.cleanTraces(); done(); }); }); - afterEach(function(done) { - client.quit(function() { + afterEach(done => { + client.quit(() => { common.cleanTraces(); done(); }); }); - it('should accurately measure get time', function(done) { - common.runInTransaction(function(endTransaction) { - client.get('beforeEach', function(err, n) { + it('should accurately measure get time', done => { + common.runInTransaction(endTransaction => { + client.get('beforeEach', (err, n) => { endTransaction(); assert.strictEqual(Number(n), 42); - var trace = common.getMatchingSpan(redisPredicate.bind(null, 'redis-get')); + const trace = common.getMatchingSpan( + redisPredicate.bind(null, 'redis-get') + ); assert(trace); done(); }); }); }); - it('should propagate context', function(done) { - common.runInTransaction(function(endTransaction) { - client.get('beforeEach', function(err, n) { + it('should propagate context', done => { + common.runInTransaction(endTransaction => { + client.get('beforeEach', () => { assert.ok(common.hasContext()); endTransaction(); done(); @@ -86,40 +90,51 @@ describe('redis', function() { }); }); - it('should accurately measure set time', function(done) { - common.runInTransaction(function(endTransaction) { - client.set('key', 'redis_value', function(err) { + it('should accurately measure set time', done => { + common.runInTransaction(endTransaction => { + client.set('key', 'redis_value', () => { endTransaction(); - var trace = common.getMatchingSpan(redisPredicate.bind(null, 'redis-set')); + const trace = common.getMatchingSpan( + redisPredicate.bind(null, 'redis-set') + ); assert(trace); done(); }); }); }); - it('should accurately measure hset time', function(done) { - common.runInTransaction(function(endTransaction) { + it('should accurately measure hset time', done => { + common.runInTransaction(endTransaction => { // Test error case as hset requires 3 parameters - client.hset('key', 'redis_value', function(err) { + client.hset('key', 'redis_value', () => { endTransaction(); - var trace = common.getMatchingSpan(redisPredicate.bind(null, 'redis-hset')); + const trace = common.getMatchingSpan( + redisPredicate.bind(null, 'redis-hset') + ); assert(trace); done(); }); }); }); - it('should remove trace frames from stack', function(done) { - common.runInTransaction(function(endTransaction) { + it('should remove trace frames from stack', done => { + common.runInTransaction(endTransaction => { // Test error case as hset requires 3 parameters - client.hset('key', 'redis_value', function(err) { + client.hset('key', 'redis_value', () => { endTransaction(); - var trace = common.getMatchingSpan(redisPredicate.bind(null, 'redis-hset')); - var labels = trace.labels; - var stackTrace = JSON.parse(labels[TraceLabels.STACK_TRACE_DETAILS_KEY]); + const trace = common.getMatchingSpan( + redisPredicate.bind(null, 'redis-hset') + ); + const labels = trace.labels; + const stackTrace = JSON.parse( + labels[TraceLabels.STACK_TRACE_DETAILS_KEY] + ); // Ensure that our patch is on top of the stack assert( - stackTrace.stack_frame[0].method_name.indexOf('send_command_trace') !== -1); + stackTrace.stack_frame[0].method_name.indexOf( + 'send_command_trace' + ) !== -1 + ); done(); }); }); @@ -128,8 +143,7 @@ describe('redis', function() { }); function redisPredicate(id, span) { - return span.name.length >= id.length && - span.name.substr(0, id.length) === id; + return span.name.length >= id.length && span.name.substr(0, id.length) === id; } export default {}; diff --git a/test/test-agent-stopped.ts b/test/test-agent-stopped.ts index c7d66e68a..21764c4c5 100644 --- a/test/test-agent-stopped.ts +++ b/test/test-agent-stopped.ts @@ -13,12 +13,12 @@ // limitations under the License. import * as assert from 'assert'; -import {describe, it} from 'mocha'; +import {describe, it, before, after} from 'mocha'; import * as http from 'http'; import * as traceTestModule from './trace'; -import { pluginLoader, PluginLoaderState } from '../src/trace-plugin-loader'; -import { TraceWriter } from '../src/trace-writer'; -import { StackdriverTracer } from '../src/trace-api'; +import {pluginLoader, PluginLoaderState} from '../src/trace-plugin-loader'; +import {TraceWriter} from '../src/trace-writer'; +import {StackdriverTracer} from '../src/trace-api'; describe('test-agent-stopped', () => { class InitErrorTraceWriter extends TraceWriter { @@ -27,7 +27,7 @@ describe('test-agent-stopped', () => { } } - before((done) => { + before(done => { traceTestModule.setPluginLoaderForTest(); traceTestModule.setTraceWriterForTest(InitErrorTraceWriter); traceTestModule.start(); @@ -44,20 +44,26 @@ describe('test-agent-stopped', () => { }); it('deactivates the plugin loader', () => { - assert.notStrictEqual(pluginLoader.get()!.state, PluginLoaderState.ACTIVATED); + assert.notStrictEqual( + pluginLoader.get()!.state, + PluginLoaderState.ACTIVATED + ); }); - describe('express', function() { - it('should not break if no project number is found', function(done) { - var app = require('./plugins/fixtures/express4')(); - app.get('/', function (req, res) { + describe('express', () => { + it('should not break if no project number is found', done => { + // eslint-disable-next-line @typescript-eslint/no-var-requires + const app = require('./plugins/fixtures/express4')(); + app.get('/', (req, res) => { res.send('hi'); }); - var server = app.listen(8080, function() { - http.get('http://localhost:8080', function(res) { - var result = ''; - res.on('data', function(data) { result += data; }); - res.on('end', function() { + const server = app.listen(8080, () => { + http.get('http://localhost:8080', res => { + let result = ''; + res.on('data', data => { + result += data; + }); + res.on('end', () => { assert.strictEqual('hi', result); server.close(); done(); @@ -67,23 +73,26 @@ describe('test-agent-stopped', () => { }); }); - describe('hapi', function() { - it('should not break if no project number is found', function(done) { - var hapi = require('./plugins/fixtures/hapi8'); - var server = new hapi.Server(); - server.connection({ port: 8081 }); + describe('hapi', () => { + it('should not break if no project number is found', done => { + // eslint-disable-next-line @typescript-eslint/no-var-requires + const hapi = require('./plugins/fixtures/hapi8'); + const server = new hapi.Server(); + server.connection({port: 8081}); server.route({ method: 'GET', path: '/', - handler: function(req, reply) { + handler: function (req, reply) { reply('hi'); - } + }, }); - server.start(function() { - http.get('http://localhost:8081', function(res) { - var result = ''; - res.on('data', function(data) { result += data; }); - res.on('end', function() { + server.start(() => { + http.get('http://localhost:8081', res => { + let result = ''; + res.on('data', data => { + result += data; + }); + res.on('end', () => { assert.strictEqual('hi', result); server.stop(); done(); @@ -93,23 +102,26 @@ describe('test-agent-stopped', () => { }); }); - describe('restify', function() { - it('should not break if no project number is found', function(done) { - var restify = require('./plugins/fixtures/restify4'); - var server = restify.createServer(); - server.get('/', function (req, res, next) { + describe('restify', () => { + it('should not break if no project number is found', done => { + // eslint-disable-next-line @typescript-eslint/no-var-requires + const restify = require('./plugins/fixtures/restify4'); + const server = restify.createServer(); + server.get('/', (req, res, next) => { res.writeHead(200, { - 'Content-Type': 'text/plain' + 'Content-Type': 'text/plain', }); res.write('hi'); res.end(); return next(); }); - server.listen(8082, function() { - http.get('http://localhost:8082', function(res) { - var result = ''; - res.on('data', function(data) { result += data; }); - res.on('end', function() { + server.listen(8082, () => { + http.get('http://localhost:8082', res => { + let result = ''; + res.on('data', data => { + result += data; + }); + res.on('end', () => { assert.strictEqual('hi', result); server.close(); done(); diff --git a/test/test-cls-ah.ts b/test/test-cls-ah.ts index 9f4d34629..d92409b88 100644 --- a/test/test-cls-ah.ts +++ b/test/test-cls-ah.ts @@ -13,7 +13,7 @@ // limitations under the License. import * as assert from 'assert'; -import {describe, it} from 'mocha'; +import {describe, it, beforeEach, before, after} from 'mocha'; import * as asyncHooksModule from 'async_hooks'; import * as semver from 'semver'; @@ -37,22 +37,25 @@ maybeSkip(describe)('AsyncHooks-based CLS', () => { // Polyfill for versions in which runInAsyncScope isn't defined. // This can be removed when it's guaranteed that runInAsyncScope is // present on AsyncResource. - // tslint:disable:no-any runInAsyncScope( + // eslint-disable-next-line @typescript-eslint/no-explicit-any fn: (this: This, ...args: any[]) => Result, thisArg?: This ): Result { if (super.runInAsyncScope) { + // eslint-disable-next-line prefer-rest-params return super.runInAsyncScope.apply(this, arguments); } else { - // tslint:disable:deprecation + // eslint-disable-next-line @typescript-eslint/no-explicit-any (this as any).emitBefore(); try { return fn.apply( thisArg, + // eslint-disable-next-line prefer-rest-params Array.prototype.slice.apply(arguments).slice(2) ); } finally { + // eslint-disable-next-line @typescript-eslint/no-explicit-any (this as any).emitAfter(); } // tslint:enable:deprecation @@ -75,7 +78,9 @@ maybeSkip(describe)('AsyncHooks-based CLS', () => { init: ( uid: number, type: string, + // eslint-disable-next-line @typescript-eslint/no-unused-vars tid: number, + // eslint-disable-next-line @typescript-eslint/no-unused-vars resource: {promise: Promise} ) => { if (type === 'PROMISE') { @@ -199,7 +204,7 @@ maybeSkip(describe)('AsyncHooks-based CLS', () => { ]; for (const testCase of testCases) { - const skipIfTestSpecifies = !!testCase.skip ? it.skip : it; + const skipIfTestSpecifies = testCase.skip ? it.skip : it; skipIfTestSpecifies( `Doesn't retain stale references when running ${testCase.description} in a context`, async () => { diff --git a/test/test-cls.ts b/test/test-cls.ts index d372f1e27..7d72f643c 100644 --- a/test/test-cls.ts +++ b/test/test-cls.ts @@ -13,7 +13,7 @@ // limitations under the License. import * as assert from 'assert'; -import {describe, it} from 'mocha'; +import {describe, it, beforeEach, afterEach} from 'mocha'; import {EventEmitter} from 'events'; import * as semver from 'semver'; import {inspect} from 'util'; @@ -25,7 +25,7 @@ import {CLS} from '../src/cls/base'; import {NullCLS} from '../src/cls/null'; import {SingularCLS} from '../src/cls/singular'; import {SpanType} from '../src/constants'; -import {createStackTrace, FORCE_NEW} from '../src/util'; +import {createStackTrace} from '../src/util'; import {TestLogger} from './logger'; import {plan} from './utils'; @@ -269,7 +269,7 @@ describe('Continuation-Local Storage', () => { logger.clearLogs(); }); - it(`when disabled, doesn't throw and has reasonable default values`, () => { + it("when disabled, doesn't throw and has reasonable default values", () => { c.disable(); assert.ok(!c.isEnabled()); assert.ok(c.getContext().type, SpanType.UNSAMPLED); @@ -307,13 +307,10 @@ describe('Continuation-Local Storage', () => { } const invalidTestCases: TraceCLSConfig[] = asyncAwaitSupported - ? [ - {mechanism: 'unknown'} as any, // tslint:disable-line:no-any - ] - : [ - {mechanism: 'unknown'} as any, // tslint:disable-line:no-any - {mechanism: 'async-hooks'}, - ]; + ? // eslint-disable-next-line @typescript-eslint/no-explicit-any + [{mechanism: 'unknown'} as any] + : // eslint-disable-next-line @typescript-eslint/no-explicit-any + [{mechanism: 'unknown'} as any, {mechanism: 'async-hooks'}]; for (const testCase of invalidTestCases) { describe(`with configuration ${inspect(testCase)}`, () => { diff --git a/test/test-config-max-label-size.ts b/test/test-config-max-label-size.ts index 52e46616c..998b7daea 100644 --- a/test/test-config-max-label-size.ts +++ b/test/test-config-max-label-size.ts @@ -12,25 +12,27 @@ // See the License for the specific language governing permissions and // limitations under the License. -'use strict'; +import {Constants} from '../src/constants'; +import {traceWriter} from '../src/trace-writer'; +import {FORCE_NEW} from '../src/util'; -import { Constants } from '../src/constants'; -import { traceWriter } from '../src/trace-writer'; -import { FORCE_NEW } from '../src/util'; +import * as assert from 'assert'; +import {describe, it} from 'mocha'; +import * as trace from '../src'; -var assert = require('assert'); -var trace = require('../..'); - -describe('maximumLabelValueSize configuration', function() { - it('should not allow values above server maximum', function() { - trace.start({[FORCE_NEW]: true, maximumLabelValueSize: 1000000}); - var valueMax = traceWriter.get().getConfig().maximumLabelValueSize; +describe('maximumLabelValueSize configuration', () => { + it('should not allow values above server maximum', () => { + (trace.start as Function)({ + [FORCE_NEW]: true, + maximumLabelValueSize: 1000000, + }); + const valueMax = traceWriter.get().getConfig().maximumLabelValueSize; assert.strictEqual(valueMax, Constants.TRACE_SERVICE_LABEL_VALUE_LIMIT); }); - it('should not modify values below server maximum', function() { - trace.start({[FORCE_NEW]: true, maximumLabelValueSize: 10}); - var valueMax = traceWriter.get().getConfig().maximumLabelValueSize; + it('should not modify values below server maximum', () => { + (trace.start as Function)({[FORCE_NEW]: true, maximumLabelValueSize: 10}); + const valueMax = traceWriter.get().getConfig().maximumLabelValueSize; assert.strictEqual(valueMax, 10); }); }); diff --git a/test/test-config-plugins.ts b/test/test-config-plugins.ts index eb7b8f2c4..b3332d47d 100644 --- a/test/test-config-plugins.ts +++ b/test/test-config-plugins.ts @@ -13,8 +13,7 @@ // limitations under the License. import * as assert from 'assert'; -import {describe, it} from 'mocha'; - +import {describe, it, before, after, afterEach} from 'mocha'; import {defaultConfig} from '../src/config'; import {StackdriverTracerComponents} from '../src/trace-api'; import {PluginLoader, PluginLoaderConfig} from '../src/trace-plugin-loader'; diff --git a/test/test-config-priority.ts b/test/test-config-priority.ts index 0f28098a4..bc67fe680 100644 --- a/test/test-config-priority.ts +++ b/test/test-config-priority.ts @@ -13,10 +13,8 @@ // limitations under the License. import * as assert from 'assert'; -import {describe, it} from 'mocha'; +import {describe, it, before, after, afterEach} from 'mocha'; import * as path from 'path'; - -import {Trace} from '../src/trace'; import {StackdriverTracer} from '../src/trace-api'; import {TraceWriter} from '../src/trace-writer'; import {TopLevelConfig, Tracing} from '../src/tracing'; @@ -34,7 +32,7 @@ describe('should respect config load order', () => { class NoopTraceWriter extends TraceWriter { async initialize(): Promise {} - writeTrace(trace: Trace): void {} + writeTrace(): void {} } function getCapturedConfig() { diff --git a/test/test-config.ts b/test/test-config.ts index 0a08bc79b..f9fafdbaa 100644 --- a/test/test-config.ts +++ b/test/test-config.ts @@ -13,23 +13,24 @@ // limitations under the License. import * as assert from 'assert'; -import {describe, it} from 'mocha'; +import {describe, it, beforeEach, before, after} from 'mocha'; import * as semver from 'semver'; import * as util from 'util'; import {TraceCLSConfig, TraceCLSMechanism} from '../src/cls'; import * as testTraceModule from './trace'; -import { TopLevelConfig } from '../src/tracing'; -import { StackdriverTracer } from '../src/trace-api'; +import {TopLevelConfig} from '../src/tracing'; +import {StackdriverTracer} from '../src/trace-api'; import {Logger} from '../src/logger'; -import { TraceWriterConfig } from '../src/trace-writer'; +import {TraceWriterConfig} from '../src/trace-writer'; describe('Behavior set by config for CLS', () => { const useAH = semver.satisfies(process.version, '>=8'); - const autoMechanism = - useAH ? TraceCLSMechanism.ASYNC_HOOKS : TraceCLSMechanism.ASYNC_LISTENER; - let capturedConfig: TraceCLSConfig|null; + const autoMechanism = useAH + ? TraceCLSMechanism.ASYNC_HOOKS + : TraceCLSMechanism.ASYNC_LISTENER; + let capturedConfig: TraceCLSConfig | null; class CaptureConfigTestCLS extends testTraceModule.TestCLS { constructor(config: TraceCLSConfig, logger: Logger) { @@ -52,49 +53,49 @@ describe('Behavior set by config for CLS', () => { }); const testCases: Array<{ - tracingConfig: testTraceModule.Config, - contextPropagationConfig: TraceCLSConfig - }> = - [ - { - tracingConfig: {clsMechanism: 'none'}, - contextPropagationConfig: {mechanism: 'none'} - }, - { - tracingConfig: {clsMechanism: 'auto'}, - contextPropagationConfig: {mechanism: autoMechanism} - }, - { - tracingConfig: {}, - contextPropagationConfig: {mechanism: autoMechanism} - }, - { - tracingConfig: {clsMechanism: 'singular'}, - contextPropagationConfig: {mechanism: 'singular'} - }, - { - // tslint:disable:no-any - tracingConfig: {clsMechanism: 'unknown' as any}, - contextPropagationConfig: {mechanism: 'unknown' as any} - // tslint:enable:no-any - } - ]; + tracingConfig: testTraceModule.Config; + contextPropagationConfig: TraceCLSConfig; + }> = [ + { + tracingConfig: {clsMechanism: 'none'}, + contextPropagationConfig: {mechanism: 'none'}, + }, + { + tracingConfig: {clsMechanism: 'auto'}, + contextPropagationConfig: {mechanism: autoMechanism}, + }, + { + tracingConfig: {}, + contextPropagationConfig: {mechanism: autoMechanism}, + }, + { + tracingConfig: {clsMechanism: 'singular'}, + contextPropagationConfig: {mechanism: 'singular'}, + }, + { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + tracingConfig: {clsMechanism: 'unknown' as any}, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + contextPropagationConfig: {mechanism: 'unknown' as any}, + }, + ]; for (const testCase of testCases) { - it(`should be as expected for config: ${ - util.inspect(testCase.tracingConfig)}`, - () => { - testTraceModule.start(testCase.tracingConfig); - assert.ok(capturedConfig); - assert.strictEqual( - capturedConfig!.mechanism, - testCase.contextPropagationConfig.mechanism); - }); + it(`should be as expected for config: ${util.inspect( + testCase.tracingConfig + )}`, () => { + testTraceModule.start(testCase.tracingConfig); + assert.ok(capturedConfig); + assert.strictEqual( + capturedConfig!.mechanism, + testCase.contextPropagationConfig.mechanism + ); + }); } }); describe('Behavior set by config for Tracer', () => { - let capturedConfig: TopLevelConfig|null; + let capturedConfig: TopLevelConfig | null; // Convenience function to assert properties of capturedConfig that we want // to be true on every test, and return just the tracer config. @@ -134,7 +135,7 @@ describe('Behavior set by config for Tracer', () => { describe('Overriding root span name', () => { it('should convert a string to a function', () => { testTraceModule.start({ - rootSpanNameOverride: 'hello' + rootSpanNameOverride: 'hello', }); const config = getCapturedTracerConfig(); assert.strictEqual(typeof config.rootSpanNameOverride, 'function'); @@ -145,8 +146,8 @@ describe('Behavior set by config for Tracer', () => { testTraceModule.start({ // We should make sure passing in unsupported values at least doesn't // result in a crash. - // tslint:disable-next-line:no-any - rootSpanNameOverride: 2 as any + // eslint-disable-next-line @typescript-eslint/no-explicit-any + rootSpanNameOverride: 2 as any, }); const config = getCapturedTracerConfig(); assert.strictEqual(typeof config.rootSpanNameOverride, 'function'); @@ -157,15 +158,17 @@ describe('Behavior set by config for Tracer', () => { describe('Behavior set by config for TracePolicy', () => { it('should throw when conflicting policy options are specified', () => { - assert.throws(() => testTraceModule.start({ - samplingRate: 100, - tracePolicy: { shouldTrace: () => true } - })); + assert.throws(() => + testTraceModule.start({ + samplingRate: 100, + tracePolicy: {shouldTrace: () => true}, + }) + ); }); }); describe('Behavior set by config for TraceWriter', () => { - let capturedConfig: TraceWriterConfig|null; + let capturedConfig: TraceWriterConfig | null; class CaptureConfigTestWriter extends testTraceModule.TestTraceWriter { constructor(config: TraceWriterConfig, logger: Logger) { @@ -188,14 +191,16 @@ describe('Behavior set by config for TraceWriter', () => { }); it('should set auth variables passed to TraceWriter as authOptions', () => { - const credentials = { private_key: 'abc' }; + const credentials = {private_key: 'abc'}; testTraceModule.start({ keyFilename: 'a', - credentials + credentials, }); assert.ok(capturedConfig); assert.strictEqual(capturedConfig!.authOptions.keyFilename, 'a'); - assert.deepStrictEqual(capturedConfig!.authOptions.credentials, credentials); + assert.deepStrictEqual( + capturedConfig!.authOptions.credentials, + credentials + ); }); }); - diff --git a/test/test-env-log-level.ts b/test/test-env-log-level.ts index 5d8efcbe8..5e57e286d 100644 --- a/test/test-env-log-level.ts +++ b/test/test-env-log-level.ts @@ -13,7 +13,7 @@ // limitations under the License. import * as assert from 'assert'; -import {describe, it} from 'mocha'; +import {describe, it, before, after, afterEach} from 'mocha'; import * as shimmer from 'shimmer'; import * as logger from '../src/logger'; diff --git a/test/test-grpc-async-handler.ts b/test/test-grpc-async-handler.ts index 7a5b1423d..21266d5fd 100644 --- a/test/test-grpc-async-handler.ts +++ b/test/test-grpc-async-handler.ts @@ -14,7 +14,7 @@ import * as protoLoader from '@grpc/proto-loader'; import * as grpcModule from 'grpc'; - +import {describe, it, before, afterEach, after} from 'mocha'; import {Tester, TesterClient} from './test-grpc-proto'; import * as traceTestModule from './trace'; import {describeInterop} from './utils'; @@ -93,9 +93,7 @@ describeInterop('grpc', fixture => { const tracer = traceTestModule.get(); await tracer.runInRootSpan({name: 'client-outer'}, async span => { await new Promise((resolve, reject) => - client.TestUnary({n: 0}, (err, res) => - err ? reject(err) : resolve() - ) + client.TestUnary({n: 0}, err => (err ? reject(err) : resolve())) ); span.endSpan(); }); @@ -112,9 +110,7 @@ describeInterop('grpc', fixture => { const tracer = traceTestModule.get(); await tracer.runInRootSpan({name: 'client-outer'}, async span => { await new Promise((resolve, reject) => - client - .TestClientStream((err, res) => (err ? reject(err) : resolve())) - .end() + client.TestClientStream(err => (err ? reject(err) : resolve())).end() ); span.endSpan(); }); diff --git a/test/test-grpc-context.ts b/test/test-grpc-context.ts index 00befb60f..a3f2925d7 100644 --- a/test/test-grpc-context.ts +++ b/test/test-grpc-context.ts @@ -11,36 +11,37 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. -'use strict'; -import { describeInterop } from './utils'; +import {describeInterop} from './utils'; // Trace agent must be started out of the loop over gRPC versions, // because express can't be re-patched. -var agent = require('../..').start({ +require('../..').start({ projectId: '0', samplingRate: 0, - ignoreUrls: ['/no-trace'] + ignoreUrls: ['/no-trace'], }); -var common = require('./plugins/common'/*.js*/); +// eslint-disable-next-line @typescript-eslint/no-var-requires +const common = require('./plugins/common' /*.js*/); +import {describe, it, before, beforeEach, after, afterEach} from 'mocha'; +import * as assert from 'assert'; +// eslint-disable-next-line @typescript-eslint/no-var-requires +const express = require('./plugins/fixtures/express4'); +import * as http from 'http'; -var assert = require('assert'); -var express = require('./plugins/fixtures/express4'); -var http = require('http'); - -var grpcPort = 50051; -var protoFile = __dirname + '/fixtures/test-grpc.proto'; -var client, grpcServer, server; +const grpcPort = 50051; +const protoFile = __dirname + '/fixtures/test-grpc.proto'; +let client, grpcServer, server; function makeHttpRequester(callback, expectedReqs) { - var pendingHttpReqs = expectedReqs; - return function() { + let pendingHttpReqs = expectedReqs; + return function () { // Make a request to an endpoint that won't create an additional server // trace. - http.get(`http://localhost:${common.serverPort}/no-trace`, function(httpRes) { - httpRes.on('data', function() {}); - httpRes.on('end', function() { + http.get(`http://localhost:${common.serverPort}/no-trace`, httpRes => { + httpRes.on('data', () => {}); + httpRes.on('end', () => { if (--pendingHttpReqs === 0) { callback(); } @@ -50,128 +51,132 @@ function makeHttpRequester(callback, expectedReqs) { } function requestAndSendHTTPStatus(res, expectedReqs) { - return makeHttpRequester(function () { + return makeHttpRequester(() => { res.sendStatus(200); }, expectedReqs); } describeInterop('grpc', fixture => { describe('Context Propagation', () => { - var grpc; - var httpLogCount; + let grpc; + let httpLogCount; - before(function(done) { + before(done => { grpc = fixture.require(); - common.replaceWarnLogger(function(msg) { + common.replaceWarnLogger(msg => { if (msg.indexOf('http') !== -1) { httpLogCount++; } }); - var proto = grpc.load(protoFile).nodetest; - var app = express(); + const proto = grpc.load(protoFile).nodetest; + const app = express(); - app.get('/no-trace', function(req, res) { + app.get('/no-trace', (req, res) => { res.sendStatus(200); }); - app.get('/unary', function(req, res) { - var httpRequester = requestAndSendHTTPStatus(res, 1); + app.get('/unary', (req, res) => { + const httpRequester = requestAndSendHTTPStatus(res, 1); client.testUnary({n: 42}, httpRequester); }); - app.get('/client', function(req, res) { - var httpRequester = requestAndSendHTTPStatus(res, 1); - var stream = client.testClientStream(httpRequester); - for (var i = 0; i < 10; ++i) { + app.get('/client', (req, res) => { + const httpRequester = requestAndSendHTTPStatus(res, 1); + const stream = client.testClientStream(httpRequester); + for (let i = 0; i < 10; ++i) { stream.write({n: i}); } stream.end(); }); - app.get('/server', function(req, res) { - var httpRequester = requestAndSendHTTPStatus(res, 11); - var stream = client.testServerStream({n: 3}); + app.get('/server', (req, res) => { + const httpRequester = requestAndSendHTTPStatus(res, 11); + const stream = client.testServerStream({n: 3}); stream.on('data', httpRequester); stream.on('status', httpRequester); }); - app.get('/bidi', function(req, res) { - var httpRequester = requestAndSendHTTPStatus(res, 11); - var stream = client.testBidiStream(); + app.get('/bidi', (req, res) => { + const httpRequester = requestAndSendHTTPStatus(res, 11); + const stream = client.testBidiStream(); stream.on('data', httpRequester); stream.on('status', httpRequester); - for (var i = 0; i < 10; ++i) { + for (let i = 0; i < 10; ++i) { stream.write({n: i}); } stream.end(); }); - client = new proto.Tester('localhost:' + grpcPort, - grpc.credentials.createInsecure()); + client = new proto.Tester( + 'localhost:' + grpcPort, + grpc.credentials.createInsecure() + ); - server = app.listen(common.serverPort, function() { + server = app.listen(common.serverPort, () => { grpcServer = new grpc.Server(); grpcServer.addProtoService(proto.Tester.service, { - testUnary: function(call, cb) { - var httpRequester = makeHttpRequester(function () { + testUnary: function (call, cb) { + const httpRequester = makeHttpRequester(() => { cb(null, {n: call.request.n}); }, 1); httpRequester(); }, - testClientStream: function(call, cb) { - var httpRequester = makeHttpRequester(function () { + testClientStream: function (call, cb) { + const httpRequester = makeHttpRequester(() => { cb(null, {n: 43}); }, 11); call.on('data', httpRequester); call.on('end', httpRequester); }, - testServerStream: function(stream) { - var httpRequester = makeHttpRequester(function () { + testServerStream: function (stream) { + const httpRequester = makeHttpRequester(() => { stream.end(); }, 1); - for (var i = 0; i < 10; ++i) { + for (let i = 0; i < 10; ++i) { stream.write({n: i}); } httpRequester(); }, - testBidiStream: function(stream) { - var httpRequester = makeHttpRequester(function () { + testBidiStream: function (stream) { + const httpRequester = makeHttpRequester(() => { stream.end(); }, 11); - stream.on('data', function(data) { + stream.on('data', data => { stream.write({n: data.n}); httpRequester(); }); stream.on('end', httpRequester); - } + }, }); - grpcServer.bind('localhost:' + grpcPort, - grpc.ServerCredentials.createInsecure()); + grpcServer.bind( + 'localhost:' + grpcPort, + grpc.ServerCredentials.createInsecure() + ); grpcServer.start(); done(); }); }); - beforeEach(function() { + beforeEach(() => { httpLogCount = 0; }); - after(function() { + after(() => { grpcServer.forceShutdown(); server.close(); }); - afterEach(function() { + afterEach(() => { // We expect a single untraced http request for each test cooresponding to the // top level request used to start the desired test. assert.strictEqual(httpLogCount, 1); common.cleanTraces(); }); - it('grpc should preserve context for unary requests', function(done) { - http.get({port: common.serverPort, path: '/unary'}, function(res) { + it('grpc should preserve context for unary requests', done => { + http.get({port: common.serverPort, path: '/unary'}, () => { assert.strictEqual(common.getTraces().length, 2); // gRPC Server: 1 root span, 1 http span. assert.strictEqual(common.getTraces()[0].spans.length, 2); @@ -182,8 +187,8 @@ describeInterop('grpc', fixture => { }); }); - it('grpc should preserve context for client requests', function(done) { - http.get({port: common.serverPort, path: '/client'}, function(res) { + it('grpc should preserve context for client requests', done => { + http.get({port: common.serverPort, path: '/client'}, () => { assert.strictEqual(common.getTraces().length, 2); // gRPC Server: 1 root span, 11 http spans (10 from 'data' listeners, // 1 from 'end' listener). @@ -195,8 +200,8 @@ describeInterop('grpc', fixture => { }); }); - it('grpc should preserve context for server requests', function(done) { - http.get({port: common.serverPort, path: '/server'}, function(res) { + it('grpc should preserve context for server requests', done => { + http.get({port: common.serverPort, path: '/server'}, () => { assert.strictEqual(common.getTraces().length, 2); // gRPC Server: 1 root span, 1 http span. assert.strictEqual(common.getTraces()[0].spans.length, 2); @@ -208,8 +213,8 @@ describeInterop('grpc', fixture => { }); }); - it('grpc should preserve context for bidi requests', function(done) { - http.get({port: common.serverPort, path: '/bidi'}, function(res) { + it('grpc should preserve context for bidi requests', done => { + http.get({port: common.serverPort, path: '/bidi'}, () => { assert.strictEqual(common.getTraces().length, 2); // gRPC Server: 1 root span, 11 http spans (10 from 'data' listeners, // 1 from 'end' listener). diff --git a/test/test-grpc-proto.d.ts b/test/test-grpc-proto.d.ts index 79ddea8f2..cd34269df 100644 --- a/test/test-grpc-proto.d.ts +++ b/test/test-grpc-proto.d.ts @@ -12,10 +12,21 @@ // See the License for the specific language governing permissions and // limitations under the License. -import { handleUnaryCall, handleClientStreamingCall, handleServerStreamingCall, handleBidiStreamingCall, Client, requestCallback, ClientUnaryCall, ClientWritableStream, ClientReadableStream, ClientDuplexStream } from 'grpc'; +import { + handleUnaryCall, + handleClientStreamingCall, + handleServerStreamingCall, + handleBidiStreamingCall, + Client, + requestCallback, + ClientUnaryCall, + ClientWritableStream, + ClientReadableStream, + ClientDuplexStream, +} from 'grpc'; -export type TestRequest = { n: number }; -export type TestResponse = { n: number }; +export type TestRequest = {n: number}; +export type TestResponse = {n: number}; export type Tester = { TestUnary?: handleUnaryCall; TestClientStream?: handleClientStreamingCall; @@ -30,8 +41,13 @@ export type Tester = { // Incomplete definition for Tester client. Overloads and lowercase aliases are // not included for now, as they're not used anywhere. export type TesterClient = Client & { - TestUnary: (arg: TestRequest, cb: requestCallback) => ClientUnaryCall; - TestClientStream: (cb: requestCallback) => ClientWritableStream; + TestUnary: ( + arg: TestRequest, + cb: requestCallback + ) => ClientUnaryCall; + TestClientStream: ( + cb: requestCallback + ) => ClientWritableStream; TestServerStream: (arg: TestRequest) => ClientReadableStream; TestBidiStream: () => ClientDuplexStream; }; diff --git a/test/test-index.ts b/test/test-index.ts index e03b3fbc7..8c08e54a6 100644 --- a/test/test-index.ts +++ b/test/test-index.ts @@ -12,23 +12,21 @@ // See the License for the specific language governing permissions and // limitations under the License. -'use strict'; - import './override-gcp-metadata'; -import { StackdriverTracer } from '../src/trace-api'; -import { SpanType } from '../src/constants'; -import { FORCE_NEW } from '../src/util'; - -var assert = require('assert'); -var trace = require('../..'); +import {StackdriverTracer} from '../src/trace-api'; +import {SpanType} from '../src/constants'; +import {FORCE_NEW} from '../src/util'; +import * as assert from 'assert'; +import * as trace from '../src'; +import {describe, it, before} from 'mocha'; -var disabledAgent: StackdriverTracer = trace.get(); +const disabledAgent = (trace.get() as {}) as StackdriverTracer; -describe('index.js', function() { - it('should get a disabled agent with `Trace.get`', async function() { +describe('index.js', () => { + it('should get a disabled agent with `Trace.get`', async () => { assert.ok(!disabledAgent.isActive()); // ensure it's disabled first let ranInRootSpan = false; - disabledAgent.runInRootSpan({ name: '' }, (span) => { + disabledAgent.runInRootSpan({name: ''}, span => { assert.strictEqual(span.type, SpanType.DISABLED); ranInRootSpan = true; }); @@ -36,37 +34,51 @@ describe('index.js', function() { assert.strictEqual(disabledAgent.enhancedDatabaseReportingEnabled(), false); assert.strictEqual(disabledAgent.getCurrentContextId(), null); assert.strictEqual(disabledAgent.getWriterProjectId(), null); - assert.strictEqual(disabledAgent.getCurrentRootSpan().type, SpanType.DISABLED); + assert.strictEqual( + disabledAgent.getCurrentRootSpan().type, + SpanType.DISABLED + ); // getting project ID should reject. await disabledAgent.getProjectId().then( - () => Promise.reject(new Error()), () => Promise.resolve()); - assert.strictEqual(disabledAgent.createChildSpan({ name: '' }).type, SpanType.DISABLED); - assert.strictEqual(disabledAgent.getResponseTraceContext({ - traceId: '1', - spanId: '1' - }, false), null); + () => Promise.reject(new Error()), + () => Promise.resolve() + ); + assert.strictEqual( + disabledAgent.createChildSpan({name: ''}).type, + SpanType.DISABLED + ); + assert.strictEqual( + disabledAgent.getResponseTraceContext( + { + traceId: '1', + spanId: '1', + }, + false + ), + null + ); const fn = () => {}; assert.strictEqual(disabledAgent.wrap(fn), fn); // TODO(kjin): Figure out how to test wrapEmitter }); - describe('in valid environment', function() { - var agent; - before(function() { - agent = trace.start({ projectId: '0', [FORCE_NEW]: true }); + describe('in valid environment', () => { + let agent; + before(() => { + agent = (trace.start as Function)({projectId: '0', [FORCE_NEW]: true}); }); - it('should get the agent with `Trace.get`', function() { + it('should get the agent with `Trace.get`', () => { assert.strictEqual(agent, trace.get()); }); - it('should throw an error if `start` is called on an active agent', - function() { - assert.throws(trace.start, Error); + it('should throw an error if `start` is called on an active agent', () => { + assert.throws(trace.start, Error); }); - it('should set agent on global object', function() { - assert.strictEqual(global._google_trace_agent, agent); + it('should set agent on global object', () => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + assert.strictEqual((global as any)._google_trace_agent, agent); }); }); }); diff --git a/test/test-invalid-project-id.ts b/test/test-invalid-project-id.ts index 5f0731327..64551dc99 100644 --- a/test/test-invalid-project-id.ts +++ b/test/test-invalid-project-id.ts @@ -12,21 +12,20 @@ // See the License for the specific language governing permissions and // limitations under the License. -'use strict'; - import {FORCE_NEW} from '../src/util'; delete process.env.GCLOUD_PROJECT; -var assert = require('assert'); +import * as assert from 'assert'; +import {describe, it} from 'mocha'; -describe('index.js', function() { - it('should complain when config.projectId is not a string or number', function() { - var agent = require('../..').start({ +describe('index.js', () => { + it('should complain when config.projectId is not a string or number', () => { + const agent = require('../..').start({ projectId: {test: false}, enabled: true, logLevel: 0, - [FORCE_NEW]: true + [FORCE_NEW]: true, }); assert(!agent.isActive()); }); diff --git a/test/test-modules-loaded-before-agent.ts b/test/test-modules-loaded-before-agent.ts index 85c89fa18..70dbdc556 100644 --- a/test/test-modules-loaded-before-agent.ts +++ b/test/test-modules-loaded-before-agent.ts @@ -13,7 +13,7 @@ // limitations under the License. import * as assert from 'assert'; -import {describe, it} from 'mocha'; +import {describe, it, before, after, afterEach} from 'mocha'; import * as shimmer from 'shimmer'; import * as log from '../src/logger'; diff --git a/test/test-mysql-pool.ts b/test/test-mysql-pool.ts index f3cfd5c02..41d86179a 100644 --- a/test/test-mysql-pool.ts +++ b/test/test-mysql-pool.ts @@ -11,60 +11,68 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. -'use strict'; -var common = require('./plugins/common'/*.js*/); -var assert = require('assert'); -var http = require('http'); -var semver = require('semver'); +// eslint-disable-next-line @typescript-eslint/no-var-requires +const common = require('./plugins/common' /*.js*/); +import * as assert from 'assert'; +import * as http from 'http'; +import * as semver from 'semver'; +import {describe, it, before} from 'mocha'; // hapi 13 and hapi-plugin-mysql uses const if (semver.satisfies(process.version, '>=4')) { - describe('test-trace-mysql', function() { - var agent; - var Hapi; - before(function() { + describe('test-trace-mysql', () => { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + let agent; + let Hapi; + before(() => { agent = require('../..').start({ projectId: '0', samplingRate: 0, - enhancedDatabaseReporting: true + enhancedDatabaseReporting: true, }); Hapi = require('./plugins/fixtures/hapi16'); }); - it('should work with connection pool access', function(done) { - var server = new Hapi.Server(); - server.connection({ port: common.serverPort }); - server.register({ - register: require('./plugins/fixtures/hapi-plugin-mysql3'), - options: require('./mysql-config'/*.js*/) - }, function (err) { - assert(!err); - server.route({ - method: 'GET', - path: '/', - handler: function (request, reply) { - request.app.db.query('SELECT * FROM t', function(err, res) { - return reply('hello'); - }); - } - }); - server.start(function(err) { + it('should work with connection pool access', done => { + const server = new Hapi.Server(); + server.connection({port: common.serverPort}); + server.register( + { + register: require('./plugins/fixtures/hapi-plugin-mysql3'), + options: require('./mysql-config' /*.js*/), + }, + err => { assert(!err); - http.get({port: common.serverPort}, function(res) { - var result = ''; - res.on('data', function(data) { result += data; }); - res.on('end', function() { - var spans = common.getMatchingSpans(function (span) { - return span.name === 'mysql-query'; + server.route({ + method: 'GET', + path: '/', + handler: function (request, reply) { + request.app.db.query('SELECT * FROM t', () => { + return reply('hello'); + }); + }, + }); + server.start(err => { + assert(!err); + http.get({port: common.serverPort}, res => { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + let result = ''; + res.on('data', data => { + result += data; + }); + res.on('end', () => { + const spans = common.getMatchingSpans(span => { + return span.name === 'mysql-query'; + }); + assert.strictEqual(spans.length, 1); + assert.strictEqual(spans[0].labels.sql, 'SELECT * FROM t'); + server.stop(done); }); - assert.strictEqual(spans.length, 1); - assert.strictEqual(spans[0].labels.sql, 'SELECT * FROM t'); - server.stop(done); }); }); - }); - }); + } + ); }); }); } diff --git a/test/test-no-self-tracing.ts b/test/test-no-self-tracing.ts index a8a7740eb..bfe1e0769 100644 --- a/test/test-no-self-tracing.ts +++ b/test/test-no-self-tracing.ts @@ -12,56 +12,60 @@ // See the License for the specific language governing permissions and // limitations under the License. -'use strict'; - import {FORCE_NEW} from '../src/util'; import {HOST_ADDRESS} from 'gcp-metadata'; - -var assert = require('assert'); -var nock = require('nock'); -var newWarn = function(error) { +import {describe, it} from 'mocha'; +import * as assert from 'assert'; +import * as nock from 'nock'; +const newWarn = function (error) { if (error.indexOf('http') !== -1) { assert(false, error); } }; -var common = require('./plugins/common'/*.js*/); +// eslint-disable-next-line @typescript-eslint/no-var-requires +const common = require('./plugins/common' /*.js*/); nock.disableNetConnect(); -describe('test-no-self-tracing', function() { - it('should not trace metadata queries', function(done) { - var scope = nock(HOST_ADDRESS) - .get('/computeMetadata/v1/instance/hostname').reply(200) - .get('/computeMetadata/v1/instance/id').reply(200); +describe('test-no-self-tracing', () => { + it('should not trace metadata queries', done => { + const scope = nock(HOST_ADDRESS) + .get('/computeMetadata/v1/instance/hostname') + .reply(200) + .get('/computeMetadata/v1/instance/id') + .reply(200); require('../..').start({[FORCE_NEW]: true}); require('http'); // Must require http to force patching of the module - var oldWarn = common.replaceWarnLogger(newWarn); - setTimeout(function() { + const oldWarn = common.replaceWarnLogger(newWarn); + setTimeout(() => { common.replaceWarnLogger(oldWarn); scope.done(); done(); }, 200); // Need to wait for metadata access attempt }); - it('should not trace publishes', function(done) { - var metadataScope = nock(HOST_ADDRESS) - .get('/computeMetadata/v1/instance/hostname').reply(200) - .get('/computeMetadata/v1/instance/id').reply(200); - var apiScope = nock('https://cloudtrace.googleapis.com') - .patch('/v1/projects/0/traces').reply(200); + it('should not trace publishes', done => { + const metadataScope = nock(HOST_ADDRESS) + .get('/computeMetadata/v1/instance/hostname') + .reply(200) + .get('/computeMetadata/v1/instance/id') + .reply(200); + const apiScope = nock('https://cloudtrace.googleapis.com') + .patch('/v1/projects/0/traces') + .reply(200); delete process.env.GCLOUD_PROJECT; require('../..').start({ projectId: '0', bufferSize: 1, - [FORCE_NEW]: true + [FORCE_NEW]: true, }); common.avoidTraceWriterAuth(); require('http'); // Must require http to force patching of the module - var oldWarn = common.replaceWarnLogger(newWarn); - common.runInTransaction(function(end) { + const oldWarn = common.replaceWarnLogger(newWarn); + common.runInTransaction(end => { end(); - setTimeout(function() { + setTimeout(() => { assert.strictEqual(common.getTraces().length, 0); common.replaceWarnLogger(oldWarn); metadataScope.done(); diff --git a/test/test-plugin-loader.ts b/test/test-plugin-loader.ts index 25ae16d35..7bd733f57 100644 --- a/test/test-plugin-loader.ts +++ b/test/test-plugin-loader.ts @@ -12,11 +12,10 @@ // See the License for the specific language governing permissions and // limitations under the License. -import * as assert from 'assert'; -import {describe, it} from 'mocha'; -import * as path from 'path'; +/* eslint-disable @typescript-eslint/no-var-requires */ -import {OpenCensusPropagation} from '../src/config'; +import * as assert from 'assert'; +import {describe, it, before, afterEach} from 'mocha'; import { PluginLoader, PluginLoaderState, @@ -110,13 +109,13 @@ describe('Trace Plugin Loader', () => { describe('deactivate', () => { class TestPluginWrapper implements PluginWrapper { unapplyCalled = false; - isSupported(version: string): boolean { + isSupported(): boolean { return false; } unapplyAll(): void { this.unapplyCalled = true; } - applyPlugin(moduleExports: T, file: string, version: string): T { + applyPlugin(moduleExports: T): T { return moduleExports; } } @@ -139,12 +138,11 @@ describe('Trace Plugin Loader', () => { describe('parseModuleString', () => { it('parses module strings', () => { const p = PluginLoader.parseModuleString; - const sep = path.sep; assert.deepStrictEqual(p('m'), {name: 'm', file: ''}); assert.deepStrictEqual(p('m/f'), {name: 'm', file: 'f'}); assert.deepStrictEqual(p('m/d/f'), {name: 'm', file: 'd/f'}); - assert.deepStrictEqual(p(`m\\d\\f`), {name: 'm', file: 'd/f'}); - assert.deepStrictEqual(p(`@o\\m\\d\\f`), {name: '@o/m', file: 'd/f'}); + assert.deepStrictEqual(p('m\\d\\f'), {name: 'm', file: 'd/f'}); + assert.deepStrictEqual(p('@o\\m\\d\\f'), {name: '@o/m', file: 'd/f'}); assert.deepStrictEqual(p('@o/m/d/f'), {name: '@o/m', file: 'd/f'}); assert.deepStrictEqual(p('@o/m/d/f'), {name: '@o/m', file: 'd/f'}); }); @@ -162,7 +160,7 @@ describe('Trace Plugin Loader', () => { assert.strictEqual(require('my-version-2.0'), '2.0.0'); }); - it(`doesn't patch before activation`, () => { + it("doesn't patch before activation", () => { const loader = makePluginLoader({ plugins: {'small-number': 'plugin-small-number'}, }); @@ -170,7 +168,7 @@ describe('Trace Plugin Loader', () => { loader.deactivate(); }); - it(`doesn't patch modules for which plugins aren't specified`, () => { + it("doesn't patch modules for which plugins aren't specified", () => { const loader = makePluginLoader({plugins: {}}).activate(); assert.strictEqual(require('small-number').value, 0); loader.deactivate(); @@ -241,7 +239,7 @@ describe('Trace Plugin Loader', () => { }); }); - it(`doesn't load plugins with falsey paths`, () => { + it("doesn't load plugins with falsey paths", () => { const loader = makePluginLoader({ plugins: {'small-number': ''}, }).activate(); diff --git a/test/test-plugins-no-project-num.ts b/test/test-plugins-no-project-num.ts index 91904f82c..9ed39ed45 100644 --- a/test/test-plugins-no-project-num.ts +++ b/test/test-plugins-no-project-num.ts @@ -11,133 +11,147 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. -'use strict'; -var assert = require('assert'); -var write; +import * as assert from 'assert'; +import {describe, before, after, it} from 'mocha'; -describe('test-plugins-no-project-num', function(){ - var agent; - var savedProject; +let write; - before(function() { +describe('test-plugins-no-project-num', () => { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + let agent; + let savedProject; + + before(() => { savedProject = process.env.GCLOUD_PROJECT; delete process.env.GCLOUD_PROJECT; agent = require('../..').start(); }); - after(function() { + after(() => { process.env.GCLOUD_PROJECT = savedProject; }); - describe('should not break without project num', function() { - before(function() { + describe('should not break without project num', () => { + before(() => { // Mute stderr to satiate appveyor write = process.stderr.write; - process.stderr.write = function(c, e?, cb?) { + process.stderr.write = function (c, e?, cb?) { if (cb) { cb(); } return true; }; }); - after(function() { + after(() => { process.stderr.write = write; }); - it('mongo', function(done) { - var mongoose = require('./plugins/fixtures/mongoose4'); - var Simple = mongoose.model('Simple', new mongoose.Schema({ - f1: String, - f2: Boolean, - f3: Number - })); - mongoose.connect('mongodb://localhost:27017/testdb', function(err) { + it('mongo', done => { + // eslint-disable-next-line @typescript-eslint/no-var-requires + const mongoose = require('./plugins/fixtures/mongoose4'); + const Simple = mongoose.model( + 'Simple', + new mongoose.Schema({ + f1: String, + f2: Boolean, + f3: Number, + }) + ); + mongoose.connect('mongodb://localhost:27017/testdb', err => { assert(!err, 'Skipping: error connecting to mongo at localhost:27017.'); - Simple.find({}, function(err, results) { - mongoose.connection.close(function(err) { + Simple.find({}, () => { + mongoose.connection.close(() => { done(); }); }); }); }); - it('redis', function(done) { - var redis = require('./plugins/fixtures/redis2.3'); - var client = redis.createClient(); - client.set('i', 1, function() { - client.quit(function() { + it('redis', done => { + // eslint-disable-next-line @typescript-eslint/no-var-requires + const redis = require('./plugins/fixtures/redis2.3'); + const client = redis.createClient(); + client.set('i', 1, () => { + client.quit(() => { done(); }); }); }); - it('express', function(done) { - var http = require('http'); - var express = require('./plugins/fixtures/express4'); - var app = express(); - var server; - app.get('/', function (req, res) { + it('express', done => { + // eslint-disable-next-line @typescript-eslint/no-var-requires + const http = require('http'); + // eslint-disable-next-line @typescript-eslint/no-var-requires + const express = require('./plugins/fixtures/express4'); + const app = express(); + app.get('/', (req, res) => { res.send('hi'); server.close(); done(); }); - server = app.listen(8081, function() { - http.get({ port: 8081 }); + const server = app.listen(8081, () => { + http.get({port: 8081}); }); }); - it('restify', function(done) { - var http = require('http'); - var restify = require('./plugins/fixtures/restify4'); - var server = restify.createServer(); - server.get('/', function (req, res, next) { + it('restify', done => { + // eslint-disable-next-line @typescript-eslint/no-var-requires + const http = require('http'); + // eslint-disable-next-line @typescript-eslint/no-var-requires + const restify = require('./plugins/fixtures/restify4'); + const server = restify.createServer(); + server.get('/', (req, res) => { res.writeHead(200, { - 'Content-Type': 'text/plain' + 'Content-Type': 'text/plain', }); res.write('hi'); res.end(); server.close(); done(); }); - server.listen(8081, function() { - http.get({ port: 8081 }); + server.listen(8081, () => { + http.get({port: 8081}); }); }); - it('hapi', function(done) { - var http = require('http'); - var hapi = require('./plugins/fixtures/hapi8'); - var server = new hapi.Server(); - server.connection({ port: 8081 }); + it('hapi', done => { + // eslint-disable-next-line @typescript-eslint/no-var-requires + const http = require('http'); + // eslint-disable-next-line @typescript-eslint/no-var-requires + const hapi = require('./plugins/fixtures/hapi8'); + const server = new hapi.Server(); + server.connection({port: 8081}); server.route({ method: 'GET', path: '/', - handler: function(req, reply) { + handler: function (req, reply) { reply('hi'); server.stop(); done(); - } + }, }); - server.start(function() { - http.get({ port: 8081 }); + server.start(() => { + http.get({port: 8081}); }); }); - it('http', function(done) { - var req = require('http').get({ port: 8081 }); - req.on('error', function() { + it('http', done => { + const req = require('http').get({port: 8081}); + req.on('error', () => { done(); }); }); - var mysql_implementations = ['mysql-2', 'mysql2-1']; - mysql_implementations.forEach(function(impl) { - it(impl, function(done) { - var mysql = require('./plugins/fixtures/' + impl); - var pool = mysql.createPool(require('./mysql-config'/*.js*/)); - pool.getConnection(function(err, conn) { + const mysql_implementations = ['mysql-2', 'mysql2-1']; + mysql_implementations.forEach(impl => { + it(impl, done => { + // eslint-disable-next-line @typescript-eslint/no-var-requires + const mysql = require('./plugins/fixtures/' + impl); + // eslint-disable-next-line @typescript-eslint/no-var-requires + const pool = mysql.createPool(require('./mysql-config' /*.js*/)); + pool.getConnection((err, conn) => { assert(!err, 'Skipping: Failed to connect to mysql.'); - conn.query('SHOW TABLES', function(err, result) { + conn.query('SHOW TABLES', () => { conn.release(); pool.end(); done(); diff --git a/test/test-plugins-sample-warning.ts b/test/test-plugins-sample-warning.ts index c6e1d7679..81fe2e2db 100644 --- a/test/test-plugins-sample-warning.ts +++ b/test/test-plugins-sample-warning.ts @@ -11,61 +11,65 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. -'use strict'; // Prereqs: // Start docker daemon // ex) docker -d // Run a mongo image binding the mongo port // ex) docker run -p 27017:27017 -d mongo -var common = require('./plugins/common'/*.js*/); +// eslint-disable-next-line @typescript-eslint/no-var-requires +const common = require('./plugins/common' /*.js*/); -var assert = require('assert'); -var http = require('http'); +import * as assert from 'assert'; +import * as http from 'http'; +import {describe, it, before, beforeEach, afterEach} from 'mocha'; -describe('express + dbs', function() { - var untracedHttpSpanCount = 0; - var oldWarn; - var agent; +describe('express + dbs', () => { + let untracedHttpSpanCount = 0; + let oldWarn; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + let agent; - before(function() { + before(() => { agent = require('../..').start({ projectId: '0', samplingRate: 0, - ignoreUrls: ['/ignore-me'] + ignoreUrls: ['/ignore-me'], }); }); - beforeEach(function() { - oldWarn = common.replaceWarnLogger(function(msg) { + beforeEach(() => { + oldWarn = common.replaceWarnLogger(msg => { if (msg.indexOf('http') !== -1) { untracedHttpSpanCount++; } }); }); - afterEach(function() { + afterEach(() => { common.replaceWarnLogger(oldWarn); untracedHttpSpanCount = 0; }); - it('mongo should not warn', function(done) { - var mongoose = require('./plugins/fixtures/mongoose4'); - var express = require('./plugins/fixtures/express4'); + it('mongo should not warn', done => { + // eslint-disable-next-line @typescript-eslint/no-var-requires + const mongoose = require('./plugins/fixtures/mongoose4'); + // eslint-disable-next-line @typescript-eslint/no-var-requires + const express = require('./plugins/fixtures/express4'); - var app = express(); - app.get('/', function (req, res) { - mongoose.connect('mongodb://localhost:27017/testdb', function(err) { + const app = express(); + app.get('/', (req, res) => { + mongoose.connect('mongodb://localhost:27017/testdb', err => { assert(!err, 'Skipping: no mongo server found at localhost:27017.'); - mongoose.connection.close(function(err) { + mongoose.connection.close(err => { assert(!err); res.sendStatus(200); }); }); }); - var server = app.listen(common.serverPort, function() { - http.get({port: common.serverPort}, function(res) { - http.get({port: common.serverPort}, function(res) { + const server = app.listen(common.serverPort, () => { + http.get({port: common.serverPort}, () => { + http.get({port: common.serverPort}, () => { server.close(); common.cleanTraces(); assert.strictEqual(untracedHttpSpanCount, 2); @@ -75,20 +79,22 @@ describe('express + dbs', function() { }); }); - it('redis should not warn', function(done) { - var redis = require('./plugins/fixtures/redis2.3'); - var express = require('./plugins/fixtures/express4'); + it('redis should not warn', done => { + // eslint-disable-next-line @typescript-eslint/no-var-requires + const redis = require('./plugins/fixtures/redis2.3'); + // eslint-disable-next-line @typescript-eslint/no-var-requires + const express = require('./plugins/fixtures/express4'); - var app = express(); - app.get('/', function (req, res) { - var client = redis.createClient(); - client.quit(function() { + const app = express(); + app.get('/', (req, res) => { + const client = redis.createClient(); + client.quit(() => { res.sendStatus(200); }); }); - var server = app.listen(common.serverPort + 1, function() { - http.get({port: common.serverPort + 1}, function(res) { - http.get({port: common.serverPort + 1}, function(res) { + const server = app.listen(common.serverPort + 1, () => { + http.get({port: common.serverPort + 1}, () => { + http.get({port: common.serverPort + 1}, () => { server.close(); common.cleanTraces(); assert.strictEqual(untracedHttpSpanCount, 2); @@ -98,21 +104,22 @@ describe('express + dbs', function() { }); }); - it('http should not warn', function(done) { - var express = require('./plugins/fixtures/express4'); + it('http should not warn', done => { + // eslint-disable-next-line @typescript-eslint/no-var-requires + const express = require('./plugins/fixtures/express4'); - var app = express(); + const app = express(); app.get('/ignore-me', (req, res) => { res.sendStatus(200); }); - app.get('/', function (req, res) { - http.get(`http://localhost:${common.serverPort + 2}/ignore-me`, function() { + app.get('/', (req, res) => { + http.get(`http://localhost:${common.serverPort + 2}/ignore-me`, () => { res.sendStatus(200); }); }); - var server = app.listen(common.serverPort + 2, function() { - http.get({port: common.serverPort + 2}, function(res) { - http.get({port: common.serverPort + 2}, function(res) { + const server = app.listen(common.serverPort + 2, () => { + http.get({port: common.serverPort + 2}, () => { + http.get({port: common.serverPort + 2}, () => { server.close(); common.cleanTraces(); assert.strictEqual(untracedHttpSpanCount, 2); @@ -122,29 +129,32 @@ describe('express + dbs', function() { }); }); - var mysql_implementations = ['mysql-2', 'mysql2-1']; - mysql_implementations.forEach(function(impl) { - it(impl + ' should not warn', function(done) { - var mysql = require('./plugins/fixtures/' + impl); - var express = require('./plugins/fixtures/express4'); - var pool = mysql.createPool(require('./mysql-config'/*.js*/)); + const mysql_implementations = ['mysql-2', 'mysql2-1']; + mysql_implementations.forEach(impl => { + it(impl + ' should not warn', done => { + // eslint-disable-next-line @typescript-eslint/no-var-requires + const mysql = require('./plugins/fixtures/' + impl); + // eslint-disable-next-line @typescript-eslint/no-var-requires + const express = require('./plugins/fixtures/express4'); + // eslint-disable-next-line @typescript-eslint/no-var-requires + const pool = mysql.createPool(require('./mysql-config' /*.js*/)); - var app = express(); + const app = express(); app.get('/ignore-me', (req, res) => { res.sendStatus(200); }); - app.get('/', function (req, res) { - http.get(`http://localhost:${common.serverPort + 3}/ignore-me`, function() { - pool.getConnection(function(err, conn) { - conn.query('SHOW COLUMNS FROM t', function(err) { + app.get('/', (req, res) => { + http.get(`http://localhost:${common.serverPort + 3}/ignore-me`, () => { + pool.getConnection((err, conn) => { + conn.query('SHOW COLUMNS FROM t', () => { res.sendStatus(200); }); }); }); }); - var server = app.listen(common.serverPort + 3, function() { - http.get({port: common.serverPort + 3}, function(res) { - http.get({port: common.serverPort + 3}, function(res) { + const server = app.listen(common.serverPort + 3, () => { + http.get({port: common.serverPort + 3}, () => { + http.get({port: common.serverPort + 3}, () => { pool.end(); server.close(); common.cleanTraces(); diff --git a/test/test-preloaded-agent.ts b/test/test-preloaded-agent.ts index 1bf9ce9e8..cc966a2d5 100644 --- a/test/test-preloaded-agent.ts +++ b/test/test-preloaded-agent.ts @@ -12,15 +12,16 @@ // See the License for the specific language governing permissions and // limitations under the License. -import * as semver from 'semver'; -import { execSync } from 'child_process'; +import {execSync} from 'child_process'; import * as assert from 'assert'; import {describe, it} from 'mocha'; describe('preloaded agent', () => { it('should start automatically when preloaded using --require', () => { console.log(process.cwd()); - const output = execSync('node --require "./src" test/fixtures/preloaded-agent.js'); + const output = execSync( + 'node --require "./src" test/fixtures/preloaded-agent.js' + ); assert.ok(output.toString().match(/passed/)); }); }); diff --git a/test/test-span-data.ts b/test/test-span-data.ts index 0982f9076..738814979 100644 --- a/test/test-span-data.ts +++ b/test/test-span-data.ts @@ -13,10 +13,10 @@ // limitations under the License. import * as assert from 'assert'; -import {describe, it} from 'mocha'; +import {describe, it, before, after, beforeEach} from 'mocha'; -import {Constants, SpanType} from '../src/constants'; -import {BaseSpanData, ChildSpanData, RootSpanData} from '../src/span-data'; +import {Constants} from '../src/constants'; +import {ChildSpanData, RootSpanData} from '../src/span-data'; import {Trace} from '../src/trace'; import {TraceLabels} from '../src/trace-labels'; import {traceWriter, TraceWriter, TraceWriterConfig} from '../src/trace-writer'; @@ -234,10 +234,10 @@ describe('SpanData', () => { }); } - it(`doesn't break when there are no source maps`, () => { + it("doesn't break when there are no source maps", () => { const { applyGeneric, - } = require(`./fixtures/source-maps-test/no-source-map`) as { + } = require('./fixtures/source-maps-test/no-source-map') as { applyGeneric: (fn: () => T) => T; }; const spanData = applyGeneric( @@ -250,7 +250,7 @@ describe('SpanData', () => { }); }); - it(`doesn't call TraceWriter#writeTrace when ended`, () => { + it("doesn't call TraceWriter#writeTrace when ended", () => { const spanData = new CommonSpanData(trace, 'name', '0', 0); spanData.endSpan(); // writeTrace writes to capturedTrace. @@ -276,7 +276,7 @@ describe('SpanData', () => { assert.strictEqual(capturedTrace, rootSpanData.trace); }); - it(`doesn't write to a Trace Writer more than once`, () => { + it("doesn't write to a Trace Writer more than once", () => { const rootSpanData = new RootSpanData(trace, 'root', '0', 0); rootSpanData.endSpan(); assert.strictEqual(capturedTrace, rootSpanData.trace); diff --git a/test/test-trace-api-none-cls.ts b/test/test-trace-api-none-cls.ts index 9ad1e2e6b..6c1b5b899 100644 --- a/test/test-trace-api-none-cls.ts +++ b/test/test-trace-api-none-cls.ts @@ -13,11 +13,9 @@ // limitations under the License. import * as assert from 'assert'; -import {describe, it} from 'mocha'; - +import {describe, it, before, after, beforeEach, afterEach} from 'mocha'; import {SpanType} from '../src/constants'; import {Tracer} from '../src/plugin-types'; - import * as testTraceModule from './trace'; import {asChildSpanData, asRootSpanData} from './utils'; diff --git a/test/test-trace-api.ts b/test/test-trace-api.ts index 16de9eeaa..18aa1fc2d 100644 --- a/test/test-trace-api.ts +++ b/test/test-trace-api.ts @@ -13,7 +13,7 @@ // limitations under the License. import * as assert from 'assert'; -import {describe, it} from 'mocha'; +import {describe, it, before, after, afterEach} from 'mocha'; import {cls, TraceCLS, TraceCLSMechanism} from '../src/cls'; import { @@ -22,7 +22,6 @@ import { OpenCensusPropagation, RequestDetails, SetHeaderFunction as HeaderSetter, - TracePolicy, } from '../src/config'; import {SpanType} from '../src/constants'; import { @@ -190,7 +189,7 @@ describe('Trace Interface', () => { for (let i = 0; i < 9; i++) { tracer.createChildSpan({name: `span-${i + 10}`}).endSpan(); } - const child = tracer.createChildSpan({name: `span-19`}); + const child = tracer.createChildSpan({name: 'span-19'}); assert.ok(!tracer.isRealSpan(child)); assert.strictEqual(logger.getNumLogsWith('error', '[span-19]'), 1); rootSpan.endSpan(); diff --git a/test/test-trace-cluster.ts b/test/test-trace-cluster.ts index 4866a3d7e..57fe8e46f 100644 --- a/test/test-trace-cluster.ts +++ b/test/test-trace-cluster.ts @@ -13,13 +13,11 @@ // limitations under the License. import * as assert from 'assert'; -import {describe, it} from 'mocha'; +import {describe, it, before, after} from 'mocha'; import axiosModule from 'axios'; import * as cluster from 'cluster'; import {Server} from 'http'; import {AddressInfo} from 'net'; - -import * as cls from '../src/cls'; import {express_4 as expressModule} from '../src/plugins/types'; import * as testTraceModule from './trace'; diff --git a/test/test-trace-hapi-tails.ts b/test/test-trace-hapi-tails.ts index 1e6b0dfa3..cab2559f4 100644 --- a/test/test-trace-hapi-tails.ts +++ b/test/test-trace-hapi-tails.ts @@ -13,7 +13,7 @@ // limitations under the License. import * as assert from 'assert'; -import {describe, it} from 'mocha'; +import {describe, it, before, after} from 'mocha'; import axiosModule from 'axios'; import * as semver from 'semver'; diff --git a/test/test-trace-options-sampling.ts b/test/test-trace-options-sampling.ts index 844febbc2..b9999f405 100644 --- a/test/test-trace-options-sampling.ts +++ b/test/test-trace-options-sampling.ts @@ -11,37 +11,39 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. -'use strict'; -var common = require('./plugins/common'/*.js*/); -var assert = require('assert'); -var http = require('http'); +// eslint-disable-next-line @typescript-eslint/no-var-requires +const common = require('./plugins/common' /*.js*/); +import * as assert from 'assert'; +import * as http from 'http'; +import {describe, it, before} from 'mocha'; -describe('express + http with trace options header + sampling', function() { - var agent; - var express; - before(function() { +describe('express + http with trace options header + sampling', () => { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + let agent; + let express; + before(() => { agent = require('../..').start({ projectId: '0', - samplingRate: 1 + samplingRate: 1, }); express = require('express'); }); - it('should trace when enabled', function(done) { - var app = express(); - app.get('/', function (req, res) { - setTimeout(function() { + it('should trace when enabled', done => { + const app = express(); + app.get('/', (req, res) => { + setTimeout(() => { res.send('Hello World'); }, 50); }); - var server = app.listen(common.serverPort, function() { - var headers = {}; + const server = app.listen(common.serverPort, () => { + const headers = {}; headers['x-cloud-trace-context'] = '42/1729;o=1'; - var doneCount = 0; - var cb = function(res) { - res.on('data', function() {}); - res.on('end', function() { + let doneCount = 0; + const cb = function (res) { + res.on('data', () => {}); + res.on('end', () => { if (++doneCount === 5) { // Only one trace should be sampled even though all have enabled header. assert.strictEqual(common.getTraces().length, 1); @@ -51,7 +53,7 @@ describe('express + http with trace options header + sampling', function() { } }); }; - for (var i = 0; i < 5; i++) { + for (let i = 0; i < 5; i++) { http.get({port: common.serverPort, headers: headers}, cb); } }); diff --git a/test/test-trace-options.ts b/test/test-trace-options.ts index 1027b8d26..22a209bfe 100644 --- a/test/test-trace-options.ts +++ b/test/test-trace-options.ts @@ -11,36 +11,36 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. -'use strict'; -var common = require('./plugins/common'/*.js*/); +// eslint-disable-next-line @typescript-eslint/no-var-requires +const common = require('./plugins/common' /*.js*/); +import * as assert from 'assert'; +import * as http from 'http'; +import {describe, it, before} from 'mocha'; -var assert = require('assert'); -var http = require('http'); - -describe('express + http with trace options header', function() { - var agent; - var express; - before(function() { +describe('express + http with trace options header', () => { + let agent; + let express; + before(() => { agent = require('../..').start({ projectId: '0', - samplingRate: 0 + samplingRate: 0, }); express = require('express'); }); - it('should trace when enabled', function(done) { - var app = express(); - app.get('/', function (req, res) { - setTimeout(function() { + it('should trace when enabled', done => { + const app = express(); + app.get('/', (req, res) => { + setTimeout(() => { res.send('Hello World'); }, 50); }); - var server = app.listen(common.serverPort, function() { - var shouldTraceOptions = [1,3,5,7]; - var shouldNotTraceOptions = [0,2,4,6]; - sendRequests(agent, shouldTraceOptions, shouldTraceOptions.length, function() { - sendRequests(agent, shouldNotTraceOptions, 0, function() { + const server = app.listen(common.serverPort, () => { + const shouldTraceOptions = [1, 3, 5, 7]; + const shouldNotTraceOptions = [0, 2, 4, 6]; + sendRequests(agent, shouldTraceOptions, shouldTraceOptions.length, () => { + sendRequests(agent, shouldNotTraceOptions, 0, () => { server.close(); done(); }); @@ -50,13 +50,13 @@ describe('express + http with trace options header', function() { }); function sendRequests(agent, options, expectedTraceCount, done) { - var doneCount = 0; - options.forEach(function(option) { - var headers = {}; + let doneCount = 0; + options.forEach(option => { + const headers = {}; headers['x-cloud-trace-context'] = '42/1729;o=' + option; - http.get({port: common.serverPort, headers: headers}, function(res) { - res.on('data', function() {}); - res.on('end', function() { + http.get({port: common.serverPort, headers: headers}, res => { + res.on('data', () => {}); + res.on('end', () => { if (++doneCount === options.length) { assert.strictEqual(common.getTraces().length, expectedTraceCount); common.cleanTraces(); diff --git a/test/test-trace-policy.ts b/test/test-trace-policy.ts index a47477561..61eca315a 100644 --- a/test/test-trace-policy.ts +++ b/test/test-trace-policy.ts @@ -186,7 +186,7 @@ describe('TracePolicy', () => { const NUM_SECONDS = 10; const testCases = [0.1, 0.5, 1, 10, 50, 150, 200, 500, 1000]; for (const testCase of testCases) { - it(`should throttle traces when samplingRate = ` + testCase, () => { + it('should throttle traces when samplingRate = ' + testCase, () => { const policy = new TracePolicyForTest({samplingRate: testCase}); const expected = NUM_SECONDS * testCase; let actual = 0; diff --git a/test/test-trace-uncaught-exception.ts b/test/test-trace-uncaught-exception.ts index 3ef1804cb..d1adafcbd 100644 --- a/test/test-trace-uncaught-exception.ts +++ b/test/test-trace-uncaught-exception.ts @@ -13,7 +13,7 @@ // limitations under the License. import * as assert from 'assert'; -import {describe, it} from 'mocha'; +import {describe, it, before, after} from 'mocha'; import {Logger} from '../src/logger'; import {Trace} from '../src/trace'; @@ -78,7 +78,7 @@ describe('Trace Writer', () => { trace.setLoggerForTest(TestLogger); }); - it(`should publish on unhandled exception for 'flush' config option`, done => { + it("should publish on unhandled exception for 'flush' config option", done => { const restoreOriginalUncaughtExceptionListeners = removeAllUncaughtExceptionListeners(); trace.start({onUncaughtException: 'flush', projectId: '0'}); setImmediate(() => { @@ -95,7 +95,7 @@ describe('Trace Writer', () => { }); }); - it(`should not assign an oUE listener for 'ignore' config option`, () => { + it("should not assign an oUE listener for 'ignore' config option", () => { const restoreOriginalUncaughtExceptionListeners = removeAllUncaughtExceptionListeners(); trace.start({onUncaughtException: 'ignore'}); assert.strictEqual(process.listenerCount('onHandledException'), 0); diff --git a/test/test-trace-web-frameworks.ts b/test/test-trace-web-frameworks.ts index eb8214d92..6049c1818 100644 --- a/test/test-trace-web-frameworks.ts +++ b/test/test-trace-web-frameworks.ts @@ -13,7 +13,7 @@ // limitations under the License. import * as assert from 'assert'; -import {describe, it} from 'mocha'; +import {describe, it, before, after, afterEach, beforeEach} from 'mocha'; import axiosModule from 'axios'; import * as semver from 'semver'; @@ -261,8 +261,9 @@ describe('Web framework tracing', () => { } if (i === ABORTED_SPAN_RETRIES - 1) { assert.fail( - `Aborted span was not written after ${DEFAULT_SPAN_DURATION * - ABORTED_SPAN_RETRIES} milliseconds.` + `Aborted span was not written after ${ + DEFAULT_SPAN_DURATION * ABORTED_SPAN_RETRIES + } milliseconds.` ); } else { await wait(DEFAULT_SPAN_DURATION); @@ -271,13 +272,13 @@ describe('Web framework tracing', () => { }); it('assigns different trace IDs to distinct requests', async () => { - // tslint:disable-next-line:no-any + // eslint-disable-next-line @typescript-eslint/no-explicit-any let requests: Array>; // Setting the URL allows us not to record this root span, but also // not get warnings for child spans. await testTraceModule .get() - .runInRootSpan({name: 'outer', url: '/ignore-me'}, async span => { + .runInRootSpan({name: 'outer', url: '/ignore-me'}, async () => { requests = [ axios.get(`http://localhost:${port}/hello?this-is=dog`), axios.get(`http://localhost:${port}/hello?this-is=puppy`), diff --git a/test/test-trace-writer.ts b/test/test-trace-writer.ts index 709edeb55..4c431b57a 100644 --- a/test/test-trace-writer.ts +++ b/test/test-trace-writer.ts @@ -14,10 +14,8 @@ import {Service, DecorateRequestOptions} from '@google-cloud/common'; import * as assert from 'assert'; -import {describe, it} from 'mocha'; -import {GoogleAuth} from 'google-auth-library'; -import {JWTInput} from 'google-auth-library/build/src/auth/credentials'; -import {RefreshOptions} from 'google-auth-library/build/src/auth/oauth2client'; +import {GoogleAuth, JWTInput, RefreshOptions} from 'google-auth-library'; +import {describe, it, before, after, beforeEach, afterEach} from 'mocha'; import * as nock from 'nock'; import * as os from 'os'; import * as path from 'path'; @@ -26,7 +24,7 @@ import * as shimmer from 'shimmer'; import {SpanKind, Trace} from '../src/trace'; import {TraceLabels} from '../src/trace-labels'; -import {TraceBuffer, TraceWriter, TraceWriterConfig} from '../src/trace-writer'; +import {TraceWriter, TraceWriterConfig} from '../src/trace-writer'; import {TestLogger} from './logger'; import {hostname, instanceId, oauth2} from './nocks'; @@ -60,7 +58,7 @@ function createDummyTrace(numSpans: number): Trace { return { projectId: '', traceId: `${traceIdHighWatermark++}`, - spans: new Array(numSpans).fill(null).map(_ => ({ + spans: new Array(numSpans).fill(null).map(() => ({ labels: {}, startTime: time, endTime: time, @@ -72,6 +70,7 @@ function createDummyTrace(numSpans: number): Trace { } describe('Trace Writer', () => { + // eslint-disable-next-line @typescript-eslint/no-var-requires const pjson = require('../../package.json'); const DEFAULT_CONFIG: TraceWriterConfig = { authOptions: {}, @@ -100,7 +99,7 @@ describe('Trace Writer', () => { Service.prototype, 'getProjectId', () => - function(this: Service) { + function (this: Service) { return getProjectIdOverride().then(projectId => { this.projectId = projectId; return projectId; @@ -145,7 +144,7 @@ describe('Trace Writer', () => { }, '_cacheClientFromJSON', cacheClientFromJSON => { - return function( + return function ( this: GoogleAuth, json: JWTInput, options?: RefreshOptions @@ -172,6 +171,7 @@ describe('Trace Writer', () => { }); it('should use the keyFilename field of the config object', async () => { + // eslint-disable-next-line @typescript-eslint/no-var-requires const expectedCredentials: TestCredentials = require('./fixtures/gcloud-credentials.json'); const actualCredentials = await captureCredentialsForConfig({ authOptions: { @@ -183,6 +183,7 @@ describe('Trace Writer', () => { }); it('should use the credentials field of the config object', async () => { + // eslint-disable-next-line @typescript-eslint/no-var-requires const expectedCredentials: TestCredentials = require('./fixtures/gcloud-credentials.json'); const actualCredentials = await captureCredentialsForConfig({ authOptions: { @@ -220,7 +221,7 @@ describe('Trace Writer', () => { writer.stop(); }); - it(`doesn't call Service#getProjectId if project ID is passed`, async () => { + it("doesn't call Service#getProjectId if project ID is passed", async () => { const writer = new TraceWriter( Object.assign({}, DEFAULT_CONFIG, { authOptions: {projectId: 'my-project'}, @@ -233,7 +234,7 @@ describe('Trace Writer', () => { writer.stop(); }); - it(`errors when a project ID can't be determined`, async () => { + it("errors when a project ID can't be determined", async () => { const writer = new TraceWriter(DEFAULT_CONFIG, logger); getProjectIdOverride = () => Promise.reject(new Error()); try { @@ -383,7 +384,7 @@ describe('Trace Writer', () => { writer.stop(); }); - it(`doesn't enqueue open spans`, async () => { + it("doesn't enqueue open spans", async () => { const NUM_SPANS = 5; const writer = new MockedRequestTraceWriter( Object.assign({}, DEFAULT_CONFIG, {bufferSize: NUM_SPANS}), diff --git a/test/test-util.ts b/test/test-util.ts index 9c7276dd6..6c0dfb301 100644 --- a/test/test-util.ts +++ b/test/test-util.ts @@ -165,7 +165,7 @@ describe('util.parseContextFromHeader', () => { inputs.forEach(s => { it(`should reject ${s}`, () => { // TS: Cast s as any rather than coerce it to a value - // tslint:disable-next-line:no-any + // eslint-disable-next-line @typescript-eslint/no-explicit-any const result = util.parseContextFromHeader(s as any); assert.ok(!result); }); @@ -188,7 +188,7 @@ describe('util.generateTraceContext', () => { }); it('returns an empty string if passed a falsy value', () => { - // tslint:disable-next-line:no-any + // eslint-disable-next-line @typescript-eslint/no-explicit-any const context = util.generateTraceContext(null as any); assert.strictEqual(context, ''); }); diff --git a/test/trace.ts b/test/trace.ts index 8a4085b27..87aac9a1d 100644 --- a/test/trace.ts +++ b/test/trace.ts @@ -33,7 +33,6 @@ */ import * as assert from 'assert'; -import {describe, it} from 'mocha'; import * as shimmer from 'shimmer'; import * as trace from '../src'; diff --git a/test/utils.ts b/test/utils.ts index 1409c5dc2..6703efdc2 100644 --- a/test/utils.ts +++ b/test/utils.ts @@ -15,7 +15,7 @@ // TODO(kjin): This file should supercede plugins/common.ts. import * as assert from 'assert'; -import {describe, it} from 'mocha'; +import {describe} from 'mocha'; import * as fs from 'fs'; import * as semver from 'semver'; @@ -166,6 +166,7 @@ interface FixtureHelper { * @param moduleName The module name to look up. */ function getFixturesForModule(moduleName: string): Array> { + // eslint-disable-next-line @typescript-eslint/no-var-requires const pluginFixtures: PluginFixtures = require('./fixtures/plugin-fixtures'); const keys = Object.keys(pluginFixtures); return keys diff --git a/test/web-frameworks/express.ts b/test/web-frameworks/express.ts index 8bba8debf..5db392179 100644 --- a/test/web-frameworks/express.ts +++ b/test/web-frameworks/express.ts @@ -59,7 +59,7 @@ export class Express4 implements WebFramework { } listen(port: number): number { - this.app.use((err: Error, req: {}, res: express_4.Response, next: {}) => { + this.app.use((err: Error, req: {}, res: express_4.Response) => { // silence error if (err) { res.sendStatus(500); diff --git a/test/web-frameworks/hapi17.ts b/test/web-frameworks/hapi17.ts index 277bbe88a..483056f23 100644 --- a/test/web-frameworks/hapi17.ts +++ b/test/web-frameworks/hapi17.ts @@ -61,6 +61,7 @@ class Hapi implements WebFramework { this.server.register({ plugin: { name: options.path, + // eslint-disable-next-line @typescript-eslint/no-unused-vars register: async (server, registerOpts) => { server.route({ method: 'GET', diff --git a/test/web-frameworks/koa1.ts b/test/web-frameworks/koa1.ts index 9b6545e4d..d76b81f67 100644 --- a/test/web-frameworks/koa1.ts +++ b/test/web-frameworks/koa1.ts @@ -43,7 +43,7 @@ export class Koa1 implements WebFramework { `${this.constructor.name} wrapper for testing doesn't support non-blocking handlers.` ); } - this.app.use(function*(next) { + this.app.use(function* (next) { if (this.request.path === options.path) { // Context doesn't automatically get propagated to yielded functions. yield testTraceModule.get().wrap(async (cb: Function) => { diff --git a/test/web-frameworks/koa2.ts b/test/web-frameworks/koa2.ts index 27dd3abd4..4d7559f85 100644 --- a/test/web-frameworks/koa2.ts +++ b/test/web-frameworks/koa2.ts @@ -28,6 +28,7 @@ export class Koa2 implements WebFramework { constructor() { // tslint:disable-next-line:variable-name (Koa is a constructor) + // eslint-disable-next-line @typescript-eslint/no-var-requires const Koa = require('../plugins/fixtures/koa2'); this.app = new Koa(); } diff --git a/test/web-frameworks/restify.ts b/test/web-frameworks/restify.ts index cdde8a957..79776c06d 100644 --- a/test/web-frameworks/restify.ts +++ b/test/web-frameworks/restify.ts @@ -12,8 +12,6 @@ // See the License for the specific language governing permissions and // limitations under the License. -import * as http from 'http'; - import {restify_5} from '../../src/plugins/types'; import {