diff --git a/archive/opentelemetry-browser-extension-autoinjection/src/ui/index.tsx b/archive/opentelemetry-browser-extension-autoinjection/src/ui/index.tsx index 2d6ed46554..95aa1151d0 100644 --- a/archive/opentelemetry-browser-extension-autoinjection/src/ui/index.tsx +++ b/archive/opentelemetry-browser-extension-autoinjection/src/ui/index.tsx @@ -14,7 +14,7 @@ * limitations under the License. */ import * as React from 'react'; -import * as ReactDOM from 'react-dom'; +import { render } from 'react-dom'; import { AppType } from '../types'; import { styles } from './styles'; import { withStyles } from '@material-ui/core'; @@ -52,7 +52,7 @@ loadFromStorage() const StyledApp = withStyles(styles)(App); - ReactDOM.render( + render( { diff --git a/archive/opentelemetry-browser-extension-autoinjection/test/background.test.ts b/archive/opentelemetry-browser-extension-autoinjection/test/background.test.ts index 4e5c711ea0..9bd218987d 100644 --- a/archive/opentelemetry-browser-extension-autoinjection/test/background.test.ts +++ b/archive/opentelemetry-browser-extension-autoinjection/test/background.test.ts @@ -18,7 +18,7 @@ import { ProgrammaticContentScriptInjector } from '../src/background/ProgrammaticContentScriptInjector'; import * as chromeMock from 'sinon-chrome'; -import * as assert from 'assert'; +import {ok,deepStrictEqual} from 'assert'; import sinon = require('sinon'); import { TAB_ID } from './utils'; @@ -41,7 +41,7 @@ describe('ProgrammaticContentScriptInjector', () => { }); it('should subscribe on chrome.tabs.onUpdated', () => { - assert.ok(chromeMock.tabs.onUpdated.addListener.calledOnce); + ok(chromeMock.tabs.onUpdated.addListener.calledOnce); }); it('should only be triggered on tab status "loading"', () => { @@ -52,14 +52,14 @@ describe('ProgrammaticContentScriptInjector', () => { chromeMock.tabs.onUpdated.dispatch(TAB_ID, { status: TabStatus.UNLOADED, }); - assert.ok(spy.notCalled); - assert.ok(chromeMock.tabs.get.notCalled); + ok(spy.notCalled); + ok(chromeMock.tabs.get.notCalled); chromeMock.tabs.onUpdated.dispatch(TAB_ID, { status: TabStatus.LOADING, }); - assert.ok(spy.calledOnce, 'injectContentScript not triggered on "loading"'); - assert.ok(chromeMock.tabs.get.calledOnce); + ok(spy.calledOnce, 'injectContentScript not triggered on "loading"'); + ok(chromeMock.tabs.get.calledOnce); }); it('should inject the content script if the url property of a tab is accessible', () => { @@ -78,13 +78,13 @@ describe('ProgrammaticContentScriptInjector', () => { status: TabStatus.LOADING, }); - assert.ok(chromeMock.tabs.executeScript.notCalled); + ok(chromeMock.tabs.executeScript.notCalled); chromeMock.tabs.onUpdated.dispatch(TAB_ID, { status: TabStatus.LOADING, }); - assert.ok( + ok( chromeMock.tabs.executeScript.calledOnceWith(TAB_ID, { file: CONTENT_SCRIPT_NAME, allFrames: true, @@ -99,7 +99,7 @@ describe('ProgrammaticContentScriptInjector', () => { chromeMockV3.scripting = { executeScript: args => { - assert.deepStrictEqual(args, { + deepStrictEqual(args, { target: { allFrames: true, tabId: TAB_ID, diff --git a/archive/opentelemetry-browser-extension-autoinjection/test/contentScript.test.ts b/archive/opentelemetry-browser-extension-autoinjection/test/contentScript.test.ts index fd8e842a71..c32d34ebf7 100644 --- a/archive/opentelemetry-browser-extension-autoinjection/test/contentScript.test.ts +++ b/archive/opentelemetry-browser-extension-autoinjection/test/contentScript.test.ts @@ -16,9 +16,9 @@ /* eslint-disable node/no-unpublished-import */ -import * as chromeMock from 'sinon-chrome'; -import * as assert from 'assert'; -import * as sinon from 'sinon'; +import {reset,storage,chromeMock,runtime} from 'sinon-chrome'; +import {ok,deepStrictEqual} from 'assert'; +import {SinonSandbox,createSandbox} from 'sinon'; import { InstrumentationInjector } from '../src/contentScript/InstrumentationInjector'; import { JSDOM } from 'jsdom'; @@ -31,12 +31,12 @@ import { import { TEST_URL } from './utils'; describe('InstrumentationInjector', () => { - let sandbox: sinon.SinonSandbox; + let sandbox: SinonSandbox; let injector: InstrumentationInjector; let jsdom: JSDOM; beforeEach(() => { - sandbox = sinon.createSandbox(); + sandbox = createSandbox(); jsdom = new JSDOM('', { url: TEST_URL, }); @@ -51,36 +51,36 @@ describe('InstrumentationInjector', () => { afterEach(async () => { sandbox.restore(); - chromeMock.reset(); + reset(); }); describe('checkUrlFilter', () => { it('matches on parts of the URL', () => { - assert.ok( + ok( InstrumentationInjector.checkUrlFilter( 'example', 'http://www.example.com' ) ); - assert.ok( + ok( InstrumentationInjector.checkUrlFilter( 'www.exa', 'http://www.example.com' ) ); - assert.ok( + ok( !InstrumentationInjector.checkUrlFilter('123', 'http://www.example.com') ); }); it('accepts "*" as a catch all', () => { - assert.ok( + ok( InstrumentationInjector.checkUrlFilter('*', 'http://www.example.com') ); - assert.ok( + ok( InstrumentationInjector.checkUrlFilter( '*', 'http://www.opentelemetry.io' @@ -92,27 +92,27 @@ describe('InstrumentationInjector', () => { describe('execute', () => { it('should load settings from storage', () => { injector.execute(); - assert.ok(chromeMock.storage.local.get.calledOnceWith('settings')); + ok(storage.local.get.calledOnceWith('settings')); }); it('should only inject instrumentation if urlFilter matches', () => { const spy = sandbox.spy(injector, 'inject'); - chromeMock.storage.local.get.onFirstCall().callsArgWith(1, { + storage.local.get.onFirstCall().callsArgWith(1, { settings: { urlFilter: '123', }, }); - chromeMock.storage.local.get.onSecondCall().callsArgWith(1, { + storage.local.get.onSecondCall().callsArgWith(1, { settings: { urlFilter: 'example', }, }); injector.execute(); - assert.ok(spy.notCalled); + ok(spy.notCalled); injector.execute(); - assert.ok(spy.calledOnce); + ok(spy.calledOnce); }); }); @@ -120,21 +120,21 @@ describe('InstrumentationInjector', () => { it('adds a script element to the DOM that loads the instrumentation code', () => { const scriptName = `chrome-extension://id/${INSTRUMENTATION_SCRIPT_NAME}`; - chromeMock.runtime.getURL.onFirstCall().returns(scriptName); + runtime.getURL.onFirstCall().returns(scriptName); const settings = { exporters: {} }; injector.inject(settings as Settings); const configTag = jsdom.window.document.getElementById( DomElements.CONFIG_TAG ); - assert.ok(configTag instanceof jsdom.window.HTMLScriptElement); - assert.deepStrictEqual( + ok(configTag instanceof jsdom.window.HTMLScriptElement); + deepStrictEqual( settings, JSON.parse( String(configTag.getAttribute(`data-${DomAttributes.CONFIG}`)) ) ); - assert.ok(configTag.getAttribute('src'), scriptName); + ok(configTag.getAttribute('src'), scriptName); }); }); }); diff --git a/archive/opentelemetry-browser-extension-autoinjection/test/instrumentation.test.ts b/archive/opentelemetry-browser-extension-autoinjection/test/instrumentation.test.ts index 759d3c2589..af6a1ae7f3 100644 --- a/archive/opentelemetry-browser-extension-autoinjection/test/instrumentation.test.ts +++ b/archive/opentelemetry-browser-extension-autoinjection/test/instrumentation.test.ts @@ -16,9 +16,9 @@ /* eslint-disable node/no-unpublished-import */ -import * as chromeMock from 'sinon-chrome'; -import * as assert from 'assert'; -import * as sinon from 'sinon'; +import {reset} from 'sinon-chrome'; +import {ok} from 'assert'; +import {SinonSandbox,createSandbox,spy} from 'sinon'; import { WebInstrumentation } from '../src/instrumentation/WebInstrumentation'; import { ExporterType, @@ -30,11 +30,11 @@ import { JSDOM } from 'jsdom'; import { TEST_URL } from './utils'; describe('WebInstrumentation', () => { - let sandbox: sinon.SinonSandbox; + let sandbox: SinonSandbox; let provider: WebTracerProvider; beforeEach(() => { - sandbox = sinon.createSandbox(); + sandbox = createSandbox(); provider = new WebTracerProvider(); const { window } = new JSDOM('', { url: TEST_URL, @@ -51,7 +51,7 @@ describe('WebInstrumentation', () => { }); it('adds exporters to the trace provider', () => { - const addSpanProcessorSpy = sinon.spy(provider, 'addSpanProcessor'); + const addSpanProcessorSpy = spy(provider, 'addSpanProcessor'); const instrumentation = new WebInstrumentation( { exporters: { @@ -83,6 +83,6 @@ describe('WebInstrumentation', () => { provider ); instrumentation.register(); - assert.ok(addSpanProcessorSpy.callCount === 3); + ok(addSpanProcessorSpy.callCount === 3); }); }); diff --git a/archive/opentelemetry-browser-extension-autoinjection/webpack.config.ts b/archive/opentelemetry-browser-extension-autoinjection/webpack.config.ts index 53fdc8fa85..7a9affa355 100644 --- a/archive/opentelemetry-browser-extension-autoinjection/webpack.config.ts +++ b/archive/opentelemetry-browser-extension-autoinjection/webpack.config.ts @@ -16,9 +16,9 @@ /* eslint-disable node/no-unpublished-import */ -import * as path from 'path'; +import {resolve} from 'path'; import { mergeWithRules } from 'webpack-merge'; -import * as HtmlWebpackPlugin from 'html-webpack-plugin'; +import {HtmlWebpackPlugin as HtmlWebpackPlugin} from 'html-webpack-plugin'; // Read the environment variables, and check for the existence of the "MV" variable // This can be used to only build the one or the other target. @@ -34,7 +34,7 @@ module.exports = (env: { MV?: string; WEBPACK_BUILD: boolean }) => { module: { rules: [ { - include: [path.resolve(__dirname, 'src/manifest.json5')], + include: [resolve(__dirname, 'src/manifest.json5')], test: /manifest.json5$/, use: [ { @@ -42,7 +42,7 @@ module.exports = (env: { MV?: string; WEBPACK_BUILD: boolean }) => { options: {}, }, { - loader: path.resolve('src/utils/manifest-loader.ts'), + loader: resolve('src/utils/manifest-loader.ts'), options: { manifestVersion: 2, }, @@ -50,7 +50,7 @@ module.exports = (env: { MV?: string; WEBPACK_BUILD: boolean }) => { ], }, { - include: [path.resolve(__dirname, 'src')], + include: [resolve(__dirname, 'src')], test: /\.tsx?$/, use: [ { @@ -63,7 +63,7 @@ module.exports = (env: { MV?: string; WEBPACK_BUILD: boolean }) => { ], }, { - include: [path.resolve(__dirname, 'src/icons')], + include: [resolve(__dirname, 'src/icons')], test: /\.(jpe?g|png|webp)$/i, use: [ // We are not going to use any of the images for real, throw away all output @@ -118,18 +118,18 @@ module.exports = (env: { MV?: string; WEBPACK_BUILD: boolean }) => { const targetMV2 = merge(baseConfig, { output: { filename: '[name].js', - path: path.resolve(__dirname, 'build/mv2'), + path: resolve(__dirname, 'build/mv2'), }, }); const targetMV3 = merge(baseConfig, { module: { rules: [ { - include: [path.resolve(__dirname, 'src/manifest.json5')], + include: [resolve(__dirname, 'src/manifest.json5')], test: /manifest.json5$/, use: [ { - loader: path.resolve('src/utils/manifest-loader.ts'), + loader: resolve('src/utils/manifest-loader.ts'), options: { manifestVersion: 3, }, @@ -140,7 +140,7 @@ module.exports = (env: { MV?: string; WEBPACK_BUILD: boolean }) => { }, output: { filename: '[name].js', - path: path.resolve(__dirname, 'build/mv3'), + path: resolve(__dirname, 'build/mv3'), }, }); diff --git a/detectors/node/opentelemetry-resource-detector-alibaba-cloud/src/detectors/AlibabaCloudEcsDetector.ts b/detectors/node/opentelemetry-resource-detector-alibaba-cloud/src/detectors/AlibabaCloudEcsDetector.ts index 10420186a8..f90d81e1f8 100644 --- a/detectors/node/opentelemetry-resource-detector-alibaba-cloud/src/detectors/AlibabaCloudEcsDetector.ts +++ b/detectors/node/opentelemetry-resource-detector-alibaba-cloud/src/detectors/AlibabaCloudEcsDetector.ts @@ -36,7 +36,7 @@ import { SEMRESATTRS_HOST_TYPE, } from '@opentelemetry/semantic-conventions'; -import * as http from 'http'; +import { RequestOptions, request } from 'http'; /** * The AlibabaCloudEcsDetector can be used to detect if a process is running in @@ -121,13 +121,13 @@ class AlibabaCloudEcsDetector implements DetectorSync { return await this._fetchString(options); } - private async _fetchString(options: http.RequestOptions): Promise { + private async _fetchString(options: RequestOptions): Promise { return new Promise((resolve, reject) => { const timeoutId = setTimeout(() => { req.destroy(new Error('ECS metadata api request timed out.')); }, this.MILLISECONDS_TIME_OUT); - const req = http.request(options, res => { + const req = request(options, res => { clearTimeout(timeoutId); const { statusCode } = res; if ( diff --git a/detectors/node/opentelemetry-resource-detector-alibaba-cloud/test/detectors/AlibabaCloudEcsDetector.test.ts b/detectors/node/opentelemetry-resource-detector-alibaba-cloud/test/detectors/AlibabaCloudEcsDetector.test.ts index 15cd13dd99..036f5281bb 100644 --- a/detectors/node/opentelemetry-resource-detector-alibaba-cloud/test/detectors/AlibabaCloudEcsDetector.test.ts +++ b/detectors/node/opentelemetry-resource-detector-alibaba-cloud/test/detectors/AlibabaCloudEcsDetector.test.ts @@ -14,8 +14,8 @@ * limitations under the License. */ -import * as nock from 'nock'; -import * as assert from 'assert'; +import { disableNetConnect, cleanAll, enableNetConnect } from 'nock'; +import { ok, deepStrictEqual } from 'assert'; import { Resource } from '@opentelemetry/resources'; import { CLOUDPROVIDERVALUES_ALIBABA_CLOUD } from '@opentelemetry/semantic-conventions'; import { @@ -23,6 +23,7 @@ import { assertHostResource, } from '@opentelemetry/contrib-test-utils'; import { alibabaCloudEcsDetector } from '../../src'; +import nock = require('nock'); const ALIYUN_HOST = 'http://' + alibabaCloudEcsDetector.ALIBABA_CLOUD_IDMS_ENDPOINT; @@ -46,12 +47,12 @@ const mockedHostResponse = 'my-hostname'; describe('alibabaCloudEcsDetector', () => { beforeEach(() => { - nock.disableNetConnect(); - nock.cleanAll(); + disableNetConnect(); + cleanAll(); }); afterEach(() => { - nock.enableNetConnect(); + enableNetConnect(); }); describe('with successful request', () => { @@ -68,7 +69,7 @@ describe('alibabaCloudEcsDetector', () => { scope.done(); - assert.ok(resource); + ok(resource); assertCloudResource(resource, { provider: CLOUDPROVIDERVALUES_ALIBABA_CLOUD, @@ -96,7 +97,7 @@ describe('alibabaCloudEcsDetector', () => { const resource = await alibabaCloudEcsDetector.detect(); await resource.waitForAsyncAttributes?.(); - assert.deepStrictEqual(resource.attributes, {}); + deepStrictEqual(resource.attributes, {}); scope.done(); }); @@ -112,7 +113,7 @@ describe('alibabaCloudEcsDetector', () => { const resource = await alibabaCloudEcsDetector.detect(); await resource.waitForAsyncAttributes?.(); - assert.deepStrictEqual(resource.attributes, {}); + deepStrictEqual(resource.attributes, {}); scope.done(); }); @@ -125,7 +126,7 @@ describe('alibabaCloudEcsDetector', () => { const resource = await alibabaCloudEcsDetector.detect(); await resource.waitForAsyncAttributes?.(); - assert.deepStrictEqual(resource.attributes, {}); + deepStrictEqual(resource.attributes, {}); scope.done(); }); diff --git a/detectors/node/opentelemetry-resource-detector-alibaba-cloud/test/detectors/AlibabaCloudEcsDetectorIntegration.test.ts b/detectors/node/opentelemetry-resource-detector-alibaba-cloud/test/detectors/AlibabaCloudEcsDetectorIntegration.test.ts index d523dc1533..dfc651de4d 100644 --- a/detectors/node/opentelemetry-resource-detector-alibaba-cloud/test/detectors/AlibabaCloudEcsDetectorIntegration.test.ts +++ b/detectors/node/opentelemetry-resource-detector-alibaba-cloud/test/detectors/AlibabaCloudEcsDetectorIntegration.test.ts @@ -14,7 +14,7 @@ * limitations under the License. */ -import * as assert from 'assert'; +import { equal } from 'assert'; import { HttpInstrumentation } from '@opentelemetry/instrumentation-http'; import { @@ -54,7 +54,7 @@ describe('[Integration] AlibabaCloudEcsDetector', () => { await new Promise(r => setTimeout(r, 0)); const spans = memoryExporter.getFinishedSpans(); - assert.equal(spans.length, 0, 'no spans exported for GcpDetector'); + equal(spans.length, 0, 'no spans exported for GcpDetector'); await sdk.shutdown(); }); diff --git a/detectors/node/opentelemetry-resource-detector-aws/src/detectors/AwsBeanstalkDetectorSync.ts b/detectors/node/opentelemetry-resource-detector-aws/src/detectors/AwsBeanstalkDetectorSync.ts index 9f938f91a8..e8835accb9 100644 --- a/detectors/node/opentelemetry-resource-detector-aws/src/detectors/AwsBeanstalkDetectorSync.ts +++ b/detectors/node/opentelemetry-resource-detector-aws/src/detectors/AwsBeanstalkDetectorSync.ts @@ -34,8 +34,8 @@ import { CLOUDPROVIDERVALUES_AWS, CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK, } from '@opentelemetry/semantic-conventions'; -import * as fs from 'fs'; -import * as util from 'util'; +import { readFile, access, constants } from 'fs'; +import { promisify } from 'util'; /** * The AwsBeanstalkDetector can be used to detect if a process is running in AWS Elastic @@ -53,8 +53,8 @@ const WIN_OS_BEANSTALK_CONF_PATH = export class AwsBeanstalkDetectorSync implements DetectorSync { BEANSTALK_CONF_PATH: string; - private static readFileAsync = util.promisify(fs.readFile); - private static fileAccessAsync = util.promisify(fs.access); + private static readFileAsync = promisify(readFile); + private static fileAccessAsync = promisify(access); constructor() { if (process.platform === 'win32') { @@ -85,7 +85,7 @@ export class AwsBeanstalkDetectorSync implements DetectorSync { try { await AwsBeanstalkDetectorSync.fileAccessAsync( this.BEANSTALK_CONF_PATH, - fs.constants.R_OK + constants.R_OK ); const rawData = await AwsBeanstalkDetectorSync.readFileAsync( diff --git a/detectors/node/opentelemetry-resource-detector-aws/src/detectors/AwsEc2DetectorSync.ts b/detectors/node/opentelemetry-resource-detector-aws/src/detectors/AwsEc2DetectorSync.ts index a0ef6b47b1..d8d70ee878 100644 --- a/detectors/node/opentelemetry-resource-detector-aws/src/detectors/AwsEc2DetectorSync.ts +++ b/detectors/node/opentelemetry-resource-detector-aws/src/detectors/AwsEc2DetectorSync.ts @@ -35,7 +35,7 @@ import { CLOUDPROVIDERVALUES_AWS, CLOUDPLATFORMVALUES_AWS_EC2, } from '@opentelemetry/semantic-conventions'; -import * as http from 'http'; +import { request, RequestOptions } from 'http'; /** * The AwsEc2DetectorSync can be used to detect if a process is running in AWS EC2 @@ -139,14 +139,14 @@ class AwsEc2DetectorSync implements DetectorSync { * to get back a valid JSON document. Parses that document and stores * the identity properties in a local map. */ - private async _fetchString(options: http.RequestOptions): Promise { + private async _fetchString(options: RequestOptions): Promise { return new Promise((resolve, reject) => { const timeoutId = setTimeout(() => { req.abort(); reject(new Error('EC2 metadata api request timed out.')); }, this.MILLISECOND_TIME_OUT); - const req = http.request(options, res => { + const req = request(options, res => { clearTimeout(timeoutId); const { statusCode } = res; res.setEncoding('utf8'); diff --git a/detectors/node/opentelemetry-resource-detector-aws/src/detectors/AwsEcsDetectorSync.ts b/detectors/node/opentelemetry-resource-detector-aws/src/detectors/AwsEcsDetectorSync.ts index 56977c2c01..0f208d22bd 100644 --- a/detectors/node/opentelemetry-resource-detector-aws/src/detectors/AwsEcsDetectorSync.ts +++ b/detectors/node/opentelemetry-resource-detector-aws/src/detectors/AwsEcsDetectorSync.ts @@ -45,10 +45,10 @@ import { } from '@opentelemetry/semantic-conventions'; // Patch until the OpenTelemetry SDK is updated to ship this attribute import { SemanticResourceAttributes as AdditionalSemanticResourceAttributes } from './SemanticResourceAttributes'; -import * as http from 'http'; -import * as util from 'util'; -import * as fs from 'fs'; -import * as os from 'os'; +import { get, IncomingMessage } from 'http'; +import { promisify } from 'util'; +import { readFile } from 'fs'; +import { hostname } from 'os'; import { getEnv } from '@opentelemetry/core'; const HTTP_TIMEOUT_IN_MS = 1000; @@ -68,7 +68,7 @@ export class AwsEcsDetectorSync implements DetectorSync { static readonly CONTAINER_ID_LENGTH = 64; static readonly DEFAULT_CGROUP_PATH = '/proc/self/cgroup'; - private static readFileAsync = util.promisify(fs.readFile); + private static readFileAsync = promisify(readFile); detect(): IResource { const attributes = context.with(suppressTracing(context.active()), () => @@ -123,7 +123,7 @@ export class AwsEcsDetectorSync implements DetectorSync { * and then return null string */ private static async _getContainerIdAndHostnameResource(): Promise { - const hostName = os.hostname(); + const hostName = hostname(); let containerId = ''; try { @@ -241,7 +241,7 @@ export class AwsEcsDetectorSync implements DetectorSync { private static _getUrlAsJson(url: string): Promise { return new Promise((resolve, reject) => { - const request = http.get(url, (response: http.IncomingMessage) => { + const request = get(url, (response: IncomingMessage) => { if (response.statusCode && response.statusCode >= 400) { reject( new Error( diff --git a/detectors/node/opentelemetry-resource-detector-aws/src/detectors/AwsEksDetectorSync.ts b/detectors/node/opentelemetry-resource-detector-aws/src/detectors/AwsEksDetectorSync.ts index 051d3af5e8..82491e02fc 100644 --- a/detectors/node/opentelemetry-resource-detector-aws/src/detectors/AwsEksDetectorSync.ts +++ b/detectors/node/opentelemetry-resource-detector-aws/src/detectors/AwsEksDetectorSync.ts @@ -31,9 +31,9 @@ import { CLOUDPROVIDERVALUES_AWS, CLOUDPLATFORMVALUES_AWS_EKS, } from '@opentelemetry/semantic-conventions'; -import * as https from 'https'; -import * as fs from 'fs'; -import * as util from 'util'; +import { RequestOptions, request } from 'https'; +import { readFile, access } from 'fs'; +import { promisify } from 'util'; import { diag } from '@opentelemetry/api'; /** @@ -60,8 +60,8 @@ export class AwsEksDetectorSync implements DetectorSync { readonly TIMEOUT_MS = 2000; readonly UTF8_UNICODE = 'utf8'; - private static readFileAsync = util.promisify(fs.readFile); - private static fileAccessAsync = util.promisify(fs.access); + private static readFileAsync = promisify(readFile); + private static fileAccessAsync = promisify(access); detect(_config?: ResourceDetectionConfig): IResource { const attributes = context.with(suppressTracing(context.active()), () => @@ -205,14 +205,14 @@ export class AwsEksDetectorSync implements DetectorSync { * to get back a valid JSON document. Parses that document and stores * the identity properties in a local map. */ - private async _fetchString(options: https.RequestOptions): Promise { + private async _fetchString(options: RequestOptions): Promise { return await new Promise((resolve, reject) => { const timeoutId = setTimeout(() => { req.abort(); reject(new Error('EKS metadata api request timed out.')); }, 2000); - const req = https.request(options, res => { + const req = request(options, res => { clearTimeout(timeoutId); const { statusCode } = res; res.setEncoding(this.UTF8_UNICODE); diff --git a/detectors/node/opentelemetry-resource-detector-aws/src/index.ts b/detectors/node/opentelemetry-resource-detector-aws/src/index.ts index 0acba8788c..8d31ba1298 100644 --- a/detectors/node/opentelemetry-resource-detector-aws/src/index.ts +++ b/detectors/node/opentelemetry-resource-detector-aws/src/index.ts @@ -14,4 +14,16 @@ * limitations under the License. */ -export * from './detectors'; +export { AwsBeanstalkDetector, awsBeanstalkDetector } from './detectors'; +export { + AwsBeanstalkDetectorSync, + awsBeanstalkDetectorSync, +} from './detectors'; +export { awsEc2Detector } from './detectors'; +export { awsEc2DetectorSync } from './detectors'; +export { AwsEcsDetector, awsEcsDetector } from './detectors'; +export { AwsEcsDetectorSync, awsEcsDetectorSync } from './detectors'; +export { AwsEksDetector, awsEksDetector } from './detectors'; +export { AwsEksDetectorSync, awsEksDetectorSync } from './detectors'; +export { AwsLambdaDetector, awsLambdaDetector } from './detectors'; +export { AwsLambdaDetectorSync, awsLambdaDetectorSync } from './detectors'; diff --git a/detectors/node/opentelemetry-resource-detector-aws/test/detectors/AwsBeanstalkDetector.test.ts b/detectors/node/opentelemetry-resource-detector-aws/test/detectors/AwsBeanstalkDetector.test.ts index 9b00ed3548..398f234a99 100644 --- a/detectors/node/opentelemetry-resource-detector-aws/test/detectors/AwsBeanstalkDetector.test.ts +++ b/detectors/node/opentelemetry-resource-detector-aws/test/detectors/AwsBeanstalkDetector.test.ts @@ -14,8 +14,8 @@ * limitations under the License. */ -import * as assert from 'assert'; -import * as sinon from 'sinon'; +import { ok } from 'assert'; +import { assert, restore, stub } from 'sinon'; import { awsBeanstalkDetector, AwsBeanstalkDetectorSync } from '../../src'; import { assertEmptyResource, @@ -40,24 +40,25 @@ describe('BeanstalkResourceDetector', () => { let readStub, fileStub; afterEach(() => { - sinon.restore(); + restore(); }); it('should successfully return resource data', async () => { - fileStub = sinon - .stub(AwsBeanstalkDetectorSync, 'fileAccessAsync' as any) - .resolves(); - readStub = sinon - .stub(AwsBeanstalkDetectorSync, 'readFileAsync' as any) - .resolves(JSON.stringify(data)); - sinon.stub(JSON, 'parse').returns(data); + fileStub = stub( + AwsBeanstalkDetectorSync, + 'fileAccessAsync' as any + ).resolves(); + readStub = stub(AwsBeanstalkDetectorSync, 'readFileAsync' as any).resolves( + JSON.stringify(data) + ); + stub(JSON, 'parse').returns(data); const resource = await awsBeanstalkDetector.detect(); await resource.waitForAsyncAttributes?.(); - sinon.assert.calledOnce(fileStub); - sinon.assert.calledOnce(readStub); - assert.ok(resource); + assert.calledOnce(fileStub); + assert.calledOnce(readStub); + ok(resource); assertServiceResource(resource, { name: CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK, namespace: 'scorekeep', @@ -67,20 +68,21 @@ describe('BeanstalkResourceDetector', () => { }); it('should successfully return resource data with noise', async () => { - fileStub = sinon - .stub(AwsBeanstalkDetectorSync, 'fileAccessAsync' as any) - .resolves(); - readStub = sinon - .stub(AwsBeanstalkDetectorSync, 'readFileAsync' as any) - .resolves(JSON.stringify(noisyData)); - sinon.stub(JSON, 'parse').returns(noisyData); + fileStub = stub( + AwsBeanstalkDetectorSync, + 'fileAccessAsync' as any + ).resolves(); + readStub = stub(AwsBeanstalkDetectorSync, 'readFileAsync' as any).resolves( + JSON.stringify(noisyData) + ); + stub(JSON, 'parse').returns(noisyData); const resource = await awsBeanstalkDetector.detect(); await resource.waitForAsyncAttributes?.(); - sinon.assert.calledOnce(fileStub); - sinon.assert.calledOnce(readStub); - assert.ok(resource); + assert.calledOnce(fileStub); + assert.calledOnce(readStub); + ok(resource); assertServiceResource(resource, { name: CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK, namespace: 'scorekeep', @@ -90,36 +92,37 @@ describe('BeanstalkResourceDetector', () => { }); it('should return empty resource when failing to read file', async () => { - fileStub = sinon - .stub(AwsBeanstalkDetectorSync, 'fileAccessAsync' as any) - .resolves(); - readStub = sinon - .stub(AwsBeanstalkDetectorSync, 'readFileAsync' as any) - .rejects(err); + fileStub = stub( + AwsBeanstalkDetectorSync, + 'fileAccessAsync' as any + ).resolves(); + readStub = stub(AwsBeanstalkDetectorSync, 'readFileAsync' as any).rejects( + err + ); const resource = await awsBeanstalkDetector.detect(); await resource.waitForAsyncAttributes?.(); - sinon.assert.calledOnce(fileStub); - sinon.assert.calledOnce(readStub); - assert.ok(resource); + assert.calledOnce(fileStub); + assert.calledOnce(readStub); + ok(resource); assertEmptyResource(resource); }); it('should return empty resource when config file does not exist', async () => { - fileStub = sinon - .stub(AwsBeanstalkDetectorSync, 'fileAccessAsync' as any) - .rejects(err); - readStub = sinon - .stub(AwsBeanstalkDetectorSync, 'readFileAsync' as any) - .resolves(JSON.stringify(data)); + fileStub = stub(AwsBeanstalkDetectorSync, 'fileAccessAsync' as any).rejects( + err + ); + readStub = stub(AwsBeanstalkDetectorSync, 'readFileAsync' as any).resolves( + JSON.stringify(data) + ); const resource = await awsBeanstalkDetector.detect(); await resource.waitForAsyncAttributes?.(); - sinon.assert.calledOnce(fileStub); - sinon.assert.notCalled(readStub); - assert.ok(resource); + assert.calledOnce(fileStub); + assert.notCalled(readStub); + ok(resource); assertEmptyResource(resource); }); }); diff --git a/detectors/node/opentelemetry-resource-detector-aws/test/detectors/AwsBeanstalkDetectorSync.test.ts b/detectors/node/opentelemetry-resource-detector-aws/test/detectors/AwsBeanstalkDetectorSync.test.ts index 76096c4bee..13cbc9beef 100644 --- a/detectors/node/opentelemetry-resource-detector-aws/test/detectors/AwsBeanstalkDetectorSync.test.ts +++ b/detectors/node/opentelemetry-resource-detector-aws/test/detectors/AwsBeanstalkDetectorSync.test.ts @@ -14,8 +14,8 @@ * limitations under the License. */ -import * as assert from 'assert'; -import * as sinon from 'sinon'; +import { ok } from 'assert'; +import { restore, assert, stub } from 'sinon'; import { awsBeanstalkDetectorSync, AwsBeanstalkDetectorSync } from '../../src'; import { assertEmptyResource, @@ -40,24 +40,25 @@ describe('BeanstalkResourceDetectorSync', () => { let readStub, fileStub; afterEach(() => { - sinon.restore(); + restore(); }); it('should successfully return resource data', async () => { - fileStub = sinon - .stub(AwsBeanstalkDetectorSync, 'fileAccessAsync' as any) - .resolves(); - readStub = sinon - .stub(AwsBeanstalkDetectorSync, 'readFileAsync' as any) - .resolves(JSON.stringify(data)); - sinon.stub(JSON, 'parse').returns(data); + fileStub = stub( + AwsBeanstalkDetectorSync, + 'fileAccessAsync' as any + ).resolves(); + readStub = stub(AwsBeanstalkDetectorSync, 'readFileAsync' as any).resolves( + JSON.stringify(data) + ); + stub(JSON, 'parse').returns(data); const resource = awsBeanstalkDetectorSync.detect(); await resource.waitForAsyncAttributes?.(); - sinon.assert.calledOnce(fileStub); - sinon.assert.calledOnce(readStub); - assert.ok(resource); + assert.calledOnce(fileStub); + assert.calledOnce(readStub); + ok(resource); assertServiceResource(resource, { name: CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK, namespace: 'scorekeep', @@ -67,20 +68,21 @@ describe('BeanstalkResourceDetectorSync', () => { }); it('should successfully return resource data with noise', async () => { - fileStub = sinon - .stub(AwsBeanstalkDetectorSync, 'fileAccessAsync' as any) - .resolves(); - readStub = sinon - .stub(AwsBeanstalkDetectorSync, 'readFileAsync' as any) - .resolves(JSON.stringify(noisyData)); - sinon.stub(JSON, 'parse').returns(noisyData); + fileStub = stub( + AwsBeanstalkDetectorSync, + 'fileAccessAsync' as any + ).resolves(); + readStub = stub(AwsBeanstalkDetectorSync, 'readFileAsync' as any).resolves( + JSON.stringify(noisyData) + ); + stub(JSON, 'parse').returns(noisyData); const resource = awsBeanstalkDetectorSync.detect(); await resource.waitForAsyncAttributes?.(); - sinon.assert.calledOnce(fileStub); - sinon.assert.calledOnce(readStub); - assert.ok(resource); + assert.calledOnce(fileStub); + assert.calledOnce(readStub); + ok(resource); assertServiceResource(resource, { name: CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK, namespace: 'scorekeep', @@ -90,36 +92,37 @@ describe('BeanstalkResourceDetectorSync', () => { }); it('should return empty resource when failing to read file', async () => { - fileStub = sinon - .stub(AwsBeanstalkDetectorSync, 'fileAccessAsync' as any) - .resolves(); - readStub = sinon - .stub(AwsBeanstalkDetectorSync, 'readFileAsync' as any) - .rejects(err); + fileStub = stub( + AwsBeanstalkDetectorSync, + 'fileAccessAsync' as any + ).resolves(); + readStub = stub(AwsBeanstalkDetectorSync, 'readFileAsync' as any).rejects( + err + ); const resource = awsBeanstalkDetectorSync.detect(); await resource.waitForAsyncAttributes?.(); - sinon.assert.calledOnce(fileStub); - sinon.assert.calledOnce(readStub); - assert.ok(resource); + assert.calledOnce(fileStub); + assert.calledOnce(readStub); + ok(resource); assertEmptyResource(resource); }); it('should return empty resource when config file does not exist', async () => { - fileStub = sinon - .stub(AwsBeanstalkDetectorSync, 'fileAccessAsync' as any) - .rejects(err); - readStub = sinon - .stub(AwsBeanstalkDetectorSync, 'readFileAsync' as any) - .resolves(JSON.stringify(data)); + fileStub = stub(AwsBeanstalkDetectorSync, 'fileAccessAsync' as any).rejects( + err + ); + readStub = stub(AwsBeanstalkDetectorSync, 'readFileAsync' as any).resolves( + JSON.stringify(data) + ); const resource = awsBeanstalkDetectorSync.detect(); await resource.waitForAsyncAttributes?.(); - sinon.assert.calledOnce(fileStub); - sinon.assert.notCalled(readStub); - assert.ok(resource); + assert.calledOnce(fileStub); + assert.notCalled(readStub); + ok(resource); assertEmptyResource(resource); }); }); diff --git a/detectors/node/opentelemetry-resource-detector-aws/test/detectors/AwsEc2Detector.test.ts b/detectors/node/opentelemetry-resource-detector-aws/test/detectors/AwsEc2Detector.test.ts index c837f4c6ed..56276b7c86 100644 --- a/detectors/node/opentelemetry-resource-detector-aws/test/detectors/AwsEc2Detector.test.ts +++ b/detectors/node/opentelemetry-resource-detector-aws/test/detectors/AwsEc2Detector.test.ts @@ -14,14 +14,15 @@ * limitations under the License. */ -import * as nock from 'nock'; -import * as assert from 'assert'; +import { disableNetConnect, cleanAll, enableNetConnect } from 'nock'; +import { deepStrictEqual, ok } from 'assert'; import { awsEc2Detector, awsEc2DetectorSync } from '../../src'; import { assertCloudResource, assertHostResource, } from '@opentelemetry/contrib-test-utils'; +import nock = require('nock'); const AWS_HOST = 'http://' + awsEc2DetectorSync.AWS_IDMS_ENDPOINT; const AWS_TOKEN_PATH = awsEc2DetectorSync.AWS_INSTANCE_TOKEN_DOCUMENT_PATH; @@ -43,12 +44,12 @@ const mockedHostResponse = 'my-hostname'; describe('awsEc2Detector', () => { beforeEach(() => { - nock.disableNetConnect(); - nock.cleanAll(); + disableNetConnect(); + cleanAll(); }); afterEach(() => { - nock.enableNetConnect(); + enableNetConnect(); }); describe('with successful request', () => { @@ -70,7 +71,7 @@ describe('awsEc2Detector', () => { scope.done(); - assert.ok(resource); + ok(resource); assertCloudResource(resource, { provider: 'aws', @@ -103,7 +104,7 @@ describe('awsEc2Detector', () => { const resource = await awsEc2Detector.detect(); await resource.waitForAsyncAttributes?.(); - assert.deepStrictEqual(resource.attributes, {}); + deepStrictEqual(resource.attributes, {}); scope.done(); }); @@ -125,7 +126,7 @@ describe('awsEc2Detector', () => { const resource = await awsEc2Detector.detect(); await resource.waitForAsyncAttributes?.(); - assert.deepStrictEqual(resource.attributes, {}); + deepStrictEqual(resource.attributes, {}); scope.done(); }); @@ -143,7 +144,7 @@ describe('awsEc2Detector', () => { const resource = await awsEc2Detector.detect(); await resource.waitForAsyncAttributes?.(); - assert.deepStrictEqual(resource.attributes, {}); + deepStrictEqual(resource.attributes, {}); scope.done(); }); diff --git a/detectors/node/opentelemetry-resource-detector-aws/test/detectors/AwsEc2DetectorSync.test.ts b/detectors/node/opentelemetry-resource-detector-aws/test/detectors/AwsEc2DetectorSync.test.ts index 4f309d5ec5..cec0e8ce82 100644 --- a/detectors/node/opentelemetry-resource-detector-aws/test/detectors/AwsEc2DetectorSync.test.ts +++ b/detectors/node/opentelemetry-resource-detector-aws/test/detectors/AwsEc2DetectorSync.test.ts @@ -14,8 +14,8 @@ * limitations under the License. */ -import * as nock from 'nock'; -import * as assert from 'assert'; +import { disableNetConnect, cleanAll, enableNetConnect } from 'nock'; +import { deepStrictEqual, ok } from 'assert'; import { assertCloudResource, @@ -23,6 +23,7 @@ import { } from '@opentelemetry/contrib-test-utils'; import { awsEc2DetectorSync } from '../../src'; +import nock = require('nock'); const AWS_HOST = 'http://' + awsEc2DetectorSync.AWS_IDMS_ENDPOINT; const AWS_TOKEN_PATH = awsEc2DetectorSync.AWS_INSTANCE_TOKEN_DOCUMENT_PATH; @@ -44,12 +45,12 @@ const mockedHostResponse = 'my-hostname'; describe('awsEc2DetectorSync', () => { beforeEach(() => { - nock.disableNetConnect(); - nock.cleanAll(); + disableNetConnect(); + cleanAll(); }); afterEach(() => { - nock.enableNetConnect(); + enableNetConnect(); }); describe('with successful request', () => { @@ -71,7 +72,7 @@ describe('awsEc2DetectorSync', () => { scope.done(); - assert.ok(resource); + ok(resource); assertCloudResource(resource, { provider: 'aws', @@ -104,7 +105,7 @@ describe('awsEc2DetectorSync', () => { const resource = awsEc2DetectorSync.detect(); await resource.waitForAsyncAttributes?.(); - assert.deepStrictEqual(resource.attributes, {}); + deepStrictEqual(resource.attributes, {}); scope.done(); }); @@ -126,7 +127,7 @@ describe('awsEc2DetectorSync', () => { const resource = awsEc2DetectorSync.detect(); await resource.waitForAsyncAttributes?.(); - assert.deepStrictEqual(resource.attributes, {}); + deepStrictEqual(resource.attributes, {}); scope.done(); }); @@ -144,7 +145,7 @@ describe('awsEc2DetectorSync', () => { const resource = awsEc2DetectorSync.detect(); await resource.waitForAsyncAttributes?.(); - assert.deepStrictEqual(resource.attributes, {}); + deepStrictEqual(resource.attributes, {}); scope.done(); }); diff --git a/detectors/node/opentelemetry-resource-detector-aws/test/detectors/AwsEcsDetector.test.ts b/detectors/node/opentelemetry-resource-detector-aws/test/detectors/AwsEcsDetector.test.ts index 6a019fc82f..5dd3830b35 100644 --- a/detectors/node/opentelemetry-resource-detector-aws/test/detectors/AwsEcsDetector.test.ts +++ b/detectors/node/opentelemetry-resource-detector-aws/test/detectors/AwsEcsDetector.test.ts @@ -14,9 +14,9 @@ * limitations under the License. */ -import * as assert from 'assert'; -import * as nock from 'nock'; -import * as sinon from 'sinon'; +import { Scope } from 'nock'; +import { ok, strictEqual, deepEqual, deepStrictEqual } from 'assert'; +import { restore, assert, stub } from 'sinon'; import { awsEcsDetector, AwsEcsDetectorSync } from '../../src'; import { assertEmptyResource, @@ -44,6 +44,7 @@ import { SemanticResourceAttributes as AdditionalSemanticResourceAttributes } fr import { readFileSync } from 'fs'; import * as os from 'os'; import { join } from 'path'; +import nock = require('nock'); interface EcsResourceAttributes { readonly accountId?: string; @@ -71,61 +72,61 @@ const assertEcsResource = ( region: validations.region, zone: validations.zone, }); - assert.strictEqual( + strictEqual( resource.attributes[SEMRESATTRS_CLOUD_PLATFORM], CLOUDPLATFORMVALUES_AWS_ECS ); if (validations.containerArn) - assert.strictEqual( + strictEqual( resource.attributes[SEMRESATTRS_AWS_ECS_CONTAINER_ARN], validations.containerArn ); - assert.strictEqual( + strictEqual( resource.attributes[AdditionalSemanticResourceAttributes.CLOUD_RESOURCE_ID], validations.containerArn ); if (validations.clusterArn) - assert.strictEqual( + strictEqual( resource.attributes[SEMRESATTRS_AWS_ECS_CLUSTER_ARN], validations.clusterArn ); if (validations.launchType) - assert.strictEqual( + strictEqual( resource.attributes[SEMRESATTRS_AWS_ECS_LAUNCHTYPE], validations.launchType ); if (validations.taskArn) - assert.strictEqual( + strictEqual( resource.attributes[SEMRESATTRS_AWS_ECS_TASK_ARN], validations.taskArn ); if (validations.taskFamily) - assert.strictEqual( + strictEqual( resource.attributes[SEMRESATTRS_AWS_ECS_TASK_FAMILY], validations.taskFamily ); if (validations.taskRevision) - assert.strictEqual( + strictEqual( resource.attributes[SEMRESATTRS_AWS_ECS_TASK_REVISION], validations.taskRevision ); if (validations.logGroupNames) - assert.deepEqual( + deepEqual( resource.attributes[SEMRESATTRS_AWS_LOG_GROUP_NAMES], validations.logGroupNames ); if (validations.logGroupArns) - assert.deepEqual( + deepEqual( resource.attributes[SEMRESATTRS_AWS_LOG_GROUP_ARNS], validations.logGroupArns ); if (validations.logStreamNames) - assert.deepEqual( + deepEqual( resource.attributes[SEMRESATTRS_AWS_LOG_STREAM_NAMES], validations.logStreamNames ); if (validations.logStreamArns) - assert.deepEqual( + deepEqual( resource.attributes[SEMRESATTRS_AWS_LOG_STREAM_ARNS], validations.logStreamArns ); @@ -152,21 +153,21 @@ describe('AwsEcsResourceDetector', () => { }); afterEach(() => { - sinon.restore(); + restore(); }); it('should successfully return resource data with noisy cgroup file', async () => { process.env.ECS_CONTAINER_METADATA_URI = 'ecs_metadata_v3_uri'; - sinon.stub(os, 'hostname').returns(hostNameData); - readStub = sinon - .stub(AwsEcsDetectorSync, 'readFileAsync' as any) - .resolves(noisyCgroupData); + stub(os, 'hostname').returns(hostNameData); + readStub = stub(AwsEcsDetectorSync, 'readFileAsync' as any).resolves( + noisyCgroupData + ); const resource = await awsEcsDetector.detect(); await resource.waitForAsyncAttributes?.(); - sinon.assert.calledOnce(readStub); - assert.ok(resource); + assert.calledOnce(readStub); + ok(resource); assertEcsResource(resource, {}); assertContainerResource(resource, { name: 'abcd.test.testing.com', @@ -176,16 +177,16 @@ describe('AwsEcsResourceDetector', () => { it('should always return first valid line of data', async () => { process.env.ECS_CONTAINER_METADATA_URI = 'ecs_metadata_v3_uri'; - sinon.stub(os, 'hostname').returns(hostNameData); - readStub = sinon - .stub(AwsEcsDetectorSync, 'readFileAsync' as any) - .resolves(multiValidCgroupData); + stub(os, 'hostname').returns(hostNameData); + readStub = stub(AwsEcsDetectorSync, 'readFileAsync' as any).resolves( + multiValidCgroupData + ); const resource = await awsEcsDetector.detect(); await resource.waitForAsyncAttributes?.(); - sinon.assert.calledOnce(readStub); - assert.ok(resource); + assert.calledOnce(readStub); + ok(resource); assertEcsResource(resource, {}); assertContainerResource(resource, { name: 'abcd.test.testing.com', @@ -194,16 +195,16 @@ describe('AwsEcsResourceDetector', () => { }); it('should empty resource without accessing files', async () => { - sinon.stub(os, 'hostname').returns(hostNameData); - readStub = sinon - .stub(AwsEcsDetectorSync, 'readFileAsync' as any) - .resolves(correctCgroupData); + stub(os, 'hostname').returns(hostNameData); + readStub = stub(AwsEcsDetectorSync, 'readFileAsync' as any).resolves( + correctCgroupData + ); const resource = await awsEcsDetector.detect(); await resource.waitForAsyncAttributes?.(); - sinon.assert.notCalled(readStub); - assert.ok(resource); + assert.notCalled(readStub); + ok(resource); assertEmptyResource(resource); }); @@ -220,7 +221,7 @@ describe('AwsEcsResourceDetector', () => { resourceAttributes: EcsResourceAttributes, suffix = '' ) { - let nockScope: nock.Scope; + let nockScope: Scope; beforeEach(() => { function readTestFileName(testFileName: string) { @@ -254,16 +255,16 @@ describe('AwsEcsResourceDetector', () => { }); it('should successfully return resource data', async () => { - sinon.stub(os, 'hostname').returns(hostNameData); - readStub = sinon - .stub(AwsEcsDetectorSync, 'readFileAsync' as any) - .resolves(correctCgroupData); + stub(os, 'hostname').returns(hostNameData); + readStub = stub(AwsEcsDetectorSync, 'readFileAsync' as any).resolves( + correctCgroupData + ); const resource = await awsEcsDetector.detect(); await resource.waitForAsyncAttributes?.(); - sinon.assert.calledOnce(readStub); - assert.ok(resource); + assert.calledOnce(readStub); + ok(resource); assertEcsResource(resource, resourceAttributes); assertContainerResource(resource, { name: 'abcd.test.testing.com', @@ -272,16 +273,16 @@ describe('AwsEcsResourceDetector', () => { }); it('should return resource only with hostname attribute without cgroup file', async () => { - sinon.stub(os, 'hostname').returns(hostNameData); - readStub = sinon - .stub(AwsEcsDetectorSync, 'readFileAsync' as any) - .rejects(errorMsg.fileNotFoundError); + stub(os, 'hostname').returns(hostNameData); + readStub = stub(AwsEcsDetectorSync, 'readFileAsync' as any).rejects( + errorMsg.fileNotFoundError + ); const resource = await awsEcsDetector.detect(); await resource.waitForAsyncAttributes?.(); - sinon.assert.calledOnce(readStub); - assert.ok(resource); + assert.calledOnce(readStub); + ok(resource); assertEcsResource(resource, resourceAttributes); assertContainerResource(resource, { name: 'abcd.test.testing.com', @@ -289,16 +290,16 @@ describe('AwsEcsResourceDetector', () => { }); it('should return resource only with hostname attribute when cgroup file does not contain valid container ID', async () => { - sinon.stub(os, 'hostname').returns(hostNameData); - readStub = sinon - .stub(AwsEcsDetectorSync, 'readFileAsync' as any) - .resolves(''); + stub(os, 'hostname').returns(hostNameData); + readStub = stub(AwsEcsDetectorSync, 'readFileAsync' as any).resolves( + '' + ); const resource = await awsEcsDetector.detect(); await resource.waitForAsyncAttributes?.(); - sinon.assert.calledOnce(readStub); - assert.ok(resource); + assert.calledOnce(readStub); + ok(resource); assertEcsResource(resource, resourceAttributes); assertContainerResource(resource, { name: 'abcd.test.testing.com', @@ -306,16 +307,16 @@ describe('AwsEcsResourceDetector', () => { }); it('should return resource only with container ID attribute without hostname', async () => { - sinon.stub(os, 'hostname').returns(''); - readStub = sinon - .stub(AwsEcsDetectorSync, 'readFileAsync' as any) - .resolves(correctCgroupData); + stub(os, 'hostname').returns(''); + readStub = stub(AwsEcsDetectorSync, 'readFileAsync' as any).resolves( + correctCgroupData + ); const resource = await awsEcsDetector.detect(); await resource.waitForAsyncAttributes?.(); - sinon.assert.calledOnce(readStub); - assert.ok(resource); + assert.calledOnce(readStub); + ok(resource); assertEcsResource(resource, resourceAttributes); assertContainerResource(resource, { id: 'bcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklm', @@ -323,16 +324,16 @@ describe('AwsEcsResourceDetector', () => { }); it('should return metadata v4 resource attributes when both hostname and container ID are invalid', async () => { - sinon.stub(os, 'hostname').returns(''); - readStub = sinon - .stub(AwsEcsDetectorSync, 'readFileAsync' as any) - .rejects(errorMsg.fileNotFoundError); + stub(os, 'hostname').returns(''); + readStub = stub(AwsEcsDetectorSync, 'readFileAsync' as any).rejects( + errorMsg.fileNotFoundError + ); const resource = await awsEcsDetector.detect(); await resource.waitForAsyncAttributes?.(); - sinon.assert.calledOnce(readStub); - assert.ok(resource); + assert.calledOnce(readStub); + ok(resource); assertEcsResource(resource, resourceAttributes); }); } @@ -411,14 +412,14 @@ describe('AwsEcsResourceDetector', () => { const error = new Error('ERROR'); beforeEach(() => { - sinon.stub(AwsEcsDetectorSync, '_getUrlAsJson' as any).rejects(error); + stub(AwsEcsDetectorSync, '_getUrlAsJson' as any).rejects(error); }); it('should return empty resource if when there is an error', async () => { const resource = await awsEcsDetector.detect(); await resource.waitForAsyncAttributes?.(); - assert.deepStrictEqual(resource.attributes, {}); + deepStrictEqual(resource.attributes, {}); }); }); }); diff --git a/detectors/node/opentelemetry-resource-detector-aws/test/detectors/AwsEcsDetectorSync.test.ts b/detectors/node/opentelemetry-resource-detector-aws/test/detectors/AwsEcsDetectorSync.test.ts index 171804bf1b..d0b8a7f9e8 100644 --- a/detectors/node/opentelemetry-resource-detector-aws/test/detectors/AwsEcsDetectorSync.test.ts +++ b/detectors/node/opentelemetry-resource-detector-aws/test/detectors/AwsEcsDetectorSync.test.ts @@ -14,9 +14,9 @@ * limitations under the License. */ -import * as assert from 'assert'; -import * as nock from 'nock'; -import * as sinon from 'sinon'; +import { Scope } from 'nock'; +import { ok, strictEqual, deepEqual, deepStrictEqual } from 'assert'; +import { restore, assert, stub } from 'sinon'; import { awsEcsDetectorSync, AwsEcsDetectorSync } from '../../src'; import { assertEmptyResource, @@ -44,6 +44,7 @@ import { SemanticResourceAttributes as AdditionalSemanticResourceAttributes } fr import { readFileSync } from 'fs'; import * as os from 'os'; import { join } from 'path'; +import nock = require('nock'); interface EcsResourceAttributes { readonly accountId?: string; @@ -71,61 +72,61 @@ const assertEcsResource = ( region: validations.region, zone: validations.zone, }); - assert.strictEqual( + strictEqual( resource.attributes[SEMRESATTRS_CLOUD_PLATFORM], CLOUDPLATFORMVALUES_AWS_ECS ); if (validations.containerArn) - assert.strictEqual( + strictEqual( resource.attributes[SEMRESATTRS_AWS_ECS_CONTAINER_ARN], validations.containerArn ); - assert.strictEqual( + strictEqual( resource.attributes[AdditionalSemanticResourceAttributes.CLOUD_RESOURCE_ID], validations.containerArn ); if (validations.clusterArn) - assert.strictEqual( + strictEqual( resource.attributes[SEMRESATTRS_AWS_ECS_CLUSTER_ARN], validations.clusterArn ); if (validations.launchType) - assert.strictEqual( + strictEqual( resource.attributes[SEMRESATTRS_AWS_ECS_LAUNCHTYPE], validations.launchType ); if (validations.taskArn) - assert.strictEqual( + strictEqual( resource.attributes[SEMRESATTRS_AWS_ECS_TASK_ARN], validations.taskArn ); if (validations.taskFamily) - assert.strictEqual( + strictEqual( resource.attributes[SEMRESATTRS_AWS_ECS_TASK_FAMILY], validations.taskFamily ); if (validations.taskRevision) - assert.strictEqual( + strictEqual( resource.attributes[SEMRESATTRS_AWS_ECS_TASK_REVISION], validations.taskRevision ); if (validations.logGroupNames) - assert.deepEqual( + deepEqual( resource.attributes[SEMRESATTRS_AWS_LOG_GROUP_NAMES], validations.logGroupNames ); if (validations.logGroupArns) - assert.deepEqual( + deepEqual( resource.attributes[SEMRESATTRS_AWS_LOG_GROUP_ARNS], validations.logGroupArns ); if (validations.logStreamNames) - assert.deepEqual( + deepEqual( resource.attributes[SEMRESATTRS_AWS_LOG_STREAM_NAMES], validations.logStreamNames ); if (validations.logStreamArns) - assert.deepEqual( + deepEqual( resource.attributes[SEMRESATTRS_AWS_LOG_STREAM_ARNS], validations.logStreamArns ); @@ -152,21 +153,21 @@ describe('AwsEcsResourceDetectorSync', () => { }); afterEach(() => { - sinon.restore(); + restore(); }); it('should successfully return resource data with noisy cgroup file', async () => { process.env.ECS_CONTAINER_METADATA_URI = 'ecs_metadata_v3_uri'; - sinon.stub(os, 'hostname').returns(hostNameData); - readStub = sinon - .stub(AwsEcsDetectorSync, 'readFileAsync' as any) - .resolves(noisyCgroupData); + stub(os, 'hostname').returns(hostNameData); + readStub = stub(AwsEcsDetectorSync, 'readFileAsync' as any).resolves( + noisyCgroupData + ); const resource = awsEcsDetectorSync.detect(); await resource.waitForAsyncAttributes?.(); - sinon.assert.calledOnce(readStub); - assert.ok(resource); + assert.calledOnce(readStub); + ok(resource); assertEcsResource(resource, {}); assertContainerResource(resource, { name: 'abcd.test.testing.com', @@ -176,16 +177,16 @@ describe('AwsEcsResourceDetectorSync', () => { it('should always return first valid line of data', async () => { process.env.ECS_CONTAINER_METADATA_URI = 'ecs_metadata_v3_uri'; - sinon.stub(os, 'hostname').returns(hostNameData); - readStub = sinon - .stub(AwsEcsDetectorSync, 'readFileAsync' as any) - .resolves(multiValidCgroupData); + stub(os, 'hostname').returns(hostNameData); + readStub = stub(AwsEcsDetectorSync, 'readFileAsync' as any).resolves( + multiValidCgroupData + ); const resource = awsEcsDetectorSync.detect(); await resource.waitForAsyncAttributes?.(); - sinon.assert.calledOnce(readStub); - assert.ok(resource); + assert.calledOnce(readStub); + ok(resource); assertEcsResource(resource, {}); assertContainerResource(resource, { name: 'abcd.test.testing.com', @@ -194,16 +195,16 @@ describe('AwsEcsResourceDetectorSync', () => { }); it('should empty resource without accessing files', async () => { - sinon.stub(os, 'hostname').returns(hostNameData); - readStub = sinon - .stub(AwsEcsDetectorSync, 'readFileAsync' as any) - .resolves(correctCgroupData); + stub(os, 'hostname').returns(hostNameData); + readStub = stub(AwsEcsDetectorSync, 'readFileAsync' as any).resolves( + correctCgroupData + ); const resource = awsEcsDetectorSync.detect(); await resource.waitForAsyncAttributes?.(); - sinon.assert.notCalled(readStub); - assert.ok(resource); + assert.notCalled(readStub); + ok(resource); assertEmptyResource(resource); }); @@ -220,7 +221,7 @@ describe('AwsEcsResourceDetectorSync', () => { resourceAttributes: EcsResourceAttributes, suffix = '' ) { - let nockScope: nock.Scope; + let nockScope: Scope; beforeEach(() => { function readTestFileName(testFileName: string) { @@ -254,16 +255,16 @@ describe('AwsEcsResourceDetectorSync', () => { }); it('should successfully return resource data', async () => { - sinon.stub(os, 'hostname').returns(hostNameData); - readStub = sinon - .stub(AwsEcsDetectorSync, 'readFileAsync' as any) - .resolves(correctCgroupData); + stub(os, 'hostname').returns(hostNameData); + readStub = stub(AwsEcsDetectorSync, 'readFileAsync' as any).resolves( + correctCgroupData + ); const resource = awsEcsDetectorSync.detect(); await resource.waitForAsyncAttributes?.(); - sinon.assert.calledOnce(readStub); - assert.ok(resource); + assert.calledOnce(readStub); + ok(resource); assertEcsResource(resource, resourceAttributes); assertContainerResource(resource, { name: 'abcd.test.testing.com', @@ -272,16 +273,16 @@ describe('AwsEcsResourceDetectorSync', () => { }); it('should return resource only with hostname attribute without cgroup file', async () => { - sinon.stub(os, 'hostname').returns(hostNameData); - readStub = sinon - .stub(AwsEcsDetectorSync, 'readFileAsync' as any) - .rejects(errorMsg.fileNotFoundError); + stub(os, 'hostname').returns(hostNameData); + readStub = stub(AwsEcsDetectorSync, 'readFileAsync' as any).rejects( + errorMsg.fileNotFoundError + ); const resource = awsEcsDetectorSync.detect(); await resource.waitForAsyncAttributes?.(); - sinon.assert.calledOnce(readStub); - assert.ok(resource); + assert.calledOnce(readStub); + ok(resource); assertEcsResource(resource, resourceAttributes); assertContainerResource(resource, { name: 'abcd.test.testing.com', @@ -289,16 +290,16 @@ describe('AwsEcsResourceDetectorSync', () => { }); it('should return resource only with hostname attribute when cgroup file does not contain valid container ID', async () => { - sinon.stub(os, 'hostname').returns(hostNameData); - readStub = sinon - .stub(AwsEcsDetectorSync, 'readFileAsync' as any) - .resolves(''); + stub(os, 'hostname').returns(hostNameData); + readStub = stub(AwsEcsDetectorSync, 'readFileAsync' as any).resolves( + '' + ); const resource = awsEcsDetectorSync.detect(); await resource.waitForAsyncAttributes?.(); - sinon.assert.calledOnce(readStub); - assert.ok(resource); + assert.calledOnce(readStub); + ok(resource); assertEcsResource(resource, resourceAttributes); assertContainerResource(resource, { name: 'abcd.test.testing.com', @@ -306,16 +307,16 @@ describe('AwsEcsResourceDetectorSync', () => { }); it('should return resource only with container ID attribute without hostname', async () => { - sinon.stub(os, 'hostname').returns(''); - readStub = sinon - .stub(AwsEcsDetectorSync, 'readFileAsync' as any) - .resolves(correctCgroupData); + stub(os, 'hostname').returns(''); + readStub = stub(AwsEcsDetectorSync, 'readFileAsync' as any).resolves( + correctCgroupData + ); const resource = awsEcsDetectorSync.detect(); await resource.waitForAsyncAttributes?.(); - sinon.assert.calledOnce(readStub); - assert.ok(resource); + assert.calledOnce(readStub); + ok(resource); assertEcsResource(resource, resourceAttributes); assertContainerResource(resource, { id: 'bcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklm', @@ -323,16 +324,16 @@ describe('AwsEcsResourceDetectorSync', () => { }); it('should return metadata v4 resource attributes when both hostname and container ID are invalid', async () => { - sinon.stub(os, 'hostname').returns(''); - readStub = sinon - .stub(AwsEcsDetectorSync, 'readFileAsync' as any) - .rejects(errorMsg.fileNotFoundError); + stub(os, 'hostname').returns(''); + readStub = stub(AwsEcsDetectorSync, 'readFileAsync' as any).rejects( + errorMsg.fileNotFoundError + ); const resource = awsEcsDetectorSync.detect(); await resource.waitForAsyncAttributes?.(); - sinon.assert.calledOnce(readStub); - assert.ok(resource); + assert.calledOnce(readStub); + ok(resource); assertEcsResource(resource, resourceAttributes); }); } @@ -411,14 +412,14 @@ describe('AwsEcsResourceDetectorSync', () => { const error = new Error('ERROR'); beforeEach(() => { - sinon.stub(AwsEcsDetectorSync, '_getUrlAsJson' as any).rejects(error); + stub(AwsEcsDetectorSync, '_getUrlAsJson' as any).rejects(error); }); it('should return empty resource if when there is an error', async () => { const resource = awsEcsDetectorSync.detect(); await resource.waitForAsyncAttributes?.(); - assert.deepStrictEqual(resource.attributes, {}); + deepStrictEqual(resource.attributes, {}); }); }); }); diff --git a/detectors/node/opentelemetry-resource-detector-aws/test/detectors/AwsEksDetector.test.ts b/detectors/node/opentelemetry-resource-detector-aws/test/detectors/AwsEksDetector.test.ts index ab743dc3b5..3c4f070413 100644 --- a/detectors/node/opentelemetry-resource-detector-aws/test/detectors/AwsEksDetector.test.ts +++ b/detectors/node/opentelemetry-resource-detector-aws/test/detectors/AwsEksDetector.test.ts @@ -14,9 +14,9 @@ * limitations under the License. */ -import * as nock from 'nock'; -import * as sinon from 'sinon'; -import * as assert from 'assert'; +import { enableNetConnect, cleanAll, disableNetConnect } from 'nock'; +import { ok } from 'assert'; +import { restore, assert, stub } from 'sinon'; import { Resource } from '@opentelemetry/resources'; import { awsEksDetector, @@ -28,6 +28,7 @@ import { assertContainerResource, assertEmptyResource, } from '@opentelemetry/contrib-test-utils'; +import nock = require('nock'); const K8S_SVC_URL = awsEksDetector.K8S_SVC_URL; const AUTH_CONFIGMAP_PATH = awsEksDetector.AUTH_CONFIGMAP_PATH; @@ -46,26 +47,25 @@ describe('awsEksDetector', () => { let readStub, fileStub, getCredStub; beforeEach(() => { - nock.disableNetConnect(); - nock.cleanAll(); + disableNetConnect(); + cleanAll(); }); afterEach(() => { - sinon.restore(); - nock.enableNetConnect(); + restore(); + enableNetConnect(); }); describe('on successful request', () => { it('should return an aws_eks_instance_resource', async () => { - fileStub = sinon - .stub(AwsEksDetectorSync, 'fileAccessAsync' as any) - .resolves(); - readStub = sinon - .stub(AwsEksDetectorSync, 'readFileAsync' as any) - .resolves(correctCgroupData); - getCredStub = sinon - .stub(awsEksDetectorSync, '_getK8sCredHeader' as any) - .resolves(k8s_token); + fileStub = stub(AwsEksDetectorSync, 'fileAccessAsync' as any).resolves(); + readStub = stub(AwsEksDetectorSync, 'readFileAsync' as any).resolves( + correctCgroupData + ); + getCredStub = stub( + awsEksDetectorSync, + '_getK8sCredHeader' as any + ).resolves(k8s_token); const scope = nock('https://' + K8S_SVC_URL) .persist() .get(AUTH_CONFIGMAP_PATH) @@ -80,11 +80,11 @@ describe('awsEksDetector', () => { scope.done(); - sinon.assert.calledOnce(fileStub); - sinon.assert.calledTwice(readStub); - sinon.assert.calledTwice(getCredStub); + assert.calledOnce(fileStub); + assert.calledTwice(readStub); + assert.calledTwice(getCredStub); - assert.ok(resource); + ok(resource); assertK8sResource(resource, { clusterName: 'my-cluster', }); @@ -94,16 +94,14 @@ describe('awsEksDetector', () => { }); it('should return a resource with clusterName attribute without cgroup file', async () => { - fileStub = sinon - .stub(AwsEksDetectorSync, 'fileAccessAsync' as any) - .resolves(); - readStub = sinon - .stub(AwsEksDetectorSync, 'readFileAsync' as any) + fileStub = stub(AwsEksDetectorSync, 'fileAccessAsync' as any).resolves(); + readStub = stub(AwsEksDetectorSync, 'readFileAsync' as any) .onSecondCall() .rejects(errorMsg.fileNotFoundError); - getCredStub = sinon - .stub(awsEksDetectorSync, '_getK8sCredHeader' as any) - .resolves(k8s_token); + getCredStub = stub( + awsEksDetectorSync, + '_getK8sCredHeader' as any + ).resolves(k8s_token); const scope = nock('https://' + K8S_SVC_URL) .persist() .get(AUTH_CONFIGMAP_PATH) @@ -118,22 +116,21 @@ describe('awsEksDetector', () => { scope.done(); - assert.ok(resource); + ok(resource); assertK8sResource(resource, { clusterName: 'my-cluster', }); }); it('should return a resource with container ID attribute without a clusterName', async () => { - fileStub = sinon - .stub(AwsEksDetectorSync, 'fileAccessAsync' as any) - .resolves(); - readStub = sinon - .stub(AwsEksDetectorSync, 'readFileAsync' as any) - .resolves(correctCgroupData); - getCredStub = sinon - .stub(awsEksDetectorSync, '_getK8sCredHeader' as any) - .resolves(k8s_token); + fileStub = stub(AwsEksDetectorSync, 'fileAccessAsync' as any).resolves(); + readStub = stub(AwsEksDetectorSync, 'readFileAsync' as any).resolves( + correctCgroupData + ); + getCredStub = stub( + awsEksDetectorSync, + '_getK8sCredHeader' as any + ).resolves(k8s_token); const scope = nock('https://' + K8S_SVC_URL) .persist() .get(AUTH_CONFIGMAP_PATH) @@ -148,23 +145,21 @@ describe('awsEksDetector', () => { scope.done(); - assert.ok(resource); + ok(resource); assertContainerResource(resource, { id: 'bcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklm', }); }); it('should return a resource with clusterName attribute when cgroup file does not contain valid Container ID', async () => { - fileStub = sinon - .stub(AwsEksDetectorSync, 'fileAccessAsync' as any) - .resolves(); - readStub = sinon - .stub(AwsEksDetectorSync, 'readFileAsync' as any) + fileStub = stub(AwsEksDetectorSync, 'fileAccessAsync' as any).resolves(); + readStub = stub(AwsEksDetectorSync, 'readFileAsync' as any) .onSecondCall() .resolves(''); - getCredStub = sinon - .stub(awsEksDetectorSync, '_getK8sCredHeader' as any) - .resolves(k8s_token); + getCredStub = stub( + awsEksDetectorSync, + '_getK8sCredHeader' as any + ).resolves(k8s_token); const scope = nock('https://' + K8S_SVC_URL) .persist() .get(AUTH_CONFIGMAP_PATH) @@ -179,23 +174,24 @@ describe('awsEksDetector', () => { scope.done(); - assert.ok(resource); - assert.ok(resource); + ok(resource); + ok(resource); assertK8sResource(resource, { clusterName: 'my-cluster', }); }); it('should return an empty resource when not running on Eks', async () => { - fileStub = sinon - .stub(AwsEksDetectorSync, 'fileAccessAsync' as any) - .resolves(''); - readStub = sinon - .stub(AwsEksDetectorSync, 'readFileAsync' as any) - .resolves(correctCgroupData); - getCredStub = sinon - .stub(awsEksDetectorSync, '_getK8sCredHeader' as any) - .resolves(k8s_token); + fileStub = stub(AwsEksDetectorSync, 'fileAccessAsync' as any).resolves( + '' + ); + readStub = stub(AwsEksDetectorSync, 'readFileAsync' as any).resolves( + correctCgroupData + ); + getCredStub = stub( + awsEksDetectorSync, + '_getK8sCredHeader' as any + ).resolves(k8s_token); const scope = nock('https://' + K8S_SVC_URL) .persist() .get(AUTH_CONFIGMAP_PATH) @@ -207,7 +203,7 @@ describe('awsEksDetector', () => { scope.done(); - assert.ok(resource); + ok(resource); assertEmptyResource(resource); }); @@ -215,28 +211,28 @@ describe('awsEksDetector', () => { const errorMsg = { fileNotFoundError: new Error('cannot file k8s token file'), }; - fileStub = sinon - .stub(AwsEksDetectorSync, 'fileAccessAsync' as any) - .rejects(errorMsg.fileNotFoundError); + fileStub = stub(AwsEksDetectorSync, 'fileAccessAsync' as any).rejects( + errorMsg.fileNotFoundError + ); const resource: Resource = await awsEksDetector.detect(); - assert.ok(resource); + ok(resource); assertEmptyResource(resource); }); it('should return an empty resource when containerId and clusterName are invalid', async () => { - fileStub = sinon - .stub(AwsEksDetectorSync, 'fileAccessAsync' as any) - .resolves(''); - readStub = sinon - .stub(AwsEksDetectorSync, 'readFileAsync' as any) + fileStub = stub(AwsEksDetectorSync, 'fileAccessAsync' as any).resolves( + '' + ); + readStub = stub(AwsEksDetectorSync, 'readFileAsync' as any) .onSecondCall() .rejects(errorMsg.fileNotFoundError); - getCredStub = sinon - .stub(awsEksDetectorSync, '_getK8sCredHeader' as any) - .resolves(k8s_token); + getCredStub = stub( + awsEksDetectorSync, + '_getK8sCredHeader' as any + ).resolves(k8s_token); const scope = nock('https://' + K8S_SVC_URL) .persist() .get(AUTH_CONFIGMAP_PATH) @@ -251,22 +247,21 @@ describe('awsEksDetector', () => { scope.isDone(); - assert.ok(resource); + ok(resource); assertEmptyResource(resource); }); }); describe('on unsuccessful request', () => { it('should return an empty resource when timed out', async () => { - fileStub = sinon - .stub(AwsEksDetectorSync, 'fileAccessAsync' as any) - .resolves(); - readStub = sinon - .stub(AwsEksDetectorSync, 'readFileAsync' as any) - .resolves(correctCgroupData); - getCredStub = sinon - .stub(awsEksDetectorSync, '_getK8sCredHeader' as any) - .resolves(k8s_token); + fileStub = stub(AwsEksDetectorSync, 'fileAccessAsync' as any).resolves(); + readStub = stub(AwsEksDetectorSync, 'readFileAsync' as any).resolves( + correctCgroupData + ); + getCredStub = stub( + awsEksDetectorSync, + '_getK8sCredHeader' as any + ).resolves(k8s_token); const scope = nock('https://' + K8S_SVC_URL) .persist() .get(AUTH_CONFIGMAP_PATH) @@ -279,20 +274,19 @@ describe('awsEksDetector', () => { scope.done(); - assert.ok(resource); + ok(resource); assertEmptyResource(resource); }).timeout(awsEksDetector.TIMEOUT_MS + 100); it('should return an empty resource when receiving error response code', async () => { - fileStub = sinon - .stub(AwsEksDetectorSync, 'fileAccessAsync' as any) - .resolves(); - readStub = sinon - .stub(AwsEksDetectorSync, 'readFileAsync' as any) - .resolves(correctCgroupData); - getCredStub = sinon - .stub(awsEksDetectorSync, '_getK8sCredHeader' as any) - .resolves(k8s_token); + fileStub = stub(AwsEksDetectorSync, 'fileAccessAsync' as any).resolves(); + readStub = stub(AwsEksDetectorSync, 'readFileAsync' as any).resolves( + correctCgroupData + ); + getCredStub = stub( + awsEksDetectorSync, + '_getK8sCredHeader' as any + ).resolves(k8s_token); const scope = nock('https://' + K8S_SVC_URL) .persist() .get(AUTH_CONFIGMAP_PATH) @@ -304,7 +298,7 @@ describe('awsEksDetector', () => { scope.done(); - assert.ok(resource); + ok(resource); assertEmptyResource(resource); }); }); diff --git a/detectors/node/opentelemetry-resource-detector-aws/test/detectors/AwsEksDetectorSync.test.ts b/detectors/node/opentelemetry-resource-detector-aws/test/detectors/AwsEksDetectorSync.test.ts index 432e113464..c0dba5f31b 100644 --- a/detectors/node/opentelemetry-resource-detector-aws/test/detectors/AwsEksDetectorSync.test.ts +++ b/detectors/node/opentelemetry-resource-detector-aws/test/detectors/AwsEksDetectorSync.test.ts @@ -14,9 +14,9 @@ * limitations under the License. */ -import * as nock from 'nock'; -import * as sinon from 'sinon'; -import * as assert from 'assert'; +import { enableNetConnect, cleanAll, disableNetConnect } from 'nock'; +import { ok } from 'assert'; +import { restore, assert, stub } from 'sinon'; import { Resource } from '@opentelemetry/resources'; import { awsEksDetectorSync, AwsEksDetectorSync } from '../../src'; import { @@ -24,6 +24,7 @@ import { assertContainerResource, assertEmptyResource, } from '@opentelemetry/contrib-test-utils'; +import nock = require('nock'); const K8S_SVC_URL = awsEksDetectorSync.K8S_SVC_URL; const AUTH_CONFIGMAP_PATH = awsEksDetectorSync.AUTH_CONFIGMAP_PATH; @@ -42,26 +43,25 @@ describe('awsEksDetectorSync', () => { let readStub, fileStub, getCredStub; beforeEach(() => { - nock.disableNetConnect(); - nock.cleanAll(); + disableNetConnect(); + cleanAll(); }); afterEach(() => { - sinon.restore(); - nock.enableNetConnect(); + restore(); + enableNetConnect(); }); describe('on successful request', () => { it('should return an aws_eks_instance_resource', async () => { - fileStub = sinon - .stub(AwsEksDetectorSync, 'fileAccessAsync' as any) - .resolves(); - readStub = sinon - .stub(AwsEksDetectorSync, 'readFileAsync' as any) - .resolves(correctCgroupData); - getCredStub = sinon - .stub(awsEksDetectorSync, '_getK8sCredHeader' as any) - .resolves(k8s_token); + fileStub = stub(AwsEksDetectorSync, 'fileAccessAsync' as any).resolves(); + readStub = stub(AwsEksDetectorSync, 'readFileAsync' as any).resolves( + correctCgroupData + ); + getCredStub = stub( + awsEksDetectorSync, + '_getK8sCredHeader' as any + ).resolves(k8s_token); const scope = nock('https://' + K8S_SVC_URL) .persist() .get(AUTH_CONFIGMAP_PATH) @@ -76,11 +76,11 @@ describe('awsEksDetectorSync', () => { scope.done(); - sinon.assert.calledOnce(fileStub); - sinon.assert.calledTwice(readStub); - sinon.assert.calledTwice(getCredStub); + assert.calledOnce(fileStub); + assert.calledTwice(readStub); + assert.calledTwice(getCredStub); - assert.ok(resource); + ok(resource); assertK8sResource(resource, { clusterName: 'my-cluster', }); @@ -90,16 +90,14 @@ describe('awsEksDetectorSync', () => { }); it('should return a resource with clusterName attribute without cgroup file', async () => { - fileStub = sinon - .stub(AwsEksDetectorSync, 'fileAccessAsync' as any) - .resolves(); - readStub = sinon - .stub(AwsEksDetectorSync, 'readFileAsync' as any) + fileStub = stub(AwsEksDetectorSync, 'fileAccessAsync' as any).resolves(); + readStub = stub(AwsEksDetectorSync, 'readFileAsync' as any) .onSecondCall() .rejects(errorMsg.fileNotFoundError); - getCredStub = sinon - .stub(awsEksDetectorSync, '_getK8sCredHeader' as any) - .resolves(k8s_token); + getCredStub = stub( + awsEksDetectorSync, + '_getK8sCredHeader' as any + ).resolves(k8s_token); const scope = nock('https://' + K8S_SVC_URL) .persist() .get(AUTH_CONFIGMAP_PATH) @@ -114,22 +112,21 @@ describe('awsEksDetectorSync', () => { scope.done(); - assert.ok(resource); + ok(resource); assertK8sResource(resource, { clusterName: 'my-cluster', }); }); it('should return a resource with container ID attribute without a clusterName', async () => { - fileStub = sinon - .stub(AwsEksDetectorSync, 'fileAccessAsync' as any) - .resolves(); - readStub = sinon - .stub(AwsEksDetectorSync, 'readFileAsync' as any) - .resolves(correctCgroupData); - getCredStub = sinon - .stub(awsEksDetectorSync, '_getK8sCredHeader' as any) - .resolves(k8s_token); + fileStub = stub(AwsEksDetectorSync, 'fileAccessAsync' as any).resolves(); + readStub = stub(AwsEksDetectorSync, 'readFileAsync' as any).resolves( + correctCgroupData + ); + getCredStub = stub( + awsEksDetectorSync, + '_getK8sCredHeader' as any + ).resolves(k8s_token); const scope = nock('https://' + K8S_SVC_URL) .persist() .get(AUTH_CONFIGMAP_PATH) @@ -144,23 +141,21 @@ describe('awsEksDetectorSync', () => { scope.done(); - assert.ok(resource); + ok(resource); assertContainerResource(resource, { id: 'bcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklm', }); }); it('should return a resource with clusterName attribute when cgroup file does not contain valid Container ID', async () => { - fileStub = sinon - .stub(AwsEksDetectorSync, 'fileAccessAsync' as any) - .resolves(); - readStub = sinon - .stub(AwsEksDetectorSync, 'readFileAsync' as any) + fileStub = stub(AwsEksDetectorSync, 'fileAccessAsync' as any).resolves(); + readStub = stub(AwsEksDetectorSync, 'readFileAsync' as any) .onSecondCall() .resolves(''); - getCredStub = sinon - .stub(awsEksDetectorSync, '_getK8sCredHeader' as any) - .resolves(k8s_token); + getCredStub = stub( + awsEksDetectorSync, + '_getK8sCredHeader' as any + ).resolves(k8s_token); const scope = nock('https://' + K8S_SVC_URL) .persist() .get(AUTH_CONFIGMAP_PATH) @@ -175,23 +170,24 @@ describe('awsEksDetectorSync', () => { scope.done(); - assert.ok(resource); - assert.ok(resource); + ok(resource); + ok(resource); assertK8sResource(resource, { clusterName: 'my-cluster', }); }); it('should return an empty resource when not running on Eks', async () => { - fileStub = sinon - .stub(AwsEksDetectorSync, 'fileAccessAsync' as any) - .resolves(''); - readStub = sinon - .stub(AwsEksDetectorSync, 'readFileAsync' as any) - .resolves(correctCgroupData); - getCredStub = sinon - .stub(awsEksDetectorSync, '_getK8sCredHeader' as any) - .resolves(k8s_token); + fileStub = stub(AwsEksDetectorSync, 'fileAccessAsync' as any).resolves( + '' + ); + readStub = stub(AwsEksDetectorSync, 'readFileAsync' as any).resolves( + correctCgroupData + ); + getCredStub = stub( + awsEksDetectorSync, + '_getK8sCredHeader' as any + ).resolves(k8s_token); const scope = nock('https://' + K8S_SVC_URL) .persist() .get(AUTH_CONFIGMAP_PATH) @@ -203,7 +199,7 @@ describe('awsEksDetectorSync', () => { scope.done(); - assert.ok(resource); + ok(resource); assertEmptyResource(resource); }); @@ -211,28 +207,28 @@ describe('awsEksDetectorSync', () => { const errorMsg = { fileNotFoundError: new Error('cannot file k8s token file'), }; - fileStub = sinon - .stub(AwsEksDetectorSync, 'fileAccessAsync' as any) - .rejects(errorMsg.fileNotFoundError); + fileStub = stub(AwsEksDetectorSync, 'fileAccessAsync' as any).rejects( + errorMsg.fileNotFoundError + ); const resource: Resource = await awsEksDetectorSync.detect(); - assert.ok(resource); + ok(resource); assertEmptyResource(resource); }); it('should return an empty resource when containerId and clusterName are invalid', async () => { - fileStub = sinon - .stub(AwsEksDetectorSync, 'fileAccessAsync' as any) - .resolves(''); - readStub = sinon - .stub(AwsEksDetectorSync, 'readFileAsync' as any) + fileStub = stub(AwsEksDetectorSync, 'fileAccessAsync' as any).resolves( + '' + ); + readStub = stub(AwsEksDetectorSync, 'readFileAsync' as any) .onSecondCall() .rejects(errorMsg.fileNotFoundError); - getCredStub = sinon - .stub(awsEksDetectorSync, '_getK8sCredHeader' as any) - .resolves(k8s_token); + getCredStub = stub( + awsEksDetectorSync, + '_getK8sCredHeader' as any + ).resolves(k8s_token); const scope = nock('https://' + K8S_SVC_URL) .persist() .get(AUTH_CONFIGMAP_PATH) @@ -247,22 +243,21 @@ describe('awsEksDetectorSync', () => { scope.isDone(); - assert.ok(resource); + ok(resource); assertEmptyResource(resource); }); }); describe('on unsuccessful request', () => { it('should return an empty resource when timed out', async () => { - fileStub = sinon - .stub(AwsEksDetectorSync, 'fileAccessAsync' as any) - .resolves(); - readStub = sinon - .stub(AwsEksDetectorSync, 'readFileAsync' as any) - .resolves(correctCgroupData); - getCredStub = sinon - .stub(awsEksDetectorSync, '_getK8sCredHeader' as any) - .resolves(k8s_token); + fileStub = stub(AwsEksDetectorSync, 'fileAccessAsync' as any).resolves(); + readStub = stub(AwsEksDetectorSync, 'readFileAsync' as any).resolves( + correctCgroupData + ); + getCredStub = stub( + awsEksDetectorSync, + '_getK8sCredHeader' as any + ).resolves(k8s_token); const scope = nock('https://' + K8S_SVC_URL) .persist() .get(AUTH_CONFIGMAP_PATH) @@ -275,20 +270,19 @@ describe('awsEksDetectorSync', () => { scope.done(); - assert.ok(resource); + ok(resource); assertEmptyResource(resource); }).timeout(awsEksDetectorSync.TIMEOUT_MS + 100); it('should return an empty resource when receiving error response code', async () => { - fileStub = sinon - .stub(AwsEksDetectorSync, 'fileAccessAsync' as any) - .resolves(); - readStub = sinon - .stub(AwsEksDetectorSync, 'readFileAsync' as any) - .resolves(correctCgroupData); - getCredStub = sinon - .stub(awsEksDetectorSync, '_getK8sCredHeader' as any) - .resolves(k8s_token); + fileStub = stub(AwsEksDetectorSync, 'fileAccessAsync' as any).resolves(); + readStub = stub(AwsEksDetectorSync, 'readFileAsync' as any).resolves( + correctCgroupData + ); + getCredStub = stub( + awsEksDetectorSync, + '_getK8sCredHeader' as any + ).resolves(k8s_token); const scope = nock('https://' + K8S_SVC_URL) .persist() .get(AUTH_CONFIGMAP_PATH) @@ -300,7 +294,7 @@ describe('awsEksDetectorSync', () => { scope.done(); - assert.ok(resource); + ok(resource); assertEmptyResource(resource); }); }); diff --git a/detectors/node/opentelemetry-resource-detector-aws/test/detectors/AwsLambdaDetector.test.ts b/detectors/node/opentelemetry-resource-detector-aws/test/detectors/AwsLambdaDetector.test.ts index daaa34c61b..7aacf45e86 100644 --- a/detectors/node/opentelemetry-resource-detector-aws/test/detectors/AwsLambdaDetector.test.ts +++ b/detectors/node/opentelemetry-resource-detector-aws/test/detectors/AwsLambdaDetector.test.ts @@ -14,7 +14,7 @@ * limitations under the License. */ -import * as assert from 'assert'; +import { strictEqual } from 'assert'; import { assertCloudResource, assertEmptyResource, @@ -46,8 +46,8 @@ describe('awsLambdaDetector', () => { region: 'us-east-1', }); - assert.strictEqual(resource.attributes['faas.name'], 'name'); - assert.strictEqual(resource.attributes['faas.version'], 'v1'); + strictEqual(resource.attributes['faas.name'], 'name'); + strictEqual(resource.attributes['faas.version'], 'v1'); }); }); diff --git a/detectors/node/opentelemetry-resource-detector-aws/test/detectors/AwsLambdaDetectorSync.test.ts b/detectors/node/opentelemetry-resource-detector-aws/test/detectors/AwsLambdaDetectorSync.test.ts index e849dc436f..5aad654229 100644 --- a/detectors/node/opentelemetry-resource-detector-aws/test/detectors/AwsLambdaDetectorSync.test.ts +++ b/detectors/node/opentelemetry-resource-detector-aws/test/detectors/AwsLambdaDetectorSync.test.ts @@ -14,7 +14,7 @@ * limitations under the License. */ -import * as assert from 'assert'; +import { strictEqual } from 'assert'; import { assertCloudResource, assertEmptyResource, @@ -46,8 +46,8 @@ describe('awsLambdaDetectorSync', () => { region: 'us-east-1', }); - assert.strictEqual(resource.attributes['faas.name'], 'name'); - assert.strictEqual(resource.attributes['faas.version'], 'v1'); + strictEqual(resource.attributes['faas.name'], 'name'); + strictEqual(resource.attributes['faas.version'], 'v1'); }); }); diff --git a/detectors/node/opentelemetry-resource-detector-aws/test/detectors/AwsSuppressTracing.test.ts b/detectors/node/opentelemetry-resource-detector-aws/test/detectors/AwsSuppressTracing.test.ts index 96c8e841ed..3d3bbf2dc9 100644 --- a/detectors/node/opentelemetry-resource-detector-aws/test/detectors/AwsSuppressTracing.test.ts +++ b/detectors/node/opentelemetry-resource-detector-aws/test/detectors/AwsSuppressTracing.test.ts @@ -14,7 +14,7 @@ * limitations under the License. */ -import * as assert from 'assert'; +import { equal } from 'assert'; import { FsInstrumentation } from '@opentelemetry/instrumentation-fs'; import { HttpInstrumentation } from '@opentelemetry/instrumentation-http'; @@ -78,11 +78,7 @@ describe('[Integration] Internal tracing', () => { await new Promise(r => setTimeout(r, 0)); const spans = memoryExporter.getFinishedSpans(); - assert.equal( - spans.length, - 0, - 'no spans exported from any AWS resource detector' - ); + equal(spans.length, 0, 'no spans exported from any AWS resource detector'); await sdk.shutdown(); delete process.env.ECS_CONTAINER_METADATA_URI_V4; diff --git a/detectors/node/opentelemetry-resource-detector-azure/src/detectors/AzureVmDetector.ts b/detectors/node/opentelemetry-resource-detector-azure/src/detectors/AzureVmDetector.ts index c644e7a4b4..4cf2d2a194 100644 --- a/detectors/node/opentelemetry-resource-detector-azure/src/detectors/AzureVmDetector.ts +++ b/detectors/node/opentelemetry-resource-detector-azure/src/detectors/AzureVmDetector.ts @@ -14,7 +14,7 @@ * limitations under the License. */ -import * as http from 'http'; +import { request } from 'http'; import { context } from '@opentelemetry/api'; import { suppressTracing } from '@opentelemetry/core'; @@ -72,7 +72,7 @@ class AzureVmResourceDetector implements DetectorSync { reject(new Error('Azure metadata service request timed out.')); }, 1000); - const req = http.request(options, res => { + const req = request(options, res => { clearTimeout(timeoutId); const { statusCode } = res; res.setEncoding('utf8'); diff --git a/detectors/node/opentelemetry-resource-detector-azure/test/detectors/AzureAppServiceDetector.test.ts b/detectors/node/opentelemetry-resource-detector-azure/test/detectors/AzureAppServiceDetector.test.ts index c178106f32..06f72ea95d 100644 --- a/detectors/node/opentelemetry-resource-detector-azure/test/detectors/AzureAppServiceDetector.test.ts +++ b/detectors/node/opentelemetry-resource-detector-azure/test/detectors/AzureAppServiceDetector.test.ts @@ -14,7 +14,7 @@ * limitations under the License. */ -import * as assert from 'assert'; +import { strictEqual, ok } from 'assert'; import { azureAppServiceDetector } from '../../src/detectors/AzureAppServiceDetector'; import { SEMRESATTRS_CLOUD_PLATFORM, @@ -51,32 +51,23 @@ describe('AzureAppServiceDetector', () => { const resource = detectResourcesSync({ detectors: [azureFunctionsDetector, azureAppServiceDetector], }); - assert.ok(resource); + ok(resource); const attributes = resource.attributes; - assert.strictEqual(attributes[SEMRESATTRS_SERVICE_NAME], 'test-site'); - assert.strictEqual(attributes[SEMRESATTRS_CLOUD_PROVIDER], 'azure'); - assert.strictEqual( - attributes[SEMRESATTRS_CLOUD_PLATFORM], - 'azure_app_service' - ); - assert.strictEqual( + strictEqual(attributes[SEMRESATTRS_SERVICE_NAME], 'test-site'); + strictEqual(attributes[SEMRESATTRS_CLOUD_PROVIDER], 'azure'); + strictEqual(attributes[SEMRESATTRS_CLOUD_PLATFORM], 'azure_app_service'); + strictEqual( attributes['cloud.resource_id'], `/subscriptions/${process.env.WEBSITE_OWNER_NAME}/resourceGroups/${process.env.WEBSITE_RESOURCE_GROUP}/providers/Microsoft.Web/sites/${process.env.WEBSITE_SITE_NAME}` ); - assert.strictEqual(attributes[SEMRESATTRS_CLOUD_REGION], 'test-region'); - assert.strictEqual( - attributes[SEMRESATTRS_DEPLOYMENT_ENVIRONMENT], - 'test-slot' - ); - assert.strictEqual(attributes[SEMRESATTRS_HOST_ID], 'test-hostname'); - assert.strictEqual( + strictEqual(attributes[SEMRESATTRS_CLOUD_REGION], 'test-region'); + strictEqual(attributes[SEMRESATTRS_DEPLOYMENT_ENVIRONMENT], 'test-slot'); + strictEqual(attributes[SEMRESATTRS_HOST_ID], 'test-hostname'); + strictEqual( attributes[SEMRESATTRS_SERVICE_INSTANCE_ID], 'test-instance-id' ); - assert.strictEqual( - attributes['azure.app.service.stamp'], - 'test-home-stamp' - ); + strictEqual(attributes['azure.app.service.stamp'], 'test-home-stamp'); }); it('should test with no resource group', () => { @@ -91,22 +82,16 @@ describe('AzureAppServiceDetector', () => { const resource = detectResourcesSync({ detectors: [azureFunctionsDetector, azureAppServiceDetector], }); - assert.ok(resource); + ok(resource); const attributes = resource.attributes; - assert.strictEqual(attributes[SEMRESATTRS_CLOUD_REGION], 'test-region'); - assert.strictEqual( - attributes[SEMRESATTRS_DEPLOYMENT_ENVIRONMENT], - 'test-slot' - ); - assert.strictEqual(attributes[SEMRESATTRS_HOST_ID], 'test-hostname'); - assert.strictEqual( + strictEqual(attributes[SEMRESATTRS_CLOUD_REGION], 'test-region'); + strictEqual(attributes[SEMRESATTRS_DEPLOYMENT_ENVIRONMENT], 'test-slot'); + strictEqual(attributes[SEMRESATTRS_HOST_ID], 'test-hostname'); + strictEqual( attributes[SEMRESATTRS_SERVICE_INSTANCE_ID], 'test-instance-id' ); - assert.strictEqual( - attributes['azure.app.service.stamp'], - 'test-home-stamp' - ); + strictEqual(attributes['azure.app.service.stamp'], 'test-home-stamp'); }); it('should test with no owner name', () => { @@ -122,22 +107,16 @@ describe('AzureAppServiceDetector', () => { const resource = detectResourcesSync({ detectors: [azureFunctionsDetector, azureAppServiceDetector], }); - assert.ok(resource); + ok(resource); const attributes = resource.attributes; - assert.strictEqual(attributes[SEMRESATTRS_CLOUD_REGION], 'test-region'); - assert.strictEqual( - attributes[SEMRESATTRS_DEPLOYMENT_ENVIRONMENT], - 'test-slot' - ); - assert.strictEqual(attributes[SEMRESATTRS_HOST_ID], 'test-hostname'); - assert.strictEqual( + strictEqual(attributes[SEMRESATTRS_CLOUD_REGION], 'test-region'); + strictEqual(attributes[SEMRESATTRS_DEPLOYMENT_ENVIRONMENT], 'test-slot'); + strictEqual(attributes[SEMRESATTRS_HOST_ID], 'test-hostname'); + strictEqual( attributes[SEMRESATTRS_SERVICE_INSTANCE_ID], 'test-instance-id' ); - assert.strictEqual( - attributes['azure.app.service.stamp'], - 'test-home-stamp' - ); - assert.strictEqual(attributes['cloud.resource_id'], undefined); + strictEqual(attributes['azure.app.service.stamp'], 'test-home-stamp'); + strictEqual(attributes['cloud.resource_id'], undefined); }); }); diff --git a/detectors/node/opentelemetry-resource-detector-azure/test/detectors/AzureFunctionsDetector.test.ts b/detectors/node/opentelemetry-resource-detector-azure/test/detectors/AzureFunctionsDetector.test.ts index 4c5710958c..e74b4830ab 100644 --- a/detectors/node/opentelemetry-resource-detector-azure/test/detectors/AzureFunctionsDetector.test.ts +++ b/detectors/node/opentelemetry-resource-detector-azure/test/detectors/AzureFunctionsDetector.test.ts @@ -14,7 +14,7 @@ * limitations under the License. */ -import * as assert from 'assert'; +import { strictEqual, ok } from 'assert'; import { azureFunctionsDetector } from '../../src/detectors/AzureFunctionsDetector'; import { azureAppServiceDetector } from '../../src/detectors/AzureAppServiceDetector'; import { @@ -52,30 +52,24 @@ describe('AzureFunctionsDetector', () => { const resource = detectResourcesSync({ detectors: [azureFunctionsDetector, azureAppServiceDetector], }); - assert.ok(resource); + ok(resource); const attributes = resource.attributes; - assert.strictEqual(attributes[SEMRESATTRS_SERVICE_NAME], 'test-service'); - assert.strictEqual(attributes[SEMRESATTRS_CLOUD_PROVIDER], 'azure'); - assert.strictEqual( - attributes[SEMRESATTRS_CLOUD_PLATFORM], - 'azure_functions' - ); - assert.strictEqual(attributes[SEMRESATTRS_CLOUD_REGION], 'test-region'); - assert.strictEqual( - attributes[SEMRESATTRS_FAAS_INSTANCE], - 'test-instance-id' - ); - assert.strictEqual(attributes[SEMRESATTRS_FAAS_MAX_MEMORY], '1000'); + strictEqual(attributes[SEMRESATTRS_SERVICE_NAME], 'test-service'); + strictEqual(attributes[SEMRESATTRS_CLOUD_PROVIDER], 'azure'); + strictEqual(attributes[SEMRESATTRS_CLOUD_PLATFORM], 'azure_functions'); + strictEqual(attributes[SEMRESATTRS_CLOUD_REGION], 'test-region'); + strictEqual(attributes[SEMRESATTRS_FAAS_INSTANCE], 'test-instance-id'); + strictEqual(attributes[SEMRESATTRS_FAAS_MAX_MEMORY], '1000'); // Should not detect app service values - assert.strictEqual(attributes[SEMRESATTRS_SERVICE_INSTANCE_ID], undefined); - assert.strictEqual(attributes[SEMRESATTRS_PROCESS_PID], process.pid); + strictEqual(attributes[SEMRESATTRS_SERVICE_INSTANCE_ID], undefined); + strictEqual(attributes[SEMRESATTRS_PROCESS_PID], process.pid); - assert.strictEqual( + strictEqual( attributes['cloud.resource_id'], `/subscriptions/${process.env.WEBSITE_OWNER_NAME}/resourceGroups/${process.env.WEBSITE_RESOURCE_GROUP}/providers/Microsoft.Web/sites/${process.env.WEBSITE_SITE_NAME}` ); - assert.strictEqual( + strictEqual( attributes[AZURE_APP_SERVICE_STAMP_RESOURCE_ATTRIBUTE], undefined ); @@ -94,9 +88,9 @@ describe('AzureFunctionsDetector', () => { const resource = detectResourcesSync({ detectors: [azureFunctionsDetector, azureAppServiceDetector], }); - assert.ok(resource); + ok(resource); const attributes = resource.attributes; - assert.strictEqual( + strictEqual( attributes['cloud.resource_id'], `/subscriptions/${expectedWebsiteOwnerName}/resourceGroups/${process.env.WEBSITE_RESOURCE_GROUP}/providers/Microsoft.Web/sites/${process.env.WEBSITE_SITE_NAME}` ); @@ -104,7 +98,7 @@ describe('AzureFunctionsDetector', () => { }); it('should detect azure functions if websiteSku is defined as FlexConsumption', () => { - assert.ok(!process.env.WEBSITE_SKU && !process.env.FUNCTIONS_VERSION); + ok(!process.env.WEBSITE_SKU && !process.env.FUNCTIONS_VERSION); process.env.WEBSITE_SITE_NAME = 'test-service'; process.env.REGION_NAME = 'test-region'; process.env.WEBSITE_INSTANCE_ID = 'test-instance-id'; @@ -116,13 +110,13 @@ it('should detect azure functions if websiteSku is defined as FlexConsumption', const resource = detectResourcesSync({ detectors: [azureFunctionsDetector, azureAppServiceDetector], }); - assert.ok(resource); + ok(resource); const attributes = resource.attributes; - assert.strictEqual(attributes[SEMRESATTRS_SERVICE_NAME], 'test-service'); - assert.strictEqual(attributes[SEMRESATTRS_CLOUD_PROVIDER], 'azure'); + strictEqual(attributes[SEMRESATTRS_SERVICE_NAME], 'test-service'); + strictEqual(attributes[SEMRESATTRS_CLOUD_PROVIDER], 'azure'); // Should not detect app service values - assert.strictEqual(attributes[SEMRESATTRS_SERVICE_INSTANCE_ID], undefined); - assert.strictEqual(attributes[SEMRESATTRS_PROCESS_PID], process.pid); + strictEqual(attributes[SEMRESATTRS_SERVICE_INSTANCE_ID], undefined); + strictEqual(attributes[SEMRESATTRS_PROCESS_PID], process.pid); delete process.env.WEBSITE_SKU; }); diff --git a/detectors/node/opentelemetry-resource-detector-azure/test/detectors/AzureVmDetector.test.ts b/detectors/node/opentelemetry-resource-detector-azure/test/detectors/AzureVmDetector.test.ts index edf413faa3..020e5acf5c 100644 --- a/detectors/node/opentelemetry-resource-detector-azure/test/detectors/AzureVmDetector.test.ts +++ b/detectors/node/opentelemetry-resource-detector-azure/test/detectors/AzureVmDetector.test.ts @@ -14,11 +14,12 @@ * limitations under the License. */ -import * as assert from 'assert'; -import * as nock from 'nock'; +import { strictEqual } from 'assert'; +import { disableNetConnect, cleanAll, enableNetConnect } from 'nock'; import { azureVmDetector } from '../../src/detectors/AzureVmDetector'; import { IResource } from '@opentelemetry/resources'; import { AzureVmMetadata } from '../../src/types'; +import nock = require('nock'); const linuxTestResponse: AzureVmMetadata = { additionalCapabilities: { @@ -374,12 +375,12 @@ const AZURE_VM_METADATA_PATH = describe('AzureVmServiceDetector', () => { beforeEach(() => { - nock.disableNetConnect(); - nock.cleanAll(); + disableNetConnect(); + cleanAll(); }); afterEach(() => { - nock.enableNetConnect(); + enableNetConnect(); }); it('should get linux virtual machine attributes', async () => { @@ -394,7 +395,7 @@ describe('AzureVmServiceDetector', () => { const attributes = resource.attributes; for (let i = 0; i < Object.keys(attributes).length; i++) { const key = Object.keys(attributes)[i]; - assert.strictEqual(attributes[key], linuxAttributes[key]); + strictEqual(attributes[key], linuxAttributes[key]); } scope.done(); }); @@ -411,7 +412,7 @@ describe('AzureVmServiceDetector', () => { const attributes = resource.attributes; for (let i = 0; i < Object.keys(attributes).length; i++) { const key = Object.keys(attributes)[i]; - assert.strictEqual(attributes[key], windowsAttributes[key]); + strictEqual(attributes[key], windowsAttributes[key]); } scope.done(); }); diff --git a/detectors/node/opentelemetry-resource-detector-azure/test/detectors/AzureVmDetectorIntegration.test.ts b/detectors/node/opentelemetry-resource-detector-azure/test/detectors/AzureVmDetectorIntegration.test.ts index 2cdf2cafc1..36c55c4abc 100644 --- a/detectors/node/opentelemetry-resource-detector-azure/test/detectors/AzureVmDetectorIntegration.test.ts +++ b/detectors/node/opentelemetry-resource-detector-azure/test/detectors/AzureVmDetectorIntegration.test.ts @@ -14,7 +14,7 @@ * limitations under the License. */ -import * as assert from 'assert'; +import { equal } from 'assert'; import { HttpInstrumentation } from '@opentelemetry/instrumentation-http'; import { @@ -53,7 +53,7 @@ describe('[Integration] AzureVmServiceDetector', () => { await new Promise(r => setTimeout(r, 0)); const spans = memoryExporter.getFinishedSpans(); - assert.equal(spans.length, 0, 'no spans exported for AzureVmDetector'); + equal(spans.length, 0, 'no spans exported for AzureVmDetector'); await sdk.shutdown(); }); diff --git a/detectors/node/opentelemetry-resource-detector-container/src/detectors/ContainerDetector.ts b/detectors/node/opentelemetry-resource-detector-container/src/detectors/ContainerDetector.ts index 239228e7df..a90ad2a800 100644 --- a/detectors/node/opentelemetry-resource-detector-container/src/detectors/ContainerDetector.ts +++ b/detectors/node/opentelemetry-resource-detector-container/src/detectors/ContainerDetector.ts @@ -23,8 +23,8 @@ import { import { SEMRESATTRS_CONTAINER_ID } from '@opentelemetry/semantic-conventions'; -import * as fs from 'fs'; -import * as util from 'util'; +import { readFile } from 'fs'; +import { promisify } from 'util'; import { context, diag } from '@opentelemetry/api'; import { suppressTracing } from '@opentelemetry/core'; import { extractContainerIdFromLine } from './utils'; @@ -41,7 +41,7 @@ export class ContainerDetector implements DetectorSync { readonly DOCKER = 'docker-'; readonly HEX_STRING_REGEX: RegExp = /^[a-f0-9]+$/i; - private static readFileAsync = util.promisify(fs.readFile); + private static readFileAsync = promisify(readFile); detect(_config?: ResourceDetectionConfig): IResource { const attributes = context.with(suppressTracing(context.active()), () => diff --git a/detectors/node/opentelemetry-resource-detector-container/src/detectors/index.ts b/detectors/node/opentelemetry-resource-detector-container/src/detectors/index.ts index edd915f6aa..66d84b4057 100644 --- a/detectors/node/opentelemetry-resource-detector-container/src/detectors/index.ts +++ b/detectors/node/opentelemetry-resource-detector-container/src/detectors/index.ts @@ -13,4 +13,4 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -export * from './ContainerDetector'; +export { ContainerDetector } from './ContainerDetector'; diff --git a/detectors/node/opentelemetry-resource-detector-container/src/index.ts b/detectors/node/opentelemetry-resource-detector-container/src/index.ts index 9bfde8defd..f75bd6e55b 100644 --- a/detectors/node/opentelemetry-resource-detector-container/src/index.ts +++ b/detectors/node/opentelemetry-resource-detector-container/src/index.ts @@ -13,4 +13,4 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -export * from './detectors'; +export { ContainerDetector } from './detectors/ContainerDetector'; diff --git a/detectors/node/opentelemetry-resource-detector-container/test/ContainerDetector.test.ts b/detectors/node/opentelemetry-resource-detector-container/test/ContainerDetector.test.ts index cb6a7e0133..01c49f7d76 100644 --- a/detectors/node/opentelemetry-resource-detector-container/test/ContainerDetector.test.ts +++ b/detectors/node/opentelemetry-resource-detector-container/test/ContainerDetector.test.ts @@ -17,13 +17,13 @@ import * as sinon from 'sinon'; import * as assert from 'assert'; -import { containerDetector } from '../src'; +import { ContainerDetector } from '../src'; import { assertContainerResource, assertEmptyResource, } from '@opentelemetry/contrib-test-utils'; -import { ContainerDetector } from '../src'; +const containerDetector = new ContainerDetector; describe('ContainerDetector', () => { let readStub: sinon.SinonStub; diff --git a/detectors/node/opentelemetry-resource-detector-container/test/ContainerDetectorIntegration.test.ts b/detectors/node/opentelemetry-resource-detector-container/test/ContainerDetectorIntegration.test.ts index 0927e03dfc..1bf99dba42 100644 --- a/detectors/node/opentelemetry-resource-detector-container/test/ContainerDetectorIntegration.test.ts +++ b/detectors/node/opentelemetry-resource-detector-container/test/ContainerDetectorIntegration.test.ts @@ -14,7 +14,7 @@ * limitations under the License. */ -import * as assert from 'assert'; +import { equal } from 'assert'; import { FsInstrumentation } from '@opentelemetry/instrumentation-fs'; import { @@ -60,7 +60,7 @@ describe('[Integration] ContainerDetector', () => { await new Promise(r => setTimeout(r, 0)); const spans = memoryExporter.getFinishedSpans(); - assert.equal( + equal( spans.length, numSpansAfterRequire, 'no spans exported for ContainerDetector' diff --git a/detectors/node/opentelemetry-resource-detector-container/test/utils.test.ts b/detectors/node/opentelemetry-resource-detector-container/test/utils.test.ts index 193feb6fa3..8b9584f637 100644 --- a/detectors/node/opentelemetry-resource-detector-container/test/utils.test.ts +++ b/detectors/node/opentelemetry-resource-detector-container/test/utils.test.ts @@ -14,7 +14,7 @@ * limitations under the License. */ -import * as assert from 'assert'; +import { strictEqual } from 'assert'; import { extractContainerIdFromLine } from '../src/detectors/utils'; describe(' extractContainerId from line tests', () => { @@ -22,7 +22,7 @@ describe(' extractContainerId from line tests', () => { const line = '11:devices:/kubepods.slice/kubepods-besteffort.slice/kubepods-besteffort-pod5c5979ec_6b2b_11e9_a923_42010a800002.slice/crio-1234567890abcdef.scope'; const expected = '1234567890abcdef'; - assert.strictEqual(extractContainerIdFromLine(line), expected); + strictEqual(extractContainerIdFromLine(line), expected); }); it('should extract container ID from docker-prefixed line', () => { @@ -30,7 +30,7 @@ describe(' extractContainerId from line tests', () => { '11:devices:/docker/1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef'; const expected = '1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef'; - assert.strictEqual(extractContainerIdFromLine(line), expected); + strictEqual(extractContainerIdFromLine(line), expected); }); it('should extract container ID from cri-containerd-prefixed line', () => { @@ -38,30 +38,30 @@ describe(' extractContainerId from line tests', () => { '11:devices:/kubepods/burstable/pod2c4b2241-5c01-11e9-8e4e-42010a800002/cri-containerd-1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef'; const expected = '1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef'; - assert.strictEqual(extractContainerIdFromLine(line), expected); + strictEqual(extractContainerIdFromLine(line), expected); }); it('should handle containerd v1.5.0+ format with systemd cgroup driver', () => { const line = '0::/system.slice/containerd.service/kubepods-burstable-pod2c4b2241-5c01-11e9-8e4e-42010a800002.slice:cri-containerd:1234567890abcdef'; const expected = '1234567890abcdef'; - assert.strictEqual(extractContainerIdFromLine(line), expected); + strictEqual(extractContainerIdFromLine(line), expected); }); it('should return undefined for invalid container ID', () => { const line = '11:devices:/kubepods.slice/kubepods-besteffort.slice/kubepods-besteffort-pod5c5979ec_6b2b_11e9_a923_42010a800002.slice/invalid-id.scope'; - assert.strictEqual(extractContainerIdFromLine(line), undefined); + strictEqual(extractContainerIdFromLine(line), undefined); }); it('should return undefined for empty line', () => { const line = ''; - assert.strictEqual(extractContainerIdFromLine(line), undefined); + strictEqual(extractContainerIdFromLine(line), undefined); }); it('should return undefined for line without container ID', () => { const line = '11:devices:/'; - assert.strictEqual(extractContainerIdFromLine(line), undefined); + strictEqual(extractContainerIdFromLine(line), undefined); }); // Additional test cases @@ -69,13 +69,13 @@ describe(' extractContainerId from line tests', () => { const line = '0::/system.slice/containerd.service/kubepods-burstable-pod2c4b2241-5c01-11e9-8e4e-42010a800002.slice:cri-containerd-1234567890abcdef.extra'; const expected = '1234567890abcdef'; - assert.strictEqual(extractContainerIdFromLine(line), expected); + strictEqual(extractContainerIdFromLine(line), expected); }); it('should return containerid for valid hex string with any length', () => { const line = '11:devices:/docker/1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcde'; - assert.strictEqual( + strictEqual( extractContainerIdFromLine(line), '1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcde' ); @@ -86,6 +86,6 @@ describe(' extractContainerId from line tests', () => { '11:devices:/docker/1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef.suffix'; const expected = '1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef'; - assert.strictEqual(extractContainerIdFromLine(line), expected); + strictEqual(extractContainerIdFromLine(line), expected); }); }); diff --git a/detectors/node/opentelemetry-resource-detector-gcp/src/detectors/GcpDetector.ts b/detectors/node/opentelemetry-resource-detector-gcp/src/detectors/GcpDetector.ts index 8c4cccc8d9..2fd0875d69 100644 --- a/detectors/node/opentelemetry-resource-detector-gcp/src/detectors/GcpDetector.ts +++ b/detectors/node/opentelemetry-resource-detector-gcp/src/detectors/GcpDetector.ts @@ -14,7 +14,7 @@ * limitations under the License. */ -import * as gcpMetadata from 'gcp-metadata'; +import { isAvailable, project, instance } from 'gcp-metadata'; import { context, diag } from '@opentelemetry/api'; import { suppressTracing } from '@opentelemetry/core'; import { @@ -58,7 +58,7 @@ class GcpDetector implements DetectorSync { * empty {@link ResourceAttributes} if the connection or parsing of the metadata fails. */ private async _getAttributes(): Promise { - if (!(await gcpMetadata.isAvailable())) { + if (!(await isAvailable())) { diag.debug('GcpDetector failed: GCP Metadata unavailable.'); return {}; } @@ -101,7 +101,7 @@ class GcpDetector implements DetectorSync { /** Gets project id from GCP project metadata. */ private async _getProjectId(): Promise { try { - return await gcpMetadata.project('project-id'); + return await project('project-id'); } catch { return ''; } @@ -110,7 +110,7 @@ class GcpDetector implements DetectorSync { /** Gets instance id from GCP instance metadata. */ private async _getInstanceId(): Promise { try { - const id = await gcpMetadata.instance('id'); + const id = await instance('id'); return id.toString(); } catch { return ''; @@ -120,7 +120,7 @@ class GcpDetector implements DetectorSync { /** Gets zone from GCP instance metadata. */ private async _getZone(): Promise { try { - const zoneId = await gcpMetadata.instance('zone'); + const zoneId = await instance('zone'); if (zoneId) { return zoneId.split('/').pop(); } @@ -133,7 +133,7 @@ class GcpDetector implements DetectorSync { /** Gets cluster name from GCP instance metadata. */ private async _getClusterName(): Promise { try { - return await gcpMetadata.instance('attributes/cluster-name'); + return await instance('attributes/cluster-name'); } catch { return ''; } @@ -142,7 +142,7 @@ class GcpDetector implements DetectorSync { /** Gets hostname from GCP instance metadata. */ private async _getHostname(): Promise { try { - return await gcpMetadata.instance('hostname'); + return await instance('hostname'); } catch { return ''; } diff --git a/detectors/node/opentelemetry-resource-detector-gcp/src/detectors/index.ts b/detectors/node/opentelemetry-resource-detector-gcp/src/detectors/index.ts index 9e856721bc..63782b5e64 100644 --- a/detectors/node/opentelemetry-resource-detector-gcp/src/detectors/index.ts +++ b/detectors/node/opentelemetry-resource-detector-gcp/src/detectors/index.ts @@ -14,4 +14,4 @@ * limitations under the License. */ -export * from './GcpDetector'; +export { gcpDetector } from './GcpDetector'; diff --git a/detectors/node/opentelemetry-resource-detector-gcp/src/index.ts b/detectors/node/opentelemetry-resource-detector-gcp/src/index.ts index f281d4fdcd..d5675245dc 100644 --- a/detectors/node/opentelemetry-resource-detector-gcp/src/index.ts +++ b/detectors/node/opentelemetry-resource-detector-gcp/src/index.ts @@ -14,7 +14,7 @@ * limitations under the License. */ -export * from './detectors'; +export { gcpDetector } from './detectors'; // Internal - used for tests only export { resetIsAvailableCache } from 'gcp-metadata'; diff --git a/detectors/node/opentelemetry-resource-detector-gcp/test/detectors/GcpDetector.test.ts b/detectors/node/opentelemetry-resource-detector-gcp/test/detectors/GcpDetector.test.ts index 4d2bc6ea48..7a252d2970 100644 --- a/detectors/node/opentelemetry-resource-detector-gcp/test/detectors/GcpDetector.test.ts +++ b/detectors/node/opentelemetry-resource-detector-gcp/test/detectors/GcpDetector.test.ts @@ -22,7 +22,7 @@ import { SECONDARY_HOST_ADDRESS, resetIsAvailableCache, } from 'gcp-metadata'; -import * as nock from 'nock'; +import { disableNetConnect, enableNetConnect, cleanAll } from 'nock'; import { gcpDetector } from '../../src'; import { assertCloudResource, @@ -31,6 +31,7 @@ import { assertContainerResource, assertEmptyResource, } from '@opentelemetry/contrib-test-utils'; +import nock = require('nock'); const HEADERS = { [HEADER_NAME.toLowerCase()]: HEADER_VALUE, @@ -45,11 +46,11 @@ const HOSTNAME_PATH = BASE_PATH + '/instance/hostname'; describe('gcpDetector', () => { describe('.detect', () => { before(() => { - nock.disableNetConnect(); + disableNetConnect(); }); after(() => { - nock.enableNetConnect(); + enableNetConnect(); delete process.env.KUBERNETES_SERVICE_HOST; delete process.env.NAMESPACE; delete process.env.CONTAINER_NAME; @@ -58,7 +59,7 @@ describe('gcpDetector', () => { beforeEach(() => { resetIsAvailableCache(); - nock.cleanAll(); + cleanAll(); delete process.env.KUBERNETES_SERVICE_HOST; delete process.env.NAMESPACE; delete process.env.CONTAINER_NAME; diff --git a/detectors/node/opentelemetry-resource-detector-gcp/test/detectors/GcpDetectorIntegration.test.ts b/detectors/node/opentelemetry-resource-detector-gcp/test/detectors/GcpDetectorIntegration.test.ts index 77bf0334d7..af62240ee8 100644 --- a/detectors/node/opentelemetry-resource-detector-gcp/test/detectors/GcpDetectorIntegration.test.ts +++ b/detectors/node/opentelemetry-resource-detector-gcp/test/detectors/GcpDetectorIntegration.test.ts @@ -30,7 +30,7 @@ Object.keys(require.cache) delete require.cache[key]; }); -import * as assert from 'assert'; +import { equal } from 'assert'; import { HttpInstrumentation } from '@opentelemetry/instrumentation-http'; import { @@ -70,7 +70,7 @@ describe('[Integration] GcpDetector', () => { await new Promise(r => setTimeout(r, 0)); const spans = memoryExporter.getFinishedSpans(); - assert.equal(spans.length, 0, 'no spans exported for GcpDetector'); + equal(spans.length, 0, 'no spans exported for GcpDetector'); await sdk.shutdown(); }).timeout(15000); diff --git a/detectors/node/opentelemetry-resource-detector-github/src/detectors/index.ts b/detectors/node/opentelemetry-resource-detector-github/src/detectors/index.ts index 1927c949d4..7a22440b66 100644 --- a/detectors/node/opentelemetry-resource-detector-github/src/detectors/index.ts +++ b/detectors/node/opentelemetry-resource-detector-github/src/detectors/index.ts @@ -13,4 +13,4 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -export * from './GitHubDetector'; +export { gitHubDetector } from './GitHubDetector'; diff --git a/detectors/node/opentelemetry-resource-detector-github/src/index.ts b/detectors/node/opentelemetry-resource-detector-github/src/index.ts index 9bfde8defd..7c42591dc4 100644 --- a/detectors/node/opentelemetry-resource-detector-github/src/index.ts +++ b/detectors/node/opentelemetry-resource-detector-github/src/index.ts @@ -13,4 +13,4 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -export * from './detectors'; +export { gitHubDetector } from './detectors'; diff --git a/detectors/node/opentelemetry-resource-detector-github/test/detectors/GitHubDetector.test.ts b/detectors/node/opentelemetry-resource-detector-github/test/detectors/GitHubDetector.test.ts index 1fcb9a9c13..590c670ea8 100644 --- a/detectors/node/opentelemetry-resource-detector-github/test/detectors/GitHubDetector.test.ts +++ b/detectors/node/opentelemetry-resource-detector-github/test/detectors/GitHubDetector.test.ts @@ -14,16 +14,16 @@ * limitations under the License. */ -import * as assert from 'assert'; -import * as sinon from 'sinon'; +import { deepStrictEqual, ok } from 'assert'; +import { createSandbox, SinonSandbox } from 'sinon'; import { gitHubDetector } from '../../src/detectors'; describe('GitHubResourceDetector', () => { - let sandbox: sinon.SinonSandbox; + let sandbox: SinonSandbox; beforeEach(() => { - sandbox = sinon.createSandbox(); + sandbox = createSandbox(); process.env.GITHUB_WORKFLOW = ''; process.env.GITHUB_RUN_ID = ''; @@ -51,8 +51,8 @@ describe('GitHubResourceDetector', () => { const resource = await gitHubDetector.detect(); - assert.ok(resource); - assert.deepStrictEqual(resource.attributes, { + ok(resource); + deepStrictEqual(resource.attributes, { 'github.workflow': 'workflow-foo', 'github.run_id': 'run-id-foo', 'github.run_number': '42', @@ -67,7 +67,7 @@ describe('GitHubResourceDetector', () => { it('should return empty resource when no GitHub env vars exists', async () => { const resource = await gitHubDetector.detect(); - assert.ok(resource); - assert.deepStrictEqual(resource.attributes, {}); + ok(resource); + deepStrictEqual(resource.attributes, {}); }); }); diff --git a/detectors/node/opentelemetry-resource-detector-instana/src/detectors/InstanaAgentDetector.ts b/detectors/node/opentelemetry-resource-detector-instana/src/detectors/InstanaAgentDetector.ts index 2a22951803..aa85001a08 100644 --- a/detectors/node/opentelemetry-resource-detector-instana/src/detectors/InstanaAgentDetector.ts +++ b/detectors/node/opentelemetry-resource-detector-instana/src/detectors/InstanaAgentDetector.ts @@ -24,7 +24,7 @@ import { SEMRESATTRS_PROCESS_PID, SEMRESATTRS_SERVICE_INSTANCE_ID, } from '@opentelemetry/semantic-conventions'; -import * as http from 'http'; +import { request } from 'http'; class InstanaAgentDetector implements DetectorSync { readonly INSTANA_AGENT_DEFAULT_HOST = 'localhost'; @@ -114,7 +114,7 @@ class InstanaAgentDetector implements DetectorSync { timeout: agentTimeoutMs, }; - const req = http.request(opts, res => { + const req = request(opts, res => { res.setEncoding('utf8'); let rawData = ''; diff --git a/detectors/node/opentelemetry-resource-detector-instana/src/detectors/index.ts b/detectors/node/opentelemetry-resource-detector-instana/src/detectors/index.ts index 838b64dd94..4738db7606 100644 --- a/detectors/node/opentelemetry-resource-detector-instana/src/detectors/index.ts +++ b/detectors/node/opentelemetry-resource-detector-instana/src/detectors/index.ts @@ -14,4 +14,4 @@ * limitations under the License. */ -export * from './InstanaAgentDetector'; +export { instanaAgentDetector } from './InstanaAgentDetector'; diff --git a/detectors/node/opentelemetry-resource-detector-instana/src/index.ts b/detectors/node/opentelemetry-resource-detector-instana/src/index.ts index 0acba8788c..4ba2ecdea7 100644 --- a/detectors/node/opentelemetry-resource-detector-instana/src/index.ts +++ b/detectors/node/opentelemetry-resource-detector-instana/src/index.ts @@ -14,4 +14,4 @@ * limitations under the License. */ -export * from './detectors'; +export { instanaAgentDetector } from './detectors'; diff --git a/detectors/node/opentelemetry-resource-detector-instana/test/InstanaAgentDetectorIntegrationTest.test.ts b/detectors/node/opentelemetry-resource-detector-instana/test/InstanaAgentDetectorIntegrationTest.test.ts index e99aa78487..85e3a22146 100644 --- a/detectors/node/opentelemetry-resource-detector-instana/test/InstanaAgentDetectorIntegrationTest.test.ts +++ b/detectors/node/opentelemetry-resource-detector-instana/test/InstanaAgentDetectorIntegrationTest.test.ts @@ -14,8 +14,8 @@ * limitations under the License. */ -import * as nock from 'nock'; -import * as assert from 'assert'; +import { disableNetConnect, enableNetConnect, cleanAll } from 'nock'; +import { equal } from 'assert'; import { Resource, processDetector, @@ -24,6 +24,7 @@ import { import { SEMRESATTRS_SERVICE_NAME } from '@opentelemetry/semantic-conventions'; import { NodeSDK } from '@opentelemetry/sdk-node'; import { instanaAgentDetector } from '../src'; +import nock = require('nock'); const delay = (ms: number) => new Promise(resolve => { @@ -32,13 +33,13 @@ const delay = (ms: number) => describe('[Integration] instanaAgentDetector', () => { beforeEach(() => { - nock.disableNetConnect(); - nock.cleanAll(); + disableNetConnect(); + cleanAll(); }); afterEach(() => { - nock.enableNetConnect(); - nock.cleanAll(); + enableNetConnect(); + cleanAll(); }); it('#1 should return merged resource', async () => { @@ -69,10 +70,10 @@ describe('[Integration] instanaAgentDetector', () => { // await resource.waitForAsyncAttributes?.(); [>= @opentelemetry/sdk-node@0.37.0] await resource.waitForAsyncAttributes?.(); - assert.equal(resource.attributes['process.pid'], 123); - assert.equal(resource.attributes['process.runtime.name'], 'nodejs'); - assert.equal(resource.attributes['service.name'], 'TestService'); - assert.equal( + equal(resource.attributes['process.pid'], 123); + equal(resource.attributes['process.runtime.name'], 'nodejs'); + equal(resource.attributes['service.name'], 'TestService'); + equal( resource.attributes['service.instance.id'], '14:7d:da:ff:fe:e4:08:d5' ); @@ -106,10 +107,10 @@ describe('[Integration] instanaAgentDetector', () => { await delay(500); - assert.equal(resource.attributes['process.pid'], 123); - assert.equal(resource.attributes['process.runtime.name'], 'nodejs'); - assert.equal(resource.attributes['service.name'], 'TestService'); - assert.equal( + equal(resource.attributes['process.pid'], 123); + equal(resource.attributes['process.runtime.name'], 'nodejs'); + equal(resource.attributes['service.name'], 'TestService'); + equal( resource.attributes['service.instance.id'], '14:7d:da:ff:fe:e4:08:d5' ); diff --git a/detectors/node/opentelemetry-resource-detector-instana/test/InstanaAgentDetectorUnitTest.test.ts b/detectors/node/opentelemetry-resource-detector-instana/test/InstanaAgentDetectorUnitTest.test.ts index db66c0dc0d..9b99eed9ac 100644 --- a/detectors/node/opentelemetry-resource-detector-instana/test/InstanaAgentDetectorUnitTest.test.ts +++ b/detectors/node/opentelemetry-resource-detector-instana/test/InstanaAgentDetectorUnitTest.test.ts @@ -14,9 +14,10 @@ * limitations under the License. */ -import * as nock from 'nock'; -import * as assert from 'assert'; +import { disableNetConnect, enableNetConnect, cleanAll } from 'nock'; +import { deepEqual, deepStrictEqual } from 'assert'; import { instanaAgentDetector } from '../src'; +import nock = require('nock'); describe('[UNIT] instanaAgentDetector', () => { describe('when agent is running', () => { @@ -29,8 +30,8 @@ describe('[UNIT] instanaAgentDetector', () => { }); beforeEach(() => { - nock.disableNetConnect(); - nock.cleanAll(); + disableNetConnect(); + cleanAll(); }); afterEach(() => { @@ -38,8 +39,8 @@ describe('[UNIT] instanaAgentDetector', () => { delete process.env.INSTANA_AGENT_HOST; delete process.env.INSTANA_AGENT_PORT; - nock.enableNetConnect(); - nock.cleanAll(); + enableNetConnect(); + cleanAll(); }); it('should return agent resource with default host/port', async () => { @@ -58,7 +59,7 @@ describe('[UNIT] instanaAgentDetector', () => { scope.done(); - assert.deepEqual(resource.attributes, { + deepEqual(resource.attributes, { 'process.pid': 123, 'service.instance.id': '14:7d:da:ff:fe:e4:08:d5', }); @@ -85,7 +86,7 @@ describe('[UNIT] instanaAgentDetector', () => { scope.done(); - assert.deepEqual(resource.attributes, { + deepEqual(resource.attributes, { 'process.pid': 222, 'service.instance.id': '14:7d:da:ff:fe:e4:08:d5', }); @@ -100,7 +101,7 @@ describe('[UNIT] instanaAgentDetector', () => { const resource = instanaAgentDetector.detect(); await resource.waitForAsyncAttributes?.(); - assert.deepStrictEqual(resource.attributes, {}); + deepStrictEqual(resource.attributes, {}); scope.done(); }); @@ -121,7 +122,7 @@ describe('[UNIT] instanaAgentDetector', () => { const resource = instanaAgentDetector.detect(); await resource.waitForAsyncAttributes?.(); - assert.deepStrictEqual(resource.attributes, {}); + deepStrictEqual(resource.attributes, {}); }); }); @@ -134,7 +135,7 @@ describe('[UNIT] instanaAgentDetector', () => { const resource = instanaAgentDetector.detect(); await resource.waitForAsyncAttributes?.(); - assert.deepStrictEqual(resource.attributes, {}); + deepStrictEqual(resource.attributes, {}); }); }); }); diff --git a/eslint.config.js b/eslint.config.js index 71488af0c9..a3961fb9bb 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -19,6 +19,7 @@ module.exports = { "prefer-rest-params": "off", "no-shadow": "off", "node/no-deprecated-api": ["warn"], + "no-restricted-syntax": ["error", "ExportAllDeclaration"], "header/header": ["error", "block", [{ pattern: / \* Copyright The OpenTelemetry Authors(, .+)*[\r\n]+ \*[\r\n]+ \* Licensed under the Apache License, Version 2\.0 \(the \"License\"\);[\r\n]+ \* you may not use this file except in compliance with the License\.[\r\n]+ \* You may obtain a copy of the License at[\r\n]+ \*[\r\n]+ \* https:\/\/www\.apache\.org\/licenses\/LICENSE-2\.0[\r\n]+ \*[\r\n]+ \* Unless required by applicable law or agreed to in writing, software[\r\n]+ \* distributed under the License is distributed on an \"AS IS\" BASIS,[\r\n]+ \* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied\.[\r\n]+ \* See the License for the specific language governing permissions and[\r\n]+ \* limitations under the License\./gm, template: diff --git a/examples/koa/src/client.ts b/examples/koa/src/client.ts index 40af549da4..26f2242a1d 100644 --- a/examples/koa/src/client.ts +++ b/examples/koa/src/client.ts @@ -2,22 +2,22 @@ import { setupTracing } from "./tracer"; const tracer = setupTracing('example-koa-client'); -import * as api from '@opentelemetry/api'; +import {trace, context,ROOT_CONTEXT,SpanKind,SpanStatusCode} from '@opentelemetry/api'; import { default as axios } from 'axios'; function makeRequest() { const span = tracer.startSpan('client.makeRequest()', { - kind: api.SpanKind.CLIENT, + kind: SpanKind.CLIENT, }); - api.context.with(api.trace.setSpan(api.ROOT_CONTEXT, span), async () => { + context.with(trace.setSpan(ROOT_CONTEXT, span), async () => { try { const res = await axios.get('http://localhost:8081/run_test'); - span.setStatus({ code: api.SpanStatusCode.OK }); + span.setStatus({ code: SpanStatusCode.OK }); console.log(res.statusText); } catch (e) { if(e instanceof Error) { - span.setStatus({ code: api.SpanStatusCode.ERROR, message: e.message }); + span.setStatus({ code: SpanStatusCode.ERROR, message: e.message }); } } span.end(); diff --git a/examples/koa/src/server.ts b/examples/koa/src/server.ts index f21f77e7bb..5fae0c15d3 100644 --- a/examples/koa/src/server.ts +++ b/examples/koa/src/server.ts @@ -1,6 +1,6 @@ 'use strict'; -import * as api from '@opentelemetry/api'; +import {trace, context} from '@opentelemetry/api'; import { setupTracing } from './tracer' setupTracing('example-koa-server'); @@ -32,7 +32,7 @@ const posts = ['post 0', 'post 1', 'post 2']; function addPost(ctx: Koa.Context) { const newPostId = posts.length; posts.push(`post ${newPostId}`); - const currentSpan = api.trace.getSpan(api.context.active()); + const currentSpan = trace.getSpan(context.active()); currentSpan?.addEvent('Added post'); currentSpan?.setAttribute('post.id', newPostId) ctx.body = `Added post: ${posts[posts.length - 1]}`; @@ -51,7 +51,7 @@ async function showNewPost(ctx: Koa.Context) { function runTest(ctx: Koa.Context) { console.log('runTest'); - const currentSpan = api.trace.getSpan(api.context.active()); + const currentSpan = trace.getSpan(context.active()); if (currentSpan){ const { traceId } = currentSpan.spanContext(); console.log(`traceid: ${traceId}`); diff --git a/examples/koa/src/tracer.ts b/examples/koa/src/tracer.ts index d0a3321a68..dd59eb091e 100644 --- a/examples/koa/src/tracer.ts +++ b/examples/koa/src/tracer.ts @@ -3,7 +3,7 @@ import { KoaInstrumentation } from '@opentelemetry/instrumentation-koa'; import { HttpInstrumentation } from '@opentelemetry/instrumentation-http'; -import * as api from '@opentelemetry/api'; +import {trace} from '@opentelemetry/api'; import { registerInstrumentations } from '@opentelemetry/instrumentation'; import { NodeTracerProvider } from '@opentelemetry/sdk-trace-node'; import { SimpleSpanProcessor } from '@opentelemetry/sdk-trace-base'; @@ -40,5 +40,5 @@ export const setupTracing = (serviceName: string) => { // Initialize the OpenTelemetry APIs to use the NodeTracerProvider bindings provider.register(); - return api.trace.getTracer(serviceName); + return trace.getTracer(serviceName); }; diff --git a/examples/mongodb/src/client.ts b/examples/mongodb/src/client.ts index 556aeb248f..af40751671 100644 --- a/examples/mongodb/src/client.ts +++ b/examples/mongodb/src/client.ts @@ -1,6 +1,6 @@ 'use strict'; -import * as api from '@opentelemetry/api'; +import {trace, context,ROOT_CONTEXT} from '@opentelemetry/api'; import { setupTracing } from './tracer'; const tracer = setupTracing('example-mongodb-http-client') @@ -17,7 +17,7 @@ function makeRequest() { let queries = 0; let responses = 0; - api.context.with(api.trace.setSpan(api.ROOT_CONTEXT, span), () => { + context.with(trace.setSpan(ROOT_CONTEXT, span), () => { queries += 1; http.get({ host: 'localhost', @@ -33,7 +33,7 @@ function makeRequest() { }); }); }); - api.context.with(api.trace.setSpan(api.ROOT_CONTEXT, span), () => { + context.with(trace.setSpan(ROOT_CONTEXT, span), () => { queries += 1; http.get({ host: 'localhost', @@ -49,7 +49,7 @@ function makeRequest() { }); }); }); - api.context.with(api.trace.setSpan(api.ROOT_CONTEXT, span), () => { + context.with(trace.setSpan(ROOT_CONTEXT, span), () => { queries += 1; http.get({ host: 'localhost', diff --git a/examples/mongodb/src/tracer.ts b/examples/mongodb/src/tracer.ts index 4e63724503..ba4c295d83 100644 --- a/examples/mongodb/src/tracer.ts +++ b/examples/mongodb/src/tracer.ts @@ -1,4 +1,4 @@ -import * as api from "@opentelemetry/api"; +import {trace, Tracer} from '@opentelemetry/api'; import { NodeTracerProvider } from '@opentelemetry/sdk-trace-node'; import { Resource } from '@opentelemetry/resources'; @@ -11,7 +11,7 @@ import { MongoDBInstrumentation } from '@opentelemetry/instrumentation-mongodb'; import { SEMRESATTRS_SERVICE_NAME } from '@opentelemetry/semantic-conventions'; -export const setupTracing = (serviceName: string): api.Tracer => { +export const setupTracing = (serviceName: string): Tracer => { const provider = new NodeTracerProvider({ resource: new Resource({ [SEMRESATTRS_SERVICE_NAME]: serviceName @@ -34,5 +34,5 @@ export const setupTracing = (serviceName: string): api.Tracer => { provider.addSpanProcessor(new SimpleSpanProcessor(new ZipkinExporter())); provider.addSpanProcessor(new SimpleSpanProcessor(new JaegerExporter())); - return api.trace.getTracer('mongodb-example'); + return trace.getTracer('mongodb-example'); }; diff --git a/examples/mysql/src/client.ts b/examples/mysql/src/client.ts index de80b7bc11..64362efba1 100644 --- a/examples/mysql/src/client.ts +++ b/examples/mysql/src/client.ts @@ -1,9 +1,9 @@ 'use strict'; -import * as api from '@opentelemetry/api'; +import {trace, context,ROOT_CONTEXT} from '@opentelemetry/api'; import { setupTracing } from "./tracer"; const tracer = setupTracing('example-mysql-client'); -import * as http from 'http'; +import {get} from 'http'; /** A function which makes requests and handles response. */ function makeRequest() { @@ -15,9 +15,9 @@ function makeRequest() { let queries = 0; let responses = 0; - api.context.with(api.trace.setSpan(api.ROOT_CONTEXT, span), () => { + context.with(trace.setSpan(ROOT_CONTEXT, span), () => { queries += 1; - http.get({ + get({ host: 'localhost', port: 8080, path: '/connection/query', @@ -31,9 +31,9 @@ function makeRequest() { }); }); }); - api.context.with(api.trace.setSpan(api.ROOT_CONTEXT, span), () => { + context.with(trace.setSpan(ROOT_CONTEXT, span), () => { queries += 1; - http.get({ + get({ host: 'localhost', port: 8080, path: '/pool/query', @@ -47,9 +47,9 @@ function makeRequest() { }); }); }); - api.context.with(api.trace.setSpan(api.ROOT_CONTEXT, span), () => { + context.with(trace.setSpan(ROOT_CONTEXT, span), () => { queries += 1; - http.get({ + get({ host: 'localhost', port: 8080, path: '/pool/query-with-2-connections', @@ -63,9 +63,9 @@ function makeRequest() { }); }); }); - api.context.with(api.trace.setSpan(api.ROOT_CONTEXT, span), () => { + context.with(trace.setSpan(ROOT_CONTEXT, span), () => { queries += 1; - http.get({ + get({ host: 'localhost', port: 8080, path: '/pool/query-2-pools', @@ -79,9 +79,9 @@ function makeRequest() { }); }); }); - api.context.with(api.trace.setSpan(api.ROOT_CONTEXT, span), () => { + context.with(trace.setSpan(ROOT_CONTEXT, span), () => { queries += 1; - http.get({ + get({ host: 'localhost', port: 8080, path: '/cluster/query', diff --git a/examples/mysql/src/server.ts b/examples/mysql/src/server.ts index 180224e2c7..99c66fb252 100644 --- a/examples/mysql/src/server.ts +++ b/examples/mysql/src/server.ts @@ -3,32 +3,32 @@ // eslint-disable-next-line import/order import { setupTracing } from "./tracer"; setupTracing('example-mysql-server'); -import * as api from '@opentelemetry/api'; -import * as mysql from 'mysql' -import * as http from 'http'; +import {trace, context} from '@opentelemetry/api'; +import {createPool, createPoolCluster,createConnection} from 'mysql' +import {createServer} from 'http'; import { MysqlError } from "mysql"; import { PoolConnection } from "mysql"; -const pool = mysql.createPool({ +const pool = createPool({ host: 'localhost', user: 'root', password: 'secret', }); -const pool2 = mysql.createPool({ +const pool2 = createPool({ host: 'localhost', user: 'root', password: 'secret', database: 'db_test' //this db is created by init.sql }); -const connection = mysql.createConnection({ +const connection = createConnection({ host: 'localhost', user: 'root', password: 'secret', }); -const cluster = mysql.createPoolCluster(); +const cluster = createPoolCluster(); cluster.add({ host: 'localhost', @@ -39,7 +39,7 @@ cluster.add({ /** Starts a HTTP server that receives requests on sample server port. */ function startServer(port: number | undefined) { // Creates a server - const server = http.createServer(handleRequest); + const server = createServer(handleRequest); // Starts the server server.listen(port, () => { console.log(`Node HTTP listening on ${port}`); @@ -48,7 +48,7 @@ function startServer(port: number | undefined) { /** A function which handles requests and send response. */ function handleRequest(request: any, response: any) { - const currentSpan = api.trace.getSpan(api.context.active()) + const currentSpan = trace.getSpan(context.active()) // display traceid in the terminal const traceId = currentSpan?.spanContext().traceId; console.log(`traceid: ${traceId}`); @@ -92,7 +92,7 @@ function handlePoolQuery(response: any) { } else { conn.query(query, (err, results) => { conn.release(); - api.trace.getSpan(api.context.active())?.addEvent('results'); + trace.getSpan(context.active())?.addEvent('results'); if (err) { console.log('Error code:', err.code); response.end(err.message); @@ -114,7 +114,7 @@ function handle2PoolsQuery(response: any) { } else { conn.query(query1, (err, results) => { conn.release(); - api.trace.getSpan(api.context.active())?.addEvent('results'); + trace.getSpan(context.active())?.addEvent('results'); if (err) { console.log('Error code:', err.code); response.end(err.message); @@ -131,7 +131,7 @@ function handle2PoolsQuery(response: any) { } else { conn.query(query2, (err, results) => { conn.release(); - api.trace.getSpan(api.context.active())?.addEvent('results'); + trace.getSpan(context.active())?.addEvent('results'); if (err) { console.log('Error code:', err.code); response.end(err.message); @@ -204,7 +204,7 @@ function handleClusterQuery(response: any) { response.end(connErr.message); } else { conn.query(query, (err, results, _fields) => { - api.trace.getSpan(api.context.active())?.addEvent('results'); + trace.getSpan(context.active())?.addEvent('results'); if (err) { console.log('Error code:', err.code); response.end(err.message); diff --git a/examples/redis/src/client.ts b/examples/redis/src/client.ts index 4f83690393..dc591ba1b7 100644 --- a/examples/redis/src/client.ts +++ b/examples/redis/src/client.ts @@ -2,22 +2,22 @@ import { setupTracing } from "./tracer"; const tracer = setupTracing('example-redis-client'); -import * as api from '@opentelemetry/api'; +import {trace, context,ROOT_CONTEXT,SpanKind,SpanStatusCode} from '@opentelemetry/api'; import { default as axios } from 'axios'; function makeRequest() { const span = tracer.startSpan('client.makeRequest()', { - kind: api.SpanKind.CLIENT, + kind: SpanKind.CLIENT, }); - api.context.with(api.trace.setSpan(api.ROOT_CONTEXT, span), async () => { + context.with(trace.setSpan(ROOT_CONTEXT, span), async () => { try { const res = await axios.get('http://localhost:8080/run_test'); - span.setStatus({ code: api.SpanStatusCode.OK }); + span.setStatus({ code: SpanStatusCode.OK }); console.log(res.statusText); } catch (e) { if(e instanceof Error) { - span.setStatus({ code: api.SpanStatusCode.ERROR, message: e.message }); + span.setStatus({ code: SpanStatusCode.ERROR, message: e.message }); } } span.end(); diff --git a/examples/redis/src/express-tracer-handlers.ts b/examples/redis/src/express-tracer-handlers.ts index 8caed1357b..a055f81c8f 100644 --- a/examples/redis/src/express-tracer-handlers.ts +++ b/examples/redis/src/express-tracer-handlers.ts @@ -1,11 +1,11 @@ 'use strict'; -import * as api from '@opentelemetry/api'; +import {trace, context,ROOT_CONTEXT,SpanKind,SpanStatusCode,Tracer} from '@opentelemetry/api'; -export function getMiddlewareTracer(tracer: api.Tracer) { +export function getMiddlewareTracer(tracer: Tracer) { return (req: any, res: any, next: any) => { const span = tracer.startSpan(`express.middleware.tracer(${req.method} ${req.path})`, { - kind: api.SpanKind.SERVER, + kind: SpanKind.SERVER, }); // End this span before sending out the response @@ -15,17 +15,17 @@ export function getMiddlewareTracer(tracer: api.Tracer) { originalSend.apply(res, args); }; - api.context.with(api.trace.setSpan(api.ROOT_CONTEXT, span), next); + context.with(trace.setSpan(ROOT_CONTEXT, span), next); }; } -export function getErrorTracer(tracer: api.Tracer) { +export function getErrorTracer(tracer: Tracer) { return (err: any, _req: any, res: any, _next: any) => { console.error('Caught error', err.message); - const span = api.trace.getSpan(api.context.active()) + const span = trace.getSpan(context.active()) if (span) { - span.setStatus({ code: api.SpanStatusCode.ERROR, message: err.message }); + span.setStatus({ code: SpanStatusCode.ERROR, message: err.message }); } res.status(500).send(err.message); }; diff --git a/incubator/opentelemetry-sampler-aws-xray/src/index.ts b/incubator/opentelemetry-sampler-aws-xray/src/index.ts index eb37ee9739..5b170c52fe 100644 --- a/incubator/opentelemetry-sampler-aws-xray/src/index.ts +++ b/incubator/opentelemetry-sampler-aws-xray/src/index.ts @@ -13,5 +13,5 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -export * from './remote-sampler'; +export {AWSXRayRemoteSampler} from './remote-sampler'; export { AWSXRaySamplerConfig } from './types'; diff --git a/incubator/opentelemetry-sampler-aws-xray/test/remote-sampler.test.ts b/incubator/opentelemetry-sampler-aws-xray/test/remote-sampler.test.ts index b7d31c7fd4..fe9cff05ca 100644 --- a/incubator/opentelemetry-sampler-aws-xray/test/remote-sampler.test.ts +++ b/incubator/opentelemetry-sampler-aws-xray/test/remote-sampler.test.ts @@ -14,12 +14,12 @@ * limitations under the License. */ -import * as sinon from 'sinon'; +import {SinonFakeTimers, SinonSpy, useFakeTimers, spy, assert} from 'sinon'; import axios from 'axios'; -import * as nock from 'nock'; -import * as assert from 'assert'; +import {strictEqual,throws } from 'assert'; import { AWSXRayRemoteSampler } from '../src'; +import nock = require('nock'); describe('GetSamplingRules', () => { // eslint-disable-next-line @typescript-eslint/no-explicit-any @@ -89,9 +89,9 @@ describe('GetSamplingRules', () => { ], }; - let clock: sinon.SinonFakeTimers; + let clock: SinonFakeTimers; let sampler: AWSXRayRemoteSampler; - let axiosPostSpy: sinon.SinonSpy; + let axiosPostSpy: SinonSpy; const defaultEndpoint = 'http://localhost:1234'; const pollingInterval = 60 * 1000; @@ -108,8 +108,8 @@ describe('GetSamplingRules', () => { }); beforeEach(() => { - clock = sinon.useFakeTimers(); - axiosPostSpy = sinon.spy(axios, 'post'); + clock = useFakeTimers(); + axiosPostSpy = spy(axios, 'post'); sampler = new AWSXRayRemoteSampler(config); }); @@ -126,34 +126,34 @@ describe('GetSamplingRules', () => { pollingIntervalMs: -5, }; - assert.throws( + throws( () => new AWSXRayRemoteSampler(configWithZeroPollingInterval), TypeError ); - assert.throws( + throws( () => new AWSXRayRemoteSampler(configWithNegativeInterval), TypeError ); }); it('should make a POST request to the /GetSamplingRules endpoint upon initialization', async () => { - sinon.assert.calledOnce(axiosPostSpy); + assert.calledOnce(axiosPostSpy); }); it('should make a POST request to the /GetSamplingRules endpoint', async () => { clock.tick(pollingInterval); - sinon.assert.calledTwice(axiosPostSpy); + assert.calledTwice(axiosPostSpy); }); it('should make 3 POST requests to the /GetSamplingRules endpoint after 3 intervals have passed', async () => { clock.tick(pollingInterval); clock.tick(pollingInterval); - sinon.assert.calledThrice(axiosPostSpy); + assert.calledThrice(axiosPostSpy); }); it('should initialize endpoint and polling interval from config correctly', async () => { - assert.strictEqual( + strictEqual( sampler.toString(), `AWSXRayRemoteSampler{endpoint=${defaultEndpoint}, pollingInterval=${pollingInterval}}` ); @@ -163,7 +163,7 @@ describe('GetSamplingRules', () => { const sampler = new AWSXRayRemoteSampler({}); // default polling interval (5 minutes) = 5 * 60 * 1000 - assert.strictEqual( + strictEqual( sampler.toString(), `AWSXRayRemoteSampler{endpoint=http://localhost:2000, pollingInterval=${ 5 * 60 * 1000 diff --git a/metapackages/auto-configuration-propagators/test/utils.test.ts b/metapackages/auto-configuration-propagators/test/utils.test.ts index 6e2c9dedcd..0455782558 100644 --- a/metapackages/auto-configuration-propagators/test/utils.test.ts +++ b/metapackages/auto-configuration-propagators/test/utils.test.ts @@ -14,7 +14,7 @@ * limitations under the License. */ -import * as assert from 'assert'; +import { deepStrictEqual } from 'assert'; import { getPropagator } from '../src/utils'; describe('utils', () => { @@ -24,7 +24,7 @@ describe('utils', () => { }); it('should return default when env var is unset', () => { - assert.deepStrictEqual(getPropagator().fields(), [ + deepStrictEqual(getPropagator().fields(), [ 'traceparent', 'tracestate', 'baggage', @@ -33,7 +33,7 @@ describe('utils', () => { it('should return default when env var is empty', () => { process.env.OTEL_PROPAGATORS = ''; - assert.deepStrictEqual(getPropagator().fields(), [ + deepStrictEqual(getPropagator().fields(), [ 'traceparent', 'tracestate', 'baggage', @@ -42,7 +42,7 @@ describe('utils', () => { it('should return default when env var is all spaces', () => { process.env.OTEL_PROPAGATORS = ' '; - assert.deepStrictEqual(getPropagator().fields(), [ + deepStrictEqual(getPropagator().fields(), [ 'traceparent', 'tracestate', 'baggage', @@ -51,25 +51,22 @@ describe('utils', () => { it('should return the selected propagator when one is in the list', () => { process.env.OTEL_PROPAGATORS = 'tracecontext'; - assert.deepStrictEqual(getPropagator().fields(), [ - 'traceparent', - 'tracestate', - ]); + deepStrictEqual(getPropagator().fields(), ['traceparent', 'tracestate']); }); it('should return the selected propagators when multiple are in the list', () => { process.env.OTEL_PROPAGATORS = 'b3,jaeger'; - assert.deepStrictEqual(getPropagator().fields(), ['b3', 'uber-trace-id']); + deepStrictEqual(getPropagator().fields(), ['b3', 'uber-trace-id']); }); it('should return no-op propagator if all propagators are unknown', () => { process.env.OTEL_PROPAGATORS = 'my, unknown, propagators'; - assert.deepStrictEqual(getPropagator().fields(), []); + deepStrictEqual(getPropagator().fields(), []); }); it('should return no-op propagator if "none" is selected', () => { process.env.OTEL_PROPAGATORS = 'none'; - assert.deepStrictEqual(getPropagator().fields(), []); + deepStrictEqual(getPropagator().fields(), []); }); }); }); diff --git a/metapackages/auto-instrumentations-node/src/register.ts b/metapackages/auto-instrumentations-node/src/register.ts index d47556f061..c8072e037e 100644 --- a/metapackages/auto-instrumentations-node/src/register.ts +++ b/metapackages/auto-instrumentations-node/src/register.ts @@ -13,19 +13,16 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import * as opentelemetry from '@opentelemetry/sdk-node'; +import { NodeSDK, core } from '@opentelemetry/sdk-node'; import { diag, DiagConsoleLogger } from '@opentelemetry/api'; import { getNodeAutoInstrumentations, getResourceDetectorsFromEnv, } from './utils'; -diag.setLogger( - new DiagConsoleLogger(), - opentelemetry.core.getEnv().OTEL_LOG_LEVEL -); +diag.setLogger(new DiagConsoleLogger(), core.getEnv().OTEL_LOG_LEVEL); -const sdk = new opentelemetry.NodeSDK({ +const sdk = new NodeSDK({ instrumentations: getNodeAutoInstrumentations(), resourceDetectors: getResourceDetectorsFromEnv(), }); diff --git a/metapackages/auto-instrumentations-node/src/utils.ts b/metapackages/auto-instrumentations-node/src/utils.ts index d7e6a0cd6b..75691c2e37 100644 --- a/metapackages/auto-instrumentations-node/src/utils.ts +++ b/metapackages/auto-instrumentations-node/src/utils.ts @@ -65,7 +65,7 @@ import { awsEksDetector, awsLambdaDetector, } from '@opentelemetry/resource-detector-aws'; -import { containerDetector } from '@opentelemetry/resource-detector-container'; +import { ContainerDetector } from '@opentelemetry/resource-detector-container'; import { gcpDetector } from '@opentelemetry/resource-detector-gcp'; import { Detector, @@ -92,6 +92,7 @@ const RESOURCE_DETECTOR_ALIBABA = 'alibaba'; const RESOURCE_DETECTOR_AWS = 'aws'; const RESOURCE_DETECTOR_AZURE = 'azure'; const RESOURCE_DETECTOR_GCP = 'gcp'; +const containerDetector = new ContainerDetector(); const InstrumentationMap = { '@opentelemetry/instrumentation-amqplib': AmqplibInstrumentation, diff --git a/metapackages/auto-instrumentations-node/test/register.test.ts b/metapackages/auto-instrumentations-node/test/register.test.ts index 2f952541db..3f86b8219a 100644 --- a/metapackages/auto-instrumentations-node/test/register.test.ts +++ b/metapackages/auto-instrumentations-node/test/register.test.ts @@ -15,7 +15,7 @@ */ import { execFile, PromiseWithChild } from 'child_process'; -import * as assert from 'assert'; +import { equal, ok } from 'assert'; import { promisify } from 'util'; import { Readable } from 'stream'; @@ -65,26 +65,22 @@ describe('Register', function () { const runPromise = runWithRegister('./test-app/app.js'); const { child } = runPromise; const { stdout } = await runPromise; - assert.equal(child.exitCode, 0, `child.exitCode (${child.exitCode})`); - assert.equal( - child.signalCode, - null, - `child.signalCode (${child.signalCode})` - ); + equal(child.exitCode, 0, `child.exitCode (${child.exitCode})`); + equal(child.signalCode, null, `child.signalCode (${child.signalCode})`); - assert.ok( + ok( stdout.includes( 'OpenTelemetry automatic instrumentation started successfully' ) ); - assert.ok( + ok( stdout.includes('OpenTelemetry SDK terminated'), `Process output was missing message indicating successful shutdown, got stdout:\n${stdout}` ); // Check a span has been generated for the GET request done in app.js - assert.ok(stdout.includes("name: 'GET'"), 'console span output in stdout'); + ok(stdout.includes("name: 'GET'"), 'console span output in stdout'); }); it('shuts down the NodeSDK when SIGTERM is received', async () => { @@ -94,12 +90,12 @@ describe('Register', function () { child.kill('SIGTERM'); const { stdout } = await runPromise; - assert.ok( + ok( stdout.includes('OpenTelemetry SDK terminated'), `Process output was missing message indicating successful shutdown, got stdout:\n${stdout}` ); // Check a span has been generated for the GET request done in app.js - assert.ok(stdout.includes("name: 'GET'"), 'console span output in stdout'); + ok(stdout.includes("name: 'GET'"), 'console span output in stdout'); }); }); diff --git a/metapackages/auto-instrumentations-node/test/utils.test.ts b/metapackages/auto-instrumentations-node/test/utils.test.ts index d2959b6ddd..d0a2ed7dcc 100644 --- a/metapackages/auto-instrumentations-node/test/utils.test.ts +++ b/metapackages/auto-instrumentations-node/test/utils.test.ts @@ -16,8 +16,8 @@ import { diag } from '@opentelemetry/api'; import { HttpInstrumentationConfig } from '@opentelemetry/instrumentation-http'; -import * as assert from 'assert'; -import * as sinon from 'sinon'; +import { deepStrictEqual, strictEqual, equal } from 'assert'; +import { stub } from 'sinon'; import { getNodeAutoInstrumentations } from '../src'; import { getResourceDetectorsFromEnv } from '../src/utils'; @@ -34,7 +34,7 @@ describe('utils', () => { ); }); - assert.deepStrictEqual( + deepStrictEqual( new Set(instrumentations.map(i => i.instrumentationName)), new Set(installedInstrumentations) ); @@ -54,7 +54,7 @@ describe('utils', () => { ) as any; const configHttp = instrumentation._config as HttpInstrumentationConfig; - assert.strictEqual( + strictEqual( configHttp.applyCustomAttributesOnSpan, applyCustomAttributesOnSpan ); @@ -70,7 +70,7 @@ describe('utils', () => { instr => instr.instrumentationName === '@opentelemetry/instrumentation-grpc' ); - assert.strictEqual(instrumentation, undefined); + strictEqual(instrumentation, undefined); }); it('should return only instrumentations enabled via OTEL_NODE_ENABLED_INSTRUMENTATIONS environment variable', () => { @@ -79,7 +79,7 @@ describe('utils', () => { try { const instrumentations = getNodeAutoInstrumentations(); - assert.deepStrictEqual( + deepStrictEqual( new Set(instrumentations.map(i => i.instrumentationName)), new Set([ '@opentelemetry/instrumentation-http', @@ -121,7 +121,7 @@ describe('utils', () => { ); for (const disabledInstrumentation of disabledInstrumentations) { - assert.strictEqual( + strictEqual( enabledInstrumentationNames.has(disabledInstrumentation), false ); @@ -137,7 +137,7 @@ describe('utils', () => { try { const instrumentations = getNodeAutoInstrumentations(); - assert.deepStrictEqual( + deepStrictEqual( new Set(instrumentations.map(i => i.instrumentationName)), new Set([ '@opentelemetry/instrumentation-http', @@ -151,7 +151,7 @@ describe('utils', () => { }); it('should show error for none existing instrumentation', () => { - const spy = sinon.stub(diag, 'error'); + const spy = stub(diag, 'error'); const name = '@opentelemetry/instrumentation-http2'; const instrumentations = getNodeAutoInstrumentations({ // @ts-expect-error verify that wrong name works @@ -162,9 +162,9 @@ describe('utils', () => { const instrumentation = instrumentations.find( instr => instr.instrumentationName === name ); - assert.strictEqual(instrumentation, undefined); + strictEqual(instrumentation, undefined); - assert.strictEqual( + strictEqual( spy.args[0][0], `Provided instrumentation name "${name}" not found` ); @@ -175,12 +175,12 @@ describe('utils', () => { describe('getResourceDetectorsFromEnv', () => { it('should return all resource detectors by default', () => { - assert.equal(getResourceDetectorsFromEnv().length, 16); + equal(getResourceDetectorsFromEnv().length, 16); }); it('should return all resource detectors when OTEL_NODE_RESOURCE_DETECTORS contains "all"', () => { process.env.OTEL_NODE_RESOURCE_DETECTORS = 'all'; - assert.equal(getResourceDetectorsFromEnv().length, 16); + equal(getResourceDetectorsFromEnv().length, 16); delete process.env.OTEL_NODE_RESOURCE_DETECTORS; }); @@ -190,10 +190,10 @@ describe('utils', () => { const resourceDetectors = getResourceDetectorsFromEnv(); - assert.equal(resourceDetectors.length, 3); - assert.equal(resourceDetectors[0].constructor.name, 'EnvDetectorSync'); - assert.equal(resourceDetectors[1].constructor.name, 'HostDetectorSync'); - assert.equal( + equal(resourceDetectors.length, 3); + equal(resourceDetectors[0].constructor.name, 'EnvDetectorSync'); + equal(resourceDetectors[1].constructor.name, 'HostDetectorSync'); + equal( resourceDetectors[2].constructor.name, 'ServiceInstanceIdDetectorSync' ); @@ -202,18 +202,18 @@ describe('utils', () => { }); it('should return no resource detectors when OTEL_NODE_RESOURCE_DETECTORS contains "none" or a typo', () => { - const spy = sinon.stub(diag, 'error'); + const spy = stub(diag, 'error'); process.env.OTEL_NODE_RESOURCE_DETECTORS = 'none'; - assert.equal(getResourceDetectorsFromEnv().length, 0); + equal(getResourceDetectorsFromEnv().length, 0); - assert.strictEqual(spy.callCount, 0); + strictEqual(spy.callCount, 0); process.env.OTEL_NODE_RESOURCE_DETECTORS = 'test'; - assert.equal(getResourceDetectorsFromEnv().length, 0); + equal(getResourceDetectorsFromEnv().length, 0); - assert.strictEqual( + strictEqual( spy.args[0][0], 'Invalid resource detector "test" specified in the environment variable OTEL_NODE_RESOURCE_DETECTORS' ); diff --git a/metapackages/auto-instrumentations-web/test/utils.test.ts b/metapackages/auto-instrumentations-web/test/utils.test.ts index 442ed166be..d58391d730 100644 --- a/metapackages/auto-instrumentations-web/test/utils.test.ts +++ b/metapackages/auto-instrumentations-web/test/utils.test.ts @@ -16,8 +16,8 @@ import { diag } from '@opentelemetry/api'; import { XMLHttpRequestInstrumentationConfig } from '@opentelemetry/instrumentation-xml-http-request'; -import * as assert from 'assert'; -import * as sinon from 'sinon'; +import { strictEqual } from 'assert'; +import { stub } from 'sinon'; import { getWebAutoInstrumentations } from '../src'; describe('utils', () => { @@ -30,9 +30,9 @@ describe('utils', () => { '@opentelemetry/instrumentation-user-interaction', '@opentelemetry/instrumentation-xml-http-request', ]; - assert.strictEqual(instrumentations.length, 4); + strictEqual(instrumentations.length, 4); for (let i = 0, j = instrumentations.length; i < j; i++) { - assert.strictEqual( + strictEqual( instrumentations[i].instrumentationName, expectedInstrumentations[i], `Instrumentation ${expectedInstrumentations[i]}, not loaded` @@ -56,7 +56,7 @@ describe('utils', () => { const config = instrumentation._config as XMLHttpRequestInstrumentationConfig; - assert.strictEqual(config.clearTimingResources, clearTimingResources); + strictEqual(config.clearTimingResources, clearTimingResources); }); it('should not return disabled instrumentation', () => { @@ -70,11 +70,11 @@ describe('utils', () => { instr.instrumentationName === '@opentelemetry/instrumentation-xml-http-request' ); - assert.strictEqual(instrumentation, undefined); + strictEqual(instrumentation, undefined); }); it('should show error for none existing instrumentation', () => { - const spy = sinon.stub(diag, 'error'); + const spy = stub(diag, 'error'); const name = '@opentelemetry/instrumentation-http2'; const instrumentations = getWebAutoInstrumentations({ // @ts-expect-error verify that wrong name works @@ -85,9 +85,9 @@ describe('utils', () => { const instrumentation = instrumentations.find( instr => instr.instrumentationName === name ); - assert.strictEqual(instrumentation, undefined); + strictEqual(instrumentation, undefined); - assert.strictEqual( + strictEqual( spy.args[0][0], `Provided instrumentation name "${name}" not found` ); diff --git a/packages/opentelemetry-host-metrics/src/index.ts b/packages/opentelemetry-host-metrics/src/index.ts index 4554d5dbfa..ca36700c23 100644 --- a/packages/opentelemetry-host-metrics/src/index.ts +++ b/packages/opentelemetry-host-metrics/src/index.ts @@ -14,6 +14,6 @@ * limitations under the License. */ -export * from './BaseMetrics'; -export * from './metric'; -export * from './types'; +export { MetricsCollectorConfig, BaseMetrics } from './BaseMetrics'; +export { HostMetrics } from './metric'; +export { CpuUsageData, ProcessCpuUsageData, MemoryData } from './types'; diff --git a/packages/opentelemetry-host-metrics/test/metric.test.ts b/packages/opentelemetry-host-metrics/test/metric.test.ts index f3844e57e9..0825d191c3 100644 --- a/packages/opentelemetry-host-metrics/test/metric.test.ts +++ b/packages/opentelemetry-host-metrics/test/metric.test.ts @@ -25,11 +25,12 @@ import { MetricData, MetricReader, } from '@opentelemetry/sdk-metrics'; -import * as assert from 'assert'; +import { strictEqual, ok } from 'assert'; import * as os from 'os'; -import * as sinon from 'sinon'; +import { SinonSandbox, createSandbox } from 'sinon'; import { ATTRIBUTE_NAMES } from '../src/enum'; import { HostMetrics } from '../src'; +import assert = require('assert'); const cpuJson = require('./mocks/cpu.json'); const processJson = require('./mocks/process.json'); @@ -104,7 +105,7 @@ describe('Host Metrics', () => { describe('constructor', () => { it('should create a new instance', () => { const hostMetrics = new HostMetrics(); - assert.ok(hostMetrics instanceof HostMetrics); + ok(hostMetrics instanceof HostMetrics); }); it('should create a new instance with default meter provider', () => { @@ -114,17 +115,17 @@ describe('Host Metrics', () => { meterProvider, }); hostMetrics.start(); - assert.ok(hostMetrics instanceof HostMetrics); + ok(hostMetrics instanceof HostMetrics); }); }); describe('metrics', () => { - let sandbox: sinon.SinonSandbox; + let sandbox: SinonSandbox; let hostMetrics: HostMetrics; let reader: TestMetricReader; beforeEach(async () => { - sandbox = sinon.createSandbox(); + sandbox = createSandbox(); sandbox.useFakeTimers(); sandbox.stub(os, 'freemem').callsFake(mockedOS.freemem); @@ -372,9 +373,9 @@ async function getRecords( ): Promise { const collectionResult = await metricReader.collect(); assert(collectionResult != null); - assert.strictEqual(collectionResult.resourceMetrics.scopeMetrics.length, 1); + strictEqual(collectionResult.resourceMetrics.scopeMetrics.length, 1); const scopeMetrics = collectionResult.resourceMetrics.scopeMetrics[0]; - assert.strictEqual( + strictEqual( scopeMetrics.scope.name, '@opentelemetry/host-metrics', 'default instrumentation scope name is the package name' @@ -382,7 +383,7 @@ async function getRecords( const metricDataList = scopeMetrics.metrics.filter( metric => metric.descriptor.name === name ); - assert.strictEqual(metricDataList.length, 1); + strictEqual(metricDataList.length, 1); return metricDataList[0]; } @@ -395,13 +396,13 @@ function ensureValue( const matches = (metric.dataPoints as DataPoint[]).filter(it => { return attrHash === hashAttributes(it.attributes); }); - assert.strictEqual(matches.length, 1); + strictEqual(matches.length, 1); const point = matches[0]; const aggValue = typeof point.value === 'number' ? point.value : (point.value as Histogram).sum; - assert.strictEqual(aggValue, value); + strictEqual(aggValue, value); } function hashAttributes(attributes: Attributes) { diff --git a/packages/opentelemetry-id-generator-aws-xray/src/index.ts b/packages/opentelemetry-id-generator-aws-xray/src/index.ts index e76b3a3593..f834004a9a 100644 --- a/packages/opentelemetry-id-generator-aws-xray/src/index.ts +++ b/packages/opentelemetry-id-generator-aws-xray/src/index.ts @@ -13,4 +13,4 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -export * from './platform'; +export { AWSXRayIdGenerator } from './platform'; diff --git a/packages/opentelemetry-id-generator-aws-xray/src/platform/browser/index.ts b/packages/opentelemetry-id-generator-aws-xray/src/platform/browser/index.ts index 2f90698a9e..85e49dcc8a 100644 --- a/packages/opentelemetry-id-generator-aws-xray/src/platform/browser/index.ts +++ b/packages/opentelemetry-id-generator-aws-xray/src/platform/browser/index.ts @@ -14,4 +14,4 @@ * limitations under the License. */ -export * from './AWSXRayIdGenerator'; +export { AWSXRayIdGenerator } from './AWSXRayIdGenerator'; diff --git a/packages/opentelemetry-id-generator-aws-xray/src/platform/index.ts b/packages/opentelemetry-id-generator-aws-xray/src/platform/index.ts index a12506ffa9..9850cae81a 100644 --- a/packages/opentelemetry-id-generator-aws-xray/src/platform/index.ts +++ b/packages/opentelemetry-id-generator-aws-xray/src/platform/index.ts @@ -13,4 +13,4 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -export * from './node'; +export { AWSXRayIdGenerator } from './node'; diff --git a/packages/opentelemetry-id-generator-aws-xray/src/platform/node/index.ts b/packages/opentelemetry-id-generator-aws-xray/src/platform/node/index.ts index 2f90698a9e..85e49dcc8a 100644 --- a/packages/opentelemetry-id-generator-aws-xray/src/platform/node/index.ts +++ b/packages/opentelemetry-id-generator-aws-xray/src/platform/node/index.ts @@ -14,4 +14,4 @@ * limitations under the License. */ -export * from './AWSXRayIdGenerator'; +export { AWSXRayIdGenerator } from './AWSXRayIdGenerator'; diff --git a/packages/opentelemetry-id-generator-aws-xray/test/AWSXrayIdGenerator.test.ts b/packages/opentelemetry-id-generator-aws-xray/test/AWSXrayIdGenerator.test.ts index f2398a69be..f47299d89f 100644 --- a/packages/opentelemetry-id-generator-aws-xray/test/AWSXrayIdGenerator.test.ts +++ b/packages/opentelemetry-id-generator-aws-xray/test/AWSXrayIdGenerator.test.ts @@ -13,8 +13,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import * as assert from 'assert'; -import * as sinon from 'sinon'; +import { ok, notStrictEqual } from 'assert'; +import { restore, stub } from 'sinon'; import { INVALID_SPANID, INVALID_TRACEID } from '@opentelemetry/api'; @@ -35,28 +35,28 @@ describe('AwsXRayTraceId', () => { }); afterEach(() => { - sinon.restore(); + restore(); }); it('returns 32 character hex strings', () => { - assert.ok(traceId1.match(/[a-f0-9]{32}/)); - assert.ok(!traceId1.match(/^0+$/)); + ok(traceId1.match(/[a-f0-9]{32}/)); + ok(!traceId1.match(/^0+$/)); }); it('returns different ids on each call', () => { - assert.notStrictEqual(traceId1, traceId2); + notStrictEqual(traceId1, traceId2); }); it('using current time to encode trace id', () => { - assert.ok(currTime >= prevTime); - assert.ok(currTime <= nextTime); + ok(currTime >= prevTime); + ok(currTime <= nextTime); }); it('should not be all zero', () => { - sinon.stub(Math, 'random').returns(0); + stub(Math, 'random').returns(0); const traceIdTemp = idGenerator.generateTraceId(); - assert.notStrictEqual(traceIdTemp, INVALID_TRACEID); + notStrictEqual(traceIdTemp, INVALID_TRACEID); }); }); @@ -69,22 +69,22 @@ describe('AwsXRaySpanId', () => { }); afterEach(() => { - sinon.restore(); + restore(); }); it('returns 16 character hex strings', () => { - assert.ok(spanId1.match(/[a-f0-9]{16}/)); - assert.ok(!spanId1.match(/^0+$/)); + ok(spanId1.match(/[a-f0-9]{16}/)); + ok(!spanId1.match(/^0+$/)); }); it('returns different ids on each call', () => { - assert.notStrictEqual(spanId1, spanId2); + notStrictEqual(spanId1, spanId2); }); it('should not be all zero', () => { - sinon.stub(Math, 'random').returns(0); + stub(Math, 'random').returns(0); const spanIdTemp = idGenerator.generateSpanId(); - assert.notStrictEqual(spanIdTemp, INVALID_SPANID); + notStrictEqual(spanIdTemp, INVALID_SPANID); }); }); diff --git a/packages/opentelemetry-redis-common/test/redis-common.test.ts b/packages/opentelemetry-redis-common/test/redis-common.test.ts index 874903fadd..6dc4486b08 100644 --- a/packages/opentelemetry-redis-common/test/redis-common.test.ts +++ b/packages/opentelemetry-redis-common/test/redis-common.test.ts @@ -14,7 +14,7 @@ * limitations under the License. */ import { defaultDbStatementSerializer } from '../src/index'; -import * as assert from 'assert'; +import { strictEqual } from 'assert'; describe('#defaultDbStatementSerializer()', () => { [ @@ -45,10 +45,7 @@ describe('#defaultDbStatementSerializer()', () => { }, ].forEach(({ cmdName, cmdArgs, expected }) => { it(`should serialize the correct number of arguments for ${cmdName}`, () => { - assert.strictEqual( - defaultDbStatementSerializer(cmdName, cmdArgs), - expected - ); + strictEqual(defaultDbStatementSerializer(cmdName, cmdArgs), expected); }); }); }); diff --git a/packages/opentelemetry-sql-common/test/sql-common.test.ts b/packages/opentelemetry-sql-common/test/sql-common.test.ts index 16bc2d228a..f51761212d 100644 --- a/packages/opentelemetry-sql-common/test/sql-common.test.ts +++ b/packages/opentelemetry-sql-common/test/sql-common.test.ts @@ -14,7 +14,7 @@ * limitations under the License. */ -import * as assert from 'assert'; +import { strictEqual } from 'assert'; import { trace, SpanContext, @@ -33,7 +33,7 @@ describe('addSqlCommenterComment', () => { }; const query = 'SELECT * from FOO;'; - assert.strictEqual( + strictEqual( addSqlCommenterComment(trace.wrapSpanContext(spanContext), query), "SELECT * from FOO; /*traceparent='00-d4cda95b652f4a1592b449d5929fda1b-6e0c63257de34c92-01'*/" ); @@ -47,16 +47,10 @@ describe('addSqlCommenterComment', () => { }); const blockComment = 'SELECT * from FOO; /* Test comment */'; - assert.strictEqual( - addSqlCommenterComment(span, blockComment), - blockComment - ); + strictEqual(addSqlCommenterComment(span, blockComment), blockComment); const dashedComment = 'SELECT * from FOO; -- Test comment'; - assert.strictEqual( - addSqlCommenterComment(span, dashedComment), - dashedComment - ); + strictEqual(addSqlCommenterComment(span, dashedComment), dashedComment); }); it('does not add a comment to an empty query', () => { @@ -66,7 +60,7 @@ describe('addSqlCommenterComment', () => { traceFlags: TraceFlags.SAMPLED, }; - assert.strictEqual( + strictEqual( addSqlCommenterComment(trace.wrapSpanContext(spanContext), ''), '' ); @@ -74,7 +68,7 @@ describe('addSqlCommenterComment', () => { it('does not add a comment if span context is invalid', () => { const query = 'SELECT * from FOO;'; - assert.strictEqual( + strictEqual( addSqlCommenterComment( trace.wrapSpanContext(INVALID_SPAN_CONTEXT), query @@ -92,7 +86,7 @@ describe('addSqlCommenterComment', () => { }; const query = 'SELECT * from FOO;'; - assert.strictEqual( + strictEqual( addSqlCommenterComment(trace.wrapSpanContext(spanContext), query), "SELECT * from FOO; /*traceparent='00-d4cda95b652f4a1592b449d5929fda1b-6e0c63257de34c92-01',tracestate='foo%3Dbar%2Cbaz%3Dqux'*/" ); @@ -107,7 +101,7 @@ describe('addSqlCommenterComment', () => { }; const query = 'SELECT * from FOO;'; - assert.strictEqual( + strictEqual( addSqlCommenterComment(trace.wrapSpanContext(spanContext), query), "SELECT * from FOO; /*traceparent='00-d4cda95b652f4a1592b449d5929fda1b-6e0c63257de34c92-01',tracestate='foo%3D%27bar%2Cbaz%3D%27qux%21%28%29%2A%27%2Chack%3D%27DROP%20TABLE'*/" ); diff --git a/packages/opentelemetry-test-utils/src/index.ts b/packages/opentelemetry-test-utils/src/index.ts index 8729ae6f46..6b9e70a4eb 100644 --- a/packages/opentelemetry-test-utils/src/index.ts +++ b/packages/opentelemetry-test-utils/src/index.ts @@ -14,7 +14,41 @@ * limitations under the License. */ -export * from './resource-assertions'; -export * from './test-fixtures'; -export * from './test-utils'; -export * from './instrumentations'; +export { + assertCloudResource, + assertContainerResource, + assertHostResource, + assertK8sResource, + assertTelemetrySDKResource, + assertServiceResource, + assertProcessResource, + assertEmptyResource, +} from './resource-assertions'; +export { + createTestNodeSdk, + OtlpSpanKind, + TestSpan, + TestCollector, + RunTestFixtureOptions, + runTestFixture, +} from './test-fixtures'; +export { + startDocker, + cleanUpDocker, + assertSpan, + assertPropagation, + TimedEvent, + getPackageVersion, + TestMetricReader, + initMeterProvider, +} from './test-utils'; +export { + mochaHooks, + getInstrumentation, + registerInstrumentationTesting, + getTestMemoryExporter, + setTestMemoryExporter, + getTestSpans, + resetMemoryExporter, + registerInstrumentationTestingProvider, +} from './instrumentations'; diff --git a/packages/opentelemetry-test-utils/src/instrumentations/index.ts b/packages/opentelemetry-test-utils/src/instrumentations/index.ts index b480032e8e..bc32b4c425 100644 --- a/packages/opentelemetry-test-utils/src/instrumentations/index.ts +++ b/packages/opentelemetry-test-utils/src/instrumentations/index.ts @@ -19,9 +19,17 @@ import { getInstrumentation } from './instrumentation-singleton'; import { registerInstrumentationTestingProvider } from './otel-default-provider'; import { resetMemoryExporter } from './otel-provider-api'; -export * from './instrumentation-singleton'; -export * from './otel-provider-api'; -export * from './otel-default-provider'; +export { + getInstrumentation, + registerInstrumentationTesting, +} from './instrumentation-singleton'; +export { + getTestMemoryExporter, + setTestMemoryExporter, + getTestSpans, + resetMemoryExporter, +} from './otel-provider-api'; +export { registerInstrumentationTestingProvider } from './otel-default-provider'; export const mochaHooks = { beforeAll(done: Function) { diff --git a/packages/opentelemetry-test-utils/src/resource-assertions.ts b/packages/opentelemetry-test-utils/src/resource-assertions.ts index 51b1419187..15ab34ced0 100644 --- a/packages/opentelemetry-test-utils/src/resource-assertions.ts +++ b/packages/opentelemetry-test-utils/src/resource-assertions.ts @@ -15,7 +15,7 @@ */ import { SDK_INFO } from '@opentelemetry/core'; -import * as assert from 'assert'; +import { strictEqual, ok } from 'assert'; import { Resource } from '@opentelemetry/resources'; import { SEMRESATTRS_CLOUD_ACCOUNT_ID, @@ -67,22 +67,22 @@ export const assertCloudResource = ( ) => { assertHasOneLabel('cloud', resource); if (validations.provider) - assert.strictEqual( + strictEqual( resource.attributes[SEMRESATTRS_CLOUD_PROVIDER], validations.provider ); if (validations.accountId) - assert.strictEqual( + strictEqual( resource.attributes[SEMRESATTRS_CLOUD_ACCOUNT_ID], validations.accountId ); if (validations.region) - assert.strictEqual( + strictEqual( resource.attributes[SEMRESATTRS_CLOUD_REGION], validations.region ); if (validations.zone) - assert.strictEqual( + strictEqual( resource.attributes[SEMRESATTRS_CLOUD_AVAILABILITY_ZONE], validations.zone ); @@ -105,22 +105,19 @@ export const assertContainerResource = ( ) => { assertHasOneLabel('container', resource); if (validations.name) - assert.strictEqual( + strictEqual( resource.attributes[SEMRESATTRS_CONTAINER_NAME], validations.name ); if (validations.id) - assert.strictEqual( - resource.attributes[SEMRESATTRS_CONTAINER_ID], - validations.id - ); + strictEqual(resource.attributes[SEMRESATTRS_CONTAINER_ID], validations.id); if (validations.imageName) - assert.strictEqual( + strictEqual( resource.attributes[SEMRESATTRS_CONTAINER_IMAGE_NAME], validations.imageName ); if (validations.imageTag) - assert.strictEqual( + strictEqual( resource.attributes[SEMRESATTRS_CONTAINER_IMAGE_TAG], validations.imageTag ); @@ -145,32 +142,26 @@ export const assertHostResource = ( ) => { assertHasOneLabel('host', resource); if (validations.id) - assert.strictEqual( - resource.attributes[SEMRESATTRS_HOST_ID], - validations.id - ); + strictEqual(resource.attributes[SEMRESATTRS_HOST_ID], validations.id); if (validations.name) - assert.strictEqual( - resource.attributes[SEMRESATTRS_HOST_NAME], - validations.name - ); + strictEqual(resource.attributes[SEMRESATTRS_HOST_NAME], validations.name); if (validations.hostType) - assert.strictEqual( + strictEqual( resource.attributes[SEMRESATTRS_HOST_TYPE], validations.hostType ); if (validations.imageName) - assert.strictEqual( + strictEqual( resource.attributes[SEMRESATTRS_HOST_IMAGE_NAME], validations.imageName ); if (validations.imageId) - assert.strictEqual( + strictEqual( resource.attributes[SEMRESATTRS_HOST_IMAGE_ID], validations.imageId ); if (validations.imageVersion) - assert.strictEqual( + strictEqual( resource.attributes[SEMRESATTRS_HOST_IMAGE_VERSION], validations.imageVersion ); @@ -193,22 +184,22 @@ export const assertK8sResource = ( ) => { assertHasOneLabel('k8s', resource); if (validations.clusterName) - assert.strictEqual( + strictEqual( resource.attributes[SEMRESATTRS_K8S_CLUSTER_NAME], validations.clusterName ); if (validations.namespaceName) - assert.strictEqual( + strictEqual( resource.attributes[SEMRESATTRS_K8S_NAMESPACE_NAME], validations.namespaceName ); if (validations.podName) - assert.strictEqual( + strictEqual( resource.attributes[SEMRESATTRS_K8S_POD_NAME], validations.podName ); if (validations.deploymentName) - assert.strictEqual( + strictEqual( resource.attributes[SEMRESATTRS_K8S_DEPLOYMENT_NAME], validations.deploymentName ); @@ -236,17 +227,17 @@ export const assertTelemetrySDKResource = ( validations = { ...defaults, ...validations }; if (validations.name) - assert.strictEqual( + strictEqual( resource.attributes[SEMRESATTRS_TELEMETRY_SDK_NAME], validations.name ); if (validations.language) - assert.strictEqual( + strictEqual( resource.attributes[SEMRESATTRS_TELEMETRY_SDK_LANGUAGE], validations.language ); if (validations.version) - assert.strictEqual( + strictEqual( resource.attributes[SEMRESATTRS_TELEMETRY_SDK_VERSION], validations.version ); @@ -267,21 +258,18 @@ export const assertServiceResource = ( version?: string; } ) => { - assert.strictEqual( - resource.attributes[SEMRESATTRS_SERVICE_NAME], - validations.name - ); - assert.strictEqual( + strictEqual(resource.attributes[SEMRESATTRS_SERVICE_NAME], validations.name); + strictEqual( resource.attributes[SEMRESATTRS_SERVICE_INSTANCE_ID], validations.instanceId ); if (validations.namespace) - assert.strictEqual( + strictEqual( resource.attributes[SEMRESATTRS_SERVICE_NAMESPACE], validations.namespace ); if (validations.version) - assert.strictEqual( + strictEqual( resource.attributes[SEMRESATTRS_SERVICE_VERSION], validations.version ); @@ -302,24 +290,21 @@ export const assertProcessResource = ( commandLine?: string; } ) => { - assert.strictEqual( - resource.attributes[SEMRESATTRS_PROCESS_PID], - validations.pid - ); + strictEqual(resource.attributes[SEMRESATTRS_PROCESS_PID], validations.pid); if (validations.name) { - assert.strictEqual( + strictEqual( resource.attributes[SEMRESATTRS_PROCESS_EXECUTABLE_NAME], validations.name ); } if (validations.command) { - assert.strictEqual( + strictEqual( resource.attributes[SEMRESATTRS_PROCESS_COMMAND], validations.command ); } if (validations.commandLine) { - assert.strictEqual( + strictEqual( resource.attributes[SEMRESATTRS_PROCESS_COMMAND_LINE], validations.commandLine ); @@ -332,7 +317,7 @@ export const assertProcessResource = ( * @param resource the Resource to validate */ export const assertEmptyResource = (resource: Resource) => { - assert.strictEqual(Object.keys(resource.attributes).length, 0); + strictEqual(Object.keys(resource.attributes).length, 0); }; /** @@ -352,7 +337,7 @@ const assertHasOneLabel = (prefix: string, resource: Resource): void => { const hasAttrs = Object.keys(resource.attributes).filter(k => knownAttrs.has(k) ); - assert.ok( + ok( hasAttrs.length > 0, 'Resource must have one of the following attributes: ' + Array.from(knownAttrs).join(', ') diff --git a/packages/opentelemetry-test-utils/src/test-utils.ts b/packages/opentelemetry-test-utils/src/test-utils.ts index 91efd64b03..b8fafb2631 100644 --- a/packages/opentelemetry-test-utils/src/test-utils.ts +++ b/packages/opentelemetry-test-utils/src/test-utils.ts @@ -14,7 +14,7 @@ * limitations under the License. */ -import * as childProcess from 'child_process'; +import { spawnSync } from 'child_process'; import { HrTime, Span, @@ -22,15 +22,15 @@ import { SpanKind, SpanStatus, } from '@opentelemetry/api'; -import * as assert from 'assert'; +import { strictEqual, ok, deepStrictEqual, notStrictEqual } from 'assert'; import { ReadableSpan } from '@opentelemetry/sdk-trace-base'; import { MetricReader, MeterProvider } from '@opentelemetry/sdk-metrics'; import { hrTimeToMilliseconds, hrTimeToMicroseconds, } from '@opentelemetry/core'; -import * as path from 'path'; -import * as fs from 'fs'; +import { join } from 'path'; +import { readFileSync } from 'fs'; import { InstrumentationBase } from '@opentelemetry/instrumentation'; const dockerRunCmds = { @@ -67,7 +67,7 @@ export function cleanUpDocker(db: keyof typeof dockerRunCmds) { function run(cmd: string) { try { - const proc = childProcess.spawnSync(cmd, { + const proc = spawnSync(cmd, { shell: true, }); const output = Buffer.concat( @@ -94,27 +94,25 @@ export const assertSpan = ( events: TimedEvent[], status: SpanStatus ) => { - assert.strictEqual(span.spanContext().traceId.length, 32); - assert.strictEqual(span.spanContext().spanId.length, 16); - assert.strictEqual(span.kind, kind); + strictEqual(span.spanContext().traceId.length, 32); + strictEqual(span.spanContext().spanId.length, 16); + strictEqual(span.kind, kind); - assert.ok(span.endTime); - assert.strictEqual(span.links.length, 0); + ok(span.endTime); + strictEqual(span.links.length, 0); - assert.ok( - hrTimeToMicroseconds(span.startTime) < hrTimeToMicroseconds(span.endTime) - ); - assert.ok(hrTimeToMilliseconds(span.endTime) > 0); + ok(hrTimeToMicroseconds(span.startTime) < hrTimeToMicroseconds(span.endTime)); + ok(hrTimeToMilliseconds(span.endTime) > 0); // attributes - assert.deepStrictEqual(span.attributes, attributes); + deepStrictEqual(span.attributes, attributes); // events - assert.deepStrictEqual(span.events, events); + deepStrictEqual(span.events, events); - assert.strictEqual(span.status.code, status.code); + strictEqual(span.status.code, status.code); if (status.message) { - assert.strictEqual(span.status.message, status.message); + strictEqual(span.status.message, status.message); } }; @@ -125,13 +123,10 @@ export const assertPropagation = ( ) => { const targetSpanContext = childSpan.spanContext(); const sourceSpanContext = parentSpan.spanContext(); - assert.strictEqual(targetSpanContext.traceId, sourceSpanContext.traceId); - assert.strictEqual(childSpan.parentSpanId, sourceSpanContext.spanId); - assert.strictEqual( - targetSpanContext.traceFlags, - sourceSpanContext.traceFlags - ); - assert.notStrictEqual(targetSpanContext.spanId, sourceSpanContext.spanId); + strictEqual(targetSpanContext.traceId, sourceSpanContext.traceId); + strictEqual(childSpan.parentSpanId, sourceSpanContext.spanId); + strictEqual(targetSpanContext.traceFlags, sourceSpanContext.traceFlags); + notStrictEqual(targetSpanContext.spanId, sourceSpanContext.spanId); }; /** @@ -157,7 +152,7 @@ export const getPackageVersion = (packageName: string) => { // versions. Prefix the search paths with the cwd to include the workspace // dir. const mainPath = require?.resolve(packageName, { - paths: [path.join(process.cwd(), 'node_modules')].concat( + paths: [join(process.cwd(), 'node_modules')].concat( require?.main?.paths || [] ), }); @@ -173,13 +168,13 @@ export const getPackageVersion = (packageName: string) => { // } // resolving `packagePath` to `/path/to/opentelemetry-js-contrib/node_modules/tedious/lib/tedious.js` const idx = mainPath.lastIndexOf('node_modules'); - const pjPath = path.join( + const pjPath = join( mainPath.slice(0, idx), 'node_modules', packageName, 'package.json' ); - return JSON.parse(fs.readFileSync(pjPath, 'utf8')).version; + return JSON.parse(readFileSync(pjPath, 'utf8')).version; }; export class TestMetricReader extends MetricReader { diff --git a/packages/winston-transport/test/openTelemetryTransport.test.ts b/packages/winston-transport/test/openTelemetryTransport.test.ts index 17516e5e51..6fb8746e81 100644 --- a/packages/winston-transport/test/openTelemetryTransport.test.ts +++ b/packages/winston-transport/test/openTelemetryTransport.test.ts @@ -20,8 +20,8 @@ import { SimpleLogRecordProcessor, InMemoryLogRecordExporter, } from '@opentelemetry/sdk-logs'; -import * as assert from 'assert'; -import * as sinon from 'sinon'; +import { strictEqual } from 'assert'; +import { spy, assert } from 'sinon'; import { OpenTelemetryTransportV3 } from '../src'; const loggerProvider = new LoggerProvider(); @@ -40,14 +40,14 @@ describe('OpenTelemetryTransportV3', () => { it('emit LogRecord', () => { const transport = new OpenTelemetryTransportV3(); - const writeSpy = sinon.spy(transport, 'emit'); + const writeSpy = spy(transport, 'emit'); transport.log({ message: kMessage }, () => {}); setImmediate(() => { - sinon.assert.calledOnce(writeSpy); + assert.calledOnce(writeSpy); }); const logRecords = memoryLogExporter.getFinishedLogRecords(); - assert.strictEqual(logRecords.length, 1); - assert.strictEqual(kMessage, logRecords[0].body, kMessage); + strictEqual(logRecords.length, 1); + strictEqual(kMessage, logRecords[0].body, kMessage); }); it('emit LogRecord with extra attibutes', () => { @@ -59,16 +59,10 @@ describe('OpenTelemetryTransportV3', () => { const parameters = Object.assign({ message: kMessage }, extraAttributes); transport.log(parameters, () => {}); const logRecords = memoryLogExporter.getFinishedLogRecords(); - assert.strictEqual(logRecords.length, 1); - assert.strictEqual(logRecords[0].body, kMessage); - assert.strictEqual( - logRecords[0].attributes['extraAttribute1'], - 'attributeValue1' - ); - assert.strictEqual( - logRecords[0].attributes['extraAttribute2'], - 'attributeValue2' - ); + strictEqual(logRecords.length, 1); + strictEqual(logRecords[0].body, kMessage); + strictEqual(logRecords[0].attributes['extraAttribute1'], 'attributeValue1'); + strictEqual(logRecords[0].attributes['extraAttribute2'], 'attributeValue2'); }); describe('emit logRecord severity', () => { @@ -83,14 +77,14 @@ describe('OpenTelemetryTransportV3', () => { transport.log({ message: kMessage, level: 'debug' }, callback); transport.log({ message: kMessage, level: 'silly' }, callback); const logRecords = memoryLogExporter.getFinishedLogRecords(); - assert.strictEqual(logRecords.length, 7); - assert.strictEqual(logRecords[0].severityNumber, SeverityNumber.ERROR); - assert.strictEqual(logRecords[1].severityNumber, SeverityNumber.WARN); - assert.strictEqual(logRecords[2].severityNumber, SeverityNumber.INFO); - assert.strictEqual(logRecords[3].severityNumber, SeverityNumber.DEBUG3); - assert.strictEqual(logRecords[4].severityNumber, SeverityNumber.DEBUG2); - assert.strictEqual(logRecords[5].severityNumber, SeverityNumber.DEBUG); - assert.strictEqual(logRecords[6].severityNumber, SeverityNumber.TRACE); + strictEqual(logRecords.length, 7); + strictEqual(logRecords[0].severityNumber, SeverityNumber.ERROR); + strictEqual(logRecords[1].severityNumber, SeverityNumber.WARN); + strictEqual(logRecords[2].severityNumber, SeverityNumber.INFO); + strictEqual(logRecords[3].severityNumber, SeverityNumber.DEBUG3); + strictEqual(logRecords[4].severityNumber, SeverityNumber.DEBUG2); + strictEqual(logRecords[5].severityNumber, SeverityNumber.DEBUG); + strictEqual(logRecords[6].severityNumber, SeverityNumber.TRACE); }); it('cli levels', () => { @@ -107,17 +101,17 @@ describe('OpenTelemetryTransportV3', () => { transport.log({ message: kMessage, level: 'input' }, callback); transport.log({ message: kMessage, level: 'silly' }, callback); const logRecords = memoryLogExporter.getFinishedLogRecords(); - assert.strictEqual(logRecords.length, 10); - assert.strictEqual(logRecords[0].severityNumber, SeverityNumber.ERROR); - assert.strictEqual(logRecords[1].severityNumber, SeverityNumber.WARN); - assert.strictEqual(logRecords[2].severityNumber, SeverityNumber.INFO3); - assert.strictEqual(logRecords[3].severityNumber, SeverityNumber.INFO2); - assert.strictEqual(logRecords[4].severityNumber, SeverityNumber.INFO); - assert.strictEqual(logRecords[5].severityNumber, SeverityNumber.DEBUG); - assert.strictEqual(logRecords[6].severityNumber, SeverityNumber.DEBUG2); - assert.strictEqual(logRecords[7].severityNumber, SeverityNumber.TRACE4); - assert.strictEqual(logRecords[8].severityNumber, SeverityNumber.TRACE2); - assert.strictEqual(logRecords[9].severityNumber, SeverityNumber.TRACE); + strictEqual(logRecords.length, 10); + strictEqual(logRecords[0].severityNumber, SeverityNumber.ERROR); + strictEqual(logRecords[1].severityNumber, SeverityNumber.WARN); + strictEqual(logRecords[2].severityNumber, SeverityNumber.INFO3); + strictEqual(logRecords[3].severityNumber, SeverityNumber.INFO2); + strictEqual(logRecords[4].severityNumber, SeverityNumber.INFO); + strictEqual(logRecords[5].severityNumber, SeverityNumber.DEBUG); + strictEqual(logRecords[6].severityNumber, SeverityNumber.DEBUG2); + strictEqual(logRecords[7].severityNumber, SeverityNumber.TRACE4); + strictEqual(logRecords[8].severityNumber, SeverityNumber.TRACE2); + strictEqual(logRecords[9].severityNumber, SeverityNumber.TRACE); }); it('syslog levels', () => { @@ -132,15 +126,15 @@ describe('OpenTelemetryTransportV3', () => { transport.log({ message: kMessage, level: 'info' }, callback); transport.log({ message: kMessage, level: 'debug' }, callback); const logRecords = memoryLogExporter.getFinishedLogRecords(); - assert.strictEqual(logRecords.length, 8); - assert.strictEqual(logRecords[0].severityNumber, SeverityNumber.FATAL3); - assert.strictEqual(logRecords[1].severityNumber, SeverityNumber.FATAL2); - assert.strictEqual(logRecords[2].severityNumber, SeverityNumber.FATAL); - assert.strictEqual(logRecords[3].severityNumber, SeverityNumber.ERROR); - assert.strictEqual(logRecords[4].severityNumber, SeverityNumber.WARN); - assert.strictEqual(logRecords[5].severityNumber, SeverityNumber.INFO2); - assert.strictEqual(logRecords[6].severityNumber, SeverityNumber.INFO); - assert.strictEqual(logRecords[7].severityNumber, SeverityNumber.DEBUG); + strictEqual(logRecords.length, 8); + strictEqual(logRecords[0].severityNumber, SeverityNumber.FATAL3); + strictEqual(logRecords[1].severityNumber, SeverityNumber.FATAL2); + strictEqual(logRecords[2].severityNumber, SeverityNumber.FATAL); + strictEqual(logRecords[3].severityNumber, SeverityNumber.ERROR); + strictEqual(logRecords[4].severityNumber, SeverityNumber.WARN); + strictEqual(logRecords[5].severityNumber, SeverityNumber.INFO2); + strictEqual(logRecords[6].severityNumber, SeverityNumber.INFO); + strictEqual(logRecords[7].severityNumber, SeverityNumber.DEBUG); }); }); }); diff --git a/plugins/node/instrumentation-amqplib/src/index.ts b/plugins/node/instrumentation-amqplib/src/index.ts index 1fe4b66e4d..5a7810eeab 100644 --- a/plugins/node/instrumentation-amqplib/src/index.ts +++ b/plugins/node/instrumentation-amqplib/src/index.ts @@ -13,5 +13,24 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -export * from './amqplib'; -export * from './types'; +export { AmqplibInstrumentation } from './amqplib'; +export { + PublishInfo, + PublishConfirmedInfo, + ConsumeInfo, + ConsumeEndInfo, + AmqplibPublishCustomAttributeFunction, + AmqplibPublishConfirmCustomAttributeFunction, + AmqplibConsumeCustomAttributeFunction, + AmqplibConsumeEndCustomAttributeFunction, + EndOperation, + AmqplibInstrumentationConfig, + DEFAULT_CONFIG, + AmqplibPublishOptions, + Message, + ConsumeMessage, + CommonMessageFields, + MessageFields, + ConsumeMessageFields, + MessageProperties, +} from './types'; diff --git a/plugins/node/instrumentation-amqplib/test/amqplib-promise.test.ts b/plugins/node/instrumentation-amqplib/test/amqplib-promise.test.ts index 6df63296a1..6dcddf2981 100644 --- a/plugins/node/instrumentation-amqplib/test/amqplib-promise.test.ts +++ b/plugins/node/instrumentation-amqplib/test/amqplib-promise.test.ts @@ -15,7 +15,7 @@ */ import 'mocha'; import { expect } from 'expect'; -import * as sinon from 'sinon'; +import { spy, SinonSpy } from 'sinon'; import * as lodash from 'lodash'; import { AmqplibInstrumentation, @@ -56,7 +56,6 @@ import { TEST_RABBITMQ_HOST, TEST_RABBITMQ_PORT, } from './config'; -import { SinonSpy } from 'sinon'; const msgPayload = 'payload from test'; const queueName = 'queue-name-from-unittest'; @@ -112,7 +111,7 @@ describe('amqplib instrumentation promise model', () => { describe('channel', () => { let channel: amqp.Channel & { [CHANNEL_CLOSED_IN_TEST]?: boolean }; beforeEach(async () => { - endHookSpy = sinon.spy(); + endHookSpy = spy(); instrumentation.setConfig({ consumeEndHook: endHookSpy, }); @@ -651,7 +650,7 @@ describe('amqplib instrumentation promise model', () => { [CHANNEL_CLOSED_IN_TEST]?: boolean; }; beforeEach(async () => { - endHookSpy = sinon.spy(); + endHookSpy = spy(); instrumentation.setConfig({ consumeEndHook: endHookSpy, }); @@ -1249,7 +1248,7 @@ describe('amqplib instrumentation promise model', () => { describe('channel using links config', () => { let channel: amqp.Channel & { [CHANNEL_CLOSED_IN_TEST]?: boolean }; beforeEach(async () => { - endHookSpy = sinon.spy(); + endHookSpy = spy(); instrumentation.setConfig({ consumeEndHook: endHookSpy, useLinksForConsume: true, @@ -1452,7 +1451,7 @@ describe('amqplib instrumentation promise model', () => { [CHANNEL_CLOSED_IN_TEST]?: boolean; }; beforeEach(async () => { - endHookSpy = sinon.spy(); + endHookSpy = spy(); instrumentation.setConfig({ consumeEndHook: endHookSpy, useLinksForConsume: true, diff --git a/plugins/node/instrumentation-cucumber/src/index.ts b/plugins/node/instrumentation-cucumber/src/index.ts index c26f998cff..3b62e8cba6 100644 --- a/plugins/node/instrumentation-cucumber/src/index.ts +++ b/plugins/node/instrumentation-cucumber/src/index.ts @@ -14,5 +14,5 @@ * limitations under the License. */ -export * from './instrumentation'; -export * from './types'; +export { CucumberInstrumentation } from './instrumentation'; +export { AttributeNames, CucumberInstrumentationConfig } from './types'; diff --git a/plugins/node/instrumentation-cucumber/test/cucumber.test.ts b/plugins/node/instrumentation-cucumber/test/cucumber.test.ts index deffbef31d..1ab8094719 100644 --- a/plugins/node/instrumentation-cucumber/test/cucumber.test.ts +++ b/plugins/node/instrumentation-cucumber/test/cucumber.test.ts @@ -31,9 +31,10 @@ import { import { Resource } from '@opentelemetry/resources'; import * as path from 'path'; -import * as assert from 'assert'; +import { equal, deepEqual } from 'assert'; import * as fs from 'fs'; import * as semver from 'semver'; +import assert = require('assert'); import { CucumberInstrumentation, AttributeNames } from '../src'; @@ -140,7 +141,7 @@ describe('CucumberInstrumentation', () => { const parent = spans.find(span => span.name.startsWith('Feature')); assert(parent, 'Expected a parent span'); - assert.deepEqual( + deepEqual( spans.map(span => span.name), [ 'Before', @@ -169,7 +170,7 @@ describe('CucumberInstrumentation', () => { const parent = spans.find(span => span.name.startsWith('Feature')); assert(parent, 'Expected a parent span'); - assert.deepEqual(parent.attributes, { + deepEqual(parent.attributes, { [SEMATTRS_CODE_FILEPATH]: 'test/current.feature', [SEMATTRS_CODE_LINENO]: 7, [SEMATTRS_CODE_FUNCTION]: 'Button pushing', @@ -192,7 +193,7 @@ describe('CucumberInstrumentation', () => { ); assert(parameterisedSpan); - assert.deepEqual(parameterisedSpan.attributes, { + deepEqual(parameterisedSpan.attributes, { [`${AttributeNames.STEP_ARGS}[0]`]: 'limit', }); }); @@ -204,7 +205,7 @@ describe('CucumberInstrumentation', () => { ); assert(tableSpan); - assert.deepEqual(tableSpan.attributes, { + deepEqual(tableSpan.attributes, { [`${AttributeNames.STEP_ARGS}[0]`]: JSON.stringify([ ['Cucumber', 'Cucumis sativus'], ['Burr Gherkin', 'Cucumis anguria'], @@ -236,9 +237,9 @@ describe('CucumberInstrumentation', () => { it('has a scenario for every example', () => { const spans = memoryExporter.getFinishedSpans(); const scenarios = spans.filter(span => span.name.startsWith('Feature')); - assert.equal(scenarios.length, 2); + equal(scenarios.length, 2); - assert.deepEqual( + deepEqual( scenarios.map(span => span.name), [ 'Feature: Examples. Scenario: passing button pushing', @@ -252,7 +253,7 @@ describe('CucumberInstrumentation', () => { const span = spans.find(span => span.name === 'Given(a failing step)'); assert(span); - assert.equal(span.status.code, SpanStatusCode.ERROR); + equal(span.status.code, SpanStatusCode.ERROR); }); }); @@ -279,9 +280,9 @@ describe('CucumberInstrumentation', () => { const attemptSpans = spans.filter(span => span.name.startsWith('Attempt') ); - assert.equal(attemptSpans.length, 3); + equal(attemptSpans.length, 3); - assert.deepEqual( + deepEqual( attemptSpans.map(span => span.parentSpanId), Array(3).fill(parent.spanContext().spanId) ); @@ -292,10 +293,10 @@ describe('CucumberInstrumentation', () => { const attemptSpans = spans.filter(span => span.name.startsWith('Attempt') ); - assert.equal(attemptSpans.length, 3); + equal(attemptSpans.length, 3); attemptSpans.forEach(attempt => { - assert.equal( + equal( spans.filter( span => span.parentSpanId === attempt.spanContext().spanId ).length, @@ -326,7 +327,7 @@ describe('CucumberInstrumentation', () => { const span = spans.find(span => span.name.startsWith('Given(a doc')); assert(span); - assert.deepEqual(span.attributes, { + deepEqual(span.attributes, { [`${AttributeNames.STEP_ARGS}[0]`]: 'The cucumber (Cucumis sativus) is a widely cultivated plant in the gourd family Cucurbitaceae.', }); @@ -355,7 +356,7 @@ describe('CucumberInstrumentation', () => { const span = spans.find(span => span.name.startsWith('Given(a doc')); assert(span); - assert.deepEqual(span.attributes, { + deepEqual(span.attributes, { [`${AttributeNames.STEP_ARGS}[0]`]: 'This is a background', }); }); @@ -375,9 +376,9 @@ describe('CucumberInstrumentation', () => { span.name.includes(`Fails ${hook}`) ); assert(parent); - assert.equal(parent.status.code, SpanStatusCode.ERROR); - assert.equal(parent.status.message, 'FAILED'); - assert.equal(parent.attributes[AttributeNames.STEP_STATUS], 'FAILED'); + equal(parent.status.code, SpanStatusCode.ERROR); + equal(parent.status.message, 'FAILED'); + equal(parent.attributes[AttributeNames.STEP_STATUS], 'FAILED'); const span = spans.find( span => @@ -386,7 +387,7 @@ describe('CucumberInstrumentation', () => { ); assert(span); - assert.equal(span.status.code, SpanStatusCode.ERROR); + equal(span.status.code, SpanStatusCode.ERROR); }); }); }); @@ -406,25 +407,19 @@ describe('CucumberInstrumentation', () => { const spans = memoryExporter.getFinishedSpans(); const parent = spans.find(span => span.name.includes('Feature')); assert(parent); - assert.equal(parent.status.code, SpanStatusCode.ERROR); - assert.equal(parent.status.message, 'UNDEFINED'); - assert.equal( - parent.attributes[AttributeNames.STEP_STATUS], - 'UNDEFINED' - ); + equal(parent.status.code, SpanStatusCode.ERROR); + equal(parent.status.message, 'UNDEFINED'); + equal(parent.attributes[AttributeNames.STEP_STATUS], 'UNDEFINED'); const span = spans.find(span => span.name.startsWith('an undefined')); assert(span); - assert.equal(span.status.code, SpanStatusCode.ERROR); - assert.equal(span.status.message, 'UNDEFINED'); - assert.equal(span.attributes[AttributeNames.STEP_STATUS], 'UNDEFINED'); + equal(span.status.code, SpanStatusCode.ERROR); + equal(span.status.message, 'UNDEFINED'); + equal(span.attributes[AttributeNames.STEP_STATUS], 'UNDEFINED'); const skippedSpan = spans.find(span => span.name === 'does nothing'); assert(skippedSpan); - assert.equal( - skippedSpan.attributes[AttributeNames.STEP_STATUS], - 'SKIPPED' - ); + equal(skippedSpan.attributes[AttributeNames.STEP_STATUS], 'SKIPPED'); }); }); @@ -442,18 +437,15 @@ describe('CucumberInstrumentation', () => { const spans = memoryExporter.getFinishedSpans(); const parent = spans.find(span => span.name.includes('Feature')); assert(parent); - assert.equal(parent.status.code, SpanStatusCode.ERROR); - assert.equal(parent.status.message, 'AMBIGUOUS'); - assert.equal( - parent.attributes[AttributeNames.STEP_STATUS], - 'AMBIGUOUS' - ); + equal(parent.status.code, SpanStatusCode.ERROR); + equal(parent.status.message, 'AMBIGUOUS'); + equal(parent.attributes[AttributeNames.STEP_STATUS], 'AMBIGUOUS'); const span = spans.find(span => span.name.startsWith('an ambiguous')); assert(span); - assert.equal(span.status.code, SpanStatusCode.ERROR); - assert.equal( + equal(span.status.code, SpanStatusCode.ERROR); + equal( span.status.message?.split('\n')[0], 'Multiple step definitions match:' ); @@ -472,11 +464,11 @@ describe('CucumberInstrumentation', () => { const spans = memoryExporter.getFinishedSpans(); const parent = spans.find(span => span.name.includes('Feature')); assert(parent); - assert.equal(parent.attributes[AttributeNames.STEP_STATUS], 'SKIPPED'); + equal(parent.attributes[AttributeNames.STEP_STATUS], 'SKIPPED'); const span = spans.find(span => span.name.startsWith('a skipped step')); assert(span); - assert.equal(span.attributes[AttributeNames.STEP_STATUS], 'SKIPPED'); + equal(span.attributes[AttributeNames.STEP_STATUS], 'SKIPPED'); }); it('adds skipped event to skipped steps in before hook', async () => { @@ -496,7 +488,7 @@ describe('CucumberInstrumentation', () => { )?.includes?.('@skip') ); assert(parent); - assert.equal(parent.attributes[AttributeNames.STEP_STATUS], 'SKIPPED'); + equal(parent.attributes[AttributeNames.STEP_STATUS], 'SKIPPED'); }); }); @@ -512,11 +504,11 @@ describe('CucumberInstrumentation', () => { const spans = memoryExporter.getFinishedSpans(); const parent = spans.find(span => span.name.includes('Feature')); assert(parent); - assert.equal(parent.attributes[AttributeNames.STEP_STATUS], 'PENDING'); + equal(parent.attributes[AttributeNames.STEP_STATUS], 'PENDING'); const span = spans.find(span => span.name.startsWith('a pending step')); assert(span); - assert.equal(span.attributes[AttributeNames.STEP_STATUS], 'PENDING'); + equal(span.attributes[AttributeNames.STEP_STATUS], 'PENDING'); }); it('adds pending event to pending steps in before hook', async () => { @@ -530,13 +522,13 @@ describe('CucumberInstrumentation', () => { const spans = memoryExporter.getFinishedSpans(); const parent = spans.find(span => span.name.includes('Feature')); assert(parent); - assert.equal(parent.attributes[AttributeNames.STEP_STATUS], 'PENDING'); + equal(parent.attributes[AttributeNames.STEP_STATUS], 'PENDING'); const span = spans.find(span => span.name.startsWith('I push the button') ); assert(span); - assert.equal(span.attributes[AttributeNames.STEP_STATUS], 'SKIPPED'); + equal(span.attributes[AttributeNames.STEP_STATUS], 'SKIPPED'); }); }); }); @@ -558,7 +550,7 @@ describe('CucumberInstrumentation', () => { Then no spans are recorded `); const spans = memoryExporter.getFinishedSpans(); - assert.equal(spans.length, 0); + equal(spans.length, 0); }); }); }); diff --git a/plugins/node/instrumentation-dataloader/src/index.ts b/plugins/node/instrumentation-dataloader/src/index.ts index a41cc4c8df..6725a11566 100644 --- a/plugins/node/instrumentation-dataloader/src/index.ts +++ b/plugins/node/instrumentation-dataloader/src/index.ts @@ -14,5 +14,5 @@ * limitations under the License. */ -export * from './types'; -export * from './instrumentation'; +export { DataloaderInstrumentationConfig } from './types'; +export { DataloaderInstrumentation } from './instrumentation'; diff --git a/plugins/node/instrumentation-fs/src/index.ts b/plugins/node/instrumentation-fs/src/index.ts index c26f998cff..674b014299 100644 --- a/plugins/node/instrumentation-fs/src/index.ts +++ b/plugins/node/instrumentation-fs/src/index.ts @@ -14,5 +14,15 @@ * limitations under the License. */ -export * from './instrumentation'; -export * from './types'; +export { FsInstrumentation } from './instrumentation'; +export { + FunctionPropertyNames, + FunctionProperties, + FunctionPropertyNamesTwoLevels, + Member, + FMember, + FPMember, + CreateHook, + EndHook, + FsInstrumentationConfig, +} from './types'; diff --git a/plugins/node/instrumentation-fs/src/instrumentation.ts b/plugins/node/instrumentation-fs/src/instrumentation.ts index cd2f8306dc..a7aca20a20 100644 --- a/plugins/node/instrumentation-fs/src/instrumentation.ts +++ b/plugins/node/instrumentation-fs/src/instrumentation.ts @@ -14,7 +14,13 @@ * limitations under the License. */ -import * as api from '@opentelemetry/api'; +import { + context, + trace, + Span, + SpanStatusCode, + Context, +} from '@opentelemetry/api'; import { isTracingSuppressed, suppressTracing } from '@opentelemetry/core'; import { InstrumentationBase, @@ -165,7 +171,7 @@ export class FsInstrumentation extends InstrumentationBasefunction (this: any, ...args: any[]) { - const activeContext = api.context.active(); + const activeContext = context.active(); if (!instrumentation._shouldTrace(activeContext)) { return original.apply(this, args); @@ -175,7 +181,7 @@ export class FsInstrumentation extends InstrumentationBasefunction (this: any, ...args: any[]) { - const activeContext = api.context.active(); + const activeContext = context.active(); if (!instrumentation._shouldTrace(activeContext)) { return original.apply(this, args); @@ -228,7 +234,7 @@ export class FsInstrumentation extends InstrumentationBase(functionName: 'exists', original: T): T { const instrumentation = this; const patchedFunction = function (this: any, ...args: any[]) { - const activeContext = api.context.active(); + const activeContext = context.active(); if (!instrumentation._shouldTrace(activeContext)) { return original.apply(this, args); @@ -309,7 +315,7 @@ export class FsInstrumentation extends InstrumentationBaseasync function (this: any, ...args: any[]) { - const activeContext = api.context.active(); + const activeContext = context.active(); if (!instrumentation._shouldTrace(activeContext)) { return original.apply(this, args); @@ -398,7 +401,7 @@ export class FsInstrumentation extends InstrumentationBasesinon.spy( - (fnName: FMember | FPMember, { args, span }) => { +const createHook = ( + spy((fnName: FMember | FPMember, { args, span }) => { // `ts-node`, which we use via `ts-mocha` also patches module loading and creates // a lot of unrelated spans. Filter those out. if (['readFileSync', 'existsSync'].includes(fnName as string)) { @@ -49,9 +50,9 @@ const createHook = sinon.spy( } } return true; - } + }) ); -const endHook = sinon.spy((fnName, { args, span }) => { +const endHook = spy((fnName, { args, span }) => { span.setAttribute(TEST_ATTRIBUTE, TEST_VALUE); }); const pluginConfig = { @@ -81,7 +82,7 @@ describe('fs instrumentation', () => { }, configurable: true, }); - assert.strictEqual(memoryExporter.getFinishedSpans().length, 0); + strictEqual(memoryExporter.getFinishedSpans().length, 0); }); afterEach(() => { @@ -107,10 +108,10 @@ describe('fs instrumentation', () => { const { objectToPatch, functionNameToPatch } = indexFs(fs, syncName); const rootSpan = tracer.startSpan(rootSpanName); - assert.strictEqual(memoryExporter.getFinishedSpans().length, 0); + strictEqual(memoryExporter.getFinishedSpans().length, 0); context.with(trace.setSpan(context.active(), rootSpan), () => { if (error) { - assert.throws( + throws( () => Reflect.apply( objectToPatch[functionNameToPatch], @@ -120,7 +121,7 @@ describe('fs instrumentation', () => { error ); } else { - assert.deepEqual( + deepEqual( Reflect.apply( objectToPatch[functionNameToPatch], objectToPatch, @@ -161,13 +162,13 @@ describe('fs instrumentation', () => { const { objectToPatch, functionNameToPatch } = indexFs(fs, name); const rootSpan = tracer.startSpan(rootSpanName); - assert.strictEqual(memoryExporter.getFinishedSpans().length, 0); + strictEqual(memoryExporter.getFinishedSpans().length, 0); context.with(trace.setSpan(context.active(), rootSpan), () => { (objectToPatch[functionNameToPatch] as Function)( ...args, (actualError: any | undefined, actualResult: any) => { - assert.strictEqual(trace.getSpan(context.active()), rootSpan); + strictEqual(trace.getSpan(context.active()), rootSpan); try { rootSpan.end(); @@ -193,8 +194,8 @@ describe('fs instrumentation', () => { } } } - assert.deepEqual(actualError, resultAsError); - assert.deepEqual(actualResult, result); + deepEqual(actualError, resultAsError); + deepEqual(actualResult, result); } assertSpans(memoryExporter.getFinishedSpans(), [ ...spans.map((s: any) => { @@ -232,7 +233,7 @@ describe('fs instrumentation', () => { it(`promises.${name} ${error ? 'error' : 'success'}`, async () => { const rootSpan = tracer.startSpan(rootSpanName); - assert.strictEqual(memoryExporter.getFinishedSpans().length, 0); + strictEqual(memoryExporter.getFinishedSpans().length, 0); await context .with(trace.setSpan(context.active(), rootSpan), () => { // eslint-disable-next-line node/no-unsupported-features/node-builtins @@ -244,9 +245,9 @@ describe('fs instrumentation', () => { }) .then((actualResult: any) => { if (error) { - assert.fail(`promises.${name} did not reject`); + fail(`promises.${name} did not reject`); } else { - assert.deepEqual(actualResult, result ?? resultAsError); + deepEqual(actualResult, result ?? resultAsError); } }) .catch((actualError: any) => { @@ -261,7 +262,7 @@ describe('fs instrumentation', () => { ); } else { actualError.message = `Did not expect promises.${name} to reject: ${actualError.message}`; - assert.fail(actualError); + fail(actualError); } }); rootSpan.end(); @@ -299,7 +300,7 @@ describe('fs instrumentation', () => { if (node14MissingFunctionNames.has(fname) && isNode14) continue; const { objectToPatch, functionNameToPatch } = indexFs(fs, fname); - assert.strictEqual( + strictEqual( typeof objectToPatch[functionNameToPatch], 'function', `fs.${fname} is not a function` @@ -311,7 +312,7 @@ describe('fs instrumentation', () => { fs.promises, fname ); - assert.strictEqual( + strictEqual( typeof objectToPatch[functionNameToPatch], 'function', `fs.promises.${fname} is not a function` diff --git a/plugins/node/instrumentation-fs/test/fsPromises.test.ts b/plugins/node/instrumentation-fs/test/fsPromises.test.ts index 0400f57ee7..89aa6edf66 100644 --- a/plugins/node/instrumentation-fs/test/fsPromises.test.ts +++ b/plugins/node/instrumentation-fs/test/fsPromises.test.ts @@ -20,18 +20,19 @@ import { InMemorySpanExporter, SimpleSpanProcessor, } from '@opentelemetry/sdk-trace-base'; -import * as assert from 'assert'; +import { fail, strictEqual, deepEqual } from 'assert'; import { FsInstrumentation } from '../src'; -import * as sinon from 'sinon'; +import { spy } from 'sinon'; import type * as FSPromisesType from 'fs/promises'; import tests, { FsFunction, TestCase, TestCreator } from './definitions'; import type { FPMember, EndHook } from '../src/types'; import { assertSpans, makeRootSpanName } from './utils'; +import assert = require('assert'); const TEST_ATTRIBUTE = 'test.attr'; const TEST_VALUE = 'test.attr.value'; -const endHook = sinon.spy((fnName, { args, span }) => { +const endHook = spy((fnName, { args, span }) => { span.setAttribute(TEST_ATTRIBUTE, TEST_VALUE); }); const pluginConfig = { @@ -54,7 +55,7 @@ describe('fs/promises instrumentation', () => { plugin.setTracerProvider(provider); plugin.enable(); fsPromises = require('fs/promises'); - assert.strictEqual(memoryExporter.getFinishedSpans().length, 0); + strictEqual(memoryExporter.getFinishedSpans().length, 0); }); afterEach(() => { @@ -74,7 +75,7 @@ describe('fs/promises instrumentation', () => { it(`promises.${name} ${error ? 'error' : 'success'}`, async () => { const rootSpan = tracer.startSpan(rootSpanName); - assert.strictEqual(memoryExporter.getFinishedSpans().length, 0); + strictEqual(memoryExporter.getFinishedSpans().length, 0); await context .with(trace.setSpan(context.active(), rootSpan), () => { // eslint-disable-next-line node/no-unsupported-features/node-builtins @@ -86,9 +87,9 @@ describe('fs/promises instrumentation', () => { }) .then((actualResult: any) => { if (error) { - assert.fail(`promises.${name} did not reject`); + fail(`promises.${name} did not reject`); } else { - assert.deepEqual(actualResult, result ?? resultAsError); + deepEqual(actualResult, result ?? resultAsError); } }) .catch((actualError: any) => { @@ -103,7 +104,7 @@ describe('fs/promises instrumentation', () => { ); } else { actualError.message = `Did not expect promises.${name} to reject: ${actualError.message}`; - assert.fail(actualError); + fail(actualError); } }); rootSpan.end(); diff --git a/plugins/node/instrumentation-fs/test/fsPromisesHooks.test.ts b/plugins/node/instrumentation-fs/test/fsPromisesHooks.test.ts index be3db71202..2d4c56ba28 100644 --- a/plugins/node/instrumentation-fs/test/fsPromisesHooks.test.ts +++ b/plugins/node/instrumentation-fs/test/fsPromisesHooks.test.ts @@ -18,18 +18,19 @@ import { InMemorySpanExporter, SimpleSpanProcessor, } from '@opentelemetry/sdk-trace-base'; -import * as assert from 'assert'; +import { strictEqual, ok } from 'assert'; import { FsInstrumentation } from '../src'; -import * as sinon from 'sinon'; +import { assert, spy } from 'sinon'; import type * as FSPromisesType from 'fs/promises'; import type { FsInstrumentationConfig } from '../src/types'; +import Assert = require('assert'); const createHookError = new Error('createHook failed'); -const createHook = sinon.spy((_functionName: string) => { +const createHook = spy((_functionName: string) => { throw createHookError; }); const endHookError = new Error('endHook failed'); -const endHook = sinon.spy((_functionName: string) => { +const endHook = spy((_functionName: string) => { throw endHookError; }); const pluginConfig = { @@ -42,7 +43,7 @@ const memoryExporter = new InMemorySpanExporter(); provider.addSpanProcessor(new SimpleSpanProcessor(memoryExporter)); const assertNotHookError = (err?: Error | null) => { - assert.ok( + ok( err && err.message !== createHookError.message && err.message !== endHookError.message, @@ -52,13 +53,13 @@ const assertNotHookError = (err?: Error | null) => { const assertSuccessfulCallHooks = (expectedFunctionName: string) => { const createHookCall = createHook.withArgs(expectedFunctionName); - sinon.assert.called(createHookCall); - sinon.assert.threw(createHookCall, createHookError); + assert.called(createHookCall); + assert.threw(createHookCall, createHookError); const endHookCall = endHook.withArgs(expectedFunctionName); - sinon.assert.called(endHookCall); - sinon.assert.threw(endHookCall, endHookError); - assert( + assert.called(endHookCall); + assert.threw(endHookCall, endHookError); + Assert( !(endHookCall.getCall(0).args as any)[1].error, 'Did not expect an error' ); @@ -66,13 +67,13 @@ const assertSuccessfulCallHooks = (expectedFunctionName: string) => { const assertFailingCallHooks = (expectedFunctionName: string) => { const createHookCall = createHook.withArgs(expectedFunctionName); - sinon.assert.called(createHookCall); - sinon.assert.threw(createHookCall, createHookError); + assert.called(createHookCall); + assert.threw(createHookCall, createHookError); const endHookCall = endHook.withArgs(expectedFunctionName); - sinon.assert.called(endHookCall); - sinon.assert.threw(endHookCall, endHookError); - assert((endHookCall.getCall(0).args as any)[1].error, 'Expected an error'); + assert.called(endHookCall); + assert.threw(endHookCall, endHookError); + Assert((endHookCall.getCall(0).args as any)[1].error, 'Expected an error'); }; // This should equal `fs.constants.R_OK`. @@ -91,7 +92,7 @@ describe('fs/promises instrumentation: hooks', () => { fsPromises = require('fs/promises'); createHook.resetHistory(); endHook.resetHistory(); - assert.strictEqual(memoryExporter.getFinishedSpans().length, 0); + strictEqual(memoryExporter.getFinishedSpans().length, 0); }); afterEach(() => { diff --git a/plugins/node/instrumentation-fs/test/parent.test.ts b/plugins/node/instrumentation-fs/test/parent.test.ts index 903e7e48e8..ae61b6c86c 100644 --- a/plugins/node/instrumentation-fs/test/parent.test.ts +++ b/plugins/node/instrumentation-fs/test/parent.test.ts @@ -19,7 +19,7 @@ import { SimpleSpanProcessor, } from '@opentelemetry/sdk-trace-base'; import { FsInstrumentation } from '../src'; -import * as assert from 'assert'; +import { deepEqual, strictEqual } from 'assert'; import type * as FSType from 'fs'; import type { FsInstrumentationConfig } from '../src/types'; import * as api from '@opentelemetry/api'; @@ -44,7 +44,7 @@ describe('fs instrumentation: requireParentSpan', () => { plugin.setConfig(pluginConfig); plugin.enable(); fs = require('fs'); - assert.strictEqual(memoryExporter.getFinishedSpans().length, 0); + strictEqual(memoryExporter.getFinishedSpans().length, 0); }; beforeEach(() => { @@ -75,10 +75,7 @@ describe('fs instrumentation: requireParentSpan', () => { }); }).then(() => endRootSpan()); - assert.deepEqual( - memoryExporter.getFinishedSpans().length, - expectedSpanCount() - ); + deepEqual(memoryExporter.getFinishedSpans().length, expectedSpanCount()); }); it(`${prefix} a span with the synchronous API`, () => { @@ -87,10 +84,7 @@ describe('fs instrumentation: requireParentSpan', () => { endRootSpan(); }); - assert.deepEqual( - memoryExporter.getFinishedSpans().length, - expectedSpanCount() - ); + deepEqual(memoryExporter.getFinishedSpans().length, expectedSpanCount()); }); it(`${prefix} a span with the promises API`, async () => { @@ -102,10 +96,7 @@ describe('fs instrumentation: requireParentSpan', () => { }); }); - assert.deepEqual( - memoryExporter.getFinishedSpans().length, - expectedSpanCount() - ); + deepEqual(memoryExporter.getFinishedSpans().length, expectedSpanCount()); }); }; diff --git a/plugins/node/instrumentation-fs/test/utils.ts b/plugins/node/instrumentation-fs/test/utils.ts index a3f2cd33f7..ae9d4fc19c 100644 --- a/plugins/node/instrumentation-fs/test/utils.ts +++ b/plugins/node/instrumentation-fs/test/utils.ts @@ -14,12 +14,13 @@ * limitations under the License. */ import { ReadableSpan } from '@opentelemetry/sdk-trace-base'; -import * as assert from 'assert'; +import { strictEqual } from 'assert'; import { SpanKind, SpanStatusCode } from '@opentelemetry/api'; import type { FMember } from '../src/types'; +import assert = require('assert'); export const assertSpans = (spans: ReadableSpan[], expected: any) => { - assert.strictEqual( + strictEqual( spans.length, expected.length, `Expected ${expected.length} spans, got ${spans.length}(${spans @@ -34,17 +35,10 @@ export const assertSpans = (spans: ReadableSpan[], expected: any) => { const assertSpan = (span: ReadableSpan, expected: any) => { assert(span); - assert.strictEqual(span.name, expected.name); - assert.strictEqual( - span.kind, - SpanKind.INTERNAL, - 'Expected to be of INTERNAL kind' - ); + strictEqual(span.name, expected.name); + strictEqual(span.kind, SpanKind.INTERNAL, 'Expected to be of INTERNAL kind'); if (expected.parentSpan) { - assert.strictEqual( - span.parentSpanId, - expected.parentSpan.spanContext().spanId - ); + strictEqual(span.parentSpanId, expected.parentSpan.spanContext().spanId); } if (expected.attributes) { assert.deepEqual(span.attributes, expected.attributes); @@ -54,14 +48,14 @@ const assertSpan = (span: ReadableSpan, expected: any) => { expected.error.test(span.status.message), `Expected "${span.status.message}" to match ${expected.error}` ); - assert.strictEqual(span.status.code, SpanStatusCode.ERROR); + strictEqual(span.status.code, SpanStatusCode.ERROR); } else { - assert.strictEqual( + strictEqual( span.status.code, SpanStatusCode.UNSET, 'Expected status to be unset' ); - assert.strictEqual(span.status.message, undefined); + strictEqual(span.status.message, undefined); } }; diff --git a/plugins/node/instrumentation-kafkajs/src/index.ts b/plugins/node/instrumentation-kafkajs/src/index.ts index 91c7641c95..9e08c6f08a 100644 --- a/plugins/node/instrumentation-kafkajs/src/index.ts +++ b/plugins/node/instrumentation-kafkajs/src/index.ts @@ -14,5 +14,11 @@ * limitations under the License. */ -export * from './instrumentation'; -export * from './types'; +export { KafkaJsInstrumentation } from './instrumentation'; +export { + KafkajsMessage, + MessageInfo, + KafkaProducerCustomAttributeFunction, + KafkaConsumerCustomAttributeFunction, + KafkaJsInstrumentationConfig, +} from './types'; diff --git a/plugins/node/instrumentation-kafkajs/test/kafkajs.test.ts b/plugins/node/instrumentation-kafkajs/test/kafkajs.test.ts index 258dddd7d0..8068604ad5 100644 --- a/plugins/node/instrumentation-kafkajs/test/kafkajs.test.ts +++ b/plugins/node/instrumentation-kafkajs/test/kafkajs.test.ts @@ -14,7 +14,7 @@ * limitations under the License. */ -import * as assert from 'assert'; +import { strictEqual, deepStrictEqual, notStrictEqual } from 'assert'; import { KafkaJsInstrumentation, KafkaJsInstrumentationConfig } from '../src'; import { ReadableSpan } from '@opentelemetry/sdk-trace-base'; import { @@ -116,11 +116,11 @@ describe('instrumentation-kafkajs', () => { kafkaMessage: Message, span: ReadableSpan ) => { - assert.strictEqual( + strictEqual( kafkaMessage.headers?.[DummyPropagation.TRACE_CONTEXT_KEY], span.spanContext().traceId ); - assert.strictEqual( + strictEqual( kafkaMessage.headers?.[DummyPropagation.SPAN_CONTEXT_KEY], span.spanContext().spanId ); @@ -154,22 +154,22 @@ describe('instrumentation-kafkajs', () => { ], }); - assert.strictEqual(res.length, 1); - assert.strictEqual(res[0].topicName, 'topic-name-1'); + strictEqual(res.length, 1); + strictEqual(res[0].topicName, 'topic-name-1'); const spans = getTestSpans(); - assert.strictEqual(spans.length, 1); + strictEqual(spans.length, 1); const span = spans[0]; - assert.strictEqual(span.kind, SpanKind.PRODUCER); - assert.strictEqual(span.name, 'topic-name-1'); - assert.strictEqual(span.status.code, SpanStatusCode.UNSET); - assert.strictEqual(span.attributes[SEMATTRS_MESSAGING_SYSTEM], 'kafka'); - assert.strictEqual( + strictEqual(span.kind, SpanKind.PRODUCER); + strictEqual(span.name, 'topic-name-1'); + strictEqual(span.status.code, SpanStatusCode.UNSET); + strictEqual(span.attributes[SEMATTRS_MESSAGING_SYSTEM], 'kafka'); + strictEqual( span.attributes[SEMATTRS_MESSAGING_DESTINATION], 'topic-name-1' ); - assert.strictEqual(messagesSent.length, 1); + strictEqual(messagesSent.length, 1); expectKafkaHeadersToMatchSpanContext( messagesSent[0], span as ReadableSpan @@ -190,11 +190,11 @@ describe('instrumentation-kafkajs', () => { }); const spans = getTestSpans(); - assert.strictEqual(spans.length, 2); - assert.strictEqual(spans[0].name, 'topic-name-1'); - assert.strictEqual(spans[1].name, 'topic-name-1'); + strictEqual(spans.length, 2); + strictEqual(spans[0].name, 'topic-name-1'); + strictEqual(spans[1].name, 'topic-name-1'); - assert.strictEqual(messagesSent.length, 2); + strictEqual(messagesSent.length, 2); expectKafkaHeadersToMatchSpanContext( messagesSent[0], spans[0] as ReadableSpan @@ -231,12 +231,12 @@ describe('instrumentation-kafkajs', () => { }); const spans = getTestSpans(); - assert.strictEqual(spans.length, 3); - assert.strictEqual(spans[0].name, 'topic-name-1'); - assert.strictEqual(spans[1].name, 'topic-name-1'); - assert.strictEqual(spans[2].name, 'topic-name-2'); + strictEqual(spans.length, 3); + strictEqual(spans[0].name, 'topic-name-1'); + strictEqual(spans[1].name, 'topic-name-1'); + strictEqual(spans[2].name, 'topic-name-2'); - assert.strictEqual(messagesSent.length, 3); + strictEqual(messagesSent.length, 3); for (let i = 0; i < 3; i++) { expectKafkaHeadersToMatchSpanContext( messagesSent[i], @@ -271,13 +271,10 @@ describe('instrumentation-kafkajs', () => { } catch (err) {} const spans = getTestSpans(); - assert.strictEqual(spans.length, 1); + strictEqual(spans.length, 1); const span = spans[0]; - assert.strictEqual(span.status.code, SpanStatusCode.ERROR); - assert.strictEqual( - span.status.message, - 'error thrown from kafka client send' - ); + strictEqual(span.status.code, SpanStatusCode.ERROR); + strictEqual(span.status.message, 'error thrown from kafka client send'); }); it('error in send with multiple messages create failed spans', async () => { @@ -296,10 +293,10 @@ describe('instrumentation-kafkajs', () => { } catch (err) {} const spans = getTestSpans(); - assert.strictEqual(spans.length, 2); + strictEqual(spans.length, 2); spans.forEach(span => { - assert.strictEqual(span.status.code, SpanStatusCode.ERROR); - assert.strictEqual( + strictEqual(span.status.code, SpanStatusCode.ERROR); + strictEqual( span.status.message, 'error thrown from kafka client send' ); @@ -334,10 +331,10 @@ describe('instrumentation-kafkajs', () => { } catch (err) {} const spans = getTestSpans(); - assert.strictEqual(spans.length, 3); + strictEqual(spans.length, 3); spans.forEach(span => { - assert.strictEqual(span.status.code, SpanStatusCode.ERROR); - assert.strictEqual( + strictEqual(span.status.code, SpanStatusCode.ERROR); + strictEqual( span.status.message, 'error thrown from kafka client send' ); @@ -374,9 +371,9 @@ describe('instrumentation-kafkajs', () => { }); const spans = getTestSpans(); - assert.strictEqual(spans.length, 1); + strictEqual(spans.length, 1); const span = spans[0]; - assert.strictEqual( + strictEqual( span.attributes['attribute-from-hook'], 'testing message content' ); @@ -409,9 +406,9 @@ describe('instrumentation-kafkajs', () => { }); const spans = getTestSpans(); - assert.strictEqual(spans.length, 1); + strictEqual(spans.length, 1); const span = spans[0]; - assert.strictEqual(span.status.code, SpanStatusCode.UNSET); + strictEqual(span.status.code, SpanStatusCode.UNSET); }); }); }); @@ -472,21 +469,18 @@ describe('instrumentation-kafkajs', () => { await runConfig?.eachMessage!(payload); const spans = getTestSpans(); - assert.strictEqual(spans.length, 1); + strictEqual(spans.length, 1); const span = spans[0]; - assert.strictEqual(span.name, 'topic-name-1'); - assert.strictEqual(span.parentSpanId, undefined); - assert.strictEqual(span.kind, SpanKind.CONSUMER); - assert.strictEqual(span.status.code, SpanStatusCode.UNSET); - assert.strictEqual(span.attributes[SEMATTRS_MESSAGING_SYSTEM], 'kafka'); - assert.strictEqual( + strictEqual(span.name, 'topic-name-1'); + strictEqual(span.parentSpanId, undefined); + strictEqual(span.kind, SpanKind.CONSUMER); + strictEqual(span.status.code, SpanStatusCode.UNSET); + strictEqual(span.attributes[SEMATTRS_MESSAGING_SYSTEM], 'kafka'); + strictEqual( span.attributes[SEMATTRS_MESSAGING_DESTINATION], 'topic-name-1' ); - assert.strictEqual( - span.attributes[SEMATTRS_MESSAGING_OPERATION], - 'process' - ); + strictEqual(span.attributes[SEMATTRS_MESSAGING_OPERATION], 'process'); }); it('consumer eachMessage with non promise return value', async () => { @@ -500,7 +494,7 @@ describe('instrumentation-kafkajs', () => { await runConfig?.eachMessage!(payload); const spans = getTestSpans(); - assert.strictEqual(spans.length, 1); + strictEqual(spans.length, 1); }); }); @@ -532,9 +526,9 @@ describe('instrumentation-kafkajs', () => { await runConfig?.eachMessage!(payload); const spans = getTestSpans(); - assert.strictEqual(spans.length, 1); + strictEqual(spans.length, 1); const span = spans[0]; - assert.strictEqual( + strictEqual( span.attributes['attribute key from hook'], payload.message.value?.toString() ); @@ -567,7 +561,7 @@ describe('instrumentation-kafkajs', () => { const spans = getTestSpans(); // span should still be created - assert.strictEqual(spans.length, 1); + strictEqual(spans.length, 1); }); }); @@ -597,13 +591,13 @@ describe('instrumentation-kafkajs', () => { } catch (e) { exception = e; } - assert.deepStrictEqual(exception, errorToThrow); + deepStrictEqual(exception, errorToThrow); const spans = getTestSpans(); - assert.strictEqual(spans.length, 1); + strictEqual(spans.length, 1); const span = spans[0]; - assert.strictEqual(span.status.code, SpanStatusCode.ERROR); - assert.strictEqual( + strictEqual(span.status.code, SpanStatusCode.ERROR); + strictEqual( span.status.message, 'error thrown from eachMessage callback' ); @@ -626,13 +620,13 @@ describe('instrumentation-kafkajs', () => { } catch (e) { exception = e; } - assert.deepStrictEqual(exception, objectToThrow); + deepStrictEqual(exception, objectToThrow); const spans = getTestSpans(); - assert.strictEqual(spans.length, 1); + strictEqual(spans.length, 1); const span = spans[0]; - assert.strictEqual(span.status.code, SpanStatusCode.ERROR); - assert.strictEqual(span.status.message, undefined); + strictEqual(span.status.code, SpanStatusCode.ERROR); + strictEqual(span.status.message, undefined); }); it('throwing non object', async () => { @@ -649,13 +643,13 @@ describe('instrumentation-kafkajs', () => { } catch (e) { exception = e; } - assert.strictEqual(exception, undefined); + strictEqual(exception, undefined); const spans = getTestSpans(); - assert.strictEqual(spans.length, 1); + strictEqual(spans.length, 1); const span = spans[0]; - assert.strictEqual(span.status.code, SpanStatusCode.ERROR); - assert.strictEqual(span.status.message, undefined); + strictEqual(span.status.code, SpanStatusCode.ERROR); + strictEqual(span.status.message, undefined); }); }); @@ -676,15 +670,12 @@ describe('instrumentation-kafkajs', () => { await runConfig?.eachBatch!(payload); const spans = getTestSpans(); - assert.strictEqual(spans.length, 3); + strictEqual(spans.length, 3); spans.forEach(span => { - assert.strictEqual(span.name, 'topic-name-1'); - assert.strictEqual(span.status.code, SpanStatusCode.UNSET); - assert.strictEqual( - span.attributes[SEMATTRS_MESSAGING_SYSTEM], - 'kafka' - ); - assert.strictEqual( + strictEqual(span.name, 'topic-name-1'); + strictEqual(span.status.code, SpanStatusCode.UNSET); + strictEqual(span.attributes[SEMATTRS_MESSAGING_SYSTEM], 'kafka'); + strictEqual( span.attributes[SEMATTRS_MESSAGING_DESTINATION], 'topic-name-1' ); @@ -692,26 +683,20 @@ describe('instrumentation-kafkajs', () => { const [recvSpan, msg1Span, msg2Span] = spans; - assert.strictEqual(recvSpan.parentSpanId, undefined); - assert.strictEqual( + strictEqual(recvSpan.parentSpanId, undefined); + strictEqual( recvSpan.attributes[SEMATTRS_MESSAGING_OPERATION], 'receive' ); - assert.strictEqual( - msg1Span.parentSpanId, - recvSpan.spanContext().spanId - ); - assert.strictEqual( + strictEqual(msg1Span.parentSpanId, recvSpan.spanContext().spanId); + strictEqual( msg1Span.attributes[SEMATTRS_MESSAGING_OPERATION], 'process' ); - assert.strictEqual( - msg2Span.parentSpanId, - recvSpan.spanContext().spanId - ); - assert.strictEqual( + strictEqual(msg2Span.parentSpanId, recvSpan.spanContext().spanId); + strictEqual( msg2Span.attributes[SEMATTRS_MESSAGING_OPERATION], 'process' ); @@ -730,7 +715,7 @@ describe('instrumentation-kafkajs', () => { await runConfig?.eachBatch!(payload); const spans = getTestSpans(); - assert.strictEqual(spans.length, 3); + strictEqual(spans.length, 3); }); }); }); @@ -770,7 +755,7 @@ describe('instrumentation-kafkajs', () => { } ); - assert.strictEqual(messagesSent.length, 1); + strictEqual(messagesSent.length, 1); const consumerPayload: EachMessagePayload = { topic: 'topic-name-1', partition: 0, @@ -788,18 +773,15 @@ describe('instrumentation-kafkajs', () => { await runConfig?.eachMessage!(consumerPayload); const spans = getTestSpans(); - assert.strictEqual(spans.length, 2); + strictEqual(spans.length, 2); const [producerSpan, consumerSpan] = spans; - assert.strictEqual( + strictEqual( consumerSpan.spanContext().traceId, producerSpan.spanContext().traceId ); - assert.strictEqual( - consumerSpan.parentSpanId, - producerSpan.spanContext().spanId - ); - assert.strictEqual(callbackBaggage!.getAllEntries().length, 1); - assert.strictEqual(callbackBaggage!.getEntry('foo')?.value, 'bar'); + strictEqual(consumerSpan.parentSpanId, producerSpan.spanContext().spanId); + strictEqual(callbackBaggage!.getAllEntries().length, 1); + strictEqual(callbackBaggage!.getEntry('foo')?.value, 'bar'); }); it('context injected in producer is extracted as links in batch consumer', async () => { @@ -816,7 +798,7 @@ describe('instrumentation-kafkajs', () => { ], }); - assert.strictEqual(messagesSent.length, 1); + strictEqual(messagesSent.length, 1); const consumerPayload: EachBatchPayload = { batch: { topic: 'topic-name-1', @@ -838,31 +820,31 @@ describe('instrumentation-kafkajs', () => { await runConfig?.eachBatch!(consumerPayload); const spans = getTestSpans(); - assert.strictEqual(spans.length, 3); + strictEqual(spans.length, 3); const [producerSpan, receivingSpan, processingSpan] = spans; // processing span should be the child of receiving span and link to relevant producer - assert.strictEqual( + strictEqual( processingSpan.spanContext().traceId, receivingSpan.spanContext().traceId ); - assert.strictEqual( + strictEqual( processingSpan.parentSpanId, receivingSpan.spanContext().spanId ); - assert.strictEqual(processingSpan.links.length, 1); - assert.strictEqual( + strictEqual(processingSpan.links.length, 1); + strictEqual( processingSpan.links[0].context.traceId, producerSpan.spanContext().traceId ); - assert.strictEqual( + strictEqual( processingSpan.links[0].context.spanId, producerSpan.spanContext().spanId ); // receiving span should start a new trace - assert.strictEqual(receivingSpan.parentSpanId, undefined); - assert.notStrictEqual( + strictEqual(receivingSpan.parentSpanId, undefined); + notStrictEqual( receivingSpan.spanContext().traceId, producerSpan.spanContext().traceId ); @@ -871,7 +853,7 @@ describe('instrumentation-kafkajs', () => { describe('bufferTextMapGetter', () => { it('is possible to retrieve keys case insensitively', () => { - assert.strictEqual( + strictEqual( bufferTextMapGetter.get( { 'X-B3-Trace-Id': '123', diff --git a/plugins/node/instrumentation-lru-memoizer/src/index.ts b/plugins/node/instrumentation-lru-memoizer/src/index.ts index 24c76056a1..02c90b5f15 100644 --- a/plugins/node/instrumentation-lru-memoizer/src/index.ts +++ b/plugins/node/instrumentation-lru-memoizer/src/index.ts @@ -14,4 +14,4 @@ * limitations under the License. */ -export * from './instrumentation'; +export { LruMemoizerInstrumentation } from './instrumentation'; diff --git a/plugins/node/instrumentation-mongoose/src/index.ts b/plugins/node/instrumentation-mongoose/src/index.ts index 5a9c213a2b..53d1b8702c 100644 --- a/plugins/node/instrumentation-mongoose/src/index.ts +++ b/plugins/node/instrumentation-mongoose/src/index.ts @@ -13,5 +13,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -export * from './mongoose'; -export * from './types'; +export { MongooseInstrumentation, _STORED_PARENT_SPAN } from './mongoose'; +export { + SerializerPayload, + DbStatementSerializer, + ResponseInfo, + MongooseResponseCustomAttributesFunction, + MongooseInstrumentationConfig, +} from './types'; diff --git a/plugins/node/instrumentation-mongoose/test/user.ts b/plugins/node/instrumentation-mongoose/test/user.ts index 0e8eff02eb..70bdf5bec5 100644 --- a/plugins/node/instrumentation-mongoose/test/user.ts +++ b/plugins/node/instrumentation-mongoose/test/user.ts @@ -14,7 +14,7 @@ * limitations under the License. */ import { Schema, Document } from 'mongoose'; -import * as mongoose from 'mongoose'; +import { model } from 'mongoose'; export interface IUser extends Document { email: string; @@ -31,7 +31,7 @@ const UserSchema: Schema = new Schema({ }); // Export the model and return your IUser interface -const User = mongoose.model('User', UserSchema); +const User = model('User', UserSchema); export default User; export const loadUsers = async () => { diff --git a/plugins/node/instrumentation-runtime-node/src/index.ts b/plugins/node/instrumentation-runtime-node/src/index.ts index c26f998cff..779fc0e918 100644 --- a/plugins/node/instrumentation-runtime-node/src/index.ts +++ b/plugins/node/instrumentation-runtime-node/src/index.ts @@ -14,5 +14,5 @@ * limitations under the License. */ -export * from './instrumentation'; -export * from './types'; +export { RuntimeNodeInstrumentation } from './instrumentation'; +export { RuntimeNodeInstrumentationConfig } from './types'; diff --git a/plugins/node/instrumentation-runtime-node/test/event_loop_utilization.test.ts b/plugins/node/instrumentation-runtime-node/test/event_loop_utilization.test.ts index ccc3a04ff7..e184d72219 100644 --- a/plugins/node/instrumentation-runtime-node/test/event_loop_utilization.test.ts +++ b/plugins/node/instrumentation-runtime-node/test/event_loop_utilization.test.ts @@ -20,7 +20,7 @@ import { } from '@opentelemetry/sdk-metrics'; import { RuntimeNodeInstrumentation } from '../src'; -import * as assert from 'assert'; +import { deepEqual, strictEqual } from 'assert'; const MEASUREMENT_INTERVAL = 10; @@ -57,9 +57,9 @@ describe('nodejs.event_loop.utilization', function () { const { resourceMetrics, errors } = await metricReader.collect(); // assert - assert.deepEqual(errors, []); + deepEqual(errors, []); const scopeMetrics = resourceMetrics.scopeMetrics; - assert.strictEqual(scopeMetrics.length, 0); + strictEqual(scopeMetrics.length, 0); }); it('should not record result when collecting immediately with custom config', async function () { @@ -68,20 +68,14 @@ describe('nodejs.event_loop.utilization', function () { }); instrumentation.setMeterProvider(meterProvider); - assert.deepEqual( - (await metricReader.collect()).resourceMetrics.scopeMetrics, - [] - ); + deepEqual((await metricReader.collect()).resourceMetrics.scopeMetrics, []); }); it('should not record result when collecting immediately with default config', async function () { const instrumentation = new RuntimeNodeInstrumentation(); instrumentation.setMeterProvider(meterProvider); - assert.deepEqual( - (await metricReader.collect()).resourceMetrics.scopeMetrics, - [] - ); + deepEqual((await metricReader.collect()).resourceMetrics.scopeMetrics, []); }); it('should write event loop utilization metrics after eventLoopUtilizationMeasurementInterval', async function () { @@ -96,49 +90,38 @@ describe('nodejs.event_loop.utilization', function () { const { resourceMetrics, errors } = await metricReader.collect(); // assert - assert.deepEqual( + deepEqual( errors, [], 'expected no errors from the callback during collection' ); const scopeMetrics = resourceMetrics.scopeMetrics; - assert.strictEqual( + strictEqual( scopeMetrics.length, 1, 'expected one scope (one meter created by instrumentation)' ); const metrics = scopeMetrics[0].metrics; - assert.strictEqual( + strictEqual( metrics.length, 1, 'expected one metric (one metric created by instrumentation)' ); - assert.strictEqual( + strictEqual( metrics[0].dataPointType, DataPointType.GAUGE, 'expected gauge' ); - assert.strictEqual( + strictEqual( metrics[0].descriptor.name, 'nodejs.event_loop.utilization', 'descriptor.name' ); - assert.strictEqual( - metrics[0].descriptor.description, - 'Event loop utilization' - ); - assert.strictEqual( - metrics[0].descriptor.unit, - '1', - 'expected default unit' - ); - assert.strictEqual( - metrics[0].dataPoints.length, - 1, - 'expected one data point' - ); + strictEqual(metrics[0].descriptor.description, 'Event loop utilization'); + strictEqual(metrics[0].descriptor.unit, '1', 'expected default unit'); + strictEqual(metrics[0].dataPoints.length, 1, 'expected one data point'); const val = metrics[0].dataPoints[0].value; - assert.strictEqual(val > 0, true, `val (${val}) > 0`); - assert.strictEqual(val <= 1, true, `val (${val}) <= 1`); + strictEqual(val > 0, true, `val (${val}) > 0`); + strictEqual(val <= 1, true, `val (${val}) <= 1`); }); }); diff --git a/plugins/node/instrumentation-socket.io/src/index.ts b/plugins/node/instrumentation-socket.io/src/index.ts index c32b37405f..348ffb704e 100644 --- a/plugins/node/instrumentation-socket.io/src/index.ts +++ b/plugins/node/instrumentation-socket.io/src/index.ts @@ -13,6 +13,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -export * from './socket.io'; -export * from './types'; -export * from './AttributeNames'; +export { SocketIoInstrumentation } from './socket.io'; +export { + defaultSocketIoPath, + SocketIoHookInfo, + SocketIoHookFunction, + SocketIoInstrumentationConfig, +} from './types'; +export { SocketIoInstrumentationAttributes } from './AttributeNames'; diff --git a/plugins/node/instrumentation-socket.io/test/utils.ts b/plugins/node/instrumentation-socket.io/test/utils.ts index 1561a5ec4e..a9c88f03e8 100644 --- a/plugins/node/instrumentation-socket.io/test/utils.ts +++ b/plugins/node/instrumentation-socket.io/test/utils.ts @@ -25,12 +25,12 @@ import * as expect from 'expect'; import { Server } from 'socket.io'; import * as socketIo from 'socket.io'; import * as ioClient from 'socket.io-client'; -import * as path from 'path'; +import { join, dirname } from 'path'; export const io = ioClient.io || ioClient; const packageJsonPath = (packageName: string) => - path.join(path.dirname(require.resolve(packageName)), '..', 'package.json'); + join(dirname(require.resolve(packageName)), '..', 'package.json'); const version = require(packageJsonPath('socket.io')).version; assert.equal(typeof version, 'string'); diff --git a/plugins/node/instrumentation-tedious/src/index.ts b/plugins/node/instrumentation-tedious/src/index.ts index c26f998cff..9e3b39d790 100644 --- a/plugins/node/instrumentation-tedious/src/index.ts +++ b/plugins/node/instrumentation-tedious/src/index.ts @@ -14,5 +14,5 @@ * limitations under the License. */ -export * from './instrumentation'; -export * from './types'; +export { TediousInstrumentation } from './instrumentation'; +export { TediousInstrumentationConfig } from './types'; diff --git a/plugins/node/instrumentation-tedious/test/instrumentation.test.ts b/plugins/node/instrumentation-tedious/test/instrumentation.test.ts index f9419cc4c6..7ebbe6bd63 100644 --- a/plugins/node/instrumentation-tedious/test/instrumentation.test.ts +++ b/plugins/node/instrumentation-tedious/test/instrumentation.test.ts @@ -34,11 +34,12 @@ import { ReadableSpan, SimpleSpanProcessor, } from '@opentelemetry/sdk-trace-base'; -import * as assert from 'assert'; +import { strictEqual, deepStrictEqual } from 'assert'; import { TediousInstrumentation } from '../src'; import makeApi from './api'; import type { Connection } from 'tedious'; import * as semver from 'semver'; +import assert = require('assert'); const port = Number(process.env.MSSQL_PORT) || 1433; const database = process.env.MSSQL_DATABASE || 'master'; @@ -149,7 +150,7 @@ describe('tedious', () => { const queryString = "SELECT 42, 'hello world'"; const PARENT_NAME = 'parentSpan'; const parentSpan = provider.getTracer('default').startSpan(PARENT_NAME); - assert.deepStrictEqual( + deepStrictEqual( await context.with(trace.setSpan(context.active(), parentSpan), () => tedious.query(connection, queryString) ), @@ -158,7 +159,7 @@ describe('tedious', () => { parentSpan.end(); const spans = memoryExporter.getFinishedSpans(); - assert.strictEqual(spans.length, 2, 'Received incorrect number of spans'); + strictEqual(spans.length, 2, 'Received incorrect number of spans'); assertSpan(spans[0], { name: 'execSql master', @@ -166,7 +167,7 @@ describe('tedious', () => { parentSpan, }); - assert.strictEqual(spans[1].name, PARENT_NAME); + strictEqual(spans[1].name, PARENT_NAME); }); it('should catch errors', async () => { @@ -177,7 +178,7 @@ describe('tedious', () => { /incorrect syntax/i ); const spans = memoryExporter.getFinishedSpans(); - assert.strictEqual(spans.length, 1, 'Received incorrect number of spans'); + strictEqual(spans.length, 1, 'Received incorrect number of spans'); assertSpan(spans[0], { name: 'execSql master', @@ -194,12 +195,9 @@ describe('tedious', () => { of one span. */ const queryString = 'SELECT 42; SELECT 42; SELECT 42;'; - assert.deepStrictEqual( - await tedious.query(connection, queryString), - [42, 42, 42] - ); + deepStrictEqual(await tedious.query(connection, queryString), [42, 42, 42]); const spans = memoryExporter.getFinishedSpans(); - assert.strictEqual(spans.length, 1, 'Received incorrect number of spans'); + strictEqual(spans.length, 1, 'Received incorrect number of spans'); assertSpan(spans[0], { name: 'execSql master', @@ -211,12 +209,12 @@ describe('tedious', () => { it('should instrument execSqlBatch calls containing multiple queries', async () => { const queryString = 'SELECT 42; SELECT 42; SELECT 42;'; - assert.deepStrictEqual( + deepStrictEqual( await tedious.query(connection, queryString, 'execSqlBatch'), [42, 42, 42] ); const spans = memoryExporter.getFinishedSpans(); - assert.strictEqual(spans.length, 1, 'Received incorrect number of spans'); + strictEqual(spans.length, 1, 'Received incorrect number of spans'); assertSpan(spans[0], { name: 'execSqlBatch master', @@ -227,12 +225,12 @@ describe('tedious', () => { }); it('should instrument stored procedure calls', async () => { - assert.strictEqual(await tedious.storedProcedure.create(connection), true); - assert.deepStrictEqual(await tedious.storedProcedure.call(connection), { + strictEqual(await tedious.storedProcedure.create(connection), true); + deepStrictEqual(await tedious.storedProcedure.call(connection), { outputCount: 11, }); const spans = memoryExporter.getFinishedSpans(); - assert.strictEqual(spans.length, 2, 'Received incorrect number of spans'); + strictEqual(spans.length, 2, 'Received incorrect number of spans'); assertSpan(spans[0], { name: 'execSql master', @@ -245,14 +243,11 @@ describe('tedious', () => { }); it('should instrument prepared statement calls', async () => { - assert.strictEqual(await tedious.preparedSQL.createTable(connection), true); + strictEqual(await tedious.preparedSQL.createTable(connection), true); const request = await tedious.preparedSQL.prepare(connection); - assert.strictEqual( - await tedious.preparedSQL.execute(connection, request), - true - ); + strictEqual(await tedious.preparedSQL.execute(connection, request), true); const spans = memoryExporter.getFinishedSpans(); - assert.strictEqual(spans.length, 3, 'Received incorrect number of spans'); + strictEqual(spans.length, 3, 'Received incorrect number of spans'); assertSpan(spans[0], { name: 'execSql master', @@ -277,13 +272,13 @@ describe('tedious', () => { }; await tedious.query(connection, sql.create); await tedious.query(connection, sql.use); - assert.deepStrictEqual(await tedious.query(connection, sql.select), [ + deepStrictEqual(await tedious.query(connection, sql.select), [ 42, 'hello world', ]); const spans = memoryExporter.getFinishedSpans(); - assert.strictEqual(spans.length, 3, 'Received incorrect number of spans'); + strictEqual(spans.length, 3, 'Received incorrect number of spans'); assertSpan(spans[0], { name: 'execSql master', @@ -301,10 +296,10 @@ describe('tedious', () => { }); it('should instrument BulkLoads', async () => { - assert.strictEqual(await tedious.bulkLoad.createTable(connection), true); - assert.strictEqual(await tedious.bulkLoad.execute(connection), 2); + strictEqual(await tedious.bulkLoad.createTable(connection), true); + strictEqual(await tedious.bulkLoad.execute(connection), 2); const spans = memoryExporter.getFinishedSpans(); - assert.strictEqual(spans.length, 3, 'Received incorrect number of spans'); + strictEqual(spans.length, 3, 'Received incorrect number of spans'); assertSpan(spans[0], { name: 'execSql master', @@ -353,33 +348,27 @@ const assertRejects = ( function assertSpan(span: ReadableSpan, expected: any) { assert(span); - assert.strictEqual(span.name, expected.name); - assert.strictEqual(span.kind, SpanKind.CLIENT); - assert.strictEqual(span.attributes[SEMATTRS_DB_SYSTEM], DBSYSTEMVALUES_MSSQL); - assert.strictEqual( - span.attributes[SEMATTRS_DB_NAME], - expected.database ?? database - ); - assert.strictEqual(span.attributes[SEMATTRS_NET_PEER_PORT], port); - assert.strictEqual(span.attributes[SEMATTRS_NET_PEER_NAME], host); - assert.strictEqual(span.attributes[SEMATTRS_DB_USER], user); - assert.strictEqual( + strictEqual(span.name, expected.name); + strictEqual(span.kind, SpanKind.CLIENT); + strictEqual(span.attributes[SEMATTRS_DB_SYSTEM], DBSYSTEMVALUES_MSSQL); + strictEqual(span.attributes[SEMATTRS_DB_NAME], expected.database ?? database); + strictEqual(span.attributes[SEMATTRS_NET_PEER_PORT], port); + strictEqual(span.attributes[SEMATTRS_NET_PEER_NAME], host); + strictEqual(span.attributes[SEMATTRS_DB_USER], user); + strictEqual( span.attributes['tedious.procedure_count'], expected.procCount ?? 1, 'Invalid procedure_count' ); - assert.strictEqual( + strictEqual( span.attributes['tedious.statement_count'], expected.statementCount ?? 1, 'Invalid statement_count' ); if (expected.parentSpan) { - assert.strictEqual( - span.parentSpanId, - expected.parentSpan.spanContext().spanId - ); + strictEqual(span.parentSpanId, expected.parentSpan.spanContext().spanId); } - assert.strictEqual(span.attributes[SEMATTRS_DB_SQL_TABLE], expected.table); + strictEqual(span.attributes[SEMATTRS_DB_SQL_TABLE], expected.table); if (expected.sql) { if (expected.sql instanceof RegExp) { assertMatch( @@ -387,19 +376,19 @@ function assertSpan(span: ReadableSpan, expected: any) { expected.sql ); } else { - assert.strictEqual(span.attributes[SEMATTRS_DB_STATEMENT], expected.sql); + strictEqual(span.attributes[SEMATTRS_DB_STATEMENT], expected.sql); } } else { - assert.strictEqual(span.attributes[SEMATTRS_DB_STATEMENT], undefined); + strictEqual(span.attributes[SEMATTRS_DB_STATEMENT], undefined); } if (expected.error) { assert( expected.error.test(span.status.message), `Expected "${span.status.message}" to match ${expected.error}` ); - assert.strictEqual(span.status.code, SpanStatusCode.ERROR); + strictEqual(span.status.code, SpanStatusCode.ERROR); } else { - assert.strictEqual(span.status.message, undefined); - assert.strictEqual(span.status.code, SpanStatusCode.UNSET); + strictEqual(span.status.message, undefined); + strictEqual(span.status.code, SpanStatusCode.UNSET); } } diff --git a/plugins/node/instrumentation-undici/src/index.ts b/plugins/node/instrumentation-undici/src/index.ts index 809207c6ce..385e911f1a 100644 --- a/plugins/node/instrumentation-undici/src/index.ts +++ b/plugins/node/instrumentation-undici/src/index.ts @@ -14,5 +14,13 @@ * limitations under the License. */ -export * from './undici'; -export * from './types'; +export { UndiciInstrumentation } from './undici'; +export { + UndiciRequest, + UndiciResponse, + IgnoreRequestFunction, + RequestHookFunction, + ResponseHookFunction, + StartSpanHookFunction, + UndiciInstrumentationConfig, +} from './types'; diff --git a/plugins/node/instrumentation-undici/test/fetch.test.ts b/plugins/node/instrumentation-undici/test/fetch.test.ts index 9ef4e90767..8df369b005 100644 --- a/plugins/node/instrumentation-undici/test/fetch.test.ts +++ b/plugins/node/instrumentation-undici/test/fetch.test.ts @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import * as assert from 'assert'; +import { strictEqual, ok } from 'assert'; import { SpanKind, @@ -66,11 +66,11 @@ describe('UndiciInstrumentation `fetch` tests', function () { // const resp = await fetch('http://host:port') // so we need to do the assertion here try { - assert.ok( + ok( req.headers[MockPropagation.TRACE_CONTEXT_KEY], `trace propagation for ${MockPropagation.TRACE_CONTEXT_KEY} works` ); - assert.ok( + ok( req.headers[MockPropagation.SPAN_CONTEXT_KEY], `trace propagation for ${MockPropagation.SPAN_CONTEXT_KEY} works` ); @@ -103,20 +103,20 @@ describe('UndiciInstrumentation `fetch` tests', function () { describe('disable()', function () { it('should not create spans when disabled', async function () { let spans = memoryExporter.getFinishedSpans(); - assert.strictEqual(spans.length, 0); + strictEqual(spans.length, 0); // Disable instrumentation.disable(); const fetchUrl = `${protocol}://${hostname}:${mockServer.port}/?query=test`; const response = await fetch(fetchUrl); - assert.ok( + ok( response.headers.get('propagation-error') != null, 'propagation is not set if instrumentation disabled' ); spans = memoryExporter.getFinishedSpans(); - assert.strictEqual(spans.length, 0, 'no spans are created'); + strictEqual(spans.length, 0, 'no spans are created'); }); }); @@ -132,7 +132,7 @@ describe('UndiciInstrumentation `fetch` tests', function () { it('should create valid spans even if the configuration hooks fail', async function () { let spans = memoryExporter.getFinishedSpans(); - assert.strictEqual(spans.length, 0); + strictEqual(spans.length, 0); // Set the bad configuration instrumentation.setConfig({ @@ -152,7 +152,7 @@ describe('UndiciInstrumentation `fetch` tests', function () { const fetchUrl = `${protocol}://${hostname}:${mockServer.port}/?query=test`; const response = await fetch(fetchUrl); - assert.ok( + ok( response.headers.get('propagation-error') == null, 'propagation is set for instrumented requests' ); @@ -160,8 +160,8 @@ describe('UndiciInstrumentation `fetch` tests', function () { spans = memoryExporter.getFinishedSpans(); const span = spans[0]; - assert.ok(span, 'a span is present'); - assert.strictEqual(spans.length, 1); + ok(span, 'a span is present'); + strictEqual(spans.length, 1); assertSpan(span, { hostname: 'localhost', httpStatusCode: response.status, @@ -174,11 +174,11 @@ describe('UndiciInstrumentation `fetch` tests', function () { it('should create valid spans with empty configuration', async function () { let spans = memoryExporter.getFinishedSpans(); - assert.strictEqual(spans.length, 0); + strictEqual(spans.length, 0); const fetchUrl = `${protocol}://${hostname}:${mockServer.port}/?query=test`; const response = await fetch(fetchUrl); - assert.ok( + ok( response.headers.get('propagation-error') == null, 'propagation is set for instrumented requests' ); @@ -186,8 +186,8 @@ describe('UndiciInstrumentation `fetch` tests', function () { spans = memoryExporter.getFinishedSpans(); const span = spans[0]; - assert.ok(span, 'a span is present'); - assert.strictEqual(spans.length, 1); + ok(span, 'a span is present'); + strictEqual(spans.length, 1); assertSpan(span, { hostname: 'localhost', httpStatusCode: response.status, @@ -200,7 +200,7 @@ describe('UndiciInstrumentation `fetch` tests', function () { it('should create valid spans with the given configuration', async function () { let spans = memoryExporter.getFinishedSpans(); - assert.strictEqual(spans.length, 0); + strictEqual(spans.length, 0); // Set configuration instrumentation.setConfig({ @@ -242,7 +242,7 @@ describe('UndiciInstrumentation `fetch` tests', function () { 'foo-client': 'bar', }), }; - assert.ok( + ok( ignoreResponse.headers.get('propagation-error'), 'propagation is not set for ignored requests' ); @@ -251,15 +251,15 @@ describe('UndiciInstrumentation `fetch` tests', function () { `${protocol}://${hostname}:${mockServer.port}/?query=test`, reqInit ); - assert.ok( + ok( queryResponse.headers.get('propagation-error') == null, 'propagation is set for instrumented requests' ); spans = memoryExporter.getFinishedSpans(); const span = spans[0]; - assert.ok(span, 'a span is present'); - assert.strictEqual(spans.length, 1); + ok(span, 'a span is present'); + strictEqual(spans.length, 1); assertSpan(span, { hostname: 'localhost', httpStatusCode: queryResponse.status, @@ -269,27 +269,27 @@ describe('UndiciInstrumentation `fetch` tests', function () { reqHeaders: reqInit.headers, resHeaders: queryResponse.headers, }); - assert.strictEqual( + strictEqual( span.attributes['http.request.header.foo-client'], 'bar', 'request headers from fetch options are captured' ); - assert.strictEqual( + strictEqual( span.attributes['http.request.header.x-requested-with'], 'undici', 'request headers from requestHook are captured' ); - assert.strictEqual( + strictEqual( span.attributes['http.response.header.foo-server'], 'bar', 'response headers from the server are captured' ); - assert.strictEqual( + strictEqual( span.attributes['test.hook.attribute'], 'hook-value', 'startSpanHook is called' ); - assert.strictEqual( + strictEqual( span.attributes['test.response-hook.attribute'], 'OK', 'responseHook is called' @@ -298,7 +298,7 @@ describe('UndiciInstrumentation `fetch` tests', function () { it('should not create spans without parent if required in configuration', async function () { let spans = memoryExporter.getFinishedSpans(); - assert.strictEqual(spans.length, 0); + strictEqual(spans.length, 0); instrumentation.setConfig({ requireParentforSpans: true, @@ -306,18 +306,18 @@ describe('UndiciInstrumentation `fetch` tests', function () { const fetchUrl = `${protocol}://${hostname}:${mockServer.port}/?query=test`; const response = await fetch(fetchUrl); - assert.ok( + ok( response.headers.get('propagation-error') == null, 'propagation is set for instrumented requests' ); spans = memoryExporter.getFinishedSpans(); - assert.strictEqual(spans.length, 0, 'no spans are created'); + strictEqual(spans.length, 0, 'no spans are created'); }); it('should not create spans with parent if required in configuration', function (done) { let spans = memoryExporter.getFinishedSpans(); - assert.strictEqual(spans.length, 0); + strictEqual(spans.length, 0); instrumentation.setConfig({ requireParentforSpans: true, @@ -333,19 +333,19 @@ describe('UndiciInstrumentation `fetch` tests', function () { const response = await fetch(fetchUrl); span.end(); - assert.ok( + ok( response.headers.get('propagation-error') == null, 'propagation is set for instrumented requests' ); spans = memoryExporter.getFinishedSpans(); - assert.strictEqual(spans.length, 2, 'child span is created'); - assert.strictEqual( + strictEqual(spans.length, 2, 'child span is created'); + strictEqual( spans.filter(span => span.kind === SpanKind.CLIENT).length, 1, 'child span is created' ); - assert.strictEqual( + strictEqual( spans.filter(span => span.kind === SpanKind.INTERNAL).length, 1, 'parent span is present' @@ -357,7 +357,7 @@ describe('UndiciInstrumentation `fetch` tests', function () { it('should capture errors using fetch API', async function () { let spans = memoryExporter.getFinishedSpans(); - assert.strictEqual(spans.length, 0); + strictEqual(spans.length, 0); let fetchError; try { @@ -370,8 +370,8 @@ describe('UndiciInstrumentation `fetch` tests', function () { spans = memoryExporter.getFinishedSpans(); const span = spans[0]; - assert.ok(span, 'a span is present'); - assert.strictEqual(spans.length, 1); + ok(span, 'a span is present'); + strictEqual(spans.length, 1); assertSpan(span, { hostname: 'unexistent-host-name', httpMethod: 'GET', @@ -387,7 +387,7 @@ describe('UndiciInstrumentation `fetch` tests', function () { it('should capture error if fetch request is aborted', async function () { let spans = memoryExporter.getFinishedSpans(); - assert.strictEqual(spans.length, 0); + strictEqual(spans.length, 0); let fetchError; const controller = new AbortController(); @@ -406,8 +406,8 @@ describe('UndiciInstrumentation `fetch` tests', function () { spans = memoryExporter.getFinishedSpans(); const span = spans[0]; - assert.ok(span, 'a span is present'); - assert.strictEqual(spans.length, 1); + ok(span, 'a span is present'); + strictEqual(spans.length, 1); assertSpan(span, { hostname: 'localhost', httpMethod: 'GET', diff --git a/plugins/node/instrumentation-undici/test/metrics.test.ts b/plugins/node/instrumentation-undici/test/metrics.test.ts index a903698385..8e134eda31 100644 --- a/plugins/node/instrumentation-undici/test/metrics.test.ts +++ b/plugins/node/instrumentation-undici/test/metrics.test.ts @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import * as assert from 'assert'; +import { strictEqual, ok } from 'assert'; import { context, propagation } from '@opentelemetry/api'; import { AsyncHooksContextManager } from '@opentelemetry/context-async-hooks'; @@ -102,38 +102,32 @@ describe('UndiciInstrumentation metrics tests', function () { const scopeMetrics = resourceMetrics[0].scopeMetrics; const metrics = scopeMetrics[0].metrics; - assert.strictEqual(scopeMetrics.length, 1, 'scopeMetrics count'); - assert.strictEqual(metrics.length, 1, 'metrics count'); - assert.strictEqual( - metrics[0].descriptor.name, - 'http.client.request.duration' - ); - assert.strictEqual( + strictEqual(scopeMetrics.length, 1, 'scopeMetrics count'); + strictEqual(metrics.length, 1, 'metrics count'); + strictEqual(metrics[0].descriptor.name, 'http.client.request.duration'); + strictEqual( metrics[0].descriptor.description, 'Measures the duration of outbound HTTP requests.' ); - assert.strictEqual(metrics[0].descriptor.unit, 's'); - assert.strictEqual(metrics[0].dataPointType, DataPointType.HISTOGRAM); - assert.strictEqual(metrics[0].dataPoints.length, 1); + strictEqual(metrics[0].descriptor.unit, 's'); + strictEqual(metrics[0].dataPointType, DataPointType.HISTOGRAM); + strictEqual(metrics[0].dataPoints.length, 1); const metricAttributes = metrics[0].dataPoints[0].attributes; - assert.strictEqual( - metricAttributes[SemanticAttributes.URL_SCHEME], - 'http' - ); - assert.strictEqual( + strictEqual(metricAttributes[SemanticAttributes.URL_SCHEME], 'http'); + strictEqual( metricAttributes[SemanticAttributes.HTTP_REQUEST_METHOD], 'GET' ); - assert.strictEqual( + strictEqual( metricAttributes[SemanticAttributes.SERVER_ADDRESS], 'localhost' ); - assert.strictEqual( + strictEqual( metricAttributes[SemanticAttributes.SERVER_PORT], mockServer.port ); - assert.strictEqual( + strictEqual( metricAttributes[SemanticAttributes.HTTP_RESPONSE_STATUS_CODE], 200 ); @@ -153,35 +147,29 @@ describe('UndiciInstrumentation metrics tests', function () { const scopeMetrics = resourceMetrics[0].scopeMetrics; const metrics = scopeMetrics[0].metrics; - assert.strictEqual(scopeMetrics.length, 1, 'scopeMetrics count'); - assert.strictEqual(metrics.length, 1, 'metrics count'); - assert.strictEqual( - metrics[0].descriptor.name, - 'http.client.request.duration' - ); - assert.strictEqual( + strictEqual(scopeMetrics.length, 1, 'scopeMetrics count'); + strictEqual(metrics.length, 1, 'metrics count'); + strictEqual(metrics[0].descriptor.name, 'http.client.request.duration'); + strictEqual( metrics[0].descriptor.description, 'Measures the duration of outbound HTTP requests.' ); - assert.strictEqual(metrics[0].descriptor.unit, 's'); - assert.strictEqual(metrics[0].dataPointType, DataPointType.HISTOGRAM); - assert.strictEqual(metrics[0].dataPoints.length, 1); + strictEqual(metrics[0].descriptor.unit, 's'); + strictEqual(metrics[0].dataPointType, DataPointType.HISTOGRAM); + strictEqual(metrics[0].dataPoints.length, 1); const metricAttributes = metrics[0].dataPoints[0].attributes; - assert.strictEqual( - metricAttributes[SemanticAttributes.URL_SCHEME], - 'http' - ); - assert.strictEqual( + strictEqual(metricAttributes[SemanticAttributes.URL_SCHEME], 'http'); + strictEqual( metricAttributes[SemanticAttributes.HTTP_REQUEST_METHOD], 'GET' ); - assert.strictEqual( + strictEqual( metricAttributes[SemanticAttributes.SERVER_ADDRESS], 'unknownhost' ); - assert.strictEqual(metricAttributes[SemanticAttributes.SERVER_PORT], 80); - assert.ok( + strictEqual(metricAttributes[SemanticAttributes.SERVER_PORT], 80); + ok( metricAttributes[SemanticAttributes.ERROR_TYPE], `the metric contains "${SemanticAttributes.ERROR_TYPE}" attribute if request failed` ); diff --git a/plugins/node/instrumentation-undici/test/undici.test.ts b/plugins/node/instrumentation-undici/test/undici.test.ts index 451bb71f3f..ce1d435752 100644 --- a/plugins/node/instrumentation-undici/test/undici.test.ts +++ b/plugins/node/instrumentation-undici/test/undici.test.ts @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import * as assert from 'assert'; +import { strictEqual, ok } from 'assert'; import { Writable } from 'stream'; import { @@ -92,11 +92,11 @@ describe('UndiciInstrumentation `undici` tests', function () { // const resp = await fetch('http://host:port') // so we need to do the assertion here try { - assert.ok( + ok( req.headers[MockPropagation.TRACE_CONTEXT_KEY], `trace propagation for ${MockPropagation.TRACE_CONTEXT_KEY} works` ); - assert.ok( + ok( req.headers[MockPropagation.SPAN_CONTEXT_KEY], `trace propagation for ${MockPropagation.SPAN_CONTEXT_KEY} works` ); @@ -133,7 +133,7 @@ describe('UndiciInstrumentation `undici` tests', function () { describe('disable()', function () { it('should not create spans when disabled', async function () { let spans = memoryExporter.getFinishedSpans(); - assert.strictEqual(spans.length, 0); + strictEqual(spans.length, 0); // Disable via config instrumentation.disable(); @@ -142,13 +142,13 @@ describe('UndiciInstrumentation `undici` tests', function () { const { headers, body } = await undici.request(requestUrl); await consumeResponseBody(body); - assert.ok( + ok( headers['propagation-error'] != null, 'propagation is not set if instrumentation disabled' ); spans = memoryExporter.getFinishedSpans(); - assert.strictEqual(spans.length, 0, 'no spans are created'); + strictEqual(spans.length, 0, 'no spans are created'); }); }); @@ -193,7 +193,7 @@ describe('UndiciInstrumentation `undici` tests', function () { it('should ignore requests based on the result of ignoreRequestHook', async function () { let spans = memoryExporter.getFinishedSpans(); - assert.strictEqual(spans.length, 0); + strictEqual(spans.length, 0); // Do some requests const headers = { @@ -207,18 +207,18 @@ describe('UndiciInstrumentation `undici` tests', function () { }); await consumeResponseBody(ignoreResponse.body); - assert.ok( + ok( ignoreResponse.headers['propagation-error'], 'propagation is not set for ignored requests' ); spans = memoryExporter.getFinishedSpans(); - assert.ok(spans.length === 0, 'ignoreRequestHook is filtering requests'); + ok(spans.length === 0, 'ignoreRequestHook is filtering requests'); }); it('should create valid spans for different request methods', async function () { let spans = memoryExporter.getFinishedSpans(); - assert.strictEqual(spans.length, 0); + strictEqual(spans.length, 0); // Do some requests const headers = { @@ -242,7 +242,7 @@ describe('UndiciInstrumentation `undici` tests', function () { // `SocketError: other side closed`. Given this is only for old Node.js // versions and for this rare case of using a bogus HTTP method, we will // skip out of this test instead of attempting to fully understand it. - assert.strictEqual(err.message, 'other side closed'); + strictEqual(err.message, 'other side closed'); this.skip(); } if (!firstQueryResponse) { @@ -257,17 +257,17 @@ describe('UndiciInstrumentation `undici` tests', function () { }); await consumeResponseBody(secondQueryResponse.body); - assert.ok( + ok( firstQueryResponse!.headers['propagation-error'] === undefined, 'propagation is set for instrumented requests' ); - assert.ok( + ok( secondQueryResponse!.headers['propagation-error'] === undefined, 'propagation is set for instrumented requests' ); spans = memoryExporter.getFinishedSpans(); - assert.strictEqual(spans.length, 2); + strictEqual(spans.length, 2); assertSpan(spans[0], { hostname: 'localhost', httpStatusCode: firstQueryResponse!.statusCode, @@ -277,7 +277,7 @@ describe('UndiciInstrumentation `undici` tests', function () { reqHeaders: headers, resHeaders: firstQueryResponse!.headers, }); - assert.strictEqual( + strictEqual( spans[0].attributes['http.request.method_original'], 'get', 'request original method is captured' @@ -293,7 +293,7 @@ describe('UndiciInstrumentation `undici` tests', function () { reqHeaders: headers, resHeaders: secondQueryResponse!.headers, }); - assert.strictEqual( + strictEqual( spans[1].attributes['http.request.method_original'], 'custom', 'request original method is captured' @@ -302,7 +302,7 @@ describe('UndiciInstrumentation `undici` tests', function () { it('should create valid spans for "request" method', async function () { let spans = memoryExporter.getFinishedSpans(); - assert.strictEqual(spans.length, 0); + strictEqual(spans.length, 0); // Do some requests const headers = { @@ -316,7 +316,7 @@ describe('UndiciInstrumentation `undici` tests', function () { }); await consumeResponseBody(ignoreResponse.body); - assert.ok( + ok( ignoreResponse.headers['propagation-error'], 'propagation is not set for ignored requests' ); @@ -325,15 +325,15 @@ describe('UndiciInstrumentation `undici` tests', function () { const queryResponse = await undici.request(queryRequestUrl, { headers }); await consumeResponseBody(queryResponse.body); - assert.ok( + ok( queryResponse.headers['propagation-error'] == null, 'propagation is set for instrumented requests' ); spans = memoryExporter.getFinishedSpans(); const span = spans[0]; - assert.ok(span, 'a span is present'); - assert.strictEqual(spans.length, 1); + ok(span, 'a span is present'); + strictEqual(spans.length, 1); assertSpan(span, { hostname: 'localhost', httpStatusCode: queryResponse.statusCode, @@ -343,27 +343,27 @@ describe('UndiciInstrumentation `undici` tests', function () { reqHeaders: headers, resHeaders: queryResponse.headers, }); - assert.strictEqual( + strictEqual( span.attributes['http.request.header.foo-client'], 'bar', 'request headers from fetch options are captured' ); - assert.strictEqual( + strictEqual( span.attributes['http.request.header.x-requested-with'], 'undici', 'request headers from requestHook are captured' ); - assert.strictEqual( + strictEqual( span.attributes['http.response.header.foo-server'], 'bar', 'response headers from the server are captured' ); - assert.strictEqual( + strictEqual( span.attributes['test.hook.attribute'], 'hook-value', 'startSpanHook is called' ); - assert.strictEqual( + strictEqual( span.attributes['test.response-hook.attribute'], 'OK', 'responseHook is called' @@ -379,7 +379,7 @@ describe('UndiciInstrumentation `undici` tests', function () { } let spans = memoryExporter.getFinishedSpans(); - assert.strictEqual(spans.length, 0); + strictEqual(spans.length, 0); // Do some requests const headers = { @@ -390,15 +390,15 @@ describe('UndiciInstrumentation `undici` tests', function () { const queryResponse = await undici.fetch(queryRequestUrl, { headers }); await queryResponse.text(); - assert.ok( + ok( queryResponse.headers.get('propagation-error') == null, 'propagation is set for instrumented requests' ); spans = memoryExporter.getFinishedSpans(); const span = spans[0]; - assert.ok(span, 'a span is present'); - assert.strictEqual(spans.length, 1); + ok(span, 'a span is present'); + strictEqual(spans.length, 1); assertSpan(span, { hostname: 'localhost', httpStatusCode: queryResponse.status, @@ -408,27 +408,27 @@ describe('UndiciInstrumentation `undici` tests', function () { reqHeaders: headers, resHeaders: queryResponse.headers as unknown as Headers, }); - assert.strictEqual( + strictEqual( span.attributes['http.request.header.foo-client'], 'bar', 'request headers from fetch options are captured' ); - assert.strictEqual( + strictEqual( span.attributes['http.request.header.x-requested-with'], 'undici', 'request headers from requestHook are captured' ); - assert.strictEqual( + strictEqual( span.attributes['http.response.header.foo-server'], 'bar', 'response headers from the server are captured' ); - assert.strictEqual( + strictEqual( span.attributes['test.hook.attribute'], 'hook-value', 'startSpanHook is called' ); - assert.strictEqual( + strictEqual( span.attributes['test.response-hook.attribute'], 'OK', 'responseHook is called' @@ -437,7 +437,7 @@ describe('UndiciInstrumentation `undici` tests', function () { it('should create valid spans for "stream" method', async function () { let spans = memoryExporter.getFinishedSpans(); - assert.strictEqual(spans.length, 0); + strictEqual(spans.length, 0); // Do some requests const headers = { @@ -463,15 +463,15 @@ describe('UndiciInstrumentation `undici` tests', function () { } ); - assert.ok( + ok( queryResponse.headers['propagation-error'] == null, 'propagation is set for instrumented requests' ); spans = memoryExporter.getFinishedSpans(); const span = spans[0]; - assert.ok(span, 'a span is present'); - assert.strictEqual(spans.length, 1); + ok(span, 'a span is present'); + strictEqual(spans.length, 1); assertSpan(span, { hostname: 'localhost', httpStatusCode: queryResponse.statusCode, @@ -481,27 +481,27 @@ describe('UndiciInstrumentation `undici` tests', function () { reqHeaders: headers, resHeaders: queryResponse.headers as unknown as Headers, }); - assert.strictEqual( + strictEqual( span.attributes['http.request.header.foo-client'], 'bar', 'request headers from fetch options are captured' ); - assert.strictEqual( + strictEqual( span.attributes['http.request.header.x-requested-with'], 'undici', 'request headers from requestHook are captured' ); - assert.strictEqual( + strictEqual( span.attributes['http.response.header.foo-server'], 'bar', 'response headers from the server are captured' ); - assert.strictEqual( + strictEqual( span.attributes['test.hook.attribute'], 'hook-value', 'startSpanHook is called' ); - assert.strictEqual( + strictEqual( span.attributes['test.response-hook.attribute'], 'OK', 'responseHook is called' @@ -510,7 +510,7 @@ describe('UndiciInstrumentation `undici` tests', function () { it('should create valid spans for "dispatch" method', async function () { let spans = memoryExporter.getFinishedSpans(); - assert.strictEqual(spans.length, 0); + strictEqual(spans.length, 0); // Do some requests const headers = { @@ -544,15 +544,15 @@ describe('UndiciInstrumentation `undici` tests', function () { ); }); - assert.ok( + ok( queryResponse.headers['propagation-error'] == null, 'propagation is set for instrumented requests' ); spans = memoryExporter.getFinishedSpans(); const span = spans[0]; - assert.ok(span, 'a span is present'); - assert.strictEqual(spans.length, 1); + ok(span, 'a span is present'); + strictEqual(spans.length, 1); assertSpan(span, { hostname: 'localhost', httpStatusCode: queryResponse.statusCode, @@ -562,27 +562,27 @@ describe('UndiciInstrumentation `undici` tests', function () { reqHeaders: headers, resHeaders: queryResponse.headers as unknown as Headers, }); - assert.strictEqual( + strictEqual( span.attributes['http.request.header.foo-client'], 'bar', 'request headers from fetch options are captured' ); - assert.strictEqual( + strictEqual( span.attributes['http.request.header.x-requested-with'], 'undici', 'request headers from requestHook are captured' ); - assert.strictEqual( + strictEqual( span.attributes['http.response.header.foo-server'], 'bar', 'response headers from the server are captured' ); - assert.strictEqual( + strictEqual( span.attributes['test.hook.attribute'], 'hook-value', 'startSpanHook is called' ); - assert.strictEqual( + strictEqual( span.attributes['test.response-hook.attribute'], 'OK', 'responseHook is called' @@ -591,7 +591,7 @@ describe('UndiciInstrumentation `undici` tests', function () { it('should create valid spans even if the configuration hooks fail', async function () { let spans = memoryExporter.getFinishedSpans(); - assert.strictEqual(spans.length, 0); + strictEqual(spans.length, 0); // Set the bad configuration instrumentation.setConfig({ @@ -613,7 +613,7 @@ describe('UndiciInstrumentation `undici` tests', function () { const { headers, statusCode, body } = await undici.request(requestUrl); await consumeResponseBody(body); - assert.ok( + ok( headers['propagation-error'] == null, 'propagation is set for instrumented requests' ); @@ -621,8 +621,8 @@ describe('UndiciInstrumentation `undici` tests', function () { spans = memoryExporter.getFinishedSpans(); const span = spans[0]; - assert.ok(span, 'a span is present'); - assert.strictEqual(spans.length, 1); + ok(span, 'a span is present'); + strictEqual(spans.length, 1); assertSpan(span, { hostname: 'localhost', httpStatusCode: statusCode, @@ -635,7 +635,7 @@ describe('UndiciInstrumentation `undici` tests', function () { it('should not create spans without parent if required in configuration', async function () { let spans = memoryExporter.getFinishedSpans(); - assert.strictEqual(spans.length, 0); + strictEqual(spans.length, 0); instrumentation.setConfig({ requireParentforSpans: true, @@ -645,18 +645,18 @@ describe('UndiciInstrumentation `undici` tests', function () { const response = await undici.request(requestUrl); await consumeResponseBody(response.body); - assert.ok( + ok( response.headers['propagation-error'] == null, 'propagation is set for instrumented requests' ); spans = memoryExporter.getFinishedSpans(); - assert.strictEqual(spans.length, 0, 'no spans are created'); + strictEqual(spans.length, 0, 'no spans are created'); }); it('should not create spans with INVALID_SPAN_CONTEXT parent if required in configuration', async function () { let spans = memoryExporter.getFinishedSpans(); - assert.strictEqual(spans.length, 0); + strictEqual(spans.length, 0); instrumentation.setConfig({ requireParentforSpans: true, @@ -667,19 +667,19 @@ describe('UndiciInstrumentation `undici` tests', function () { const requestUrl = `${protocol}://${hostname}:${mockServer.port}/?query=test`; const response = await undici.request(requestUrl); await consumeResponseBody(response.body); - assert.ok( + ok( response.headers['propagation-error'] == null, 'propagation is set for instrumented requests' ); }); spans = memoryExporter.getFinishedSpans(); - assert.strictEqual(spans.length, 0, 'no spans are created'); + strictEqual(spans.length, 0, 'no spans are created'); }); it('should create spans with parent if required in configuration', function (done) { let spans = memoryExporter.getFinishedSpans(); - assert.strictEqual(spans.length, 0); + strictEqual(spans.length, 0); instrumentation.setConfig({ requireParentforSpans: true, @@ -696,19 +696,19 @@ describe('UndiciInstrumentation `undici` tests', function () { await consumeResponseBody(response.body); span.end(); - assert.ok( + ok( response.headers['propagation-error'] == null, 'propagation is set for instrumented requests' ); spans = memoryExporter.getFinishedSpans(); - assert.strictEqual(spans.length, 2, 'child span is created'); - assert.strictEqual( + strictEqual(spans.length, 2, 'child span is created'); + strictEqual( spans.filter(span => span.kind === SpanKind.CLIENT).length, 1, 'child span is created' ); - assert.strictEqual( + strictEqual( spans.filter(span => span.kind === SpanKind.INTERNAL).length, 1, 'parent span is present' @@ -720,7 +720,7 @@ describe('UndiciInstrumentation `undici` tests', function () { it('should capture errors while doing request', async function () { let spans = memoryExporter.getFinishedSpans(); - assert.strictEqual(spans.length, 0); + strictEqual(spans.length, 0); let fetchError; try { @@ -733,8 +733,8 @@ describe('UndiciInstrumentation `undici` tests', function () { spans = memoryExporter.getFinishedSpans(); const span = spans[0]; - assert.ok(span, 'a span is present'); - assert.strictEqual(spans.length, 1); + ok(span, 'a span is present'); + strictEqual(spans.length, 1); assertSpan(span, { hostname: 'unexistent-host-name', httpMethod: 'GET', @@ -757,7 +757,7 @@ describe('UndiciInstrumentation `undici` tests', function () { } let spans = memoryExporter.getFinishedSpans(); - assert.strictEqual(spans.length, 0); + strictEqual(spans.length, 0); let requestError; const controller = new AbortController(); @@ -778,8 +778,8 @@ describe('UndiciInstrumentation `undici` tests', function () { spans = memoryExporter.getFinishedSpans(); const span = spans[0]; - assert.ok(span, 'a span is present'); - assert.strictEqual(spans.length, 1); + ok(span, 'a span is present'); + strictEqual(spans.length, 1); assertSpan(span, { hostname: 'localhost', httpMethod: 'GET', @@ -796,7 +796,7 @@ describe('UndiciInstrumentation `undici` tests', function () { it('should not report an user-agent if it was not defined', async function () { let spans = memoryExporter.getFinishedSpans(); - assert.strictEqual(spans.length, 0); + strictEqual(spans.length, 0); // Do some requests const headers = { @@ -807,15 +807,15 @@ describe('UndiciInstrumentation `undici` tests', function () { const queryResponse = await undici.request(queryRequestUrl, { headers }); await consumeResponseBody(queryResponse.body); - assert.ok( + ok( queryResponse.headers['propagation-error'] == null, 'propagation is set for instrumented requests' ); spans = memoryExporter.getFinishedSpans(); const span = spans[0]; - assert.ok(span, 'a span is present'); - assert.strictEqual(spans.length, 1); + ok(span, 'a span is present'); + strictEqual(spans.length, 1); assertSpan(span, { hostname: 'localhost', httpStatusCode: queryResponse.statusCode, @@ -825,7 +825,7 @@ describe('UndiciInstrumentation `undici` tests', function () { reqHeaders: headers, resHeaders: queryResponse.headers, }); - assert.strictEqual( + strictEqual( span.attributes['user_agent.original'], undefined, 'user-agent is undefined' diff --git a/plugins/node/instrumentation-undici/test/utils/assertSpan.ts b/plugins/node/instrumentation-undici/test/utils/assertSpan.ts index 3ab0a66d7d..07889a5328 100644 --- a/plugins/node/instrumentation-undici/test/utils/assertSpan.ts +++ b/plugins/node/instrumentation-undici/test/utils/assertSpan.ts @@ -21,7 +21,7 @@ import { } from '@opentelemetry/api'; import { hrTimeToNanoseconds } from '@opentelemetry/core'; import { ReadableSpan } from '@opentelemetry/sdk-trace-base'; -import * as assert from 'assert'; +import { strictEqual, ok, deepStrictEqual, equal } from 'assert'; import { SemanticAttributes } from '../../src/enums/SemanticAttributes'; type IncomingHttpHeaders = Record; @@ -42,22 +42,22 @@ export const assertSpan = ( error?: Exception; } ) => { - assert.strictEqual(span.spanContext().traceId.length, 32); - assert.strictEqual(span.spanContext().spanId.length, 16); - assert.strictEqual(span.kind, SpanKind.CLIENT, 'span.kind is correct'); - assert.strictEqual( + strictEqual(span.spanContext().traceId.length, 32); + strictEqual(span.spanContext().spanId.length, 16); + strictEqual(span.kind, SpanKind.CLIENT, 'span.kind is correct'); + strictEqual( span.name, validations.spanName || validations.httpMethod, 'span.name is correct' ); - assert.strictEqual( + strictEqual( span.attributes[SemanticAttributes.HTTP_REQUEST_METHOD], validations.httpMethod, `attributes['${SemanticAttributes.HTTP_REQUEST_METHOD}'] is correct` ); if (validations.path) { - assert.strictEqual( + strictEqual( span.attributes[SemanticAttributes.URL_PATH], validations.path, `attributes['${SemanticAttributes.URL_PATH}'] is correct` @@ -65,14 +65,14 @@ export const assertSpan = ( } if (validations.query) { - assert.strictEqual( + strictEqual( span.attributes[SemanticAttributes.URL_QUERY], validations.query, `attributes['${SemanticAttributes.URL_QUERY}'] is correct` ); } - assert.strictEqual( + strictEqual( span.attributes[SemanticAttributes.HTTP_RESPONSE_STATUS_CODE], validations.httpStatusCode, `attributes['${SemanticAttributes.HTTP_RESPONSE_STATUS_CODE}'] is correct ${ @@ -80,52 +80,49 @@ export const assertSpan = ( }` ); - assert.strictEqual(span.links.length, 0, 'there are no links'); + strictEqual(span.links.length, 0, 'there are no links'); if (validations.error) { - assert.strictEqual(span.events.length, 1, 'span contains one error event'); - assert.strictEqual( + strictEqual(span.events.length, 1, 'span contains one error event'); + strictEqual( span.events[0].name, 'exception', 'error event name is correct' ); const eventAttributes = span.events[0].attributes; - assert.ok(eventAttributes != null, 'event has attributes'); - assert.deepStrictEqual( + ok(eventAttributes != null, 'event has attributes'); + deepStrictEqual( Object.keys(eventAttributes), ['exception.type', 'exception.message', 'exception.stacktrace'], 'the event attribute names are correct' ); } else { - assert.strictEqual(span.events.length, 0, 'span contains no events'); + strictEqual(span.events.length, 0, 'span contains no events'); } // Error message changes between version se we will // only assert its presence if (validations.forceStatus) { - assert.equal( + equal( span.status.code, validations.forceStatus.code, 'span `status.code` is correct' ); - assert.ok(span.status.message, 'span `status.message` is present'); + ok(span.status.message, 'span `status.message` is present'); } else { const { httpStatusCode } = validations; const isStatusUnset = httpStatusCode && httpStatusCode >= 100 && httpStatusCode < 400; - assert.equal( + equal( span.status.code, isStatusUnset ? SpanStatusCode.UNSET : SpanStatusCode.ERROR, 'span `status.code` is correct' ); } - assert.ok(span.endTime, 'must be finished'); - assert.ok( - hrTimeToNanoseconds(span.duration) > 0, - 'must have positive duration' - ); + ok(span.endTime, 'must be finished'); + ok(hrTimeToNanoseconds(span.duration) > 0, 'must have positive duration'); if (validations.resHeaders) { // Headers were added in v17.5.0, v16.15.0 @@ -136,29 +133,29 @@ export const assertSpan = ( if (contentLengthHeader) { const contentLength = Number(contentLengthHeader); - assert.strictEqual( + strictEqual( span.attributes['http.response.header.content-length'], contentLength ); } } - assert.strictEqual( + strictEqual( span.attributes[SemanticAttributes.SERVER_ADDRESS], validations.hostname, 'must be consistent (SERVER_ADDRESS and hostname)' ); if (!validations.noNetPeer) { - assert.ok( + ok( span.attributes[SemanticAttributes.NETWORK_PEER_ADDRESS], `must have ${SemanticAttributes.NETWORK_PEER_ADDRESS}` ); - assert.ok( + ok( span.attributes[SemanticAttributes.NETWORK_PEER_PORT], `must have ${SemanticAttributes.NETWORK_PEER_PORT}` ); } - assert.ok( + ok( (span.attributes[SemanticAttributes.URL_FULL] as string).indexOf( span.attributes[SemanticAttributes.SERVER_ADDRESS] as string ) > -1, @@ -169,7 +166,7 @@ export const assertSpan = ( const userAgent = getHeader(validations.reqHeaders, 'user-agent'); if (userAgent) { - assert.strictEqual( + strictEqual( span.attributes[SemanticAttributes.USER_AGENT_ORIGINAL], userAgent ); diff --git a/plugins/node/opentelemetry-instrumentation-aws-lambda/src/index.ts b/plugins/node/opentelemetry-instrumentation-aws-lambda/src/index.ts index c26f998cff..d8df083077 100644 --- a/plugins/node/opentelemetry-instrumentation-aws-lambda/src/index.ts +++ b/plugins/node/opentelemetry-instrumentation-aws-lambda/src/index.ts @@ -14,5 +14,14 @@ * limitations under the License. */ -export * from './instrumentation'; -export * from './types'; +export { + AwsLambdaInstrumentation, + lambdaMaxInitInMilliseconds, + traceContextEnvironmentKey, +} from './instrumentation'; +export { + RequestHook, + ResponseHook, + EventContextExtractor, + AwsLambdaInstrumentationConfig, +} from './types'; diff --git a/plugins/node/opentelemetry-instrumentation-aws-lambda/test/integrations/lambda-handler.force-flush.test.ts b/plugins/node/opentelemetry-instrumentation-aws-lambda/test/integrations/lambda-handler.force-flush.test.ts index 0a067dc758..4ad4bf1653 100644 --- a/plugins/node/opentelemetry-instrumentation-aws-lambda/test/integrations/lambda-handler.force-flush.test.ts +++ b/plugins/node/opentelemetry-instrumentation-aws-lambda/test/integrations/lambda-handler.force-flush.test.ts @@ -26,7 +26,7 @@ import { } from '@opentelemetry/sdk-trace-base'; import { NodeTracerProvider } from '@opentelemetry/sdk-trace-node'; import { Context } from 'aws-lambda'; -import * as assert from 'assert'; +import { strictEqual } from 'assert'; import { ProxyTracerProvider, TracerProvider } from '@opentelemetry/api'; import { AggregationTemporality, @@ -114,7 +114,7 @@ describe('force flush', () => { ); }); - assert.strictEqual(forceFlushed, true); + strictEqual(forceFlushed, true); }); it('should force flush ProxyTracerProvider with NodeTracerProvider', async () => { @@ -148,7 +148,7 @@ describe('force flush', () => { ); }); - assert.strictEqual(forceFlushed, true); + strictEqual(forceFlushed, true); }); it('should force flush MeterProvider', async () => { @@ -179,7 +179,7 @@ describe('force flush', () => { ); }); - assert.strictEqual(forceFlushed, true); + strictEqual(forceFlushed, true); }); it('should callback once after force flush providers', async () => { @@ -232,8 +232,8 @@ describe('force flush', () => { ); }); - assert.strictEqual(tracerForceFlushed, true); - assert.strictEqual(meterForceFlushed, true); - assert.strictEqual(callbackCount, 1); + strictEqual(tracerForceFlushed, true); + strictEqual(meterForceFlushed, true); + strictEqual(callbackCount, 1); }); }); diff --git a/plugins/node/opentelemetry-instrumentation-aws-lambda/test/integrations/lambda-handler.test.ts b/plugins/node/opentelemetry-instrumentation-aws-lambda/test/integrations/lambda-handler.test.ts index aa7306b48d..cf8b884b87 100644 --- a/plugins/node/opentelemetry-instrumentation-aws-lambda/test/integrations/lambda-handler.test.ts +++ b/plugins/node/opentelemetry-instrumentation-aws-lambda/test/integrations/lambda-handler.test.ts @@ -32,7 +32,7 @@ import { } from '@opentelemetry/sdk-trace-base'; import { NodeTracerProvider } from '@opentelemetry/sdk-trace-node'; import { Context } from 'aws-lambda'; -import * as assert from 'assert'; +import { strictEqual, notDeepStrictEqual } from 'assert'; import { SEMATTRS_EXCEPTION_MESSAGE, SEMATTRS_FAAS_COLDSTART, @@ -56,29 +56,23 @@ import { W3CTraceContextPropagator } from '@opentelemetry/core'; const memoryExporter = new InMemorySpanExporter(); const assertSpanSuccess = (span: ReadableSpan) => { - assert.strictEqual(span.kind, SpanKind.SERVER); - assert.strictEqual(span.name, 'my_function'); - assert.strictEqual( - span.attributes[SEMATTRS_FAAS_EXECUTION], - 'aws_request_id' - ); - assert.strictEqual(span.attributes['faas.id'], 'my_arn'); - assert.strictEqual(span.status.code, SpanStatusCode.UNSET); - assert.strictEqual(span.status.message, undefined); + strictEqual(span.kind, SpanKind.SERVER); + strictEqual(span.name, 'my_function'); + strictEqual(span.attributes[SEMATTRS_FAAS_EXECUTION], 'aws_request_id'); + strictEqual(span.attributes['faas.id'], 'my_arn'); + strictEqual(span.status.code, SpanStatusCode.UNSET); + strictEqual(span.status.message, undefined); }; const assertSpanFailure = (span: ReadableSpan) => { - assert.strictEqual(span.kind, SpanKind.SERVER); - assert.strictEqual(span.name, 'my_function'); - assert.strictEqual( - span.attributes[SEMATTRS_FAAS_EXECUTION], - 'aws_request_id' - ); - assert.strictEqual(span.attributes['faas.id'], 'my_arn'); - assert.strictEqual(span.status.code, SpanStatusCode.ERROR); - assert.strictEqual(span.status.message, 'handler error'); - assert.strictEqual(span.events.length, 1); - assert.strictEqual( + strictEqual(span.kind, SpanKind.SERVER); + strictEqual(span.name, 'my_function'); + strictEqual(span.attributes[SEMATTRS_FAAS_EXECUTION], 'aws_request_id'); + strictEqual(span.attributes['faas.id'], 'my_arn'); + strictEqual(span.status.code, SpanStatusCode.ERROR); + strictEqual(span.status.message, 'handler error'); + strictEqual(span.events.length, 1); + strictEqual( span.events[0].attributes![SEMATTRS_EXCEPTION_MESSAGE], 'handler error' ); @@ -206,12 +200,12 @@ describe('lambda handler', () => { 'arg', ctx ); - assert.strictEqual(result, 'ok'); + strictEqual(result, 'ok'); const spans = memoryExporter.getFinishedSpans(); const [span] = spans; - assert.strictEqual(spans.length, 1); + strictEqual(spans.length, 1); assertSpanSuccess(span); - assert.strictEqual(span.parentSpanId, undefined); + strictEqual(span.parentSpanId, undefined); }); it('should record error', async () => { @@ -223,12 +217,12 @@ describe('lambda handler', () => { } catch (e: any) { err = e; } - assert.strictEqual(err!.message, 'handler error'); + strictEqual(err!.message, 'handler error'); const spans = memoryExporter.getFinishedSpans(); const [span] = spans; - assert.strictEqual(spans.length, 1); + strictEqual(spans.length, 1); assertSpanFailure(span); - assert.strictEqual(span.parentSpanId, undefined); + strictEqual(span.parentSpanId, undefined); }); it('should record string error', async () => { @@ -240,11 +234,11 @@ describe('lambda handler', () => { } catch (e: any) { err = e; } - assert.strictEqual(err!, 'handler error'); + strictEqual(err!, 'handler error'); const spans = memoryExporter.getFinishedSpans(); const [span] = spans; assertSpanFailure(span); - assert.strictEqual(span.parentSpanId, undefined); + strictEqual(span.parentSpanId, undefined); }); it('context should have parent trace', async () => { @@ -256,7 +250,7 @@ describe('lambda handler', () => { ); const spans = memoryExporter.getFinishedSpans(); const [span] = spans; - assert.strictEqual(span.spanContext().traceId, result); + strictEqual(span.spanContext().traceId, result); }); it('context should have parent trace', async () => { @@ -268,7 +262,7 @@ describe('lambda handler', () => { ); const spans = memoryExporter.getFinishedSpans(); const [span] = spans; - assert.strictEqual(span.spanContext().traceId, result); + strictEqual(span.spanContext().traceId, result); }); }); @@ -289,12 +283,12 @@ describe('lambda handler', () => { } ); }); - assert.strictEqual(result, 'ok'); + strictEqual(result, 'ok'); const spans = memoryExporter.getFinishedSpans(); const [span] = spans; - assert.strictEqual(spans.length, 1); + strictEqual(spans.length, 1); assertSpanSuccess(span); - assert.strictEqual(span.parentSpanId, undefined); + strictEqual(span.parentSpanId, undefined); }); it('should record coldstart', async () => { @@ -323,18 +317,18 @@ describe('lambda handler', () => { }); const spans = memoryExporter.getFinishedSpans(); - assert.strictEqual(spans.length, 2); + strictEqual(spans.length, 2); const [span1, span2] = spans; - assert.strictEqual(result1, 'ok'); + strictEqual(result1, 'ok'); assertSpanSuccess(span1); - assert.strictEqual(span1.parentSpanId, undefined); - assert.strictEqual(span1.attributes[SEMATTRS_FAAS_COLDSTART], true); + strictEqual(span1.parentSpanId, undefined); + strictEqual(span1.attributes[SEMATTRS_FAAS_COLDSTART], true); - assert.strictEqual(result2, 'ok'); + strictEqual(result2, 'ok'); assertSpanSuccess(span2); - assert.strictEqual(span2.parentSpanId, undefined); - assert.strictEqual(span2.attributes[SEMATTRS_FAAS_COLDSTART], false); + strictEqual(span2.parentSpanId, undefined); + strictEqual(span2.attributes[SEMATTRS_FAAS_COLDSTART], false); }); it('should record coldstart with provisioned concurrency', async () => { @@ -355,13 +349,13 @@ describe('lambda handler', () => { } ); }); - assert.strictEqual(result, 'ok'); + strictEqual(result, 'ok'); const spans = memoryExporter.getFinishedSpans(); const [span] = spans; - assert.strictEqual(spans.length, 1); + strictEqual(spans.length, 1); assertSpanSuccess(span); - assert.strictEqual(span.parentSpanId, undefined); - assert.strictEqual(span.attributes[SEMATTRS_FAAS_COLDSTART], false); + strictEqual(span.parentSpanId, undefined); + strictEqual(span.attributes[SEMATTRS_FAAS_COLDSTART], false); }); it('should record coldstart with proactive initialization', async () => { @@ -382,13 +376,13 @@ describe('lambda handler', () => { } ); }); - assert.strictEqual(result, 'ok'); + strictEqual(result, 'ok'); const spans = memoryExporter.getFinishedSpans(); const [span] = spans; - assert.strictEqual(spans.length, 1); + strictEqual(spans.length, 1); assertSpanSuccess(span); - assert.strictEqual(span.parentSpanId, undefined); - assert.strictEqual(span.attributes[SEMATTRS_FAAS_COLDSTART], false); + strictEqual(span.parentSpanId, undefined); + strictEqual(span.attributes[SEMATTRS_FAAS_COLDSTART], false); }); it('should record error', async () => { @@ -404,12 +398,12 @@ describe('lambda handler', () => { } catch (e: any) { err = e; } - assert.strictEqual(err!.message, 'handler error'); + strictEqual(err!.message, 'handler error'); const spans = memoryExporter.getFinishedSpans(); const [span] = spans; - assert.strictEqual(spans.length, 1); + strictEqual(spans.length, 1); assertSpanFailure(span); - assert.strictEqual(span.parentSpanId, undefined); + strictEqual(span.parentSpanId, undefined); }); it('should record error in callback', async () => { @@ -433,12 +427,12 @@ describe('lambda handler', () => { } catch (e: any) { err = e; } - assert.strictEqual(err!.message, 'handler error'); + strictEqual(err!.message, 'handler error'); const spans = memoryExporter.getFinishedSpans(); const [span] = spans; - assert.strictEqual(spans.length, 1); + strictEqual(spans.length, 1); assertSpanFailure(span); - assert.strictEqual(span.parentSpanId, undefined); + strictEqual(span.parentSpanId, undefined); }); it('should record string error', async () => { @@ -454,12 +448,12 @@ describe('lambda handler', () => { } catch (e: any) { err = e; } - assert.strictEqual(err!, 'handler error'); + strictEqual(err!, 'handler error'); const spans = memoryExporter.getFinishedSpans(); const [span] = spans; - assert.strictEqual(spans.length, 1); + strictEqual(spans.length, 1); assertSpanFailure(span); - assert.strictEqual(span.parentSpanId, undefined); + strictEqual(span.parentSpanId, undefined); }); it('context should have parent trace', async () => { @@ -480,7 +474,7 @@ describe('lambda handler', () => { }); const spans = memoryExporter.getFinishedSpans(); const [span] = spans; - assert.strictEqual(span.spanContext().traceId, result); + strictEqual(span.spanContext().traceId, result); }); it('context should have parent trace', async () => { @@ -501,7 +495,7 @@ describe('lambda handler', () => { }); const spans = memoryExporter.getFinishedSpans(); const [span] = spans; - assert.strictEqual(span.spanContext().traceId, result); + strictEqual(span.spanContext().traceId, result); }); }); @@ -526,12 +520,12 @@ describe('lambda handler', () => { } catch (e: any) { err = e; } - assert.strictEqual(err!, 'handler error'); + strictEqual(err!, 'handler error'); const spans = memoryExporter.getFinishedSpans(); const [span] = spans; - assert.strictEqual(spans.length, 1); + strictEqual(spans.length, 1); assertSpanFailure(span); - assert.strictEqual(span.parentSpanId, undefined); + strictEqual(span.parentSpanId, undefined); }); describe('with remote parent', () => { @@ -543,16 +537,13 @@ describe('lambda handler', () => { 'arg', ctx ); - assert.strictEqual(result, 'ok'); + strictEqual(result, 'ok'); const spans = memoryExporter.getFinishedSpans(); const [span] = spans; - assert.strictEqual(spans.length, 1); + strictEqual(spans.length, 1); assertSpanSuccess(span); - assert.strictEqual( - span.spanContext().traceId, - sampledAwsSpanContext.traceId - ); - assert.strictEqual(span.parentSpanId, sampledAwsSpanContext.spanId); + strictEqual(span.spanContext().traceId, sampledAwsSpanContext.traceId); + strictEqual(span.parentSpanId, sampledAwsSpanContext.spanId); }); it('uses lambda context if unsampled and no http context', async () => { @@ -563,10 +554,10 @@ describe('lambda handler', () => { 'arg', ctx ); - assert.strictEqual(result, 'ok'); + strictEqual(result, 'ok'); const spans = memoryExporter.getFinishedSpans(); // Parent unsampled so no exported spans. - assert.strictEqual(spans.length, 0); + strictEqual(spans.length, 0); }); it('uses lambda context if sampled and http context present', async () => { @@ -583,16 +574,13 @@ describe('lambda handler', () => { proxyEvent, ctx ); - assert.strictEqual(result, 'ok'); + strictEqual(result, 'ok'); const spans = memoryExporter.getFinishedSpans(); const [span] = spans; - assert.strictEqual(spans.length, 1); + strictEqual(spans.length, 1); assertSpanSuccess(span); - assert.strictEqual( - span.spanContext().traceId, - sampledAwsSpanContext.traceId - ); - assert.strictEqual(span.parentSpanId, sampledAwsSpanContext.spanId); + strictEqual(span.spanContext().traceId, sampledAwsSpanContext.traceId); + strictEqual(span.parentSpanId, sampledAwsSpanContext.spanId); }); it('uses http context if sampled and lambda context unsampled', async () => { @@ -609,16 +597,13 @@ describe('lambda handler', () => { proxyEvent, ctx ); - assert.strictEqual(result, 'ok'); + strictEqual(result, 'ok'); const spans = memoryExporter.getFinishedSpans(); const [span] = spans; - assert.strictEqual(spans.length, 1); + strictEqual(spans.length, 1); assertSpanSuccess(span); - assert.strictEqual( - span.spanContext().traceId, - sampledHttpSpanContext.traceId - ); - assert.strictEqual(span.parentSpanId, sampledHttpSpanContext.spanId); + strictEqual(span.spanContext().traceId, sampledHttpSpanContext.traceId); + strictEqual(span.parentSpanId, sampledHttpSpanContext.spanId); }); it('uses http context if unsampled and lambda context unsampled', async () => { @@ -635,10 +620,10 @@ describe('lambda handler', () => { proxyEvent, ctx ); - assert.strictEqual(result, 'ok'); + strictEqual(result, 'ok'); const spans = memoryExporter.getFinishedSpans(); // Parent unsampled so no spans exported. - assert.strictEqual(spans.length, 0); + strictEqual(spans.length, 0); }); it('ignores sampled lambda context if env OTEL_LAMBDA_DISABLE_AWS_CONTEXT_PROPAGATION is set to "true"', async () => { @@ -650,16 +635,16 @@ describe('lambda handler', () => { 'arg', ctx ); - assert.strictEqual(result, 'ok'); + strictEqual(result, 'ok'); const spans = memoryExporter.getFinishedSpans(); const [span] = spans; - assert.strictEqual(spans.length, 1); + strictEqual(spans.length, 1); assertSpanSuccess(span); - assert.notDeepStrictEqual( + notDeepStrictEqual( span.spanContext().traceId, sampledAwsSpanContext.traceId ); - assert.strictEqual(span.parentSpanId, undefined); + strictEqual(span.parentSpanId, undefined); }); it('ignores sampled lambda context if env OTEL_LAMBDA_DISABLE_AWS_CONTEXT_PROPAGATION is set to "TRUE"', async () => { @@ -671,16 +656,16 @@ describe('lambda handler', () => { 'arg', ctx ); - assert.strictEqual(result, 'ok'); + strictEqual(result, 'ok'); const spans = memoryExporter.getFinishedSpans(); const [span] = spans; - assert.strictEqual(spans.length, 1); + strictEqual(spans.length, 1); assertSpanSuccess(span); - assert.notDeepStrictEqual( + notDeepStrictEqual( span.spanContext().traceId, sampledAwsSpanContext.traceId ); - assert.strictEqual(span.parentSpanId, undefined); + strictEqual(span.parentSpanId, undefined); }); it('ignores sampled lambda context if env OTEL_LAMBDA_DISABLE_AWS_CONTEXT_PROPAGATION is set to "True"', async () => { @@ -692,16 +677,16 @@ describe('lambda handler', () => { 'arg', ctx ); - assert.strictEqual(result, 'ok'); + strictEqual(result, 'ok'); const spans = memoryExporter.getFinishedSpans(); const [span] = spans; - assert.strictEqual(spans.length, 1); + strictEqual(spans.length, 1); assertSpanSuccess(span); - assert.notDeepStrictEqual( + notDeepStrictEqual( span.spanContext().traceId, sampledAwsSpanContext.traceId ); - assert.strictEqual(span.parentSpanId, undefined); + strictEqual(span.parentSpanId, undefined); }); it('ignores OTEL_LAMBDA_DISABLE_AWS_CONTEXT_PROPAGATION if `config.disableAwsContextPropagation` is set', async () => { @@ -715,16 +700,13 @@ describe('lambda handler', () => { 'arg', ctx ); - assert.strictEqual(result, 'ok'); + strictEqual(result, 'ok'); const spans = memoryExporter.getFinishedSpans(); const [span] = spans; - assert.strictEqual(spans.length, 1); + strictEqual(spans.length, 1); assertSpanSuccess(span); - assert.strictEqual( - span.spanContext().traceId, - sampledAwsSpanContext.traceId - ); - assert.strictEqual(span.parentSpanId, sampledAwsSpanContext.spanId); + strictEqual(span.spanContext().traceId, sampledAwsSpanContext.traceId); + strictEqual(span.parentSpanId, sampledAwsSpanContext.spanId); }); it('ignores sampled lambda context if "disableAwsContextPropagation" config option is true', async () => { @@ -737,16 +719,16 @@ describe('lambda handler', () => { 'arg', ctx ); - assert.strictEqual(result, 'ok'); + strictEqual(result, 'ok'); const spans = memoryExporter.getFinishedSpans(); const [span] = spans; - assert.strictEqual(spans.length, 1); + strictEqual(spans.length, 1); assertSpanSuccess(span); - assert.notDeepStrictEqual( + notDeepStrictEqual( span.spanContext().traceId, sampledAwsSpanContext.traceId ); - assert.strictEqual(span.parentSpanId, undefined); + strictEqual(span.parentSpanId, undefined); }); it('takes sampled http context over sampled lambda context if "disableAwsContextPropagation" config option is true', async () => { @@ -766,16 +748,13 @@ describe('lambda handler', () => { ctx ); - assert.strictEqual(result, 'ok'); + strictEqual(result, 'ok'); const spans = memoryExporter.getFinishedSpans(); const [span] = spans; - assert.strictEqual(spans.length, 1); + strictEqual(spans.length, 1); assertSpanSuccess(span); - assert.strictEqual( - span.spanContext().traceId, - sampledHttpSpanContext.traceId - ); - assert.strictEqual(span.parentSpanId, sampledHttpSpanContext.spanId); + strictEqual(span.spanContext().traceId, sampledHttpSpanContext.traceId); + strictEqual(span.parentSpanId, sampledHttpSpanContext.spanId); }); it('takes sampled custom context over sampled lambda context if "eventContextExtractor" is defined', async () => { @@ -800,16 +779,16 @@ describe('lambda handler', () => { ctx ); - assert.strictEqual(result, 'ok'); + strictEqual(result, 'ok'); const spans = memoryExporter.getFinishedSpans(); const [span] = spans; - assert.strictEqual(spans.length, 1); + strictEqual(spans.length, 1); assertSpanSuccess(span); - assert.strictEqual( + strictEqual( span.spanContext().traceId, sampledGenericSpanContext.traceId ); - assert.strictEqual(span.parentSpanId, sampledGenericSpanContext.spanId); + strictEqual(span.parentSpanId, sampledGenericSpanContext.spanId); }); it('prefers to extract baggage over sampled lambda context if "eventContextExtractor" is defined', async () => { @@ -840,7 +819,7 @@ describe('lambda handler', () => { ctx ); - assert.strictEqual(actual, baggage); + strictEqual(actual, baggage); }); it('creates trace from ROOT_CONTEXT when "disableAwsContextPropagation" is true, eventContextExtractor is provided, and no custom context is found', async () => { @@ -871,7 +850,7 @@ describe('lambda handler', () => { const spans = memoryExporter.getFinishedSpans(); const [span] = spans; - assert.strictEqual(span.parentSpanId, undefined); + strictEqual(span.parentSpanId, undefined); }); it('passes the lambda context object into the eventContextExtractor for scenarios where it is the otel context carrier', async () => { @@ -920,16 +899,16 @@ describe('lambda handler', () => { ctxWithCustomData ); - assert.strictEqual(result, 'ok'); + strictEqual(result, 'ok'); const spans = memoryExporter.getFinishedSpans(); const [span] = spans; - assert.strictEqual(spans.length, 1); + strictEqual(spans.length, 1); assertSpanSuccess(span); - assert.strictEqual( + strictEqual( span.spanContext().traceId, sampledGenericSpanContext.traceId ); - assert.strictEqual(span.parentSpanId, sampledGenericSpanContext.spanId); + strictEqual(span.parentSpanId, sampledGenericSpanContext.spanId); }); }); @@ -945,11 +924,8 @@ describe('lambda handler', () => { await lambdaRequire('lambda-test/async').handler('arg', ctx); const spans = memoryExporter.getFinishedSpans(); const [span] = spans; - assert.strictEqual(spans.length, 1); - assert.strictEqual( - span.attributes[SEMRESATTRS_FAAS_NAME], - ctx.functionName - ); + strictEqual(spans.length, 1); + strictEqual(span.attributes[SEMRESATTRS_FAAS_NAME], ctx.functionName); assertSpanSuccess(span); }); }); @@ -980,7 +956,7 @@ describe('lambda handler', () => { ctx ); const [span] = memoryExporter.getFinishedSpans(); - assert.strictEqual(span.attributes[RES_ATTR], res); + strictEqual(span.attributes[RES_ATTR], res); }); it('async - error', async () => { @@ -993,7 +969,7 @@ describe('lambda handler', () => { err = e; } const [span] = memoryExporter.getFinishedSpans(); - assert.strictEqual(span.attributes[ERR_ATTR], err!.message); + strictEqual(span.attributes[ERR_ATTR], err!.message); }); it('sync - success', async () => { @@ -1007,7 +983,7 @@ describe('lambda handler', () => { ); }); const [span] = memoryExporter.getFinishedSpans(); - assert.strictEqual(span.attributes[RES_ATTR], result); + strictEqual(span.attributes[RES_ATTR], result); }); it('sync - error', async () => { @@ -1020,7 +996,7 @@ describe('lambda handler', () => { err = e; } const [span] = memoryExporter.getFinishedSpans(); - assert.strictEqual(span.attributes[ERR_ATTR], err!.message); + strictEqual(span.attributes[ERR_ATTR], err!.message); }); it('sync - error with callback', async () => { @@ -1038,7 +1014,7 @@ describe('lambda handler', () => { ); }); const [span] = memoryExporter.getFinishedSpans(); - assert.strictEqual(span.attributes[ERR_ATTR], error!.message); + strictEqual(span.attributes[ERR_ATTR], error!.message); }); }); @@ -1049,12 +1025,12 @@ describe('lambda handler', () => { 'arg', ctx ); - assert.strictEqual(result, 'ok'); + strictEqual(result, 'ok'); const spans = memoryExporter.getFinishedSpans(); const [span] = spans; - assert.strictEqual(spans.length, 1); + strictEqual(spans.length, 1); assertSpanSuccess(span); - assert.strictEqual(span.parentSpanId, undefined); + strictEqual(span.parentSpanId, undefined); }); }); }); @@ -1071,12 +1047,12 @@ describe('lambda handler', () => { ctx ); - assert.strictEqual(result, 'ok'); + strictEqual(result, 'ok'); const spans = memoryExporter.getFinishedSpans(); const [span] = spans; - assert.strictEqual(spans.length, 1); + strictEqual(spans.length, 1); assertSpanSuccess(span); - assert.strictEqual(span.parentSpanId, undefined); + strictEqual(span.parentSpanId, undefined); }); }); }); diff --git a/plugins/node/opentelemetry-instrumentation-aws-sdk/src/aws-sdk.ts b/plugins/node/opentelemetry-instrumentation-aws-sdk/src/aws-sdk.ts index c8180d3def..14e2953a8b 100644 --- a/plugins/node/opentelemetry-instrumentation-aws-sdk/src/aws-sdk.ts +++ b/plugins/node/opentelemetry-instrumentation-aws-sdk/src/aws-sdk.ts @@ -23,7 +23,7 @@ import { SpanStatusCode, } from '@opentelemetry/api'; import { suppressTracing } from '@opentelemetry/core'; -import type * as AWS from 'aws-sdk'; +import { Request } from 'aws-sdk'; import { AttributeNames } from './enums'; import { ServicesExtensions } from './services'; import { @@ -68,7 +68,7 @@ type V3PluginCommand = AwsV3Command & { }; const REQUEST_SPAN_KEY = Symbol('opentelemetry.instrumentation.aws-sdk.span'); -type V2PluginRequest = AWS.Request & { +type V2PluginRequest = Request & { [REQUEST_SPAN_KEY]?: Span; }; @@ -236,7 +236,7 @@ export class AwsInstrumentation extends InstrumentationBase, + request: Request, metadata: RequestMetadata, normalizedRequest: NormalizedRequest ): Span { diff --git a/plugins/node/opentelemetry-instrumentation-aws-sdk/src/index.ts b/plugins/node/opentelemetry-instrumentation-aws-sdk/src/index.ts index 2abc3b4f7a..ea7143b020 100644 --- a/plugins/node/opentelemetry-instrumentation-aws-sdk/src/index.ts +++ b/plugins/node/opentelemetry-instrumentation-aws-sdk/src/index.ts @@ -13,5 +13,17 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -export * from './aws-sdk'; -export * from './types'; +export { AwsInstrumentation } from './aws-sdk'; +export { + CommandInput, + NormalizedRequest, + NormalizedResponse, + AwsSdkRequestHookInformation, + AwsSdkRequestCustomAttributeFunction, + AwsSdkResponseHookInformation, + AwsSdkResponseCustomAttributeFunction, + AwsSdkSqsProcessHookInformation, + AwsSdkSqsProcessCustomAttributeFunction, + AwsSdkDynamoDBStatementSerializer, + AwsSdkInstrumentationConfig, +} from './types'; diff --git a/plugins/node/opentelemetry-instrumentation-aws-sdk/test/aws-sdk-v2.test.ts b/plugins/node/opentelemetry-instrumentation-aws-sdk/test/aws-sdk-v2.test.ts index 545fe09bd0..aa4d3e6703 100644 --- a/plugins/node/opentelemetry-instrumentation-aws-sdk/test/aws-sdk-v2.test.ts +++ b/plugins/node/opentelemetry-instrumentation-aws-sdk/test/aws-sdk-v2.test.ts @@ -25,7 +25,7 @@ import { const instrumentation = registerInstrumentationTesting( new AwsInstrumentation() ); -import * as AWS from 'aws-sdk'; +import { Response, config, S3 } from 'aws-sdk'; import { ReadableSpan } from '@opentelemetry/sdk-trace-base'; import { SpanStatusCode, Span, SpanKind } from '@opentelemetry/api'; @@ -54,7 +54,7 @@ describe('instrumentation-aws-sdk-v2', () => { }; const responseMockWithError: Pick< - AWS.Response, + Response, 'requestId' | 'error' > & { httpResponse: Partial } = { requestId: '0000000000000', @@ -71,7 +71,7 @@ describe('instrumentation-aws-sdk-v2', () => { }; before(() => { - AWS.config.credentials = { + config.credentials = { accessKeyId: 'test key id', expired: false, expireTime: new Date(), @@ -87,7 +87,7 @@ describe('instrumentation-aws-sdk-v2', () => { }); it('adds proper number of spans with correct attributes', async () => { - const s3 = new AWS.S3(); + const s3 = new S3(); const bucketName = 'aws-test-bucket'; const keyName = 'aws-test-object.txt'; await new Promise(resolve => { @@ -163,7 +163,7 @@ describe('instrumentation-aws-sdk-v2', () => { }); it('adds proper number of spans with correct attributes if both, promise and callback were used', async () => { - const s3 = new AWS.S3(); + const s3 = new S3(); const bucketName = 'aws-test-bucket'; const keyName = 'aws-test-object.txt'; await new Promise(resolve => { @@ -212,7 +212,7 @@ describe('instrumentation-aws-sdk-v2', () => { }); it('adds proper number of spans with correct attributes if only promise was used', async () => { - const s3 = new AWS.S3(); + const s3 = new S3(); const bucketName = 'aws-test-bucket'; const keyName = 'aws-test-object.txt'; await new Promise(resolve => { @@ -248,7 +248,7 @@ describe('instrumentation-aws-sdk-v2', () => { }); it('should create span if no callback is supplied', done => { - const s3 = new AWS.S3(); + const s3 = new S3(); const bucketName = 'aws-test-bucket'; s3.putObject({ @@ -271,7 +271,7 @@ describe('instrumentation-aws-sdk-v2', () => { }); it('adds error attribute properly', async () => { - const s3 = new AWS.S3(); + const s3 = new S3(); const bucketName = 'aws-test-bucket'; await new Promise(resolve => { s3.createBucket({ Bucket: bucketName }, async () => { @@ -324,7 +324,7 @@ describe('instrumentation-aws-sdk-v2', () => { instrumentation.setConfig(config); instrumentation.enable(); - const s3 = new AWS.S3(); + const s3 = new S3(); const bucketName = 'aws-test-bucket'; s3.createBucket({ Bucket: bucketName }, async (err, data) => { @@ -349,7 +349,7 @@ describe('instrumentation-aws-sdk-v2', () => { instrumentation.setConfig(config); instrumentation.enable(); - const s3 = new AWS.S3(); + const s3 = new S3(); const bucketName = 'aws-test-bucket'; s3.createBucket({ Bucket: bucketName }, async (err, data) => { @@ -378,7 +378,7 @@ describe('instrumentation-aws-sdk-v2', () => { instrumentation.setConfig(config); instrumentation.enable(); - const s3 = new AWS.S3(); + const s3 = new S3(); const bucketName = 'aws-test-bucket'; s3.createBucket({ Bucket: bucketName }, async (err, data) => { @@ -401,7 +401,7 @@ describe('instrumentation-aws-sdk-v2', () => { instrumentation.setConfig(config); instrumentation.enable(); - const s3 = new AWS.S3(); + const s3 = new S3(); s3.createBucket({ Bucket: 'aws-test-bucket' }, (err, data) => { const awsSpans = getAwsSpans(); @@ -420,7 +420,7 @@ describe('instrumentation-aws-sdk-v2', () => { instrumentation.setConfig(config); instrumentation.enable(); - const s3 = new AWS.S3(); + const s3 = new S3(); await s3.createBucket({ Bucket: 'aws-test-bucket' }).promise(); const awsSpans = getAwsSpans(); diff --git a/plugins/node/opentelemetry-instrumentation-aws-sdk/test/sns.test.ts b/plugins/node/opentelemetry-instrumentation-aws-sdk/test/sns.test.ts index f8d4dd777f..6c9c06efad 100644 --- a/plugins/node/opentelemetry-instrumentation-aws-sdk/test/sns.test.ts +++ b/plugins/node/opentelemetry-instrumentation-aws-sdk/test/sns.test.ts @@ -21,15 +21,14 @@ import { const instrumentation = registerInstrumentationTesting( new AwsInstrumentation() ); -import * as AWSv2 from 'aws-sdk'; +import { config, SNS } from 'aws-sdk'; import { SNS as SNSv3 } from '@aws-sdk/client-sns'; -import * as fs from 'fs'; -import * as nock from 'nock'; +import { readFileSync } from 'fs'; import { mockV2AwsSend } from './testing-utils'; import { expect } from 'expect'; import { ReadableSpan } from '@opentelemetry/sdk-trace-base'; -import * as sinon from 'sinon'; +import { spy } from 'sinon'; import { MESSAGINGDESTINATIONKINDVALUES_TOPIC, SEMATTRS_MESSAGING_DESTINATION, @@ -38,6 +37,7 @@ import { SEMATTRS_RPC_METHOD, } from '@opentelemetry/semantic-conventions'; import { SpanKind } from '@opentelemetry/api'; +import nock = require('nock'); const responseMockSuccess = { requestId: '0000000000000', @@ -49,7 +49,7 @@ const fakeARN = `arn:aws:sns:region:000000000:${topicName}`; describe('SNS - v2', () => { before(() => { - AWSv2.config.credentials = { + config.credentials = { accessKeyId: 'test key id', expired: false, expireTime: new Date(), @@ -66,7 +66,7 @@ describe('SNS - v2', () => { describe('publish', () => { it('topic arn', async () => { - const sns = new AWSv2.SNS(); + const sns = new SNS(); await sns .publish({ @@ -96,7 +96,7 @@ describe('SNS - v2', () => { }); it('phone number', async () => { - const sns = new AWSv2.SNS(); + const sns = new SNS(); const PhoneNumber = 'my phone number'; await sns .publish({ @@ -119,8 +119,8 @@ describe('SNS - v2', () => { }); it('inject context propagation', async () => { - const sns = new AWSv2.SNS(); - const hookSpy = sinon.spy( + const sns = new SNS(); + const hookSpy = spy( (instrumentation['servicesExtensions'] as any)['services'].get('SNS'), 'requestPostSpanHook' ); @@ -144,7 +144,7 @@ describe('SNS - v2', () => { describe('createTopic', () => { it('basic createTopic creates a valid span', async () => { - const sns = new AWSv2.SNS(); + const sns = new SNS(); const Name = 'my new topic'; await sns.createTopic({ Name }).promise(); @@ -185,7 +185,7 @@ describe('SNS - v3', () => { .post('/') .reply( 200, - fs.readFileSync('./test/mock-responses/sns-publish.xml', 'utf8') + readFileSync('./test/mock-responses/sns-publish.xml', 'utf8') ); }); diff --git a/plugins/node/opentelemetry-instrumentation-aws-sdk/test/sqs.test.ts b/plugins/node/opentelemetry-instrumentation-aws-sdk/test/sqs.test.ts index e97d82bb2c..0f69ae76b1 100644 --- a/plugins/node/opentelemetry-instrumentation-aws-sdk/test/sqs.test.ts +++ b/plugins/node/opentelemetry-instrumentation-aws-sdk/test/sqs.test.ts @@ -21,9 +21,8 @@ import { const instrumentation = registerInstrumentationTesting( new AwsInstrumentation() ); -import * as AWS from 'aws-sdk'; +import { Response, config, SQS } from 'aws-sdk'; import { AWSError } from 'aws-sdk'; -import type { SQS } from 'aws-sdk'; import { MESSAGINGDESTINATIONKINDVALUES_QUEUE, @@ -59,7 +58,7 @@ const responseMockSuccess = { requestId: '0000000000000', error: null, httpResponse: { statusCode: 200 }, -} as AWS.Response; +} as Response; const extractContextSpy = sinon.spy( messageAttributes, @@ -68,7 +67,7 @@ const extractContextSpy = sinon.spy( describe('SQS', () => { before(() => { - AWS.config.credentials = { + config.credentials = { accessKeyId: 'test key id', expired: false, expireTime: new Date(), @@ -80,7 +79,7 @@ describe('SQS', () => { beforeEach(() => { mockV2AwsSend(responseMockSuccess, { Messages: [{ Body: 'msg 1 payload' }, { Body: 'msg 2 payload' }], - } as AWS.SQS.Types.ReceiveMessageResult); + } as SQS.Types.ReceiveMessageResult); }); describe('receive context', () => { @@ -103,12 +102,12 @@ describe('SQS', () => { }; it('should set parent context in sqs receive callback', done => { - const sqs = new AWS.SQS(); + const sqs = new SQS(); sqs.receiveMessage( { QueueUrl: 'queue/url/for/unittests', }, - (err: AWSError, data: AWS.SQS.Types.ReceiveMessageResult) => { + (err: AWSError, data: SQS.Types.ReceiveMessageResult) => { expect(err).toBeFalsy(); createReceiveChildSpan(); expectReceiverWithChildSpan(getTestSpans()); @@ -118,12 +117,12 @@ describe('SQS', () => { }); it("should set parent context in sqs receive 'send' callback", done => { - const sqs = new AWS.SQS(); + const sqs = new SQS(); sqs .receiveMessage({ QueueUrl: 'queue/url/for/unittests', }) - .send((err: AWSError, data: AWS.SQS.Types.ReceiveMessageResult) => { + .send((err: AWSError, data: SQS.Types.ReceiveMessageResult) => { expect(err).toBeFalsy(); createReceiveChildSpan(); expectReceiverWithChildSpan(getTestSpans()); @@ -132,7 +131,7 @@ describe('SQS', () => { }); it('should set parent context in sqs receive promise then', async () => { - const sqs = new AWS.SQS(); + const sqs = new SQS(); await sqs .receiveMessage({ QueueUrl: 'queue/url/for/unittests', @@ -145,7 +144,7 @@ describe('SQS', () => { }); it.skip('should set parent context in sqs receive after await', async () => { - const sqs = new AWS.SQS(); + const sqs = new SQS(); await sqs .receiveMessage({ QueueUrl: 'queue/url/for/unittests', @@ -158,7 +157,7 @@ describe('SQS', () => { it.skip('should set parent context in sqs receive from async function', async () => { const asycnReceive = async () => { - const sqs = new AWS.SQS(); + const sqs = new SQS(); return await sqs .receiveMessage({ QueueUrl: 'queue/url/for/unittests', @@ -231,7 +230,7 @@ describe('SQS', () => { const contextValueFromTest = 'context value from test'; beforeEach(async () => { - const sqs = new AWS.SQS(); + const sqs = new SQS(); await context.with( context.active().setValue(contextKeyFromTest, contextValueFromTest), async () => { @@ -377,7 +376,7 @@ describe('SQS', () => { describe('hooks', () => { it('sqsResponseHook for sendMessage should add messaging attributes', async () => { const region = 'us-east-1'; - const sqs = new AWS.SQS(); + const sqs = new SQS(); sqs.config.update({ region }); const QueueName = 'unittest'; @@ -427,7 +426,7 @@ describe('SQS', () => { instrumentation.setConfig(config); - const sqs = new AWS.SQS(); + const sqs = new SQS(); const res = await sqs .receiveMessage({ QueueUrl: 'queue/url/for/unittests', @@ -452,7 +451,7 @@ describe('SQS', () => { }); it('sqsProcessHook not set in config', async () => { - const sqs = new AWS.SQS(); + const sqs = new SQS(); const res = await sqs .receiveMessage({ QueueUrl: 'queue/url/for/unittests', @@ -480,7 +479,7 @@ describe('SQS', () => { }; instrumentation.setConfig(config); - const sqs = new AWS.SQS(); + const sqs = new SQS(); const res = await sqs .receiveMessage({ QueueUrl: 'queue/url/for/unittests', @@ -502,7 +501,7 @@ describe('SQS', () => { it('bogus sendMessageBatch input should not crash', async () => { const region = 'us-east-1'; - const sqs = new AWS.SQS(); + const sqs = new SQS(); sqs.config.update({ region }); const QueueName = 'unittest'; @@ -531,9 +530,9 @@ describe('SQS', () => { it('should not extract from payload even if set', async () => { mockV2AwsSend(responseMockSuccess, { Messages: [{ Body: JSON.stringify({ traceparent: 1 }) }], - } as AWS.SQS.Types.ReceiveMessageResult); + } as SQS.Types.ReceiveMessageResult); - const sqs = new AWS.SQS(); + const sqs = new SQS(); await sqs .receiveMessage({ QueueUrl: 'queue/url/for/unittests1', @@ -556,9 +555,9 @@ describe('SQS', () => { Messages: [ { Body: JSON.stringify({ MessageAttributes: { traceparent } }) }, ], - } as AWS.SQS.Types.ReceiveMessageResult); + } as SQS.Types.ReceiveMessageResult); - const sqs = new AWS.SQS(); + const sqs = new SQS(); await sqs .receiveMessage({ QueueUrl: 'queue/url/for/unittests', @@ -590,9 +589,9 @@ describe('SQS', () => { }), }, ], - } as AWS.SQS.Types.ReceiveMessageResult); + } as SQS.Types.ReceiveMessageResult); - const sqs = new AWS.SQS(); + const sqs = new SQS(); await sqs .receiveMessage({ QueueUrl: 'queue/url/for/unittests', diff --git a/plugins/node/opentelemetry-instrumentation-aws-sdk/test/testing-utils.ts b/plugins/node/opentelemetry-instrumentation-aws-sdk/test/testing-utils.ts index 7ce6d373cc..597aeba407 100644 --- a/plugins/node/opentelemetry-instrumentation-aws-sdk/test/testing-utils.ts +++ b/plugins/node/opentelemetry-instrumentation-aws-sdk/test/testing-utils.ts @@ -17,13 +17,13 @@ import { context } from '@opentelemetry/api'; import { isTracingSuppressed } from '@opentelemetry/core'; import { getInstrumentation } from '@opentelemetry/contrib-test-utils'; import { expect } from 'expect'; -import * as AWS from 'aws-sdk'; +import { Response, Request } from 'aws-sdk'; // we want to mock the request object and trigger events on it's events emitter. // the event emitter is not part of the public interface, so we create a type // for the mock to use it. -type CompleteEventHandler = (response: AWS.Response) => void; -type RequestWithEvents = AWS.Request & { +type CompleteEventHandler = (response: Response) => void; +type RequestWithEvents = Request & { _events: { complete: CompleteEventHandler[] }; }; @@ -37,7 +37,7 @@ export const mockV2AwsSend = ( // I would like to see another pattern for this in the future, for example - patching only // once and just setting the result and data, or patching the http layer instead with nock package. getInstrumentation()?.disable(); - AWS.Request.prototype.send = function ( + Request.prototype.send = function ( this: RequestWithEvents, cb?: (error: any, response: any) => void ) { @@ -45,7 +45,7 @@ export const mockV2AwsSend = ( expectedInstrumentationSuppressed ); if (cb) { - (this as AWS.Request).on('complete', response => { + (this as Request).on('complete', response => { cb(response.error, response); }); } @@ -56,14 +56,13 @@ export const mockV2AwsSend = ( }; setImmediate(() => { this._events.complete.forEach( - (handler: (response: AWS.Response) => void) => - handler(response) + (handler: (response: Response) => void) => handler(response) ); }); return response; }; - AWS.Request.prototype.promise = function (this: RequestWithEvents) { + Request.prototype.promise = function (this: RequestWithEvents) { expect(isTracingSuppressed(context.active())).toStrictEqual( expectedInstrumentationSuppressed ); @@ -74,8 +73,7 @@ export const mockV2AwsSend = ( }; setImmediate(() => { this._events.complete.forEach( - (handler: (response: AWS.Response) => void) => - handler(response) + (handler: (response: Response) => void) => handler(response) ); }); return new Promise(resolve => diff --git a/plugins/node/opentelemetry-instrumentation-bunyan/src/index.ts b/plugins/node/opentelemetry-instrumentation-bunyan/src/index.ts index 2418a3b930..fb246f90ea 100644 --- a/plugins/node/opentelemetry-instrumentation-bunyan/src/index.ts +++ b/plugins/node/opentelemetry-instrumentation-bunyan/src/index.ts @@ -14,6 +14,6 @@ * limitations under the License. */ -export * from './instrumentation'; -export * from './types'; -export * from './OpenTelemetryBunyanStream'; +export { BunyanInstrumentation } from './instrumentation'; +export { LogHookFunction, BunyanInstrumentationConfig } from './types'; +export { OpenTelemetryBunyanStream } from './OpenTelemetryBunyanStream'; diff --git a/plugins/node/opentelemetry-instrumentation-bunyan/test/bunyan.test.ts b/plugins/node/opentelemetry-instrumentation-bunyan/test/bunyan.test.ts index b26c290b97..0118387f7e 100644 --- a/plugins/node/opentelemetry-instrumentation-bunyan/test/bunyan.test.ts +++ b/plugins/node/opentelemetry-instrumentation-bunyan/test/bunyan.test.ts @@ -29,8 +29,8 @@ import { NodeTracerProvider } from '@opentelemetry/sdk-trace-node'; import { isWrapped } from '@opentelemetry/instrumentation'; import { Resource } from '@opentelemetry/resources'; import { SEMRESATTRS_SERVICE_NAME } from '@opentelemetry/semantic-conventions'; -import * as assert from 'assert'; -import * as sinon from 'sinon'; +import { deepEqual, strictEqual, deepStrictEqual, ok } from 'assert'; +import { assert, SinonSpy, spy } from 'sinon'; import { Writable } from 'stream'; import { BunyanInstrumentation, OpenTelemetryBunyanStream } from '../src'; import { PACKAGE_VERSION } from '../src/version'; @@ -61,10 +61,10 @@ const Logger = require('bunyan'); describe('BunyanInstrumentation', () => { let log: BunyanLogger; let stream: Writable; - let writeSpy: sinon.SinonSpy; + let writeSpy: SinonSpy; it('is instrumented', () => { - assert.ok(isWrapped((Logger.prototype as any)['_emit'])); + ok(isWrapped((Logger.prototype as any)['_emit'])); }); describe('enabled instrumentation', () => { @@ -73,7 +73,7 @@ describe('BunyanInstrumentation', () => { memExporter.getFinishedLogRecords().length = 0; // clear stream = new Writable(); stream._write = () => {}; - writeSpy = sinon.spy(stream, 'write'); + writeSpy = spy(stream, 'write'); log = Logger.createLogger({ name: 'test-logger-name', level: 'debug', @@ -86,16 +86,13 @@ describe('BunyanInstrumentation', () => { context.with(trace.setSpan(context.active(), span), () => { const { traceId, spanId, traceFlags } = span.spanContext(); log.info('foo'); - sinon.assert.calledOnce(writeSpy); + assert.calledOnce(writeSpy); const record = JSON.parse(writeSpy.firstCall.args[0].toString()); - assert.strictEqual(record['trace_id'], traceId); - assert.strictEqual(record['span_id'], spanId); - assert.strictEqual( - record['trace_flags'], - `0${traceFlags.toString(16)}` - ); + strictEqual(record['trace_id'], traceId); + strictEqual(record['span_id'], spanId); + strictEqual(record['trace_flags'], `0${traceFlags.toString(16)}`); // Sanity check the message is unchanged - assert.strictEqual('foo', record['msg']); + strictEqual('foo', record['msg']); }); }); @@ -108,33 +105,33 @@ describe('BunyanInstrumentation', () => { }); context.with(trace.setSpan(context.active(), span), () => { log.info('foo'); - sinon.assert.calledOnce(writeSpy); + assert.calledOnce(writeSpy); const record = JSON.parse(writeSpy.firstCall.args[0].toString()); - assert.strictEqual(record['resource.service.name'], 'test-service'); + strictEqual(record['resource.service.name'], 'test-service'); }); }); it('does not inject span context if no span is active', () => { log.info('foo'); - assert.strictEqual(trace.getSpan(context.active()), undefined); - sinon.assert.calledOnce(writeSpy); + strictEqual(trace.getSpan(context.active()), undefined); + assert.calledOnce(writeSpy); const record = JSON.parse(writeSpy.firstCall.args[0].toString()); - assert.strictEqual(record['trace_id'], undefined); - assert.strictEqual(record['span_id'], undefined); - assert.strictEqual(record['trace_flags'], undefined); - assert.strictEqual('foo', record['msg']); + strictEqual(record['trace_id'], undefined); + strictEqual(record['span_id'], undefined); + strictEqual(record['trace_flags'], undefined); + strictEqual('foo', record['msg']); }); it('does not inject span context if span context is invalid', () => { const span = trace.wrapSpanContext(INVALID_SPAN_CONTEXT); context.with(trace.setSpan(context.active(), span), () => { log.info('foo'); - sinon.assert.calledOnce(writeSpy); + assert.calledOnce(writeSpy); const record = JSON.parse(writeSpy.firstCall.args[0].toString()); - assert.strictEqual(record['trace_id'], undefined); - assert.strictEqual(record['span_id'], undefined); - assert.strictEqual(record['trace_flags'], undefined); - assert.strictEqual('foo', record['msg']); + strictEqual(record['trace_id'], undefined); + strictEqual(record['span_id'], undefined); + strictEqual(record['trace_flags'], undefined); + strictEqual('foo', record['msg']); }); }); @@ -148,11 +145,11 @@ describe('BunyanInstrumentation', () => { context.with(trace.setSpan(context.active(), span), () => { const { traceId, spanId } = span.spanContext(); log.info('foo'); - sinon.assert.calledOnce(writeSpy); + assert.calledOnce(writeSpy); const record = JSON.parse(writeSpy.firstCall.args[0].toString()); - assert.strictEqual(record['trace_id'], traceId); - assert.strictEqual(record['span_id'], spanId); - assert.strictEqual('foo', record['msg']); + strictEqual(record['trace_id'], traceId); + strictEqual(record['span_id'], spanId); + strictEqual('foo', record['msg']); }); }); @@ -165,14 +162,14 @@ describe('BunyanInstrumentation', () => { }); tracer.startActiveSpan('abc', span => { log.info('foo'); - sinon.assert.calledOnce(writeSpy); + assert.calledOnce(writeSpy); const record = JSON.parse(writeSpy.firstCall.args[0].toString()); - assert.strictEqual('foo', record['msg']); - assert.strictEqual(record['trace_id'], undefined); - assert.strictEqual(record['span_id'], undefined); - assert.strictEqual(record['trace_flags'], undefined); - assert.strictEqual(record['resource.service.name'], undefined); - assert.strictEqual( + strictEqual('foo', record['msg']); + strictEqual(record['trace_id'], undefined); + strictEqual(record['span_id'], undefined); + strictEqual(record['trace_flags'], undefined); + strictEqual(record['resource.service.name'], undefined); + strictEqual( memExporter.getFinishedLogRecords().length, 1, 'Log sending still works' @@ -191,50 +188,50 @@ describe('BunyanInstrumentation', () => { log.warn('at warn level'); log.error('at error level'); log.fatal('at fatal level'); - assert.strictEqual(logRecords.length, 5); - assert.strictEqual(logRecords[0].severityNumber, SeverityNumber.DEBUG); - assert.strictEqual(logRecords[0].severityText, 'debug'); - assert.strictEqual(logRecords[1].severityNumber, SeverityNumber.INFO); - assert.strictEqual(logRecords[1].severityText, 'info'); - assert.strictEqual(logRecords[2].severityNumber, SeverityNumber.WARN); - assert.strictEqual(logRecords[2].severityText, 'warn'); - assert.strictEqual(logRecords[3].severityNumber, SeverityNumber.ERROR); - assert.strictEqual(logRecords[3].severityText, 'error'); - assert.strictEqual(logRecords[4].severityNumber, SeverityNumber.FATAL); - assert.strictEqual(logRecords[4].severityText, 'fatal'); + strictEqual(logRecords.length, 5); + strictEqual(logRecords[0].severityNumber, SeverityNumber.DEBUG); + strictEqual(logRecords[0].severityText, 'debug'); + strictEqual(logRecords[1].severityNumber, SeverityNumber.INFO); + strictEqual(logRecords[1].severityText, 'info'); + strictEqual(logRecords[2].severityNumber, SeverityNumber.WARN); + strictEqual(logRecords[2].severityText, 'warn'); + strictEqual(logRecords[3].severityNumber, SeverityNumber.ERROR); + strictEqual(logRecords[3].severityText, 'error'); + strictEqual(logRecords[4].severityNumber, SeverityNumber.FATAL); + strictEqual(logRecords[4].severityText, 'fatal'); // attributes, resource, instrumentationScope, etc. log.info({ foo: 'bar' }, 'a message'); const rec = logRecords[logRecords.length - 1]; - assert.strictEqual(rec.body, 'a message'); - assert.deepStrictEqual(rec.attributes, { + strictEqual(rec.body, 'a message'); + deepStrictEqual(rec.attributes, { name: 'test-logger-name', foo: 'bar', }); - assert.strictEqual( + strictEqual( rec.resource.attributes['service.name'], 'test-instrumentation-bunyan' ); - assert.strictEqual( + strictEqual( rec.instrumentationScope.name, '@opentelemetry/instrumentation-bunyan' ); - assert.strictEqual(rec.instrumentationScope.version, PACKAGE_VERSION); - assert.strictEqual(rec.spanContext, undefined); + strictEqual(rec.instrumentationScope.version, PACKAGE_VERSION); + strictEqual(rec.spanContext, undefined); // spanContext tracer.startActiveSpan('abc', span => { const { traceId, spanId, traceFlags } = span.spanContext(); log.info('in active span'); const rec = logRecords[logRecords.length - 1]; - assert.strictEqual(rec.spanContext?.traceId, traceId); - assert.strictEqual(rec.spanContext?.spanId, spanId); - assert.strictEqual(rec.spanContext?.traceFlags, traceFlags); + strictEqual(rec.spanContext?.traceId, traceId); + strictEqual(rec.spanContext?.spanId, spanId); + strictEqual(rec.spanContext?.traceFlags, traceFlags); // This rec should *NOT* have the `trace_id` et al attributes. - assert.strictEqual(rec.attributes.trace_id, undefined); - assert.strictEqual(rec.attributes.span_id, undefined); - assert.strictEqual(rec.attributes.trace_flags, undefined); + strictEqual(rec.attributes.trace_id, undefined); + strictEqual(rec.attributes.span_id, undefined); + strictEqual(rec.attributes.trace_flags, undefined); span.end(); }); @@ -247,22 +244,22 @@ describe('BunyanInstrumentation', () => { // A non-Date "time" Bunyan field. log.info({ time: 'miller' }, 'hi'); rec = logRecords[logRecords.length - 1]; - assert.deepEqual( + deepEqual( rec.hrTime.map(n => typeof n), ['number', 'number'] ); - assert.strictEqual(rec.attributes.time, 'miller'); + strictEqual(rec.attributes.time, 'miller'); // An atypical Bunyan level number. log.info({ level: 42 }, 'just above Bunyan WARN==40'); rec = logRecords[logRecords.length - 1]; - assert.strictEqual(rec.severityNumber, SeverityNumber.WARN2); - assert.strictEqual(rec.severityText, undefined); + strictEqual(rec.severityNumber, SeverityNumber.WARN2); + strictEqual(rec.severityText, undefined); log.info({ level: 200 }, 'far above Bunyan FATAL==60'); rec = logRecords[logRecords.length - 1]; - assert.strictEqual(rec.severityNumber, SeverityNumber.FATAL4); - assert.strictEqual(rec.severityText, undefined); + strictEqual(rec.severityNumber, SeverityNumber.FATAL4); + strictEqual(rec.severityText, undefined); }); it('does not emit to the Logs SDK if disableLogSending=true', () => { @@ -276,14 +273,14 @@ describe('BunyanInstrumentation', () => { tracer.startActiveSpan('abc', span => { const { traceId, spanId } = span.spanContext(); log.info('foo'); - assert.strictEqual(memExporter.getFinishedLogRecords().length, 0); + strictEqual(memExporter.getFinishedLogRecords().length, 0); // Test log correlation still works. - sinon.assert.calledOnce(writeSpy); + assert.calledOnce(writeSpy); const record = JSON.parse(writeSpy.firstCall.args[0].toString()); - assert.strictEqual('foo', record['msg']); - assert.strictEqual(record['trace_id'], traceId); - assert.strictEqual(record['span_id'], spanId); + strictEqual('foo', record['msg']); + strictEqual(record['trace_id'], traceId); + strictEqual(record['span_id'], spanId); span.end(); }); }); @@ -293,15 +290,15 @@ describe('BunyanInstrumentation', () => { log.info('foo'); const logRecords = memExporter.getFinishedLogRecords(); - assert.strictEqual(logRecords.length, 1); + strictEqual(logRecords.length, 1); let rec = logRecords[logRecords.length - 1]; - assert.strictEqual(rec.body, 'foo'); + strictEqual(rec.body, 'foo'); const child = log.child({ aProperty: 'bar' }); child.info('hi'); rec = logRecords[logRecords.length - 1]; - assert.strictEqual(rec.body, 'hi'); - assert.strictEqual(rec.attributes.aProperty, 'bar'); + strictEqual(rec.body, 'hi'); + strictEqual(rec.attributes.aProperty, 'bar'); }); it('emits to the Logs SDK with `Logger(...)`', () => { @@ -309,15 +306,15 @@ describe('BunyanInstrumentation', () => { log.info('foo'); const logRecords = memExporter.getFinishedLogRecords(); - assert.strictEqual(logRecords.length, 1); + strictEqual(logRecords.length, 1); let rec = logRecords[logRecords.length - 1]; - assert.strictEqual(rec.body, 'foo'); + strictEqual(rec.body, 'foo'); const child = log.child({ aProperty: 'bar' }); child.info('hi'); rec = logRecords[logRecords.length - 1]; - assert.strictEqual(rec.body, 'hi'); - assert.strictEqual(rec.attributes.aProperty, 'bar'); + strictEqual(rec.body, 'hi'); + strictEqual(rec.attributes.aProperty, 'bar'); }); it('log record error level', () => { @@ -330,8 +327,8 @@ describe('BunyanInstrumentation', () => { log.fatal('fatal log'); const logRecords = memExporter.getFinishedLogRecords(); // Only one log record match configured severity - assert.strictEqual(logRecords.length, 1); - assert.strictEqual(logRecords[0].body, 'fatal log'); + strictEqual(logRecords.length, 1); + strictEqual(logRecords[0].body, 'fatal log'); }); it('log record error level', () => { @@ -344,8 +341,8 @@ describe('BunyanInstrumentation', () => { log.error('error log'); const logRecords = memExporter.getFinishedLogRecords(); // Only one log record match configured severity - assert.strictEqual(logRecords.length, 1); - assert.strictEqual(logRecords[0].body, 'error log'); + strictEqual(logRecords.length, 1); + strictEqual(logRecords[0].body, 'error log'); }); it('log record warn level', () => { @@ -358,8 +355,8 @@ describe('BunyanInstrumentation', () => { log.warn('warn log'); const logRecords = memExporter.getFinishedLogRecords(); // Only one log record match configured severity - assert.strictEqual(logRecords.length, 1); - assert.strictEqual(logRecords[0].body, 'warn log'); + strictEqual(logRecords.length, 1); + strictEqual(logRecords[0].body, 'warn log'); }); it('log record info level', () => { @@ -372,8 +369,8 @@ describe('BunyanInstrumentation', () => { log.info('info log'); const logRecords = memExporter.getFinishedLogRecords(); // Only one log record match configured severity - assert.strictEqual(logRecords.length, 1); - assert.strictEqual(logRecords[0].body, 'info log'); + strictEqual(logRecords.length, 1); + strictEqual(logRecords[0].body, 'info log'); }); it('log record debug level', () => { @@ -382,12 +379,12 @@ describe('BunyanInstrumentation', () => { log.info('info log'); log.debug('debug log'); // Just the log.info() writes to `stream`. - sinon.assert.calledOnce(writeSpy); + assert.calledOnce(writeSpy); // Both log.info() and log.debug() should be written to the OTel Logs SDK. const logRecords = memExporter.getFinishedLogRecords(); - assert.strictEqual(logRecords.length, 2); - assert.strictEqual(logRecords[0].body, 'info log'); - assert.strictEqual(logRecords[1].body, 'debug log'); + strictEqual(logRecords.length, 2); + strictEqual(logRecords[0].body, 'info log'); + strictEqual(logRecords[1].body, 'debug log'); }); it('log record trace level', () => { @@ -397,13 +394,13 @@ describe('BunyanInstrumentation', () => { log.debug('debug log'); log.debug('trace log'); // Just the log.info() writes to `stream`. - sinon.assert.calledOnce(writeSpy); + assert.calledOnce(writeSpy); // Both log.info() and log.debug() should be written to the OTel Logs SDK. const logRecords = memExporter.getFinishedLogRecords(); - assert.strictEqual(logRecords.length, 3); - assert.strictEqual(logRecords[0].body, 'info log'); - assert.strictEqual(logRecords[1].body, 'debug log'); - assert.strictEqual(logRecords[2].body, 'trace log'); + strictEqual(logRecords.length, 3); + strictEqual(logRecords[0].body, 'info log'); + strictEqual(logRecords[1].body, 'debug log'); + strictEqual(logRecords[2].body, 'trace log'); }); }); @@ -419,7 +416,7 @@ describe('BunyanInstrumentation', () => { beforeEach(() => { stream = new Writable(); stream._write = () => {}; - writeSpy = sinon.spy(stream, 'write'); + writeSpy = spy(stream, 'write'); log = Logger.createLogger({ name: 'test', stream }); memExporter.getFinishedLogRecords().length = 0; // clear }); @@ -428,13 +425,13 @@ describe('BunyanInstrumentation', () => { const span = tracer.startSpan('abc'); context.with(trace.setSpan(context.active(), span), () => { log.info('foo'); - sinon.assert.calledOnce(writeSpy); + assert.calledOnce(writeSpy); const record = JSON.parse(writeSpy.firstCall.args[0].toString()); - assert.strictEqual(record['trace_id'], undefined); - assert.strictEqual(record['span_id'], undefined); - assert.strictEqual(record['trace_flags'], undefined); + strictEqual(record['trace_id'], undefined); + strictEqual(record['span_id'], undefined); + strictEqual(record['trace_flags'], undefined); // Sanity check the message is unchanged - assert.strictEqual('foo', record['msg']); + strictEqual('foo', record['msg']); }); }); @@ -447,16 +444,16 @@ describe('BunyanInstrumentation', () => { }); context.with(trace.setSpan(context.active(), span), () => { log.info('foo'); - sinon.assert.calledOnce(writeSpy); + assert.calledOnce(writeSpy); const record = JSON.parse(writeSpy.firstCall.args[0].toString()); - assert.strictEqual(record['resource.service.name'], undefined); + strictEqual(record['resource.service.name'], undefined); }); }); it('does not emit to the Logs SDK', () => { tracer.startActiveSpan('abc', span => { log.info('foo'); - assert.strictEqual(memExporter.getFinishedLogRecords().length, 0); + strictEqual(memExporter.getFinishedLogRecords().length, 0); }); }); }); @@ -491,50 +488,50 @@ describe('OpenTelemetryBunyanStream', () => { log.error('at error level'); log.fatal('at fatal level'); const logRecords = memExporter.getFinishedLogRecords(); - assert.strictEqual(logRecords.length, 5); - assert.strictEqual(logRecords[0].severityNumber, SeverityNumber.DEBUG); - assert.strictEqual(logRecords[0].severityText, 'debug'); - assert.strictEqual(logRecords[1].severityNumber, SeverityNumber.INFO); - assert.strictEqual(logRecords[1].severityText, 'info'); - assert.strictEqual(logRecords[2].severityNumber, SeverityNumber.WARN); - assert.strictEqual(logRecords[2].severityText, 'warn'); - assert.strictEqual(logRecords[3].severityNumber, SeverityNumber.ERROR); - assert.strictEqual(logRecords[3].severityText, 'error'); - assert.strictEqual(logRecords[4].severityNumber, SeverityNumber.FATAL); - assert.strictEqual(logRecords[4].severityText, 'fatal'); + strictEqual(logRecords.length, 5); + strictEqual(logRecords[0].severityNumber, SeverityNumber.DEBUG); + strictEqual(logRecords[0].severityText, 'debug'); + strictEqual(logRecords[1].severityNumber, SeverityNumber.INFO); + strictEqual(logRecords[1].severityText, 'info'); + strictEqual(logRecords[2].severityNumber, SeverityNumber.WARN); + strictEqual(logRecords[2].severityText, 'warn'); + strictEqual(logRecords[3].severityNumber, SeverityNumber.ERROR); + strictEqual(logRecords[3].severityText, 'error'); + strictEqual(logRecords[4].severityNumber, SeverityNumber.FATAL); + strictEqual(logRecords[4].severityText, 'fatal'); // attributes, resource, instrumentationScope, etc. log.info({ foo: 'bar' }, 'a message'); const rec = logRecords[logRecords.length - 1]; - assert.strictEqual(rec.body, 'a message'); - assert.deepStrictEqual(rec.attributes, { + strictEqual(rec.body, 'a message'); + deepStrictEqual(rec.attributes, { name: 'test-logger-name', foo: 'bar', }); - assert.strictEqual( + strictEqual( rec.resource.attributes['service.name'], 'test-instrumentation-bunyan' ); - assert.strictEqual( + strictEqual( rec.instrumentationScope.name, '@opentelemetry/instrumentation-bunyan' ); - assert.strictEqual(rec.instrumentationScope.version, PACKAGE_VERSION); - assert.strictEqual(rec.spanContext, undefined); + strictEqual(rec.instrumentationScope.version, PACKAGE_VERSION); + strictEqual(rec.spanContext, undefined); // spanContext tracer.startActiveSpan('abc', span => { const { traceId, spanId, traceFlags } = span.spanContext(); log.info('in active span'); const rec = logRecords[logRecords.length - 1]; - assert.strictEqual(rec.spanContext?.traceId, traceId); - assert.strictEqual(rec.spanContext?.spanId, spanId); - assert.strictEqual(rec.spanContext?.traceFlags, traceFlags); + strictEqual(rec.spanContext?.traceId, traceId); + strictEqual(rec.spanContext?.spanId, spanId); + strictEqual(rec.spanContext?.traceFlags, traceFlags); // This rec should *NOT* have the `trace_id` et al attributes. - assert.strictEqual(rec.attributes.trace_id, undefined); - assert.strictEqual(rec.attributes.span_id, undefined); - assert.strictEqual(rec.attributes.trace_flags, undefined); + strictEqual(rec.attributes.trace_id, undefined); + strictEqual(rec.attributes.span_id, undefined); + strictEqual(rec.attributes.trace_flags, undefined); span.end(); }); diff --git a/plugins/node/opentelemetry-instrumentation-cassandra/src/index.ts b/plugins/node/opentelemetry-instrumentation-cassandra/src/index.ts index c26f998cff..10d23a5225 100644 --- a/plugins/node/opentelemetry-instrumentation-cassandra/src/index.ts +++ b/plugins/node/opentelemetry-instrumentation-cassandra/src/index.ts @@ -14,5 +14,11 @@ * limitations under the License. */ -export * from './instrumentation'; -export * from './types'; +export { CassandraDriverInstrumentation } from './instrumentation'; +export { + Row, + ResultSet, + ResponseHookInfo, + CassandraDriverResponseCustomAttributeFunction, + CassandraDriverInstrumentationConfig, +} from './types'; diff --git a/plugins/node/opentelemetry-instrumentation-connect/src/index.ts b/plugins/node/opentelemetry-instrumentation-connect/src/index.ts index 34b600dd0c..a1241f895f 100644 --- a/plugins/node/opentelemetry-instrumentation-connect/src/index.ts +++ b/plugins/node/opentelemetry-instrumentation-connect/src/index.ts @@ -14,5 +14,9 @@ * limitations under the License. */ -export * from './enums/AttributeNames'; -export * from './instrumentation'; +export { + AttributeNames, + ConnectTypes, + ConnectNames, +} from './enums/AttributeNames'; +export { ANONYMOUS_NAME, ConnectInstrumentation } from './instrumentation'; diff --git a/plugins/node/opentelemetry-instrumentation-connect/test/instrumentation.test.ts b/plugins/node/opentelemetry-instrumentation-connect/test/instrumentation.test.ts index cc2ef79fb5..10b667e0c3 100644 --- a/plugins/node/opentelemetry-instrumentation-connect/test/instrumentation.test.ts +++ b/plugins/node/opentelemetry-instrumentation-connect/test/instrumentation.test.ts @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import * as assert from 'assert'; +import { strictEqual, deepStrictEqual } from 'assert'; import { context, trace } from '@opentelemetry/api'; import { RPCType, setRPCMetadata, RPCMetadata } from '@opentelemetry/core'; @@ -27,6 +27,7 @@ import { import * as http from 'http'; import type { AddressInfo } from 'net'; import { ANONYMOUS_NAME, ConnectInstrumentation } from '../src'; +import assert = require('assert'); const httpRequest = { get: (options: http.ClientRequestArgs | string) => { @@ -97,7 +98,7 @@ describe('connect', () => { await httpRequest.get(`http://localhost:${PORT}/`); const spans = memoryExporter.getFinishedSpans(); - assert.strictEqual(spans.length, 0); + strictEqual(spans.length, 0); }); }); describe('when connect is enabled', () => { @@ -139,14 +140,14 @@ describe('connect', () => { await httpRequest.get(`http://localhost:${PORT}/`); const spans = memoryExporter.getFinishedSpans(); - assert.strictEqual(spans.length, 1); + strictEqual(spans.length, 1); const span = spans[0]; - assert.deepStrictEqual(span.attributes, { + deepStrictEqual(span.attributes, { 'connect.type': 'middleware', 'connect.name': ANONYMOUS_NAME, [SEMATTRS_HTTP_ROUTE]: '/', }); - assert.strictEqual(span.name, 'middleware - anonymous'); + strictEqual(span.name, 'middleware - anonymous'); }); it('should generate span for named middleware', async () => { @@ -158,14 +159,14 @@ describe('connect', () => { await httpRequest.get(`http://localhost:${PORT}/`); const spans = memoryExporter.getFinishedSpans(); - assert.strictEqual(spans.length, 1); + strictEqual(spans.length, 1); const span = spans[0]; - assert.deepStrictEqual(span.attributes, { + deepStrictEqual(span.attributes, { 'connect.type': 'middleware', 'connect.name': 'middleware1', [SEMATTRS_HTTP_ROUTE]: '/', }); - assert.strictEqual(span.name, 'middleware - middleware1'); + strictEqual(span.name, 'middleware - middleware1'); }); it('should generate span for route', async () => { @@ -176,14 +177,14 @@ describe('connect', () => { await httpRequest.get(`http://localhost:${PORT}/foo`); const spans = memoryExporter.getFinishedSpans(); - assert.strictEqual(spans.length, 1); + strictEqual(spans.length, 1); const span = spans[0]; - assert.deepStrictEqual(span.attributes, { + deepStrictEqual(span.attributes, { 'connect.type': 'request_handler', 'connect.name': '/foo', [SEMATTRS_HTTP_ROUTE]: '/foo', }); - assert.strictEqual(span.name, 'request handler - /foo'); + strictEqual(span.name, 'request handler - /foo'); }); it('should not change name for parent http route ', async () => { @@ -207,9 +208,9 @@ describe('connect', () => { rootSpan.end(); const spans = memoryExporter.getFinishedSpans(); - assert.strictEqual(spans.length, 3); + strictEqual(spans.length, 3); const changedRootSpan = spans[2]; - assert.strictEqual(changedRootSpan.name, 'root span'); + strictEqual(changedRootSpan.name, 'root span'); }); it('should mutate route value of RpcMetadata', async () => { @@ -233,15 +234,12 @@ describe('connect', () => { rootSpan.end(); const spans = memoryExporter.getFinishedSpans(); - assert.strictEqual(spans.length, 3); + strictEqual(spans.length, 3); const changedRootSpan = spans[2]; const span = spans[0]; - assert.strictEqual(rpcMetadata.route, '/foo'); - assert.strictEqual(span.name, 'request handler - /foo'); - assert.strictEqual( - span.parentSpanId, - changedRootSpan.spanContext().spanId - ); + strictEqual(rpcMetadata.route, '/foo'); + strictEqual(span.name, 'request handler - /foo'); + strictEqual(span.parentSpanId, changedRootSpan.spanContext().spanId); }); it('should append nested route in RpcMetadata', async () => { @@ -267,7 +265,7 @@ describe('connect', () => { await httpRequest.get(`http://localhost:${PORT}/foo/bar`); rootSpan.end(); - assert.strictEqual(rpcMetadata.route, '/foo/bar/'); + strictEqual(rpcMetadata.route, '/foo/bar/'); }); it('should use latest match route when multiple route is match', async () => { @@ -294,7 +292,7 @@ describe('connect', () => { await httpRequest.get(`http://localhost:${PORT}/foo/bar`); rootSpan.end(); - assert.strictEqual(rpcMetadata.route, '/foo/bar'); + strictEqual(rpcMetadata.route, '/foo/bar'); }); it('should use latest match route when multiple route is match (with nested app)', async () => { @@ -324,7 +322,7 @@ describe('connect', () => { await httpRequest.get(`http://localhost:${PORT}/foo/bar/test`); rootSpan.end(); - assert.strictEqual(rpcMetadata.route, '/foo/bar/test'); + strictEqual(rpcMetadata.route, '/foo/bar/test'); }); }); }); diff --git a/plugins/node/opentelemetry-instrumentation-connect/test/utils.test.ts b/plugins/node/opentelemetry-instrumentation-connect/test/utils.test.ts index b62d3d6ab8..74584fcf9e 100644 --- a/plugins/node/opentelemetry-instrumentation-connect/test/utils.test.ts +++ b/plugins/node/opentelemetry-instrumentation-connect/test/utils.test.ts @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import * as assert from 'assert'; +import { equal, strictEqual, notStrictEqual } from 'assert'; import { PatchedRequest, _LAYERS_STORE_PROPERTY } from '../src/internal-types'; import { @@ -29,7 +29,7 @@ describe('utils', () => { addNewStackLayer(fakeRequest); - assert.strictEqual(fakeRequest[_LAYERS_STORE_PROPERTY].length, 1); + strictEqual(fakeRequest[_LAYERS_STORE_PROPERTY].length, 1); }); it('should append new stack item if private symbol already exists', () => { @@ -40,8 +40,8 @@ describe('utils', () => { addNewStackLayer(fakeRequest); - assert.equal(fakeRequest[_LAYERS_STORE_PROPERTY], stack); - assert.strictEqual(fakeRequest[_LAYERS_STORE_PROPERTY].length, 2); + equal(fakeRequest[_LAYERS_STORE_PROPERTY], stack); + strictEqual(fakeRequest[_LAYERS_STORE_PROPERTY].length, 2); }); it('should return pop method to remove newly add stack', () => { @@ -49,11 +49,11 @@ describe('utils', () => { const pop = addNewStackLayer(fakeRequest); - assert.notStrictEqual(pop, undefined); + notStrictEqual(pop, undefined); pop(); - assert.strictEqual(fakeRequest[_LAYERS_STORE_PROPERTY].length, 0); + strictEqual(fakeRequest[_LAYERS_STORE_PROPERTY].length, 0); }); it('should prevent pop the same stack item multiple time', () => { @@ -65,7 +65,7 @@ describe('utils', () => { pop(); pop(); - assert.strictEqual(fakeRequest[_LAYERS_STORE_PROPERTY].length, 1); + strictEqual(fakeRequest[_LAYERS_STORE_PROPERTY].length, 1); }); }); @@ -77,8 +77,8 @@ describe('utils', () => { replaceCurrentStackRoute(fakeRequest, '/new_route'); - assert.strictEqual(fakeRequest[_LAYERS_STORE_PROPERTY].length, 2); - assert.strictEqual(fakeRequest[_LAYERS_STORE_PROPERTY][1], '/new_route'); + strictEqual(fakeRequest[_LAYERS_STORE_PROPERTY].length, 2); + strictEqual(fakeRequest[_LAYERS_STORE_PROPERTY][1], '/new_route'); }); }); @@ -90,7 +90,7 @@ describe('utils', () => { const route = generateRoute(fakeRequest); - assert.strictEqual(route, '/first/second/third/'); + strictEqual(route, '/first/second/third/'); }); }); }); diff --git a/plugins/node/opentelemetry-instrumentation-dns/src/instrumentation.ts b/plugins/node/opentelemetry-instrumentation-dns/src/instrumentation.ts index a99051a502..fe486fe100 100644 --- a/plugins/node/opentelemetry-instrumentation-dns/src/instrumentation.ts +++ b/plugins/node/opentelemetry-instrumentation-dns/src/instrumentation.ts @@ -26,7 +26,12 @@ import { } from '@opentelemetry/instrumentation'; import { AddressFamily } from './enums/AddressFamily'; import { DnsInstrumentationConfig } from './types'; -import * as utils from './utils'; +import { + isIgnored, + getOperationName, + setError, + setLookupAttributes, +} from './utils'; import { PACKAGE_NAME, PACKAGE_VERSION } from './version'; import { LookupCallbackSignature, @@ -110,10 +115,8 @@ export class DnsInstrumentation extends InstrumentationBase diag.error('caught ignoreHostname error: ', e) + isIgnored(hostname, plugin.getConfig().ignoreHostnames, (e: Error) => + diag.error('caught ignoreHostname error: ', e) ) ) { return original.apply(this, [hostname, ...args]); @@ -121,7 +124,7 @@ export class DnsInstrumentation extends InstrumentationBase original.apply(this, [hostname, ...args]), error => { if (error != null) { - utils.setError(error, span); + setError(error, span); span.end(); } } @@ -150,18 +153,18 @@ export class DnsInstrumentation extends InstrumentationBase { if (error != null) { - utils.setError(error, span); + setError(error, span); span.end(); } } ); promise.then( result => { - utils.setLookupAttributes(span, result as LookupAddress); + setLookupAttributes(span, result as LookupAddress); span.end(); }, (e: NodeJS.ErrnoException) => { - utils.setError(e, span); + setError(e, span); span.end(); } ); @@ -187,9 +190,9 @@ export class DnsInstrumentation extends InstrumentationBase { - return service ? `dns.${service}/${funcName}` : `dns.${funcName}`; + return service ? `${service}/${funcName}` : `${funcName}`; }; export const setLookupAttributes = ( span: Span, - address: string | dns.LookupAddress[] | dns.LookupAddress, + address: string | LookupAddress[] | LookupAddress, family?: number ) => { const attributes = {} as Attributes; @@ -75,13 +75,13 @@ export const setLookupAttributes = ( let addresses = address; if (!isObject) { - addresses = [{ address, family } as dns.LookupAddress]; + addresses = [{ address, family } as LookupAddress]; } else if (!(addresses instanceof Array)) { addresses = [ { - address: (address as dns.LookupAddress).address, - family: (address as dns.LookupAddress).family, - } as dns.LookupAddress, + address: (address as LookupAddress).address, + family: (address as LookupAddress).family, + } as LookupAddress, ]; } diff --git a/plugins/node/opentelemetry-instrumentation-dns/test/functionals/dns-disable.test.ts b/plugins/node/opentelemetry-instrumentation-dns/test/functionals/dns-disable.test.ts index ddcf174127..834702f9eb 100644 --- a/plugins/node/opentelemetry-instrumentation-dns/test/functionals/dns-disable.test.ts +++ b/plugins/node/opentelemetry-instrumentation-dns/test/functionals/dns-disable.test.ts @@ -19,11 +19,11 @@ import { InMemorySpanExporter, SimpleSpanProcessor, } from '@opentelemetry/sdk-trace-base'; -import * as assert from 'assert'; +import { strictEqual, ok } from 'assert'; import { NodeTracerProvider } from '@opentelemetry/sdk-trace-node'; import { DnsInstrumentation } from '../../src'; -import * as Sinon from 'sinon'; -import * as dns from 'dns'; +import { spy, restore, SinonSpy } from 'sinon'; +import { lookup } from 'dns'; const memoryExporter = new InMemorySpanExporter(); const provider = new NodeTracerProvider(); @@ -37,16 +37,16 @@ describe('DnsInstrumentation', () => { instrumentation = new DnsInstrumentation(); instrumentation.setTracerProvider(provider); require('dns'); - assert.strictEqual(dns.lookup.__wrapped, true); + strictEqual(lookup.__wrapped, true); }); beforeEach(() => { - Sinon.spy(tracer, 'startSpan'); - Sinon.spy(context, 'with'); + spy(tracer, 'startSpan'); + spy(context, 'with'); }); afterEach(() => { - Sinon.restore(); + restore(); }); describe('unpatch()', () => { @@ -54,15 +54,15 @@ describe('DnsInstrumentation', () => { instrumentation.disable(); const hostname = 'localhost'; - dns.lookup(hostname, (err, address, family) => { - assert.ok(address); - assert.ok(family); + lookup(hostname, (err, address, family) => { + ok(address); + ok(family); const spans = memoryExporter.getFinishedSpans(); - assert.strictEqual(spans.length, 0); + strictEqual(spans.length, 0); - assert.strictEqual(dns.lookup.__wrapped, undefined); - assert.strictEqual((context.with as sinon.SinonSpy).called, false); + strictEqual(lookup.__wrapped, undefined); + strictEqual((context.with as SinonSpy).called, false); done(); }); }); diff --git a/plugins/node/opentelemetry-instrumentation-dns/test/functionals/utils.test.ts b/plugins/node/opentelemetry-instrumentation-dns/test/functionals/utils.test.ts index ccf94b8788..922a8f6d80 100644 --- a/plugins/node/opentelemetry-instrumentation-dns/test/functionals/utils.test.ts +++ b/plugins/node/opentelemetry-instrumentation-dns/test/functionals/utils.test.ts @@ -15,7 +15,7 @@ */ import { diag, Span, SpanStatusCode } from '@opentelemetry/api'; -import * as assert from 'assert'; +import { strictEqual, fail, doesNotThrow } from 'assert'; import * as sinon from 'sinon'; import { AttributeNames } from '../../src/enums/AttributeNames'; import { IgnoreMatcher } from '../../src/types'; @@ -25,24 +25,24 @@ describe('Utility', () => { describe('satisfiesPattern()', () => { it('string pattern', () => { const answer1 = utils.satisfiesPattern('localhost', 'localhost'); - assert.strictEqual(answer1, true); + strictEqual(answer1, true); const answer2 = utils.satisfiesPattern('hostname', 'localhost'); - assert.strictEqual(answer2, false); + strictEqual(answer2, false); }); it('regex pattern', () => { const answer1 = utils.satisfiesPattern('LocalHost', /localhost/i); - assert.strictEqual(answer1, true); + strictEqual(answer1, true); const answer2 = utils.satisfiesPattern('Montreal.ca', /montreal.ca/); - assert.strictEqual(answer2, false); + strictEqual(answer2, false); }); it('should throw if type is unknown', () => { try { utils.satisfiesPattern('google.com', true as unknown as IgnoreMatcher); - assert.fail(); + fail(); } catch (error) { - assert.strictEqual(error instanceof TypeError, true); + strictEqual(error instanceof TypeError, true); } }); @@ -51,12 +51,12 @@ describe('Utility', () => { 'montreal.ca', (url: string) => url === 'montreal.ca' ); - assert.strictEqual(answer1, true); + strictEqual(answer1, true); const answer2 = utils.satisfiesPattern( 'montreal.ca', (url: string) => url !== 'montreal.ca' ); - assert.strictEqual(answer2, false); + strictEqual(answer2, false); }); }); @@ -72,11 +72,8 @@ describe('Utility', () => { it('should call isSatisfyPattern, n match', () => { const answer1 = utils.isIgnored('localhost', ['test']); - assert.strictEqual(answer1, false); - assert.strictEqual( - (utils.satisfiesPattern as sinon.SinonSpy).callCount, - 1 - ); + strictEqual(answer1, false); + strictEqual((utils.satisfiesPattern as sinon.SinonSpy).callCount, 1); }); it('should call isSatisfyPattern, match for function', () => { @@ -84,14 +81,14 @@ describe('Utility', () => { const answer1 = utils.isIgnored('api.montreal.ca', [ url => url.endsWith('montreal.ca'), ]); - assert.strictEqual(answer1, true); + strictEqual(answer1, true); }); it('should call isSatisfyPattern, match for a single matcher', () => { const answer1 = utils.isIgnored('api.montreal.ca', url => url.endsWith('montreal.ca') ); - assert.strictEqual(answer1, true); + strictEqual(answer1, true); }); it('should not re-throw when function throws an exception', () => { @@ -100,7 +97,7 @@ describe('Utility', () => { diag.error('error', e); }; for (const callback of [undefined, onException]) { - assert.doesNotThrow(() => + doesNotThrow(() => utils.isIgnored( 'test', [ @@ -117,7 +114,7 @@ describe('Utility', () => { it('should call onException when function throws an exception', () => { satisfiesPatternStub.restore(); const onException = sinon.spy(); - assert.doesNotThrow(() => + doesNotThrow(() => utils.isIgnored( 'test', [ @@ -128,25 +125,22 @@ describe('Utility', () => { onException ) ); - assert.strictEqual((onException as sinon.SinonSpy).callCount, 1); + strictEqual((onException as sinon.SinonSpy).callCount, 1); }); it('should not call isSatisfyPattern', () => { utils.isIgnored('test', []); - assert.strictEqual( - (utils.satisfiesPattern as sinon.SinonSpy).callCount, - 0 - ); + strictEqual((utils.satisfiesPattern as sinon.SinonSpy).callCount, 0); }); it('should return false on empty list', () => { const answer1 = utils.isIgnored('test', []); - assert.strictEqual(answer1, false); + strictEqual(answer1, false); }); it('should not throw and return false when list is undefined', () => { const answer2 = utils.isIgnored('test', undefined); - assert.strictEqual(answer2, false); + strictEqual(answer2, false); }); }); diff --git a/plugins/node/opentelemetry-instrumentation-dns/test/integrations/dns-lookup.test.ts b/plugins/node/opentelemetry-instrumentation-dns/test/integrations/dns-lookup.test.ts index e17d8b06a2..d054e8c662 100644 --- a/plugins/node/opentelemetry-instrumentation-dns/test/integrations/dns-lookup.test.ts +++ b/plugins/node/opentelemetry-instrumentation-dns/test/integrations/dns-lookup.test.ts @@ -18,11 +18,11 @@ import { InMemorySpanExporter, SimpleSpanProcessor, } from '@opentelemetry/sdk-trace-base'; -import * as assert from 'assert'; +import { strictEqual, ok, fail } from 'assert'; import { NodeTracerProvider } from '@opentelemetry/sdk-trace-node'; import { DnsInstrumentation } from '../../src'; -import * as dns from 'dns'; -import * as utils from '../utils/utils'; +import { lookup, LookupAddress } from 'dns'; +import { checkInternet } from '../utils/utils'; import { assertSpan } from '../utils/assertSpan'; import { SpanStatusCode } from '@opentelemetry/api'; @@ -30,7 +30,7 @@ const memoryExporter = new InMemorySpanExporter(); const provider = new NodeTracerProvider(); provider.addSpanProcessor(new SimpleSpanProcessor(memoryExporter)); -describe('dns.lookup()', () => { +describe('lookup()', () => { let instrumentation: DnsInstrumentation; before(function (done) { @@ -43,7 +43,7 @@ describe('dns.lookup()', () => { return; } - utils.checkInternet(isConnected => { + checkInternet(isConnected => { if (!isConnected) { this.skip(); // don't disturb people @@ -67,14 +67,14 @@ describe('dns.lookup()', () => { [4, 6].forEach(ipversion => { it(`should export a valid span with "family" arg to ${ipversion}`, done => { const hostname = 'google.com'; - dns.lookup(hostname, ipversion, (err, address, family) => { - assert.strictEqual(err, null); - assert.ok(address); - assert.ok(family); + lookup(hostname, ipversion, (err, address, family) => { + strictEqual(err, null); + ok(address); + ok(family); const spans = memoryExporter.getFinishedSpans(); const [span] = spans; - assert.strictEqual(spans.length, 1); + strictEqual(spans.length, 1); assertSpan(span, { addresses: [{ address, family }], hostname }); done(); }); @@ -85,14 +85,14 @@ describe('dns.lookup()', () => { describe('with no options param', () => { it('should export a valid span', done => { const hostname = 'google.com'; - dns.lookup(hostname, (err, address, family) => { - assert.strictEqual(err, null); - assert.ok(address); - assert.ok(family); + lookup(hostname, (err, address, family) => { + strictEqual(err, null); + ok(address); + ok(family); const spans = memoryExporter.getFinishedSpans(); const [span] = spans; - assert.strictEqual(spans.length, 1); + strictEqual(spans.length, 1); assertSpan(span, { addresses: [{ address, family }], hostname }); done(); }); @@ -105,13 +105,13 @@ describe('dns.lookup()', () => { it('should export a valid span with error NOT_FOUND', done => { const hostname = 'áš•'; - dns.lookup(hostname, (err, address, family) => { - assert.ok(err); + lookup(hostname, (err, address, family) => { + ok(err); const spans = memoryExporter.getFinishedSpans(); const [span] = spans; - assert.strictEqual(spans.length, 1); + strictEqual(spans.length, 1); assertSpan(span, { addresses: [{ address, family }], hostname, @@ -128,12 +128,12 @@ describe('dns.lookup()', () => { it('should export a valid span with error INVALID_ARGUMENT when "family" param is equal to -1', () => { const hostname = 'google.com'; try { - dns.lookup(hostname, -1, () => {}); - assert.fail(); + lookup(hostname, -1, () => {}); + fail(); } catch (error: any) { const spans = memoryExporter.getFinishedSpans(); const [span] = spans; - assert.strictEqual(spans.length, 1); + strictEqual(spans.length, 1); assertSpan(span, { addresses: [], hostname, @@ -149,12 +149,12 @@ describe('dns.lookup()', () => { const hostname = 1234; try { // tslint:disable-next-line:no-any - dns.lookup(hostname as any, 4, () => {}); - assert.fail(); + lookup(hostname as any, 4, () => {}); + fail(); } catch (error: any) { const spans = memoryExporter.getFinishedSpans(); const [span] = spans; - assert.strictEqual(spans.length, 1); + strictEqual(spans.length, 1); assertSpan(span, { addresses: [], // tslint:disable-next-line:no-any @@ -171,14 +171,14 @@ describe('dns.lookup()', () => { [4, 6].forEach(family => { it(`should export a valid span with "family" to ${family}`, done => { const hostname = 'google.com'; - dns.lookup(hostname, { family }, (err, address, family) => { - assert.strictEqual(err, null); - assert.ok(address); - assert.ok(family); + lookup(hostname, { family }, (err, address, family) => { + strictEqual(err, null); + ok(address); + ok(family); const spans = memoryExporter.getFinishedSpans(); const [span] = spans; - assert.strictEqual(spans.length, 1); + strictEqual(spans.length, 1); assertSpan(span, { addresses: [{ address, family }], hostname }); done(); @@ -187,37 +187,33 @@ describe('dns.lookup()', () => { it(`should export a valid span when setting "verbatim" property to true and "family" to ${family}`, done => { const hostname = 'google.com'; - dns.lookup( - hostname, - { family, verbatim: true }, - (err, address, family) => { - assert.strictEqual(err, null); - assert.ok(address); - assert.ok(family); - - const spans = memoryExporter.getFinishedSpans(); - const [span] = spans; - assert.strictEqual(spans.length, 1); - - assertSpan(span, { addresses: [{ address, family }], hostname }); - done(); - } - ); + lookup(hostname, { family, verbatim: true }, (err, address, family) => { + strictEqual(err, null); + ok(address); + ok(family); + + const spans = memoryExporter.getFinishedSpans(); + const [span] = spans; + strictEqual(spans.length, 1); + + assertSpan(span, { addresses: [{ address, family }], hostname }); + done(); + }); }); }); it('should export a valid span when setting "all" property to true', done => { const hostname = 'montreal.ca'; - dns.lookup( + lookup( hostname, { all: true }, - (err: NodeJS.ErrnoException | null, addresses: dns.LookupAddress[]) => { - assert.strictEqual(err, null); - assert.ok(addresses instanceof Array); + (err: NodeJS.ErrnoException | null, addresses: LookupAddress[]) => { + strictEqual(err, null); + ok(addresses instanceof Array); const spans = memoryExporter.getFinishedSpans(); const [span] = spans; - assert.strictEqual(spans.length, 1); + strictEqual(spans.length, 1); assertSpan(span, { addresses, hostname }); done(); } diff --git a/plugins/node/opentelemetry-instrumentation-dns/test/integrations/dnspromise-lookup.test.ts b/plugins/node/opentelemetry-instrumentation-dns/test/integrations/dnspromise-lookup.test.ts index 1338f43bac..4b08a1bb49 100644 --- a/plugins/node/opentelemetry-instrumentation-dns/test/integrations/dnspromise-lookup.test.ts +++ b/plugins/node/opentelemetry-instrumentation-dns/test/integrations/dnspromise-lookup.test.ts @@ -18,11 +18,11 @@ import { InMemorySpanExporter, SimpleSpanProcessor, } from '@opentelemetry/sdk-trace-base'; -import * as assert from 'assert'; +import { strictEqual, ok, fail } from 'assert'; import { NodeTracerProvider } from '@opentelemetry/sdk-trace-node'; import { DnsInstrumentation } from '../../src'; -import * as dns from 'dns'; -import * as utils from '../utils/utils'; +import { promises } from 'dns'; +import { checkInternet } from '../utils/utils'; import { assertSpan } from '../utils/assertSpan'; import { SpanStatusCode } from '@opentelemetry/api'; @@ -30,7 +30,7 @@ const memoryExporter = new InMemorySpanExporter(); const provider = new NodeTracerProvider(); provider.addSpanProcessor(new SimpleSpanProcessor(memoryExporter)); -describe('dns.promises.lookup()', () => { +describe('promises.lookup()', () => { let instrumentation: DnsInstrumentation; before(function (done) { @@ -43,7 +43,7 @@ describe('dns.promises.lookup()', () => { return; } - utils.checkInternet(isConnected => { + checkInternet(isConnected => { if (!isConnected) { this.skip(); // don't disturb people @@ -67,15 +67,15 @@ describe('dns.promises.lookup()', () => { [4, 6].forEach(ipversion => { it(`should export a valid span with "family" arg to ${ipversion}`, async () => { const hostname = 'google.com'; - const { address, family } = await dns.promises.lookup(hostname, { + const { address, family } = await promises.lookup(hostname, { family: ipversion, }); - assert.ok(address); - assert.ok(family); + ok(address); + ok(family); const spans = memoryExporter.getFinishedSpans(); const [span] = spans; - assert.strictEqual(spans.length, 1); + strictEqual(spans.length, 1); assertSpan(span, { addresses: [{ address, family }], hostname }); }); }); @@ -84,14 +84,14 @@ describe('dns.promises.lookup()', () => { describe('with no options param', () => { it('should export a valid span', async () => { const hostname = 'google.com'; - const { address, family } = await dns.promises.lookup(hostname); + const { address, family } = await promises.lookup(hostname); - assert.ok(address); - assert.ok(family); + ok(address); + ok(family); const spans = memoryExporter.getFinishedSpans(); const [span] = spans; - assert.strictEqual(spans.length, 1); + strictEqual(spans.length, 1); assertSpan(span, { addresses: [{ address, family }], hostname }); }); @@ -103,13 +103,13 @@ describe('dns.promises.lookup()', () => { it('should export a valid span with error NOT_FOUND', async () => { const hostname = 'áš•'; try { - await dns.promises.lookup(hostname); - assert.fail(); + await promises.lookup(hostname); + fail(); } catch (error: any) { const spans = memoryExporter.getFinishedSpans(); const [span] = spans; - assert.strictEqual(spans.length, 1); + strictEqual(spans.length, 1); assertSpan(span, { addresses: [], hostname, @@ -125,13 +125,13 @@ describe('dns.promises.lookup()', () => { it('should export a valid span with error INVALID_ARGUMENT when "family" param is equal to -1', async () => { const hostname = 'google.com'; try { - await dns.promises.lookup(hostname, { family: -1 }); - assert.fail(); + await promises.lookup(hostname, { family: -1 }); + fail(); } catch (error: any) { const spans = memoryExporter.getFinishedSpans(); const [span] = spans; - assert.strictEqual(spans.length, 1); + strictEqual(spans.length, 1); assertSpan(span, { addresses: [], // tslint:disable-next-line:no-any @@ -147,13 +147,13 @@ describe('dns.promises.lookup()', () => { it('should export a valid span with error INVALID_ARGUMENT when "hostname" param is a number', async () => { const hostname = 1234; try { - await dns.promises.lookup(hostname as any, { family: 4 }); - assert.fail(); + await promises.lookup(hostname as any, { family: 4 }); + fail(); } catch (error: any) { const spans = memoryExporter.getFinishedSpans(); const [span] = spans; - assert.strictEqual(spans.length, 1); + strictEqual(spans.length, 1); assertSpan(span, { addresses: [], // tslint:disable-next-line:no-any @@ -170,33 +170,33 @@ describe('dns.promises.lookup()', () => { [4, 6].forEach(ipversion => { it(`should export a valid span with "family" to ${ipversion}`, async () => { const hostname = 'google.com'; - const { address, family } = await dns.promises.lookup(hostname, { + const { address, family } = await promises.lookup(hostname, { family: ipversion, }); - assert.ok(address); - assert.ok(family); + ok(address); + ok(family); const spans = memoryExporter.getFinishedSpans(); const [span] = spans; - assert.strictEqual(spans.length, 1); + strictEqual(spans.length, 1); assertSpan(span, { addresses: [{ address, family }], hostname }); }); it(`should export a valid span when setting "verbatim" property to true and "family" to ${ipversion}`, async () => { const hostname = 'google.com'; - const { address, family } = await dns.promises.lookup(hostname, { + const { address, family } = await promises.lookup(hostname, { family: ipversion, verbatim: true, }); - assert.ok(address); - assert.ok(family); + ok(address); + ok(family); const spans = memoryExporter.getFinishedSpans(); const [span] = spans; - assert.strictEqual(spans.length, 1); + strictEqual(spans.length, 1); assertSpan(span, { addresses: [{ address, family }], hostname }); }); @@ -204,13 +204,13 @@ describe('dns.promises.lookup()', () => { it('should export a valid span when setting "all" property to true', async () => { const hostname = 'montreal.ca'; - const addresses = await dns.promises.lookup(hostname, { all: true }); + const addresses = await promises.lookup(hostname, { all: true }); - assert.ok(addresses instanceof Array); + ok(addresses instanceof Array); const spans = memoryExporter.getFinishedSpans(); const [span] = spans; - assert.strictEqual(spans.length, 1); + strictEqual(spans.length, 1); assertSpan(span, { addresses, hostname }); }); }); diff --git a/plugins/node/opentelemetry-instrumentation-dns/test/utils/assertSpan.ts b/plugins/node/opentelemetry-instrumentation-dns/test/utils/assertSpan.ts index 15faefa34a..cbdc891fcf 100644 --- a/plugins/node/opentelemetry-instrumentation-dns/test/utils/assertSpan.ts +++ b/plugins/node/opentelemetry-instrumentation-dns/test/utils/assertSpan.ts @@ -17,7 +17,7 @@ import { SpanKind, SpanStatus, SpanStatusCode } from '@opentelemetry/api'; import { hrTimeToNanoseconds } from '@opentelemetry/core'; import { ReadableSpan } from '@opentelemetry/sdk-trace-base'; -import * as assert from 'assert'; +import { strictEqual, deepStrictEqual, ok } from 'assert'; import type { LookupAddress } from 'dns'; import { AttributeNames } from '../../src/enums/AttributeNames'; import * as utils from '../../src/utils'; @@ -31,34 +31,34 @@ export const assertSpan = ( } ) => { if (span.spanContext().traceId) { - assert.strictEqual(span.spanContext().traceId.length, 32); + strictEqual(span.spanContext().traceId.length, 32); } if (span.spanContext().spanId) { - assert.strictEqual(span.spanContext().spanId.length, 16); + strictEqual(span.spanContext().spanId.length, 16); } - assert.strictEqual(span.kind, SpanKind.CLIENT); + strictEqual(span.kind, SpanKind.CLIENT); - assert.strictEqual( + strictEqual( span.attributes[AttributeNames.DNS_ERROR_MESSAGE], span.status.message ); validations.addresses.forEach((_, i) => { - assert.strictEqual( + strictEqual( span.attributes[utils.getFamilyAttribute(_.family, i)], _.address ); }); - assert.ok(span.endTime); - assert.strictEqual(span.links.length, 0); - assert.strictEqual(span.events.length, 0); + ok(span.endTime); + strictEqual(span.links.length, 0); + strictEqual(span.events.length, 0); - assert.deepStrictEqual( + deepStrictEqual( span.status, validations.forceStatus || { code: SpanStatusCode.UNSET } ); - assert.ok(hrTimeToNanoseconds(span.duration), 'must have positive duration'); + ok(hrTimeToNanoseconds(span.duration), 'must have positive duration'); }; diff --git a/plugins/node/opentelemetry-instrumentation-dns/test/utils/utils.ts b/plugins/node/opentelemetry-instrumentation-dns/test/utils/utils.ts index a4e37eabea..6e88ca8d89 100644 --- a/plugins/node/opentelemetry-instrumentation-dns/test/utils/utils.ts +++ b/plugins/node/opentelemetry-instrumentation-dns/test/utils/utils.ts @@ -14,10 +14,10 @@ * limitations under the License. */ -import * as dns from 'dns'; +import { lookup } from 'dns'; export const checkInternet = (cb: (isConnected: boolean) => void) => { - dns.lookup('google.com', err => { + lookup('google.com', err => { if (err && err.code === 'ENOTFOUND') { cb(false); } else { diff --git a/plugins/node/opentelemetry-instrumentation-express/src/index.ts b/plugins/node/opentelemetry-instrumentation-express/src/index.ts index 79da17f7d5..56561ac72c 100644 --- a/plugins/node/opentelemetry-instrumentation-express/src/index.ts +++ b/plugins/node/opentelemetry-instrumentation-express/src/index.ts @@ -14,7 +14,14 @@ * limitations under the License. */ -export * from './instrumentation'; -export * from './enums/ExpressLayerType'; -export * from './enums/AttributeNames'; -export * from './types'; +export { ExpressInstrumentation } from './instrumentation'; +export { ExpressLayerType } from './enums/ExpressLayerType'; +export { AttributeNames } from './enums/AttributeNames'; +export { + LayerPathSegment, + IgnoreMatcher, + ExpressRequestInfo, + SpanNameHook, + ExpressRequestCustomAttributeFunction, + ExpressInstrumentationConfig, +} from './types'; diff --git a/plugins/node/opentelemetry-instrumentation-express/test/hooks.test.ts b/plugins/node/opentelemetry-instrumentation-express/test/hooks.test.ts index 78cfdd3d4a..2d0571cbac 100644 --- a/plugins/node/opentelemetry-instrumentation-express/test/hooks.test.ts +++ b/plugins/node/opentelemetry-instrumentation-express/test/hooks.test.ts @@ -21,9 +21,9 @@ import { InMemorySpanExporter, SimpleSpanProcessor, } from '@opentelemetry/sdk-trace-base'; -import * as assert from 'assert'; +import { strictEqual, notStrictEqual } from 'assert'; import type * as http from 'http'; -import * as sinon from 'sinon'; +import { spy, assert } from 'sinon'; import { ExpressInstrumentation } from '../src'; import { ExpressRequestInfo, SpanNameHook } from '../src/types'; import { ExpressLayerType } from '../src/enums/ExpressLayerType'; @@ -93,9 +93,9 @@ describe('ExpressInstrumentation hooks', () => { rootSpan.end(); const spans = memoryExporter.getFinishedSpans(); - assert.strictEqual(spans.length, 2); + strictEqual(spans.length, 2); - assert.notStrictEqual( + notStrictEqual( spans.find(span => span.name === 'custom: request_handler - *'), undefined ); @@ -117,10 +117,10 @@ describe('ExpressInstrumentation hooks', () => { rootSpan.end(); const spans = memoryExporter.getFinishedSpans(); - assert.strictEqual(spans.length, 2); + strictEqual(spans.length, 2); - assert.strictEqual(rpcMetadata?.route, '*'); - assert.notStrictEqual( + strictEqual(rpcMetadata?.route, '*'); + notStrictEqual( spans.find(span => span.name === 'request handler - *'), undefined ); @@ -143,10 +143,10 @@ describe('ExpressInstrumentation hooks', () => { rootSpan.end(); const spans = memoryExporter.getFinishedSpans(); - assert.strictEqual(spans.length, 2); + strictEqual(spans.length, 2); - assert.strictEqual(rpcMetadata?.route, '*'); - assert.notStrictEqual( + strictEqual(rpcMetadata?.route, '*'); + notStrictEqual( spans.find(span => span.name === 'request handler - *'), undefined ); @@ -177,7 +177,7 @@ describe('ExpressInstrumentation hooks', () => { }); it('should call requestHook when set in config', async () => { - const requestHook = sinon.spy((span: Span, info: ExpressRequestInfo) => { + const requestHook = spy((span: Span, info: ExpressRequestInfo) => { span.setAttribute(SEMATTRS_HTTP_METHOD, info.request.method); if (info.layerType) { @@ -200,13 +200,10 @@ describe('ExpressInstrumentation hooks', () => { span => span.name === 'request handler - *' ); - assert.strictEqual(spans.length, 2); - sinon.assert.calledOnce(requestHook); - assert.strictEqual( - requestHandlerSpan?.attributes['http.method'], - 'GET' - ); - assert.strictEqual( + strictEqual(spans.length, 2); + assert.calledOnce(requestHook); + strictEqual(requestHandlerSpan?.attributes['http.method'], 'GET'); + strictEqual( requestHandlerSpan?.attributes['express.layer_type'], ExpressLayerType.REQUEST_HANDLER ); @@ -215,7 +212,7 @@ describe('ExpressInstrumentation hooks', () => { }); it('should ignore requestHook which throws exception', async () => { - const requestHook = sinon.spy((span: Span, info: ExpressRequestInfo) => { + const requestHook = spy((span: Span, info: ExpressRequestInfo) => { // This is added before the exception is thrown thus we can expect it span.setAttribute('http.method', info.request.method); throw Error('error thrown in requestHook'); @@ -236,13 +233,10 @@ describe('ExpressInstrumentation hooks', () => { span => span.name === 'request handler - *' ); - assert.strictEqual(spans.length, 2); - assert.strictEqual( - requestHandlerSpan?.attributes['http.method'], - 'GET' - ); + strictEqual(spans.length, 2); + strictEqual(requestHandlerSpan?.attributes['http.method'], 'GET'); - sinon.assert.threw(requestHook); + assert.threw(requestHook); } ); }); diff --git a/plugins/node/opentelemetry-instrumentation-fastify/src/index.ts b/plugins/node/opentelemetry-instrumentation-fastify/src/index.ts index 958c8fef60..df9f9abd22 100644 --- a/plugins/node/opentelemetry-instrumentation-fastify/src/index.ts +++ b/plugins/node/opentelemetry-instrumentation-fastify/src/index.ts @@ -14,6 +14,14 @@ * limitations under the License. */ -export * from './enums/AttributeNames'; -export * from './types'; -export * from './instrumentation'; +export { + AttributeNames, + FastifyTypes, + FastifyNames, +} from './enums/AttributeNames'; +export { + FastifyRequestInfo, + FastifyCustomAttributeFunction, + FastifyInstrumentationConfig, +} from './types'; +export { ANONYMOUS_NAME, FastifyInstrumentation } from './instrumentation'; diff --git a/plugins/node/opentelemetry-instrumentation-fastify/test/instrumentation.test.ts b/plugins/node/opentelemetry-instrumentation-fastify/test/instrumentation.test.ts index 73fb586da1..f6a8fbe8ee 100644 --- a/plugins/node/opentelemetry-instrumentation-fastify/test/instrumentation.test.ts +++ b/plugins/node/opentelemetry-instrumentation-fastify/test/instrumentation.test.ts @@ -14,7 +14,7 @@ * limitations under the License. */ -import * as assert from 'assert'; +import { strictEqual, deepStrictEqual, ifError } from 'assert'; import { context, SpanStatusCode } from '@opentelemetry/api'; import { SEMATTRS_HTTP_ROUTE, @@ -34,7 +34,7 @@ import { TestCollector, } from '@opentelemetry/contrib-test-utils'; import * as semver from 'semver'; -import * as http from 'http'; +import { get, ClientRequestArgs } from 'http'; import { HttpInstrumentation } from '@opentelemetry/instrumentation-http'; import { AttributeNames, FastifyInstrumentation } from '../src'; import { FastifyRequestInfo } from '../src/types'; @@ -44,9 +44,9 @@ const URL = require('url').URL; const fastifyVersion = getPackageVersion('fastify'); const httpRequest = { - get: (options: http.ClientRequestArgs | string) => { + get: (options: ClientRequestArgs | string) => { return new Promise((resolve, reject) => { - return http.get(options, resp => { + return get(options, resp => { let data = ''; resp.on('data', chunk => { data += chunk; @@ -91,7 +91,7 @@ const assertRootContextActive = () => { // always work because of the linking and dep resolution. // Specially in our CI environment there can be multiple instances to // different @opentelemetry/api and thus ROOT_CONTEXTs in the tree. - assert.strictEqual((context.active() as any)['_currentContext'].size, 0); + strictEqual((context.active() as any)['_currentContext'].size, 0); }; function getSpans(): ReadableSpan[] { @@ -141,7 +141,7 @@ describe('fastify', () => { await httpRequest.get(`http://localhost:${PORT}/test`); const spans = getSpans(); - assert.strictEqual(spans.length, 0); // http instrumentation only + strictEqual(spans.length, 0); // http instrumentation only }); }); @@ -155,19 +155,16 @@ describe('fastify', () => { await httpRequest.get(`http://localhost:${PORT}/test`); const spans = memoryExporter.getFinishedSpans(); - assert.strictEqual(spans.length, 5); + strictEqual(spans.length, 5); const span = spans[2]; - assert.deepStrictEqual(span.attributes, { + deepStrictEqual(span.attributes, { 'fastify.type': 'request_handler', 'plugin.name': 'fastify -> @fastify/express', [SEMATTRS_HTTP_ROUTE]: '/test', }); - assert.strictEqual( - span.name, - 'request handler - fastify -> @fastify/express' - ); + strictEqual(span.name, 'request handler - fastify -> @fastify/express'); const baseSpan = spans[1]; - assert.strictEqual(span.parentSpanId, baseSpan.spanContext().spanId); + strictEqual(span.parentSpanId, baseSpan.spanContext().spanId); }); it('should generate span for named handler', async () => { @@ -180,18 +177,18 @@ describe('fastify', () => { await httpRequest.get(`http://localhost:${PORT}/test`); const spans = memoryExporter.getFinishedSpans(); - assert.strictEqual(spans.length, 5); + strictEqual(spans.length, 5); const span = spans[2]; - assert.deepStrictEqual(span.attributes, { + deepStrictEqual(span.attributes, { 'fastify.type': 'request_handler', 'fastify.name': 'namedHandler', 'plugin.name': 'fastify -> @fastify/express', [SEMATTRS_HTTP_ROUTE]: '/test', }); - assert.strictEqual(span.name, 'request handler - namedHandler'); + strictEqual(span.name, 'request handler - namedHandler'); const baseSpan = spans[1]; - assert.strictEqual(span.parentSpanId, baseSpan.spanContext().spanId); + strictEqual(span.parentSpanId, baseSpan.spanContext().spanId); }); it('should generate span for 404 request', async () => { @@ -199,16 +196,16 @@ describe('fastify', () => { await httpRequest.get(`http://localhost:${PORT}/no-such-route`); const spans = memoryExporter.getFinishedSpans(); - assert.strictEqual(spans.length, 5); + strictEqual(spans.length, 5); const span = spans[2]; - assert.deepStrictEqual(span.attributes, { + deepStrictEqual(span.attributes, { 'fastify.name': 'basic404', 'fastify.type': 'request_handler', 'plugin.name': 'fastify -> @fastify/express', }); - assert.strictEqual(span.name, 'request handler - basic404'); + strictEqual(span.name, 'request handler - basic404'); const baseSpan = spans[1]; - assert.strictEqual(span.parentSpanId, baseSpan.spanContext().spanId); + strictEqual(span.parentSpanId, baseSpan.spanContext().spanId); }); describe('when subsystem is registered', () => { @@ -243,91 +240,91 @@ describe('fastify', () => { await startServer(); await httpRequest.get(`http://localhost:${PORT}/test/1`); - assert.strictEqual(getSpans().length, 4); + strictEqual(getSpans().length, 4); }); it('should change name for parent http route', async () => { const spans = memoryExporter.getFinishedSpans(); - assert.strictEqual(spans.length, 6); + strictEqual(spans.length, 6); const changedRootSpan = spans[4]; const span = spans[3]; - assert.strictEqual(changedRootSpan.name, 'GET /test/:id'); - assert.strictEqual(span.name, 'request handler - foo'); - assert.strictEqual(span.parentSpanId, spans[2].spanContext().spanId); + strictEqual(changedRootSpan.name, 'GET /test/:id'); + strictEqual(span.name, 'request handler - foo'); + strictEqual(span.parentSpanId, spans[2].spanContext().spanId); }); it('should create span for fastify express runConnect', async () => { const spans = memoryExporter.getFinishedSpans(); - assert.strictEqual(spans.length, 6); + strictEqual(spans.length, 6); const baseSpan = spans[0]; const span = spans[1]; - assert.strictEqual(span.name, 'middleware - runConnect'); - assert.deepStrictEqual(span.attributes, { + strictEqual(span.name, 'middleware - runConnect'); + deepStrictEqual(span.attributes, { 'fastify.type': 'middleware', 'plugin.name': 'fastify -> @fastify/express', 'hook.name': 'onRequest', }); - assert.strictEqual(span.parentSpanId, baseSpan.spanContext().spanId); + strictEqual(span.parentSpanId, baseSpan.spanContext().spanId); }); it('should create span for fastify express for enhanceRequest', async () => { const spans = memoryExporter.getFinishedSpans(); - assert.strictEqual(spans.length, 6); + strictEqual(spans.length, 6); const baseSpan = spans[4]; const span = spans[0]; - assert.strictEqual(span.name, 'middleware - enhanceRequest'); - assert.deepStrictEqual(span.attributes, { + strictEqual(span.name, 'middleware - enhanceRequest'); + deepStrictEqual(span.attributes, { 'fastify.type': 'middleware', 'plugin.name': 'fastify -> @fastify/express', 'hook.name': 'onRequest', }); - assert.strictEqual(span.parentSpanId, baseSpan.spanContext().spanId); + strictEqual(span.parentSpanId, baseSpan.spanContext().spanId); }); it('should create span for request', async () => { const spans = memoryExporter.getFinishedSpans(); - assert.strictEqual(spans.length, 6); + strictEqual(spans.length, 6); const baseSpan = spans[2]; const span = spans[3]; - assert.strictEqual(span.name, 'request handler - foo'); - assert.deepStrictEqual(span.attributes, { + strictEqual(span.name, 'request handler - foo'); + deepStrictEqual(span.attributes, { 'plugin.name': 'subsystem', 'fastify.type': 'request_handler', 'fastify.name': 'foo', 'http.route': '/test/:id', }); - assert.strictEqual(span.parentSpanId, baseSpan.spanContext().spanId); + strictEqual(span.parentSpanId, baseSpan.spanContext().spanId); }); it('should update http.route for http span', async () => { const spans = memoryExporter.getFinishedSpans(); - assert.strictEqual(spans.length, 6); + strictEqual(spans.length, 6); const span = spans[4]; - assert.strictEqual(span.attributes['http.route'], '/test/:id'); + strictEqual(span.attributes['http.route'], '/test/:id'); }); it('should create span for subsystem anonymous middleware', async () => { const spans = memoryExporter.getFinishedSpans(); - assert.strictEqual(spans.length, 6); + strictEqual(spans.length, 6); const baseSpan = spans[1]; const span = spans[2]; - assert.strictEqual(span.name, 'middleware - subsystem'); - assert.deepStrictEqual(span.attributes, { + strictEqual(span.name, 'middleware - subsystem'); + deepStrictEqual(span.attributes, { 'fastify.type': 'middleware', 'plugin.name': 'subsystem', 'hook.name': 'onRequest', }); - assert.strictEqual(span.parentSpanId, baseSpan.spanContext().spanId); + strictEqual(span.parentSpanId, baseSpan.spanContext().spanId); }); it('should update span with error that was raised', async () => { @@ -335,14 +332,14 @@ describe('fastify', () => { await httpRequest.get(`http://localhost:${PORT}/test-error`); const spans = memoryExporter.getFinishedSpans(); - assert.strictEqual(spans.length, 6); + strictEqual(spans.length, 6); const span = spans[3]; - assert.strictEqual(span.name, 'request handler - subsystem'); - assert.deepStrictEqual(span.status, { + strictEqual(span.name, 'request handler - subsystem'); + deepStrictEqual(span.status, { code: SpanStatusCode.ERROR, message: 'foo', }); - assert.deepStrictEqual(span.attributes, { + deepStrictEqual(span.attributes, { 'fastify.type': 'request_handler', 'plugin.name': 'subsystem', 'http.route': '/test-error', @@ -376,14 +373,14 @@ describe('fastify', () => { !s.attributes[AttributeNames.PLUGIN_NAME] || s.attributes[AttributeNames.PLUGIN_NAME] === 'fastify' ); - assert.strictEqual(preDoneSpans.length, 0); + strictEqual(preDoneSpans.length, 0); hookDone!(); const postDoneSpans = getSpans().filter( s => !s.attributes[AttributeNames.PLUGIN_NAME] || s.attributes[AttributeNames.PLUGIN_NAME] === 'fastify' ); - assert.strictEqual(postDoneSpans.length, 1); + strictEqual(postDoneSpans.length, 1); }); it('span should end when calling reply.send from hook', async () => { @@ -409,7 +406,7 @@ describe('fastify', () => { !s.attributes[AttributeNames.PLUGIN_NAME] || s.attributes[AttributeNames.PLUGIN_NAME] === 'fastify' ); - assert.strictEqual(spans.length, 1); + strictEqual(spans.length, 1); }); }); }); @@ -417,7 +414,7 @@ describe('fastify', () => { describe('application hooks', () => { afterEach(() => { const spans = getSpans(); - assert.strictEqual(spans.length, 0); + strictEqual(spans.length, 0); }); it('onRoute not instrumented', async () => { @@ -493,9 +490,9 @@ describe('fastify', () => { await httpRequest.get(`http://localhost:${PORT}/test`); const spans = memoryExporter.getFinishedSpans(); - assert.strictEqual(spans.length, 5); + strictEqual(spans.length, 5); const span = spans[2]; - assert.deepStrictEqual(span.attributes, { + deepStrictEqual(span.attributes, { 'fastify.type': 'request_handler', 'plugin.name': 'fastify -> @fastify/express', [SEMATTRS_HTTP_ROUTE]: '/test', @@ -523,9 +520,9 @@ describe('fastify', () => { await httpRequest.get(`http://localhost:${PORT}/test`); const spans = memoryExporter.getFinishedSpans(); - assert.strictEqual(spans.length, 5); + strictEqual(spans.length, 5); const span = spans[2]; - assert.deepStrictEqual(span.attributes, { + deepStrictEqual(span.attributes, { 'fastify.type': 'request_handler', 'plugin.name': 'fastify -> @fastify/express', [SEMATTRS_HTTP_ROUTE]: '/test', @@ -545,13 +542,13 @@ describe('fastify', () => { NODE_NO_WARNINGS: '1', }, checkResult: (err, stdout, stderr) => { - assert.ifError(err); + ifError(err); }, checkCollector: (collector: TestCollector) => { const spans = collector.sortedSpans; - assert.strictEqual(spans.length, 1); - assert.strictEqual(spans[0].name, 'request handler - aRoute'); - assert.strictEqual( + strictEqual(spans.length, 1); + strictEqual(spans[0].name, 'request handler - aRoute'); + strictEqual( spans[0].attributes.filter(a => a.key === 'plugin.name')[0]?.value ?.stringValue, 'fastify', diff --git a/plugins/node/opentelemetry-instrumentation-generic-pool/src/index.ts b/plugins/node/opentelemetry-instrumentation-generic-pool/src/index.ts index 24c76056a1..7be22dd190 100644 --- a/plugins/node/opentelemetry-instrumentation-generic-pool/src/index.ts +++ b/plugins/node/opentelemetry-instrumentation-generic-pool/src/index.ts @@ -14,4 +14,4 @@ * limitations under the License. */ -export * from './instrumentation'; +export { GenericPoolInstrumentation } from './instrumentation'; diff --git a/plugins/node/opentelemetry-instrumentation-generic-pool/test/index.test.ts b/plugins/node/opentelemetry-instrumentation-generic-pool/test/index.test.ts index e2e634d4be..cbc50de124 100644 --- a/plugins/node/opentelemetry-instrumentation-generic-pool/test/index.test.ts +++ b/plugins/node/opentelemetry-instrumentation-generic-pool/test/index.test.ts @@ -27,7 +27,7 @@ const plugin = new GenericPoolInstrumentation(); import * as util from 'util'; import * as genericPool from 'generic-pool'; -import * as assert from 'assert'; +import { strictEqual } from 'assert'; import * as semver from 'semver'; const CLIENT = '_client_'; @@ -81,7 +81,7 @@ describe('GenericPool instrumentation', () => { acquire = createPool(); contextManager = new AsyncHooksContextManager(); context.setGlobalContextManager(contextManager.enable()); - assert.strictEqual(memoryExporter.getFinishedSpans().length, 0); + strictEqual(memoryExporter.getFinishedSpans().length, 0); }); afterEach(() => { @@ -91,30 +91,30 @@ describe('GenericPool instrumentation', () => { }); it('should create a span for acquire', async () => { - assert.strictEqual(await acquire(), CLIENT); + strictEqual(await acquire(), CLIENT); const [span] = memoryExporter.getFinishedSpans(); - assert.strictEqual(memoryExporter.getFinishedSpans().length, 1); - assert.strictEqual(span.name, 'generic-pool.acquire'); + strictEqual(memoryExporter.getFinishedSpans().length, 1); + strictEqual(span.name, 'generic-pool.acquire'); }); it('should attach it to the parent span', async () => { const rootSpan: any = tracer.startSpan('clientSpan'); await context.with(trace.setSpan(context.active(), rootSpan), async () => { - assert.strictEqual(await acquire(), CLIENT); + strictEqual(await acquire(), CLIENT); rootSpan.end(); - assert.strictEqual(memoryExporter.getFinishedSpans().length, 2); + strictEqual(memoryExporter.getFinishedSpans().length, 2); const [span] = memoryExporter.getFinishedSpans(); - assert.strictEqual(span.name, 'generic-pool.acquire'); - assert.strictEqual(span.parentSpanId, rootSpan.spanContext().spanId); + strictEqual(span.name, 'generic-pool.acquire'); + strictEqual(span.parentSpanId, rootSpan.spanContext().spanId); }); }); it('should not create anything if disabled', async () => { plugin.disable(); - assert.strictEqual(await acquire(), CLIENT); - assert.strictEqual(memoryExporter.getFinishedSpans().length, 0); + strictEqual(await acquire(), CLIENT); + strictEqual(memoryExporter.getFinishedSpans().length, 0); }); }); diff --git a/plugins/node/opentelemetry-instrumentation-graphql/src/index.ts b/plugins/node/opentelemetry-instrumentation-graphql/src/index.ts index c26f998cff..7756f2f9df 100644 --- a/plugins/node/opentelemetry-instrumentation-graphql/src/index.ts +++ b/plugins/node/opentelemetry-instrumentation-graphql/src/index.ts @@ -14,5 +14,9 @@ * limitations under the License. */ -export * from './instrumentation'; -export * from './types'; +export { GraphQLInstrumentation } from './instrumentation'; +export { + GraphQLInstrumentationExecutionResponseHook, + GraphQLInstrumentationConfig, + GraphQLInstrumentationParsedConfig, +} from './types'; diff --git a/plugins/node/opentelemetry-instrumentation-graphql/test/graphql.test.ts b/plugins/node/opentelemetry-instrumentation-graphql/test/graphql.test.ts index 661304a212..866f0aa0e8 100644 --- a/plugins/node/opentelemetry-instrumentation-graphql/test/graphql.test.ts +++ b/plugins/node/opentelemetry-instrumentation-graphql/test/graphql.test.ts @@ -22,7 +22,7 @@ import { } from '@opentelemetry/sdk-trace-base'; import { Span, SpanStatusCode } from '@opentelemetry/api'; import { SEMATTRS_EXCEPTION_MESSAGE } from '@opentelemetry/semantic-conventions'; -import * as assert from 'assert'; +import { deepEqual, deepStrictEqual, ok } from 'assert'; import type * as graphqlTypes from 'graphql'; import { GraphQLInstrumentation } from '../src'; import { SpanNames } from '../src/enum'; @@ -32,6 +32,7 @@ import { GraphQLInstrumentationExecutionResponseHook, } from '../src/types'; import { assertResolveSpan } from './helper'; +import assert = require('assert'); const defaultConfig: GraphQLInstrumentationConfig = {}; const graphQLInstrumentation = new GraphQLInstrumentation(defaultConfig); @@ -125,12 +126,12 @@ describe('graphql', () => { }); it('should have 7 spans', () => { - assert.deepStrictEqual(spans.length, 7); + deepStrictEqual(spans.length, 7); }); it('should instrument parse', () => { const parseSpan = spans[0]; - assert.deepStrictEqual( + deepStrictEqual( parseSpan.attributes[AttributeNames.SOURCE], '\n' + ' query {\n' + @@ -139,20 +140,20 @@ describe('graphql', () => { ' }\n' + ' }\n' ); - assert.deepStrictEqual(parseSpan.name, SpanNames.PARSE); + deepStrictEqual(parseSpan.name, SpanNames.PARSE); }); it('should instrument validate', () => { const validateSpan = spans[1]; - assert.deepStrictEqual(validateSpan.name, SpanNames.VALIDATE); - assert.deepStrictEqual(validateSpan.parentSpanId, undefined); + deepStrictEqual(validateSpan.name, SpanNames.VALIDATE); + deepStrictEqual(validateSpan.parentSpanId, undefined); }); it('should instrument execute', () => { const executeSpan = spans[6]; - assert.deepStrictEqual( + deepStrictEqual( executeSpan.attributes[AttributeNames.SOURCE], '\n' + ' query {\n' + @@ -161,16 +162,16 @@ describe('graphql', () => { ' }\n' + ' }\n' ); - assert.deepStrictEqual( + deepStrictEqual( executeSpan.attributes[AttributeNames.OPERATION_TYPE], 'query' ); - assert.deepStrictEqual( + deepStrictEqual( executeSpan.attributes[AttributeNames.OPERATION_NAME], undefined ); - assert.deepStrictEqual(executeSpan.name, 'query'); - assert.deepStrictEqual(executeSpan.parentSpanId, undefined); + deepStrictEqual(executeSpan.name, 'query'); + deepStrictEqual(executeSpan.parentSpanId, undefined); }); it('should instrument resolvers', () => { @@ -228,13 +229,13 @@ describe('graphql', () => { }; }); - assert.ok(times[PARSE].start <= times[PARSE].end); + ok(times[PARSE].start <= times[PARSE].end); // This next line is flaky. Parse sometimes ends after Validate starts. - assert.ok(times[PARSE].end <= times[VALIDATE].start); - assert.ok(times[VALIDATE].start <= times[VALIDATE].end); - assert.ok(times[VALIDATE].end <= times[EXECUTE].start); - assert.ok(times[EXECUTE].start <= times[RESOLVE].start); - assert.ok(times[RESOLVE].end <= times[EXECUTE].end); + ok(times[PARSE].end <= times[VALIDATE].start); + ok(times[VALIDATE].start <= times[VALIDATE].end); + ok(times[VALIDATE].end <= times[EXECUTE].start); + ok(times[EXECUTE].start <= times[RESOLVE].start); + ok(times[RESOLVE].end <= times[EXECUTE].end); }); }); describe('AND source is query with param', () => { @@ -253,12 +254,12 @@ describe('graphql', () => { }); it('should have 5 spans', () => { - assert.deepStrictEqual(spans.length, 5); + deepStrictEqual(spans.length, 5); }); it('should instrument parse', () => { const parseSpan = spans[0]; - assert.deepStrictEqual( + deepStrictEqual( parseSpan.attributes[AttributeNames.SOURCE], '\n' + ' query {\n' + @@ -267,20 +268,20 @@ describe('graphql', () => { ' }\n' + ' }\n' ); - assert.deepStrictEqual(parseSpan.name, SpanNames.PARSE); + deepStrictEqual(parseSpan.name, SpanNames.PARSE); }); it('should instrument validate', () => { const validateSpan = spans[1]; - assert.deepStrictEqual(validateSpan.name, SpanNames.VALIDATE); - assert.deepStrictEqual(validateSpan.parentSpanId, undefined); + deepStrictEqual(validateSpan.name, SpanNames.VALIDATE); + deepStrictEqual(validateSpan.parentSpanId, undefined); }); it('should instrument execute', () => { const executeSpan = spans[4]; - assert.deepStrictEqual( + deepStrictEqual( executeSpan.attributes[AttributeNames.SOURCE], '\n' + ' query {\n' + @@ -289,16 +290,16 @@ describe('graphql', () => { ' }\n' + ' }\n' ); - assert.deepStrictEqual( + deepStrictEqual( executeSpan.attributes[AttributeNames.OPERATION_TYPE], 'query' ); - assert.deepStrictEqual( + deepStrictEqual( executeSpan.attributes[AttributeNames.OPERATION_NAME], undefined ); - assert.deepStrictEqual(executeSpan.name, 'query'); - assert.deepStrictEqual(executeSpan.parentSpanId, undefined); + deepStrictEqual(executeSpan.name, 'query'); + deepStrictEqual(executeSpan.parentSpanId, undefined); }); it('should instrument resolvers', () => { @@ -347,12 +348,12 @@ describe('graphql', () => { }); it('should have 5 spans', () => { - assert.deepStrictEqual(spans.length, 5); + deepStrictEqual(spans.length, 5); }); it('should instrument parse', () => { const parseSpan = spans[0]; - assert.deepStrictEqual( + deepStrictEqual( parseSpan.attributes[AttributeNames.SOURCE], '\n' + ' query Query1 ($id: Int!) {\n' + @@ -361,20 +362,20 @@ describe('graphql', () => { ' }\n' + ' }\n' ); - assert.deepStrictEqual(parseSpan.name, SpanNames.PARSE); + deepStrictEqual(parseSpan.name, SpanNames.PARSE); }); it('should instrument validate', () => { const validateSpan = spans[1]; - assert.deepStrictEqual(validateSpan.name, SpanNames.VALIDATE); - assert.deepStrictEqual(validateSpan.parentSpanId, undefined); + deepStrictEqual(validateSpan.name, SpanNames.VALIDATE); + deepStrictEqual(validateSpan.parentSpanId, undefined); }); it('should instrument execute', () => { const executeSpan = spans[4]; - assert.deepStrictEqual( + deepStrictEqual( executeSpan.attributes[AttributeNames.SOURCE], '\n' + ' query Query1 ($id: Int!) {\n' + @@ -383,20 +384,20 @@ describe('graphql', () => { ' }\n' + ' }\n' ); - assert.deepStrictEqual( + deepStrictEqual( executeSpan.attributes[AttributeNames.OPERATION_TYPE], 'query' ); - assert.deepStrictEqual( + deepStrictEqual( executeSpan.attributes[AttributeNames.OPERATION_NAME], 'Query1' ); - assert.deepStrictEqual( + deepStrictEqual( executeSpan.attributes[`${AttributeNames.VARIABLES}id`], undefined ); - assert.deepStrictEqual(executeSpan.name, 'query Query1'); - assert.deepStrictEqual(executeSpan.parentSpanId, undefined); + deepStrictEqual(executeSpan.name, 'query Query1'); + deepStrictEqual(executeSpan.parentSpanId, undefined); }); it('should instrument resolvers', () => { @@ -443,12 +444,12 @@ describe('graphql', () => { }); it('should have 3 spans', () => { - assert.deepStrictEqual(spans.length, 3); + deepStrictEqual(spans.length, 3); }); it('should instrument parse', () => { const parseSpan = spans[0]; - assert.deepStrictEqual( + deepStrictEqual( parseSpan.attributes[AttributeNames.SOURCE], '\n' + ' query {\n' + @@ -457,20 +458,20 @@ describe('graphql', () => { ' }\n' + ' }\n' ); - assert.deepStrictEqual(parseSpan.name, SpanNames.PARSE); + deepStrictEqual(parseSpan.name, SpanNames.PARSE); }); it('should instrument validate', () => { const validateSpan = spans[1]; - assert.deepStrictEqual(validateSpan.name, SpanNames.VALIDATE); - assert.deepStrictEqual(validateSpan.parentSpanId, undefined); + deepStrictEqual(validateSpan.name, SpanNames.VALIDATE); + deepStrictEqual(validateSpan.parentSpanId, undefined); }); it('should instrument execute', () => { const executeSpan = spans[2]; - assert.deepStrictEqual( + deepStrictEqual( executeSpan.attributes[AttributeNames.SOURCE], '\n' + ' query {\n' + @@ -479,16 +480,16 @@ describe('graphql', () => { ' }\n' + ' }\n' ); - assert.deepStrictEqual( + deepStrictEqual( executeSpan.attributes[AttributeNames.OPERATION_TYPE], 'query' ); - assert.deepStrictEqual( + deepStrictEqual( executeSpan.attributes[AttributeNames.OPERATION_NAME], undefined ); - assert.deepStrictEqual(executeSpan.name, 'query'); - assert.deepStrictEqual(executeSpan.parentSpanId, undefined); + deepStrictEqual(executeSpan.name, 'query'); + deepStrictEqual(executeSpan.parentSpanId, undefined); }); }); }); @@ -511,12 +512,12 @@ describe('graphql', () => { }); it('should have 5 spans', () => { - assert.deepStrictEqual(spans.length, 5); + deepStrictEqual(spans.length, 5); }); it('should instrument parse', () => { const parseSpan = spans[0]; - assert.deepStrictEqual( + deepStrictEqual( parseSpan.attributes[AttributeNames.SOURCE], '\n' + ' query {\n' + @@ -525,20 +526,20 @@ describe('graphql', () => { ' }\n' + ' }\n' ); - assert.deepStrictEqual(parseSpan.name, SpanNames.PARSE); + deepStrictEqual(parseSpan.name, SpanNames.PARSE); }); it('should instrument validate', () => { const validateSpan = spans[1]; - assert.deepStrictEqual(validateSpan.name, SpanNames.VALIDATE); - assert.deepStrictEqual(validateSpan.parentSpanId, undefined); + deepStrictEqual(validateSpan.name, SpanNames.VALIDATE); + deepStrictEqual(validateSpan.parentSpanId, undefined); }); it('should instrument execute', () => { const executeSpan = spans[4]; - assert.deepStrictEqual( + deepStrictEqual( executeSpan.attributes[AttributeNames.SOURCE], '\n' + ' query {\n' + @@ -547,16 +548,16 @@ describe('graphql', () => { ' }\n' + ' }\n' ); - assert.deepStrictEqual( + deepStrictEqual( executeSpan.attributes[AttributeNames.OPERATION_TYPE], 'query' ); - assert.deepStrictEqual( + deepStrictEqual( executeSpan.attributes[AttributeNames.OPERATION_NAME], undefined ); - assert.deepStrictEqual(executeSpan.name, 'query'); - assert.deepStrictEqual(executeSpan.parentSpanId, undefined); + deepStrictEqual(executeSpan.name, 'query'); + deepStrictEqual(executeSpan.parentSpanId, undefined); }); }); @@ -578,7 +579,7 @@ describe('graphql', () => { }); it('should have 3 spans', () => { - assert.deepStrictEqual(spans.length, 3); + deepStrictEqual(spans.length, 3); }); }); }); @@ -614,7 +615,7 @@ describe('graphql', () => { const resolveSpans = exporter .getFinishedSpans() .filter(span => span.name === `${SpanNames.RESOLVE} hello`); - assert.deepStrictEqual(resolveSpans.length, 1); + deepStrictEqual(resolveSpans.length, 1); const resolveSpan = resolveSpans[0]; assert(resolveSpan.attributes[AttributeNames.FIELD_PATH] === 'hello'); }); @@ -634,7 +635,7 @@ describe('graphql', () => { const resolveSpans = exporter .getFinishedSpans() .filter(span => span.name === `${SpanNames.RESOLVE} hello`); - assert.deepStrictEqual(resolveSpans.length, 1); + deepStrictEqual(resolveSpans.length, 1); const resolveSpan = resolveSpans[0]; assert(resolveSpan.attributes[AttributeNames.FIELD_PATH] === 'hello'); }); @@ -654,7 +655,7 @@ describe('graphql', () => { const resolveSpans = exporter .getFinishedSpans() .filter(span => span.name === `${SpanNames.RESOLVE} hello`); - assert.deepStrictEqual(resolveSpans.length, 0); + deepStrictEqual(resolveSpans.length, 0); }); it('should create resolve span for custom field resolver', async () => { @@ -683,7 +684,7 @@ describe('graphql', () => { const resolveSpans = exporter .getFinishedSpans() .filter(span => span.name === `${SpanNames.RESOLVE} hello`); - assert.deepStrictEqual(resolveSpans.length, 1); + deepStrictEqual(resolveSpans.length, 1); const resolveSpan = resolveSpans[0]; assert(resolveSpan.attributes[AttributeNames.FIELD_PATH] === 'hello'); }); @@ -716,7 +717,7 @@ describe('graphql', () => { const resolveSpans = exporter .getFinishedSpans() .filter(span => span.name === `${SpanNames.RESOLVE} hello`); - assert.deepStrictEqual(resolveSpans.length, 0); + deepStrictEqual(resolveSpans.length, 0); }); }); @@ -739,12 +740,12 @@ describe('graphql', () => { }); it('should have 5 spans', () => { - assert.deepStrictEqual(spans.length, 5); + deepStrictEqual(spans.length, 5); }); it('should instrument parse', () => { const parseSpan = spans[0]; - assert.deepStrictEqual( + deepStrictEqual( parseSpan.attributes[AttributeNames.SOURCE], '\n' + ' query {\n' + @@ -753,20 +754,20 @@ describe('graphql', () => { ' }\n' + ' }\n' ); - assert.deepStrictEqual(parseSpan.name, SpanNames.PARSE); + deepStrictEqual(parseSpan.name, SpanNames.PARSE); }); it('should instrument validate', () => { const validateSpan = spans[1]; - assert.deepStrictEqual(validateSpan.name, SpanNames.VALIDATE); - assert.deepStrictEqual(validateSpan.parentSpanId, undefined); + deepStrictEqual(validateSpan.name, SpanNames.VALIDATE); + deepStrictEqual(validateSpan.parentSpanId, undefined); }); it('should instrument execute', () => { const executeSpan = spans[4]; - assert.deepStrictEqual( + deepStrictEqual( executeSpan.attributes[AttributeNames.SOURCE], '\n' + ' query {\n' + @@ -775,16 +776,16 @@ describe('graphql', () => { ' }\n' + ' }\n' ); - assert.deepStrictEqual( + deepStrictEqual( executeSpan.attributes[AttributeNames.OPERATION_TYPE], 'query' ); - assert.deepStrictEqual( + deepStrictEqual( executeSpan.attributes[AttributeNames.OPERATION_NAME], undefined ); - assert.deepStrictEqual(executeSpan.name, 'query'); - assert.deepStrictEqual(executeSpan.parentSpanId, undefined); + deepStrictEqual(executeSpan.name, 'query'); + deepStrictEqual(executeSpan.parentSpanId, undefined); }); it('should instrument resolvers', () => { @@ -829,12 +830,12 @@ describe('graphql', () => { }); it('should have 5 spans', () => { - assert.deepStrictEqual(spans.length, 5); + deepStrictEqual(spans.length, 5); }); it('should instrument parse', () => { const parseSpan = spans[0]; - assert.deepStrictEqual( + deepStrictEqual( parseSpan.attributes[AttributeNames.SOURCE], '\n' + ' mutation AddBook {\n' + @@ -846,20 +847,20 @@ describe('graphql', () => { ' }\n' + ' }\n' ); - assert.deepStrictEqual(parseSpan.name, SpanNames.PARSE); + deepStrictEqual(parseSpan.name, SpanNames.PARSE); }); it('should instrument validate', () => { const validateSpan = spans[1]; - assert.deepStrictEqual(validateSpan.name, SpanNames.VALIDATE); - assert.deepStrictEqual(validateSpan.parentSpanId, undefined); + deepStrictEqual(validateSpan.name, SpanNames.VALIDATE); + deepStrictEqual(validateSpan.parentSpanId, undefined); }); it('should instrument execute', () => { const executeSpan = spans[4]; - assert.deepStrictEqual( + deepStrictEqual( executeSpan.attributes[AttributeNames.SOURCE], '\n' + ' mutation AddBook {\n' + @@ -871,16 +872,16 @@ describe('graphql', () => { ' }\n' + ' }\n' ); - assert.deepStrictEqual( + deepStrictEqual( executeSpan.attributes[AttributeNames.OPERATION_TYPE], 'mutation' ); - assert.deepStrictEqual( + deepStrictEqual( executeSpan.attributes[AttributeNames.OPERATION_NAME], 'AddBook' ); - assert.deepStrictEqual(executeSpan.name, 'mutation AddBook'); - assert.deepStrictEqual(executeSpan.parentSpanId, undefined); + deepStrictEqual(executeSpan.name, 'mutation AddBook'); + deepStrictEqual(executeSpan.parentSpanId, undefined); }); it('should instrument resolvers', () => { @@ -929,12 +930,12 @@ describe('graphql', () => { }); it('should have 5 spans', () => { - assert.deepStrictEqual(spans.length, 5); + deepStrictEqual(spans.length, 5); }); it('should instrument parse', () => { const parseSpan = spans[0]; - assert.deepStrictEqual( + deepStrictEqual( parseSpan.attributes[AttributeNames.SOURCE], '\n' + ' query Query1 ($id: Int!) {\n' + @@ -943,20 +944,20 @@ describe('graphql', () => { ' }\n' + ' }\n' ); - assert.deepStrictEqual(parseSpan.name, SpanNames.PARSE); + deepStrictEqual(parseSpan.name, SpanNames.PARSE); }); it('should instrument validate', () => { const validateSpan = spans[1]; - assert.deepStrictEqual(validateSpan.name, SpanNames.VALIDATE); - assert.deepStrictEqual(validateSpan.parentSpanId, undefined); + deepStrictEqual(validateSpan.name, SpanNames.VALIDATE); + deepStrictEqual(validateSpan.parentSpanId, undefined); }); it('should instrument execute', () => { const executeSpan = spans[4]; - assert.deepStrictEqual( + deepStrictEqual( executeSpan.attributes[AttributeNames.SOURCE], '\n' + ' query Query1 ($id: Int!) {\n' + @@ -965,20 +966,20 @@ describe('graphql', () => { ' }\n' + ' }\n' ); - assert.deepStrictEqual( + deepStrictEqual( executeSpan.attributes[AttributeNames.OPERATION_TYPE], 'query' ); - assert.deepStrictEqual( + deepStrictEqual( executeSpan.attributes[AttributeNames.OPERATION_NAME], 'Query1' ); - assert.deepStrictEqual( + deepStrictEqual( executeSpan.attributes[`${AttributeNames.VARIABLES}id`], 2 ); - assert.deepStrictEqual(executeSpan.name, 'query Query1'); - assert.deepStrictEqual(executeSpan.parentSpanId, undefined); + deepStrictEqual(executeSpan.name, 'query Query1'); + deepStrictEqual(executeSpan.parentSpanId, undefined); }); it('should instrument resolvers', () => { @@ -1025,12 +1026,12 @@ describe('graphql', () => { }); it('should have 5 spans', () => { - assert.deepStrictEqual(spans.length, 5); + deepStrictEqual(spans.length, 5); }); it('should instrument parse', () => { const parseSpan = spans[0]; - assert.deepStrictEqual( + deepStrictEqual( parseSpan.attributes[AttributeNames.SOURCE], '\n' + ' mutation AddBook {\n' + @@ -1042,20 +1043,20 @@ describe('graphql', () => { ' }\n' + ' }\n' ); - assert.deepStrictEqual(parseSpan.name, SpanNames.PARSE); + deepStrictEqual(parseSpan.name, SpanNames.PARSE); }); it('should instrument validate', () => { const validateSpan = spans[1]; - assert.deepStrictEqual(validateSpan.name, SpanNames.VALIDATE); - assert.deepStrictEqual(validateSpan.parentSpanId, undefined); + deepStrictEqual(validateSpan.name, SpanNames.VALIDATE); + deepStrictEqual(validateSpan.parentSpanId, undefined); }); it('should instrument execute', () => { const executeSpan = spans[4]; - assert.deepStrictEqual( + deepStrictEqual( executeSpan.attributes[AttributeNames.SOURCE], '\n' + ' mutation AddBook {\n' + @@ -1067,16 +1068,16 @@ describe('graphql', () => { ' }\n' + ' }\n' ); - assert.deepStrictEqual( + deepStrictEqual( executeSpan.attributes[AttributeNames.OPERATION_TYPE], 'mutation' ); - assert.deepStrictEqual( + deepStrictEqual( executeSpan.attributes[AttributeNames.OPERATION_NAME], 'AddBook' ); - assert.deepStrictEqual(executeSpan.name, 'mutation AddBook'); - assert.deepStrictEqual(executeSpan.parentSpanId, undefined); + deepStrictEqual(executeSpan.name, 'mutation AddBook'); + deepStrictEqual(executeSpan.parentSpanId, undefined); }); it('should instrument resolvers', () => { @@ -1118,22 +1119,19 @@ describe('graphql', () => { }); it('should have 1 span', () => { - assert.deepStrictEqual(spans.length, 1); + deepStrictEqual(spans.length, 1); }); it('should instrument parse with error', () => { const parseSpan = spans[0]; const event = parseSpan.events[0]; - assert.ok(event); + ok(event); - assert.deepStrictEqual( - event.attributes!['exception.type'], - 'GraphQLError' - ); - assert.ok(event.attributes!['exception.message']); - assert.ok(event.attributes!['exception.stacktrace']); - assert.deepStrictEqual(parseSpan.name, SpanNames.PARSE); + deepStrictEqual(event.attributes!['exception.type'], 'GraphQLError'); + ok(event.attributes!['exception.message']); + ok(event.attributes!['exception.stacktrace']); + deepStrictEqual(parseSpan.name, SpanNames.PARSE); }); }); @@ -1153,12 +1151,12 @@ describe('graphql', () => { }); it('should have 2 spans', () => { - assert.deepStrictEqual(spans.length, 2); + deepStrictEqual(spans.length, 2); }); it('should instrument parse with error', () => { const parseSpan = spans[0]; - assert.deepStrictEqual( + deepStrictEqual( parseSpan.attributes[AttributeNames.SOURCE], '\n' + ' query {\n' + @@ -1167,22 +1165,22 @@ describe('graphql', () => { ' }\n' + ' }\n' ); - assert.deepStrictEqual(parseSpan.name, SpanNames.PARSE); + deepStrictEqual(parseSpan.name, SpanNames.PARSE); }); it('should instrument validate', () => { const validateSpan = spans[1]; - assert.deepStrictEqual(validateSpan.name, SpanNames.VALIDATE); - assert.deepStrictEqual(validateSpan.parentSpanId, undefined); + deepStrictEqual(validateSpan.name, SpanNames.VALIDATE); + deepStrictEqual(validateSpan.parentSpanId, undefined); const event = validateSpan.events[0]; - assert.deepStrictEqual(event.name, 'exception'); - assert.deepStrictEqual( + deepStrictEqual(event.name, 'exception'); + deepStrictEqual( event.attributes!['exception.type'], AttributeNames.ERROR_VALIDATION_NAME ); - assert.ok(event.attributes!['exception.message']); + ok(event.attributes!['exception.message']); }); }); @@ -1213,10 +1211,7 @@ describe('graphql', () => { span => span.attributes[AttributeNames.OPERATION_TYPE] === 'query' ); const instrumentationResult = querySpan?.attributes[dataAttributeName]; - assert.deepStrictEqual( - instrumentationResult, - JSON.stringify(graphqlResult) - ); + deepStrictEqual(instrumentationResult, JSON.stringify(graphqlResult)); }); }); @@ -1232,7 +1227,7 @@ describe('graphql', () => { }); it('should not do any harm', () => { - assert.deepStrictEqual(graphqlResult.data?.books?.length, 13); + deepStrictEqual(graphqlResult.data?.books?.length, 13); }); }); @@ -1249,7 +1244,7 @@ describe('graphql', () => { }); it('should not do any harm', () => { - assert.deepStrictEqual(graphqlResult.data?.books?.length, 13); + deepStrictEqual(graphqlResult.data?.books?.length, 13); }); }); }); @@ -1274,12 +1269,12 @@ describe('graphql', () => { }); it('should have 3 spans', () => { - assert.deepStrictEqual(spans.length, 3); + deepStrictEqual(spans.length, 3); }); it('should instrument parse with error', () => { const parseSpan = spans[0]; - assert.deepStrictEqual( + deepStrictEqual( parseSpan.attributes[AttributeNames.SOURCE], '\n' + ' query {\n' + @@ -1288,23 +1283,23 @@ describe('graphql', () => { ' }\n' + ' }\n' ); - assert.deepStrictEqual(parseSpan.name, SpanNames.PARSE); + deepStrictEqual(parseSpan.name, SpanNames.PARSE); }); it('should instrument validate', () => { const validateSpan = spans[1]; - assert.deepStrictEqual(validateSpan.name, SpanNames.VALIDATE); - assert.deepStrictEqual(validateSpan.parentSpanId, undefined); + deepStrictEqual(validateSpan.name, SpanNames.VALIDATE); + deepStrictEqual(validateSpan.parentSpanId, undefined); const event = validateSpan.events[0]; - assert.ok(!event); + ok(!event); }); it('should instrument execute', () => { const executeSpan = spans[2]; - assert.deepStrictEqual( + deepStrictEqual( executeSpan.attributes[AttributeNames.SOURCE], '\n' + ' query {\n' + @@ -1313,12 +1308,12 @@ describe('graphql', () => { ' }\n' + ' }\n' ); - assert.deepStrictEqual( + deepStrictEqual( executeSpan.attributes[AttributeNames.OPERATION_NAME], 'Operation "foo" not supported' ); - assert.deepStrictEqual(executeSpan.name, SpanNames.EXECUTE); - assert.deepStrictEqual(executeSpan.parentSpanId, undefined); + deepStrictEqual(executeSpan.name, SpanNames.EXECUTE); + deepStrictEqual(executeSpan.parentSpanId, undefined); }); }); @@ -1344,18 +1339,15 @@ describe('graphql', () => { const source = '{ hello }'; const res = graphqlSync({ schema: simpleSyncSchema, rootValue, source }); - assert.deepEqual(res.data, { hello: 'Hello world!' }); + deepEqual(res.data, { hello: 'Hello world!' }); // validate execute span is present const spans = exporter.getFinishedSpans(); const executeSpans = spans.filter(s => s.name === 'query'); - assert.deepStrictEqual(executeSpans.length, 1); + deepStrictEqual(executeSpans.length, 1); const [executeSpan] = executeSpans; - assert.deepStrictEqual( - executeSpan.attributes[AttributeNames.SOURCE], - source - ); - assert.deepStrictEqual( + deepStrictEqual(executeSpan.attributes[AttributeNames.SOURCE], source); + deepStrictEqual( executeSpan.attributes[AttributeNames.OPERATION_TYPE], 'query' ); @@ -1371,16 +1363,13 @@ describe('graphql', () => { // graphql will not throw, it will return "errors" in the result and the field will be null const res = graphqlSync({ schema: simpleSyncSchema, rootValue, source }); - assert.deepEqual(res.data, { hello: null }); + deepEqual(res.data, { hello: null }); // assert errors are returned correctly - assert.deepStrictEqual(res.errors?.length, 1); + deepStrictEqual(res.errors?.length, 1); const resolverError = res.errors?.[0]; - assert.deepStrictEqual(resolverError.path, ['hello']); - assert.deepStrictEqual( - resolverError.message, - 'sync resolver error from tests' - ); + deepStrictEqual(resolverError.path, ['hello']); + deepStrictEqual(resolverError.message, 'sync resolver error from tests'); // assert relevant spans are still created with error indications const spans = exporter.getFinishedSpans(); @@ -1389,23 +1378,23 @@ describe('graphql', () => { const resolveSpans = spans.filter( s => s.name === `${SpanNames.RESOLVE} hello` ); - assert.deepStrictEqual(resolveSpans.length, 1); + deepStrictEqual(resolveSpans.length, 1); const resolveSpan = resolveSpans[0]; - assert.deepStrictEqual(resolveSpan.status.code, SpanStatusCode.ERROR); - assert.deepStrictEqual( + deepStrictEqual(resolveSpan.status.code, SpanStatusCode.ERROR); + deepStrictEqual( resolveSpan.status.message, 'sync resolver error from tests' ); const resolveEvent = resolveSpan.events[0]; - assert.deepStrictEqual(resolveEvent.name, 'exception'); - assert.deepStrictEqual( + deepStrictEqual(resolveEvent.name, 'exception'); + deepStrictEqual( resolveEvent.attributes?.[SEMATTRS_EXCEPTION_MESSAGE], 'sync resolver error from tests' ); // single execute span const executeSpans = spans.filter(s => s.name === 'query'); - assert.deepStrictEqual(executeSpans.length, 1); + deepStrictEqual(executeSpans.length, 1); }); }); }); diff --git a/plugins/node/opentelemetry-instrumentation-graphql/test/helper.ts b/plugins/node/opentelemetry-instrumentation-graphql/test/helper.ts index 56ebe30fda..97593679ed 100644 --- a/plugins/node/opentelemetry-instrumentation-graphql/test/helper.ts +++ b/plugins/node/opentelemetry-instrumentation-graphql/test/helper.ts @@ -15,7 +15,7 @@ */ import { ReadableSpan } from '@opentelemetry/sdk-trace-base'; -import * as assert from 'assert'; +import { deepStrictEqual } from 'assert'; import { SpanNames } from '../src/enum'; import { AttributeNames } from '../src/enums/AttributeNames'; @@ -28,15 +28,15 @@ export function assertResolveSpan( parentSpanId?: string ) { const attrs = span.attributes; - assert.deepStrictEqual( + deepStrictEqual( span.name, `${SpanNames.RESOLVE} ${attrs[AttributeNames.FIELD_PATH]}` ); - assert.deepStrictEqual(attrs[AttributeNames.FIELD_NAME], fieldName); - assert.deepStrictEqual(attrs[AttributeNames.FIELD_PATH], fieldPath); - assert.deepStrictEqual(attrs[AttributeNames.FIELD_TYPE], fieldType); - assert.deepStrictEqual(attrs[AttributeNames.SOURCE], source); + deepStrictEqual(attrs[AttributeNames.FIELD_NAME], fieldName); + deepStrictEqual(attrs[AttributeNames.FIELD_PATH], fieldPath); + deepStrictEqual(attrs[AttributeNames.FIELD_TYPE], fieldType); + deepStrictEqual(attrs[AttributeNames.SOURCE], source); if (parentSpanId) { - assert.deepStrictEqual(span.parentSpanId, parentSpanId); + deepStrictEqual(span.parentSpanId, parentSpanId); } } diff --git a/plugins/node/opentelemetry-instrumentation-hapi/src/index.ts b/plugins/node/opentelemetry-instrumentation-hapi/src/index.ts index c464af622c..307f48d9fd 100644 --- a/plugins/node/opentelemetry-instrumentation-hapi/src/index.ts +++ b/plugins/node/opentelemetry-instrumentation-hapi/src/index.ts @@ -14,5 +14,5 @@ * limitations under the License. */ -export * from './instrumentation'; -export * from './enums/AttributeNames'; +export { HapiInstrumentation } from './instrumentation'; +export { AttributeNames } from './enums/AttributeNames'; diff --git a/plugins/node/opentelemetry-instrumentation-hapi/test/hapi-plugin.test.ts b/plugins/node/opentelemetry-instrumentation-hapi/test/hapi-plugin.test.ts index b2737b8b1d..c3c4bd3119 100644 --- a/plugins/node/opentelemetry-instrumentation-hapi/test/hapi-plugin.test.ts +++ b/plugins/node/opentelemetry-instrumentation-hapi/test/hapi-plugin.test.ts @@ -21,7 +21,7 @@ import { InMemorySpanExporter, SimpleSpanProcessor, } from '@opentelemetry/sdk-trace-base'; -import * as assert from 'assert'; +import { strictEqual, deepStrictEqual, notStrictEqual } from 'assert'; import { getPlugin } from './plugin'; const plugin = getPlugin(); import * as hapi from '@hapi/hapi'; @@ -121,7 +121,7 @@ describe('Hapi Instrumentation - Hapi.Plugin Tests', () => { }, }); await server.start(); - assert.strictEqual(memoryExporter.getFinishedSpans().length, 0); + strictEqual(memoryExporter.getFinishedSpans().length, 0); await context.with( trace.setSpan(context.active(), rootSpan), @@ -130,20 +130,20 @@ describe('Hapi Instrumentation - Hapi.Plugin Tests', () => { method: 'GET', url: '/test', }); - assert.strictEqual(res.statusCode, 200); + strictEqual(res.statusCode, 200); rootSpan.end(); - assert.deepStrictEqual(memoryExporter.getFinishedSpans().length, 2); + deepStrictEqual(memoryExporter.getFinishedSpans().length, 2); const requestHandlerSpan = memoryExporter .getFinishedSpans() .find(span => span.name === 'multipleVersionPlugin: route - /test'); - assert.notStrictEqual(requestHandlerSpan, undefined); - assert.strictEqual( + notStrictEqual(requestHandlerSpan, undefined); + strictEqual( requestHandlerSpan?.attributes[AttributeNames.HAPI_TYPE], HapiLayerType.PLUGIN ); - assert.strictEqual( + strictEqual( requestHandlerSpan?.attributes[AttributeNames.PLUGIN_NAME], 'multipleVersionPlugin' ); @@ -151,7 +151,7 @@ describe('Hapi Instrumentation - Hapi.Plugin Tests', () => { const exportedRootSpan = memoryExporter .getFinishedSpans() .find(span => span.name === 'rootSpan'); - assert.notStrictEqual(exportedRootSpan, undefined); + notStrictEqual(exportedRootSpan, undefined); } ); }); @@ -175,7 +175,7 @@ describe('Hapi Instrumentation - Hapi.Plugin Tests', () => { }, ]); await server.start(); - assert.strictEqual(memoryExporter.getFinishedSpans().length, 0); + strictEqual(memoryExporter.getFinishedSpans().length, 0); await context.with( trace.setSpan(context.active(), rootSpan), @@ -184,38 +184,38 @@ describe('Hapi Instrumentation - Hapi.Plugin Tests', () => { method: 'GET', url: '/test', }); - assert.strictEqual(res1.statusCode, 200); + strictEqual(res1.statusCode, 200); const res2 = await server.inject({ method: 'GET', url: '/hello', }); - assert.strictEqual(res2.statusCode, 200); + strictEqual(res2.statusCode, 200); rootSpan.end(); - assert.deepStrictEqual(memoryExporter.getFinishedSpans().length, 3); + deepStrictEqual(memoryExporter.getFinishedSpans().length, 3); const firstHandlerSpan = memoryExporter .getFinishedSpans() .find(span => span.name === 'multipleVersionPlugin: route - /test'); - assert.notStrictEqual(firstHandlerSpan, undefined); - assert.strictEqual( + notStrictEqual(firstHandlerSpan, undefined); + strictEqual( firstHandlerSpan?.attributes[AttributeNames.HAPI_TYPE], HapiLayerType.PLUGIN ); - assert.strictEqual( + strictEqual( firstHandlerSpan?.attributes[AttributeNames.PLUGIN_NAME], 'multipleVersionPlugin' ); const secondHandlerSpan = memoryExporter .getFinishedSpans() .find(span => span.name === 'simplePlugin: route - /hello'); - assert.notStrictEqual(secondHandlerSpan, undefined); - assert.strictEqual( + notStrictEqual(secondHandlerSpan, undefined); + strictEqual( secondHandlerSpan?.attributes[AttributeNames.HAPI_TYPE], HapiLayerType.PLUGIN ); - assert.strictEqual( + strictEqual( secondHandlerSpan?.attributes[AttributeNames.PLUGIN_NAME], 'simplePlugin' ); @@ -223,7 +223,7 @@ describe('Hapi Instrumentation - Hapi.Plugin Tests', () => { const exportedRootSpan = memoryExporter .getFinishedSpans() .find(span => span.name === 'rootSpan'); - assert.notStrictEqual(exportedRootSpan, undefined); + notStrictEqual(exportedRootSpan, undefined); } ); }); @@ -233,7 +233,7 @@ describe('Hapi Instrumentation - Hapi.Plugin Tests', () => { await server.register([packagePlugin, simplePlugin]); await server.start(); - assert.strictEqual(memoryExporter.getFinishedSpans().length, 0); + strictEqual(memoryExporter.getFinishedSpans().length, 0); await context.with( trace.setSpan(context.active(), rootSpan), @@ -242,38 +242,38 @@ describe('Hapi Instrumentation - Hapi.Plugin Tests', () => { method: 'GET', url: '/package', }); - assert.strictEqual(res1.statusCode, 200); + strictEqual(res1.statusCode, 200); const res2 = await server.inject({ method: 'GET', url: '/hello', }); - assert.strictEqual(res2.statusCode, 200); + strictEqual(res2.statusCode, 200); rootSpan.end(); - assert.deepStrictEqual(memoryExporter.getFinishedSpans().length, 3); + deepStrictEqual(memoryExporter.getFinishedSpans().length, 3); const firstHandlerSpan = memoryExporter .getFinishedSpans() .find(span => span.name === 'plugin-by-package: route - /package'); - assert.notStrictEqual(firstHandlerSpan, undefined); - assert.strictEqual( + notStrictEqual(firstHandlerSpan, undefined); + strictEqual( firstHandlerSpan?.attributes[AttributeNames.HAPI_TYPE], HapiLayerType.PLUGIN ); - assert.strictEqual( + strictEqual( firstHandlerSpan?.attributes[AttributeNames.PLUGIN_NAME], 'plugin-by-package' ); const secondHandlerSpan = memoryExporter .getFinishedSpans() .find(span => span.name === 'simplePlugin: route - /hello'); - assert.notStrictEqual(secondHandlerSpan, undefined); - assert.strictEqual( + notStrictEqual(secondHandlerSpan, undefined); + strictEqual( secondHandlerSpan?.attributes[AttributeNames.HAPI_TYPE], HapiLayerType.PLUGIN ); - assert.strictEqual( + strictEqual( secondHandlerSpan?.attributes[AttributeNames.PLUGIN_NAME], 'simplePlugin' ); @@ -281,7 +281,7 @@ describe('Hapi Instrumentation - Hapi.Plugin Tests', () => { const exportedRootSpan = memoryExporter .getFinishedSpans() .find(span => span.name === 'rootSpan'); - assert.notStrictEqual(exportedRootSpan, undefined); + notStrictEqual(exportedRootSpan, undefined); } ); }); @@ -306,7 +306,7 @@ describe('Hapi Instrumentation - Hapi.Plugin Tests', () => { }, ]); await server.start(); - assert.strictEqual(memoryExporter.getFinishedSpans().length, 0); + strictEqual(memoryExporter.getFinishedSpans().length, 0); await context.with( trace.setSpan(context.active(), rootSpan), @@ -315,26 +315,26 @@ describe('Hapi Instrumentation - Hapi.Plugin Tests', () => { method: 'GET', url: '/test', }); - assert.strictEqual(res1.statusCode, 200); + strictEqual(res1.statusCode, 200); const res2 = await server.inject({ method: 'GET', url: '/test2', }); - assert.strictEqual(res2.statusCode, 200); + strictEqual(res2.statusCode, 200); rootSpan.end(); - assert.deepStrictEqual(memoryExporter.getFinishedSpans().length, 3); + deepStrictEqual(memoryExporter.getFinishedSpans().length, 3); const firstHandlerSpan = memoryExporter .getFinishedSpans() .find(span => span.name === 'multipleVersionPlugin: route - /test'); - assert.notStrictEqual(firstHandlerSpan, undefined); - assert.strictEqual( + notStrictEqual(firstHandlerSpan, undefined); + strictEqual( firstHandlerSpan?.attributes[AttributeNames.HAPI_TYPE], HapiLayerType.PLUGIN ); - assert.strictEqual( + strictEqual( firstHandlerSpan?.attributes[AttributeNames.PLUGIN_NAME], 'multipleVersionPlugin' ); @@ -343,12 +343,12 @@ describe('Hapi Instrumentation - Hapi.Plugin Tests', () => { .find( span => span.name === 'multipleVersionPlugin: route - /test2' ); - assert.notStrictEqual(secondHandlerSpan, undefined); - assert.strictEqual( + notStrictEqual(secondHandlerSpan, undefined); + strictEqual( secondHandlerSpan?.attributes[AttributeNames.HAPI_TYPE], HapiLayerType.PLUGIN ); - assert.strictEqual( + strictEqual( secondHandlerSpan?.attributes[AttributeNames.PLUGIN_NAME], 'multipleVersionPlugin' ); @@ -356,7 +356,7 @@ describe('Hapi Instrumentation - Hapi.Plugin Tests', () => { const exportedRootSpan = memoryExporter .getFinishedSpans() .find(span => span.name === 'rootSpan'); - assert.notStrictEqual(exportedRootSpan, undefined); + notStrictEqual(exportedRootSpan, undefined); } ); }); @@ -369,7 +369,7 @@ describe('Hapi Instrumentation - Hapi.Plugin Tests', () => { plugin: packagePlugin, }); await server.start(); - assert.strictEqual(memoryExporter.getFinishedSpans().length, 0); + strictEqual(memoryExporter.getFinishedSpans().length, 0); await context.with( trace.setSpan(context.active(), rootSpan), @@ -378,22 +378,22 @@ describe('Hapi Instrumentation - Hapi.Plugin Tests', () => { method: 'GET', url: '/package', }); - assert.strictEqual(res.statusCode, 200); + strictEqual(res.statusCode, 200); rootSpan.end(); - assert.deepStrictEqual(memoryExporter.getFinishedSpans().length, 2); + deepStrictEqual(memoryExporter.getFinishedSpans().length, 2); const requestHandlerSpan = memoryExporter .getFinishedSpans() .find( span => span.name === 'plugin-by-package: route - /package' ); - assert.notStrictEqual(requestHandlerSpan, undefined); - assert.strictEqual( + notStrictEqual(requestHandlerSpan, undefined); + strictEqual( requestHandlerSpan?.attributes[AttributeNames.HAPI_TYPE], HapiLayerType.PLUGIN ); - assert.strictEqual( + strictEqual( requestHandlerSpan?.attributes[AttributeNames.PLUGIN_NAME], 'plugin-by-package' ); @@ -401,7 +401,7 @@ describe('Hapi Instrumentation - Hapi.Plugin Tests', () => { const exportedRootSpan = memoryExporter .getFinishedSpans() .find(span => span.name === 'rootSpan'); - assert.notStrictEqual(exportedRootSpan, undefined); + notStrictEqual(exportedRootSpan, undefined); } ); }); @@ -414,7 +414,7 @@ describe('Hapi Instrumentation - Hapi.Plugin Tests', () => { plugin: nestedPackagePlugin as any, }); await server.start(); - assert.strictEqual(memoryExporter.getFinishedSpans().length, 0); + strictEqual(memoryExporter.getFinishedSpans().length, 0); await context.with( trace.setSpan(context.active(), rootSpan), @@ -423,22 +423,22 @@ describe('Hapi Instrumentation - Hapi.Plugin Tests', () => { method: 'GET', url: '/package', }); - assert.strictEqual(res.statusCode, 200); + strictEqual(res.statusCode, 200); rootSpan.end(); - assert.deepStrictEqual(memoryExporter.getFinishedSpans().length, 2); + deepStrictEqual(memoryExporter.getFinishedSpans().length, 2); const requestHandlerSpan = memoryExporter .getFinishedSpans() .find( span => span.name === 'plugin-by-package: route - /package' ); - assert.notStrictEqual(requestHandlerSpan, undefined); - assert.strictEqual( + notStrictEqual(requestHandlerSpan, undefined); + strictEqual( requestHandlerSpan?.attributes[AttributeNames.HAPI_TYPE], HapiLayerType.PLUGIN ); - assert.strictEqual( + strictEqual( requestHandlerSpan?.attributes[AttributeNames.PLUGIN_NAME], 'plugin-by-package' ); @@ -446,7 +446,7 @@ describe('Hapi Instrumentation - Hapi.Plugin Tests', () => { const exportedRootSpan = memoryExporter .getFinishedSpans() .find(span => span.name === 'rootSpan'); - assert.notStrictEqual(exportedRootSpan, undefined); + notStrictEqual(exportedRootSpan, undefined); } ); }); @@ -458,7 +458,7 @@ describe('Hapi Instrumentation - Hapi.Plugin Tests', () => { // Suppress this ts error due the Hapi plugin type definition is incomplete. server.register can accept nested plugin. See reference https://hapi.dev/api/?v=20.0.0#-routeoptionshandler await server.register(packagePlugin); await server.start(); - assert.strictEqual(memoryExporter.getFinishedSpans().length, 0); + strictEqual(memoryExporter.getFinishedSpans().length, 0); await context.with( trace.setSpan(context.active(), rootSpan), @@ -467,22 +467,22 @@ describe('Hapi Instrumentation - Hapi.Plugin Tests', () => { method: 'GET', url: '/package', }); - assert.strictEqual(res.statusCode, 200); + strictEqual(res.statusCode, 200); rootSpan.end(); - assert.deepStrictEqual(memoryExporter.getFinishedSpans().length, 2); + deepStrictEqual(memoryExporter.getFinishedSpans().length, 2); const requestHandlerSpan = memoryExporter .getFinishedSpans() .find( span => span.name === 'plugin-by-package: route - /package' ); - assert.notStrictEqual(requestHandlerSpan, undefined); - assert.strictEqual( + notStrictEqual(requestHandlerSpan, undefined); + strictEqual( requestHandlerSpan?.attributes[AttributeNames.HAPI_TYPE], HapiLayerType.PLUGIN ); - assert.strictEqual( + strictEqual( requestHandlerSpan?.attributes[AttributeNames.PLUGIN_NAME], 'plugin-by-package' ); @@ -490,7 +490,7 @@ describe('Hapi Instrumentation - Hapi.Plugin Tests', () => { const exportedRootSpan = memoryExporter .getFinishedSpans() .find(span => span.name === 'rootSpan'); - assert.notStrictEqual(exportedRootSpan, undefined); + notStrictEqual(exportedRootSpan, undefined); } ); }); diff --git a/plugins/node/opentelemetry-instrumentation-hapi/test/hapi-server-ext.test.ts b/plugins/node/opentelemetry-instrumentation-hapi/test/hapi-server-ext.test.ts index 529df11299..0319829561 100644 --- a/plugins/node/opentelemetry-instrumentation-hapi/test/hapi-server-ext.test.ts +++ b/plugins/node/opentelemetry-instrumentation-hapi/test/hapi-server-ext.test.ts @@ -21,7 +21,7 @@ import { InMemorySpanExporter, SimpleSpanProcessor, } from '@opentelemetry/sdk-trace-base'; -import * as assert from 'assert'; +import { strictEqual, deepStrictEqual, notStrictEqual } from 'assert'; import { getPlugin } from './plugin'; const plugin = getPlugin(); @@ -72,7 +72,7 @@ describe('Hapi Instrumentation - Server.Ext Tests', () => { return h.continue; }); await server.start(); - assert.strictEqual(memoryExporter.getFinishedSpans().length, 0); + strictEqual(memoryExporter.getFinishedSpans().length, 0); await context.with( trace.setSpan(context.active(), rootSpan), @@ -81,19 +81,19 @@ describe('Hapi Instrumentation - Server.Ext Tests', () => { method: 'GET', url: '/test', }); - assert.strictEqual(res.statusCode, 200); + strictEqual(res.statusCode, 200); rootSpan.end(); - assert.deepStrictEqual(memoryExporter.getFinishedSpans().length, 3); + deepStrictEqual(memoryExporter.getFinishedSpans().length, 3); const extHandlerSpan = memoryExporter .getFinishedSpans() .find(span => span.name === 'ext - onRequest'); - assert.notStrictEqual(extHandlerSpan, undefined); - assert.strictEqual( + notStrictEqual(extHandlerSpan, undefined); + strictEqual( extHandlerSpan?.attributes[AttributeNames.HAPI_TYPE], HapiLayerType.EXT ); - assert.strictEqual( + strictEqual( extHandlerSpan?.attributes[AttributeNames.EXT_TYPE], 'onRequest' ); @@ -101,7 +101,7 @@ describe('Hapi Instrumentation - Server.Ext Tests', () => { const exportedRootSpan = memoryExporter .getFinishedSpans() .find(span => span.name === 'rootSpan'); - assert.notStrictEqual(exportedRootSpan, undefined); + notStrictEqual(exportedRootSpan, undefined); } ); }); @@ -116,7 +116,7 @@ describe('Hapi Instrumentation - Server.Ext Tests', () => { }; server.ext(extension); await server.start(); - assert.strictEqual(memoryExporter.getFinishedSpans().length, 0); + strictEqual(memoryExporter.getFinishedSpans().length, 0); await context.with( trace.setSpan(context.active(), rootSpan), @@ -125,19 +125,19 @@ describe('Hapi Instrumentation - Server.Ext Tests', () => { method: 'GET', url: '/test', }); - assert.strictEqual(res.statusCode, 200); + strictEqual(res.statusCode, 200); rootSpan.end(); - assert.deepStrictEqual(memoryExporter.getFinishedSpans().length, 3); + deepStrictEqual(memoryExporter.getFinishedSpans().length, 3); const extHandlerSpan = memoryExporter .getFinishedSpans() .find(span => span.name === 'ext - onRequest'); - assert.notStrictEqual(extHandlerSpan, undefined); - assert.strictEqual( + notStrictEqual(extHandlerSpan, undefined); + strictEqual( extHandlerSpan?.attributes[AttributeNames.HAPI_TYPE], HapiLayerType.EXT ); - assert.strictEqual( + strictEqual( extHandlerSpan?.attributes[AttributeNames.EXT_TYPE], 'onRequest' ); @@ -145,7 +145,7 @@ describe('Hapi Instrumentation - Server.Ext Tests', () => { const exportedRootSpan = memoryExporter .getFinishedSpans() .find(span => span.name === 'rootSpan'); - assert.notStrictEqual(exportedRootSpan, undefined); + notStrictEqual(exportedRootSpan, undefined); } ); }); @@ -165,7 +165,7 @@ describe('Hapi Instrumentation - Server.Ext Tests', () => { }; server.ext(extension); await server.start(); - assert.strictEqual(memoryExporter.getFinishedSpans().length, 0); + strictEqual(memoryExporter.getFinishedSpans().length, 0); await context.with( trace.setSpan(context.active(), rootSpan), @@ -174,30 +174,30 @@ describe('Hapi Instrumentation - Server.Ext Tests', () => { method: 'GET', url: '/test', }); - assert.strictEqual(res.statusCode, 200); + strictEqual(res.statusCode, 200); rootSpan.end(); - assert.deepStrictEqual(memoryExporter.getFinishedSpans().length, 4); + deepStrictEqual(memoryExporter.getFinishedSpans().length, 4); const extHandlerSpans = memoryExporter .getFinishedSpans() .filter(span => span.name === 'ext - onRequest'); - assert.notStrictEqual(extHandlerSpans, undefined); - assert.strictEqual(extHandlerSpans.length, 2); + notStrictEqual(extHandlerSpans, undefined); + strictEqual(extHandlerSpans.length, 2); - assert.strictEqual( + strictEqual( extHandlerSpans[0]?.attributes[AttributeNames.HAPI_TYPE], HapiLayerType.EXT ); - assert.strictEqual( + strictEqual( extHandlerSpans[0]?.attributes[AttributeNames.EXT_TYPE], 'onRequest' ); - assert.strictEqual( + strictEqual( extHandlerSpans[1]?.attributes[AttributeNames.HAPI_TYPE], HapiLayerType.EXT ); - assert.strictEqual( + strictEqual( extHandlerSpans[1]?.attributes[AttributeNames.EXT_TYPE], 'onRequest' ); @@ -205,7 +205,7 @@ describe('Hapi Instrumentation - Server.Ext Tests', () => { const exportedRootSpan = memoryExporter .getFinishedSpans() .find(span => span.name === 'rootSpan'); - assert.notStrictEqual(exportedRootSpan, undefined); + notStrictEqual(exportedRootSpan, undefined); } ); }); @@ -228,7 +228,7 @@ describe('Hapi Instrumentation - Server.Ext Tests', () => { ]; server.ext(extensions); await server.start(); - assert.strictEqual(memoryExporter.getFinishedSpans().length, 0); + strictEqual(memoryExporter.getFinishedSpans().length, 0); await context.with( trace.setSpan(context.active(), rootSpan), @@ -237,19 +237,19 @@ describe('Hapi Instrumentation - Server.Ext Tests', () => { method: 'GET', url: '/test', }); - assert.strictEqual(res.statusCode, 200); + strictEqual(res.statusCode, 200); rootSpan.end(); - assert.deepStrictEqual(memoryExporter.getFinishedSpans().length, 4); + deepStrictEqual(memoryExporter.getFinishedSpans().length, 4); const firstExtHandlerSpan = memoryExporter .getFinishedSpans() .find(span => span.name === 'ext - onRequest'); - assert.notStrictEqual(firstExtHandlerSpan, undefined); - assert.strictEqual( + notStrictEqual(firstExtHandlerSpan, undefined); + strictEqual( firstExtHandlerSpan?.attributes[AttributeNames.HAPI_TYPE], HapiLayerType.EXT ); - assert.strictEqual( + strictEqual( firstExtHandlerSpan?.attributes[AttributeNames.EXT_TYPE], 'onRequest' ); @@ -257,12 +257,12 @@ describe('Hapi Instrumentation - Server.Ext Tests', () => { const secondExtHandlerSpan = memoryExporter .getFinishedSpans() .find(span => span.name === 'ext - onPostAuth'); - assert.notStrictEqual(secondExtHandlerSpan, undefined); - assert.strictEqual( + notStrictEqual(secondExtHandlerSpan, undefined); + strictEqual( secondExtHandlerSpan?.attributes[AttributeNames.HAPI_TYPE], HapiLayerType.EXT ); - assert.strictEqual( + strictEqual( secondExtHandlerSpan?.attributes[AttributeNames.EXT_TYPE], 'onPostAuth' ); @@ -270,7 +270,7 @@ describe('Hapi Instrumentation - Server.Ext Tests', () => { const exportedRootSpan = memoryExporter .getFinishedSpans() .find(span => span.name === 'rootSpan'); - assert.notStrictEqual(exportedRootSpan, undefined); + notStrictEqual(exportedRootSpan, undefined); } ); }); @@ -294,7 +294,7 @@ describe('Hapi Instrumentation - Server.Ext Tests', () => { }); await server.start(); - assert.strictEqual(memoryExporter.getFinishedSpans().length, 0); + strictEqual(memoryExporter.getFinishedSpans().length, 0); await context.with( trace.setSpan(context.active(), rootSpan), @@ -303,19 +303,19 @@ describe('Hapi Instrumentation - Server.Ext Tests', () => { method: 'GET', url: '/test', }); - assert.strictEqual(res.statusCode, 200); + strictEqual(res.statusCode, 200); rootSpan.end(); - assert.deepStrictEqual(memoryExporter.getFinishedSpans().length, 3); + deepStrictEqual(memoryExporter.getFinishedSpans().length, 3); const extHandlerSpan = memoryExporter .getFinishedSpans() .find(span => span.name === 'simplePlugin: ext - onRequest'); - assert.notStrictEqual(extHandlerSpan, undefined); - assert.strictEqual( + notStrictEqual(extHandlerSpan, undefined); + strictEqual( extHandlerSpan?.attributes[AttributeNames.HAPI_TYPE], HapiLayerType.EXT ); - assert.strictEqual( + strictEqual( extHandlerSpan?.attributes[AttributeNames.EXT_TYPE], 'onRequest' ); @@ -323,7 +323,7 @@ describe('Hapi Instrumentation - Server.Ext Tests', () => { const exportedRootSpan = memoryExporter .getFinishedSpans() .find(span => span.name === 'rootSpan'); - assert.notStrictEqual(exportedRootSpan, undefined); + notStrictEqual(exportedRootSpan, undefined); } ); }); @@ -336,7 +336,7 @@ describe('Hapi Instrumentation - Server.Ext Tests', () => { server.ext('onPreStart', async (server: hapi.Server) => { return; }); - assert.strictEqual(memoryExporter.getFinishedSpans().length, 0); + strictEqual(memoryExporter.getFinishedSpans().length, 0); await server.start(); @@ -344,15 +344,15 @@ describe('Hapi Instrumentation - Server.Ext Tests', () => { method: 'GET', url: '/test', }); - assert.strictEqual(res.statusCode, 200); + strictEqual(res.statusCode, 200); rootSpan.end(); - assert.deepStrictEqual(memoryExporter.getFinishedSpans().length, 2); + deepStrictEqual(memoryExporter.getFinishedSpans().length, 2); const exportedRootSpan = memoryExporter .getFinishedSpans() .find(span => span.name === 'rootSpan'); - assert.notStrictEqual(exportedRootSpan, undefined); + notStrictEqual(exportedRootSpan, undefined); } ); }); @@ -362,14 +362,14 @@ describe('Hapi Instrumentation - Server.Ext Tests', () => { return h.continue; }); await server.start(); - assert.strictEqual(memoryExporter.getFinishedSpans().length, 0); + strictEqual(memoryExporter.getFinishedSpans().length, 0); const res = await server.inject({ method: 'GET', url: '/test', }); - assert.strictEqual(res.statusCode, 200); - assert.deepStrictEqual(memoryExporter.getFinishedSpans().length, 0); + strictEqual(res.statusCode, 200); + deepStrictEqual(memoryExporter.getFinishedSpans().length, 0); }); it('should end span and record the error if an error is thrown in ext', async () => { @@ -383,7 +383,7 @@ describe('Hapi Instrumentation - Server.Ext Tests', () => { }; server.ext(extension); await server.start(); - assert.strictEqual(memoryExporter.getFinishedSpans().length, 0); + strictEqual(memoryExporter.getFinishedSpans().length, 0); await context.with( trace.setSpan(context.active(), rootSpan), @@ -392,18 +392,18 @@ describe('Hapi Instrumentation - Server.Ext Tests', () => { method: 'GET', url: '/test', }); - assert.strictEqual(res.statusCode, 500); + strictEqual(res.statusCode, 500); rootSpan.end(); - assert.deepStrictEqual(memoryExporter.getFinishedSpans().length, 2); + deepStrictEqual(memoryExporter.getFinishedSpans().length, 2); const extHandlerSpan = memoryExporter .getFinishedSpans() .find(span => span.name === 'ext - onRequest'); - assert.notStrictEqual(extHandlerSpan, undefined); - assert.strictEqual(extHandlerSpan?.events[0].name, 'exception'); - assert.strictEqual(extHandlerSpan.status.code, SpanStatusCode.ERROR); - assert.strictEqual(extHandlerSpan.status.message, errorMessage); + notStrictEqual(extHandlerSpan, undefined); + strictEqual(extHandlerSpan?.events[0].name, 'exception'); + strictEqual(extHandlerSpan.status.code, SpanStatusCode.ERROR); + strictEqual(extHandlerSpan.status.message, errorMessage); } ); }); diff --git a/plugins/node/opentelemetry-instrumentation-hapi/test/hapi.test.ts b/plugins/node/opentelemetry-instrumentation-hapi/test/hapi.test.ts index af87e04901..3a5c1a4198 100644 --- a/plugins/node/opentelemetry-instrumentation-hapi/test/hapi.test.ts +++ b/plugins/node/opentelemetry-instrumentation-hapi/test/hapi.test.ts @@ -29,7 +29,7 @@ import { import { getPlugin } from './plugin'; const plugin = getPlugin(); -import * as assert from 'assert'; +import { strictEqual, deepStrictEqual, ifError, notStrictEqual } from 'assert'; import * as hapi from '@hapi/hapi'; import { HapiLayerType } from '../src/internal-types'; import { AttributeNames } from '../src/enums/AttributeNames'; @@ -80,7 +80,7 @@ describe('Hapi Instrumentation - Core Tests', () => { }); await server.start(); - assert.strictEqual(memoryExporter.getFinishedSpans().length, 0); + strictEqual(memoryExporter.getFinishedSpans().length, 0); await context.with( trace.setSpan(context.active(), rootSpan), @@ -89,16 +89,16 @@ describe('Hapi Instrumentation - Core Tests', () => { method: 'GET', url: '/', }); - assert.strictEqual(res.statusCode, 200); + strictEqual(res.statusCode, 200); rootSpan.end(); - assert.deepStrictEqual(memoryExporter.getFinishedSpans().length, 2); + deepStrictEqual(memoryExporter.getFinishedSpans().length, 2); const requestHandlerSpan = memoryExporter .getFinishedSpans() .find(span => span.name === 'route - /'); - assert.notStrictEqual(requestHandlerSpan, undefined); - assert.strictEqual( + notStrictEqual(requestHandlerSpan, undefined); + strictEqual( requestHandlerSpan?.attributes[AttributeNames.HAPI_TYPE], HapiLayerType.ROUTER ); @@ -106,7 +106,7 @@ describe('Hapi Instrumentation - Core Tests', () => { const exportedRootSpan = memoryExporter .getFinishedSpans() .find(span => span.name === 'rootSpan'); - assert.notStrictEqual(exportedRootSpan, undefined); + notStrictEqual(exportedRootSpan, undefined); } ); }); @@ -125,7 +125,7 @@ describe('Hapi Instrumentation - Core Tests', () => { }); await server.start(); - assert.strictEqual(memoryExporter.getFinishedSpans().length, 0); + strictEqual(memoryExporter.getFinishedSpans().length, 0); await context.with( trace.setSpan(context.active(), rootSpan), @@ -134,16 +134,16 @@ describe('Hapi Instrumentation - Core Tests', () => { method: 'GET', url: '/', }); - assert.strictEqual(res.statusCode, 200); + strictEqual(res.statusCode, 200); rootSpan.end(); - assert.deepStrictEqual(memoryExporter.getFinishedSpans().length, 2); + deepStrictEqual(memoryExporter.getFinishedSpans().length, 2); const requestHandlerSpan = memoryExporter .getFinishedSpans() .find(span => span.name === 'route - /'); - assert.notStrictEqual(requestHandlerSpan, undefined); - assert.strictEqual( + notStrictEqual(requestHandlerSpan, undefined); + strictEqual( requestHandlerSpan?.attributes[AttributeNames.HAPI_TYPE], HapiLayerType.ROUTER ); @@ -151,7 +151,7 @@ describe('Hapi Instrumentation - Core Tests', () => { const exportedRootSpan = memoryExporter .getFinishedSpans() .find(span => span.name === 'rootSpan'); - assert.notStrictEqual(exportedRootSpan, undefined); + notStrictEqual(exportedRootSpan, undefined); } ); }); @@ -171,7 +171,7 @@ describe('Hapi Instrumentation - Core Tests', () => { }); await server.start(); - assert.strictEqual(memoryExporter.getFinishedSpans().length, 0); + strictEqual(memoryExporter.getFinishedSpans().length, 0); await context.with( trace.setSpan(context.active(), rootSpan), @@ -180,16 +180,16 @@ describe('Hapi Instrumentation - Core Tests', () => { method: 'GET', url: '/', }); - assert.strictEqual(res.statusCode, 200); + strictEqual(res.statusCode, 200); rootSpan.end(); - assert.deepStrictEqual(memoryExporter.getFinishedSpans().length, 2); + deepStrictEqual(memoryExporter.getFinishedSpans().length, 2); const requestHandlerSpan = memoryExporter .getFinishedSpans() .find(span => span.name === 'route - /'); - assert.notStrictEqual(requestHandlerSpan, undefined); - assert.strictEqual( + notStrictEqual(requestHandlerSpan, undefined); + strictEqual( requestHandlerSpan?.attributes[AttributeNames.HAPI_TYPE], HapiLayerType.ROUTER ); @@ -197,7 +197,7 @@ describe('Hapi Instrumentation - Core Tests', () => { const exportedRootSpan = memoryExporter .getFinishedSpans() .find(span => span.name === 'rootSpan'); - assert.notStrictEqual(exportedRootSpan, undefined); + notStrictEqual(exportedRootSpan, undefined); } ); }); @@ -219,7 +219,7 @@ describe('Hapi Instrumentation - Core Tests', () => { }); await server.start(); - assert.strictEqual(memoryExporter.getFinishedSpans().length, 0); + strictEqual(memoryExporter.getFinishedSpans().length, 0); await context.with( trace.setSpan(context.active(), rootSpan), @@ -228,16 +228,16 @@ describe('Hapi Instrumentation - Core Tests', () => { method: 'GET', url: '/', }); - assert.strictEqual(res.statusCode, 200); + strictEqual(res.statusCode, 200); rootSpan.end(); - assert.deepStrictEqual(memoryExporter.getFinishedSpans().length, 2); + deepStrictEqual(memoryExporter.getFinishedSpans().length, 2); const requestHandlerSpan = memoryExporter .getFinishedSpans() .find(span => span.name === 'route - /'); - assert.notStrictEqual(requestHandlerSpan, undefined); - assert.strictEqual( + notStrictEqual(requestHandlerSpan, undefined); + strictEqual( requestHandlerSpan?.attributes[AttributeNames.HAPI_TYPE], HapiLayerType.ROUTER ); @@ -245,7 +245,7 @@ describe('Hapi Instrumentation - Core Tests', () => { const exportedRootSpan = memoryExporter .getFinishedSpans() .find(span => span.name === 'rootSpan'); - assert.notStrictEqual(exportedRootSpan, undefined); + notStrictEqual(exportedRootSpan, undefined); } ); }); @@ -270,7 +270,7 @@ describe('Hapi Instrumentation - Core Tests', () => { ]); await server.start(); - assert.strictEqual(memoryExporter.getFinishedSpans().length, 0); + strictEqual(memoryExporter.getFinishedSpans().length, 0); await context.with( trace.setSpan(context.active(), rootSpan), @@ -284,17 +284,17 @@ describe('Hapi Instrumentation - Core Tests', () => { url: '/second', }); - assert.strictEqual(resFirst.statusCode, 200); - assert.strictEqual(resSecond.statusCode, 200); + strictEqual(resFirst.statusCode, 200); + strictEqual(resSecond.statusCode, 200); rootSpan.end(); - assert.deepStrictEqual(memoryExporter.getFinishedSpans().length, 3); + deepStrictEqual(memoryExporter.getFinishedSpans().length, 3); const firstHandlerSpan = memoryExporter .getFinishedSpans() .find(span => span.name === 'route - /first'); - assert.notStrictEqual(firstHandlerSpan, undefined); - assert.strictEqual( + notStrictEqual(firstHandlerSpan, undefined); + strictEqual( firstHandlerSpan?.attributes[AttributeNames.HAPI_TYPE], HapiLayerType.ROUTER ); @@ -302,8 +302,8 @@ describe('Hapi Instrumentation - Core Tests', () => { const secondHandlerSpan = memoryExporter .getFinishedSpans() .find(span => span.name === 'route - /second'); - assert.notStrictEqual(secondHandlerSpan, undefined); - assert.strictEqual( + notStrictEqual(secondHandlerSpan, undefined); + strictEqual( secondHandlerSpan?.attributes[AttributeNames.HAPI_TYPE], HapiLayerType.ROUTER ); @@ -311,7 +311,7 @@ describe('Hapi Instrumentation - Core Tests', () => { const exportedRootSpan = memoryExporter .getFinishedSpans() .find(span => span.name === 'rootSpan'); - assert.notStrictEqual(exportedRootSpan, undefined); + notStrictEqual(exportedRootSpan, undefined); } ); }); @@ -331,7 +331,7 @@ describe('Hapi Instrumentation - Core Tests', () => { ]); await server.start(); - assert.strictEqual(memoryExporter.getFinishedSpans().length, 0); + strictEqual(memoryExporter.getFinishedSpans().length, 0); await context.with( trace.setSpan(context.active(), rootSpan), @@ -341,16 +341,16 @@ describe('Hapi Instrumentation - Core Tests', () => { url: '/route', }); - assert.strictEqual(res.statusCode, 200); + strictEqual(res.statusCode, 200); rootSpan.end(); - assert.deepStrictEqual(memoryExporter.getFinishedSpans().length, 3); + deepStrictEqual(memoryExporter.getFinishedSpans().length, 3); const routeSpan = memoryExporter .getFinishedSpans() .find(span => span.name === 'route - /route'); - assert.notStrictEqual(routeSpan, undefined); - assert.strictEqual( + notStrictEqual(routeSpan, undefined); + strictEqual( routeSpan?.attributes[AttributeNames.HAPI_TYPE], HapiLayerType.ROUTER ); @@ -358,8 +358,8 @@ describe('Hapi Instrumentation - Core Tests', () => { const handlerSpan = memoryExporter .getFinishedSpans() .find(span => span.name === 'handler'); - assert.notStrictEqual(routeSpan, undefined); - assert.strictEqual( + notStrictEqual(routeSpan, undefined); + strictEqual( handlerSpan?.parentSpanId, routeSpan?.spanContext().spanId ); @@ -378,7 +378,7 @@ describe('Hapi Instrumentation - Core Tests', () => { }); await server.start(); - assert.strictEqual(memoryExporter.getFinishedSpans().length, 0); + strictEqual(memoryExporter.getFinishedSpans().length, 0); await context.with( trace.setSpan(context.active(), rootSpan), @@ -387,16 +387,16 @@ describe('Hapi Instrumentation - Core Tests', () => { method: 'GET', url: '/users/1', }); - assert.strictEqual(res.statusCode, 200); + strictEqual(res.statusCode, 200); rootSpan.end(); - assert.deepStrictEqual(memoryExporter.getFinishedSpans().length, 2); + deepStrictEqual(memoryExporter.getFinishedSpans().length, 2); const requestHandlerSpan = memoryExporter .getFinishedSpans() .find(span => span.name === 'route - /users/{userId}'); - assert.notStrictEqual(requestHandlerSpan, undefined); - assert.strictEqual( + notStrictEqual(requestHandlerSpan, undefined); + strictEqual( requestHandlerSpan?.attributes[AttributeNames.HAPI_TYPE], HapiLayerType.ROUTER ); @@ -404,7 +404,7 @@ describe('Hapi Instrumentation - Core Tests', () => { const exportedRootSpan = memoryExporter .getFinishedSpans() .find(span => span.name === 'rootSpan'); - assert.notStrictEqual(exportedRootSpan, undefined); + notStrictEqual(exportedRootSpan, undefined); } ); }); @@ -418,14 +418,14 @@ describe('Hapi Instrumentation - Core Tests', () => { }, }); await server.start(); - assert.strictEqual(memoryExporter.getFinishedSpans().length, 0); + strictEqual(memoryExporter.getFinishedSpans().length, 0); const res = await server.inject({ method: 'GET', url: '/', }); - assert.strictEqual(res.statusCode, 200); - assert.deepStrictEqual(memoryExporter.getFinishedSpans().length, 0); + strictEqual(res.statusCode, 200); + deepStrictEqual(memoryExporter.getFinishedSpans().length, 0); }); it('should update rpcMetadata.route information', async () => { @@ -439,7 +439,7 @@ describe('Hapi Instrumentation - Core Tests', () => { }); await server.start(); - assert.strictEqual(memoryExporter.getFinishedSpans().length, 0); + strictEqual(memoryExporter.getFinishedSpans().length, 0); const rpcMetadata: RPCMetadata = { type: RPCType.HTTP, span: rootSpan }; await context.with( setRPCMetadata(trace.setSpan(context.active(), rootSpan), rpcMetadata), @@ -448,12 +448,12 @@ describe('Hapi Instrumentation - Core Tests', () => { method: 'GET', url: '/users/1', }); - assert.strictEqual(res.statusCode, 200); + strictEqual(res.statusCode, 200); rootSpan.end(); - assert.deepStrictEqual(memoryExporter.getFinishedSpans().length, 2); + deepStrictEqual(memoryExporter.getFinishedSpans().length, 2); - assert.strictEqual(rpcMetadata.route, '/users/{userId}'); + strictEqual(rpcMetadata.route, '/users/{userId}'); } ); }); @@ -470,7 +470,7 @@ describe('Hapi Instrumentation - Core Tests', () => { }); await server.start(); - assert.strictEqual(memoryExporter.getFinishedSpans().length, 0); + strictEqual(memoryExporter.getFinishedSpans().length, 0); const rpcMetadata = { type: RPCType.HTTP, span: rootSpan }; await context.with( setRPCMetadata(trace.setSpan(context.active(), rootSpan), rpcMetadata), @@ -479,21 +479,18 @@ describe('Hapi Instrumentation - Core Tests', () => { method: 'GET', url: '/users/1', }); - assert.strictEqual(res.statusCode, 500); + strictEqual(res.statusCode, 500); rootSpan.end(); - assert.deepStrictEqual(memoryExporter.getFinishedSpans().length, 2); + deepStrictEqual(memoryExporter.getFinishedSpans().length, 2); const requestHandlerSpan = memoryExporter .getFinishedSpans() .find(span => span.name === 'route - /users/{userId}'); - assert.notStrictEqual(requestHandlerSpan, undefined); - assert.strictEqual(requestHandlerSpan?.events[0].name, 'exception'); - assert.strictEqual( - requestHandlerSpan.status.code, - SpanStatusCode.ERROR - ); - assert.strictEqual(requestHandlerSpan.status.message, errorMessage); + notStrictEqual(requestHandlerSpan, undefined); + strictEqual(requestHandlerSpan?.events[0].name, 'exception'); + strictEqual(requestHandlerSpan.status.code, SpanStatusCode.ERROR); + strictEqual(requestHandlerSpan.status.message, errorMessage); } ); }); @@ -521,7 +518,7 @@ describe('Hapi Instrumentation - Core Tests', () => { await server.start(); - assert.strictEqual(memoryExporter.getFinishedSpans().length, 0); + strictEqual(memoryExporter.getFinishedSpans().length, 0); await context.with( trace.setSpan(context.active(), rootSpan), @@ -530,13 +527,10 @@ describe('Hapi Instrumentation - Core Tests', () => { method: 'GET', url: '/', }); - assert.strictEqual(res.statusCode, 200); + strictEqual(res.statusCode, 200); rootSpan.end(); - assert.deepStrictEqual(memoryExporter.getFinishedSpans().length, 1); - assert.notStrictEqual( - memoryExporter.getFinishedSpans()[0], - undefined - ); + deepStrictEqual(memoryExporter.getFinishedSpans().length, 1); + notStrictEqual(memoryExporter.getFinishedSpans()[0], undefined); } ); }); @@ -553,18 +547,18 @@ describe('Hapi Instrumentation - Core Tests', () => { NODE_NO_WARNINGS: '1', }, checkResult: (err, stdout, stderr) => { - assert.ifError(err); + ifError(err); }, checkCollector: (collector: TestCollector) => { const spans = collector.sortedSpans; - assert.strictEqual(spans.length, 2); - assert.strictEqual(spans[0].name, 'GET /route/{param}'); - assert.strictEqual( + strictEqual(spans.length, 2); + strictEqual(spans[0].name, 'GET /route/{param}'); + strictEqual( spans[0].instrumentationScope.name, '@opentelemetry/instrumentation-http' ); - assert.strictEqual(spans[1].name, 'route - /route/{param}'); - assert.strictEqual( + strictEqual(spans[1].name, 'route - /route/{param}'); + strictEqual( spans[1].instrumentationScope.name, '@opentelemetry/instrumentation-hapi' ); diff --git a/plugins/node/opentelemetry-instrumentation-ioredis/src/index.ts b/plugins/node/opentelemetry-instrumentation-ioredis/src/index.ts index c26f998cff..fb7c861408 100644 --- a/plugins/node/opentelemetry-instrumentation-ioredis/src/index.ts +++ b/plugins/node/opentelemetry-instrumentation-ioredis/src/index.ts @@ -14,5 +14,11 @@ * limitations under the License. */ -export * from './instrumentation'; -export * from './types'; +export { IORedisInstrumentation } from './instrumentation'; +export { + CommandArgs, + DbStatementSerializer, + IORedisRequestHookInformation, + RedisRequestCustomAttributeFunction, + IORedisInstrumentationConfig, +} from './types'; diff --git a/plugins/node/opentelemetry-instrumentation-ioredis/test/ioredis.test.ts b/plugins/node/opentelemetry-instrumentation-ioredis/test/ioredis.test.ts index 6dad19a9e4..b1240062b1 100644 --- a/plugins/node/opentelemetry-instrumentation-ioredis/test/ioredis.test.ts +++ b/plugins/node/opentelemetry-instrumentation-ioredis/test/ioredis.test.ts @@ -30,8 +30,8 @@ import { ReadableSpan, SimpleSpanProcessor, } from '@opentelemetry/sdk-trace-base'; -import * as assert from 'assert'; -import * as sinon from 'sinon'; +import { strictEqual, ok, deepStrictEqual, ifError } from 'assert'; +import { spy, assert } from 'sinon'; import * as ioredisTypes from 'ioredis'; import { IORedisInstrumentation } from '../src'; import { @@ -128,7 +128,7 @@ describe('ioredis', () => { }); it('should have correct module name', () => { - assert.strictEqual( + strictEqual( instrumentation.instrumentationName, '@opentelemetry/instrumentation-ioredis' ); @@ -145,10 +145,10 @@ describe('ioredis', () => { const readyHandler = () => { const endedSpans = memoryExporter.getFinishedSpans(); - assert.strictEqual(trace.getSpan(context.active()), span); - assert.strictEqual(endedSpans.length, 2); - assert.strictEqual(endedSpans[0].name, 'connect'); - assert.strictEqual(endedSpans[1].name, 'info'); + strictEqual(trace.getSpan(context.active()), span); + strictEqual(endedSpans.length, 2); + strictEqual(endedSpans[0].name, 'connect'); + strictEqual(endedSpans[1].name, 'info'); testUtils.assertPropagation(endedSpans[0], span); testUtils.assertSpan( @@ -159,17 +159,17 @@ describe('ioredis', () => { unsetStatus ); span.end(); - assert.strictEqual(endedSpans.length, 3); - assert.strictEqual(endedSpans[2].name, 'test span'); + strictEqual(endedSpans.length, 3); + strictEqual(endedSpans[2].name, 'test span'); client.quit(() => { - assert.strictEqual(endedSpans.length, 4); - assert.strictEqual(endedSpans[3].name, 'quit'); + strictEqual(endedSpans.length, 4); + strictEqual(endedSpans[3].name, 'quit'); done(); }); }; const errorHandler = (err: Error) => { - assert.ifError(err); + ifError(err); client.quit(done); }; @@ -257,12 +257,12 @@ describe('ioredis', () => { .startSpan('test span'); context.with(trace.setSpan(context.active(), span), () => { command.method((err, _result) => { - assert.ifError(err); - assert.strictEqual(memoryExporter.getFinishedSpans().length, 1); + ifError(err); + strictEqual(memoryExporter.getFinishedSpans().length, 1); span.end(); const endedSpans = memoryExporter.getFinishedSpans(); - assert.strictEqual(endedSpans.length, 2); - assert.strictEqual(endedSpans[0].name, command.name); + strictEqual(endedSpans.length, 2); + strictEqual(endedSpans[0].name, command.name); testUtils.assertSpan( endedSpans[0], SpanKind.CLIENT, @@ -286,11 +286,11 @@ describe('ioredis', () => { await context.with(trace.setSpan(context.active(), span), async () => { try { await client.hset(hashKeyName, 'random', 'random'); - assert.strictEqual(memoryExporter.getFinishedSpans().length, 1); + strictEqual(memoryExporter.getFinishedSpans().length, 1); span.end(); const endedSpans = memoryExporter.getFinishedSpans(); - assert.strictEqual(endedSpans.length, 2); - assert.strictEqual(endedSpans[0].name, 'hset'); + strictEqual(endedSpans.length, 2); + strictEqual(endedSpans[0].name, 'hset'); testUtils.assertSpan( endedSpans[0], SpanKind.CLIENT, @@ -300,7 +300,7 @@ describe('ioredis', () => { ); testUtils.assertPropagation(endedSpans[0], span); } catch (error) { - assert.ifError(error); + ifError(error); } }); }); @@ -315,21 +315,21 @@ describe('ioredis', () => { await client.incr('non-int-key'); } catch (ex: any) { const endedSpans = memoryExporter.getFinishedSpans(); - assert.strictEqual(endedSpans.length, 2); + strictEqual(endedSpans.length, 2); const ioredisSpan = endedSpans[1]; // redis 'incr' operation failed with exception, so span should indicate it - assert.strictEqual(ioredisSpan.status.code, SpanStatusCode.ERROR); + strictEqual(ioredisSpan.status.code, SpanStatusCode.ERROR); const exceptionEvent = ioredisSpan.events[0]; - assert.strictEqual(exceptionEvent.name, 'exception'); - assert.strictEqual( + strictEqual(exceptionEvent.name, 'exception'); + strictEqual( exceptionEvent.attributes?.[SEMATTRS_EXCEPTION_MESSAGE], ex.message ); - assert.strictEqual( + strictEqual( exceptionEvent.attributes?.[SEMATTRS_EXCEPTION_STACKTRACE], ex.stack ); - assert.strictEqual( + strictEqual( exceptionEvent.attributes?.[SEMATTRS_EXCEPTION_TYPE], ex.name ); @@ -350,11 +350,11 @@ describe('ioredis', () => { }); stream .on('end', () => { - assert.strictEqual(memoryExporter.getFinishedSpans().length, 1); + strictEqual(memoryExporter.getFinishedSpans().length, 1); span.end(); const endedSpans = memoryExporter.getFinishedSpans(); - assert.strictEqual(endedSpans.length, 2); - assert.strictEqual(endedSpans[0].name, 'scan'); + strictEqual(endedSpans.length, 2); + strictEqual(endedSpans[0].name, 'scan'); testUtils.assertSpan( endedSpans[0], SpanKind.CLIENT, @@ -391,9 +391,9 @@ describe('ioredis', () => { await sub.quit(); await pub.quit(); const endedSpans = memoryExporter.getFinishedSpans(); - assert.strictEqual(endedSpans.length, 10); + strictEqual(endedSpans.length, 10); span.end(); - assert.strictEqual(endedSpans.length, 11); + strictEqual(endedSpans.length, 11); const expectedSpanNames = [ 'connect', 'info', @@ -409,10 +409,7 @@ describe('ioredis', () => { ]; const actualSpanNames = endedSpans.map(s => s.name); - assert.deepStrictEqual( - actualSpanNames.sort(), - expectedSpanNames.sort() - ); + deepStrictEqual(actualSpanNames.sort(), expectedSpanNames.sort()); const attributes = { ...DEFAULT_ATTRIBUTES, @@ -427,7 +424,7 @@ describe('ioredis', () => { ); testUtils.assertPropagation(endedSpans[0], span); } catch (error) { - assert.ifError(error); + ifError(error); } }); }); @@ -445,16 +442,16 @@ describe('ioredis', () => { .set('foo', 'bar') .get('foo') .exec((err, _results) => { - assert.ifError(err); + ifError(err); - assert.strictEqual(memoryExporter.getFinishedSpans().length, 4); + strictEqual(memoryExporter.getFinishedSpans().length, 4); span.end(); const endedSpans = memoryExporter.getFinishedSpans(); - assert.strictEqual(endedSpans.length, 5); - assert.strictEqual(endedSpans[0].name, 'multi'); - assert.strictEqual(endedSpans[1].name, 'set'); - assert.strictEqual(endedSpans[2].name, 'get'); - assert.strictEqual(endedSpans[3].name, 'exec'); + strictEqual(endedSpans.length, 5); + strictEqual(endedSpans[0].name, 'multi'); + strictEqual(endedSpans[1].name, 'set'); + strictEqual(endedSpans[2].name, 'get'); + strictEqual(endedSpans[3].name, 'exec'); testUtils.assertSpan( endedSpans[0], SpanKind.CLIENT, @@ -480,15 +477,15 @@ describe('ioredis', () => { pipeline.set('foo', 'bar'); pipeline.del('cc'); pipeline.exec((err, results) => { - assert.ifError(err); + ifError(err); - assert.strictEqual(memoryExporter.getFinishedSpans().length, 2); + strictEqual(memoryExporter.getFinishedSpans().length, 2); span.end(); const endedSpans = memoryExporter.getFinishedSpans(); - assert.strictEqual(endedSpans.length, 3); - assert.strictEqual(endedSpans[0].name, 'set'); - assert.strictEqual(endedSpans[1].name, 'del'); - assert.strictEqual(endedSpans[2].name, 'test span'); + strictEqual(endedSpans.length, 3); + strictEqual(endedSpans[0].name, 'set'); + strictEqual(endedSpans[1].name, 'del'); + strictEqual(endedSpans[2].name, 'test span'); testUtils.assertSpan( endedSpans[0], SpanKind.CLIENT, @@ -511,12 +508,12 @@ describe('ioredis', () => { await context.with(trace.setSpan(context.active(), span), async () => { try { const value = await client.get(testKeyName); - assert.strictEqual(value, 'data'); - assert.strictEqual(memoryExporter.getFinishedSpans().length, 1); + strictEqual(value, 'data'); + strictEqual(memoryExporter.getFinishedSpans().length, 1); span.end(); const endedSpans = memoryExporter.getFinishedSpans(); - assert.strictEqual(endedSpans.length, 2); - assert.strictEqual(endedSpans[0].name, 'get'); + strictEqual(endedSpans.length, 2); + strictEqual(endedSpans[0].name, 'get'); testUtils.assertSpan( endedSpans[0], SpanKind.CLIENT, @@ -526,7 +523,7 @@ describe('ioredis', () => { ); testUtils.assertPropagation(endedSpans[0], span); } catch (error) { - assert.ifError(error); + ifError(error); } }); }); @@ -540,12 +537,12 @@ describe('ioredis', () => { await context.with(trace.setSpan(context.active(), span), async () => { try { const result = await client.del(testKeyName); - assert.strictEqual(result, 1); - assert.strictEqual(memoryExporter.getFinishedSpans().length, 1); + strictEqual(result, 1); + strictEqual(memoryExporter.getFinishedSpans().length, 1); span.end(); const endedSpans = memoryExporter.getFinishedSpans(); - assert.strictEqual(endedSpans.length, 2); - assert.strictEqual(endedSpans[0].name, 'del'); + strictEqual(endedSpans.length, 2); + strictEqual(endedSpans[0].name, 'del'); testUtils.assertSpan( endedSpans[0], SpanKind.CLIENT, @@ -555,7 +552,7 @@ describe('ioredis', () => { ); testUtils.assertPropagation(endedSpans[0], span); } catch (error) { - assert.ifError(error); + ifError(error); } }); }); @@ -581,16 +578,16 @@ describe('ioredis', () => { // Now `echo` can be used just like any other ordinary command, // and ioredis will try to use `EVALSHA` internally when possible for better performance. client.echo(testKeyName, (err, result) => { - assert.ifError(err); + ifError(err); span.end(); const endedSpans = memoryExporter.getFinishedSpans(); const evalshaSpan = endedSpans[0]; // the script may be already cached on server therefore we get either 2 or 3 spans if (endedSpans.length === 3) { - assert.strictEqual(endedSpans[2].name, 'test span'); - assert.strictEqual(endedSpans[1].name, 'eval'); - assert.strictEqual(endedSpans[0].name, 'evalsha'); + strictEqual(endedSpans[2].name, 'test span'); + strictEqual(endedSpans[1].name, 'eval'); + strictEqual(endedSpans[0].name, 'evalsha'); // in this case, server returns NOSCRIPT error for evalsha, // telling the client to use EVAL instead sanitizeEventForAssertion(evalshaSpan); @@ -616,9 +613,9 @@ describe('ioredis', () => { } ); } else { - assert.strictEqual(endedSpans.length, 2); - assert.strictEqual(endedSpans[1].name, 'test span'); - assert.strictEqual(endedSpans[0].name, 'evalsha'); + strictEqual(endedSpans.length, 2); + strictEqual(endedSpans[1].name, 'test span'); + strictEqual(endedSpans[0].name, 'evalsha'); testUtils.assertSpan( evalshaSpan, SpanKind.CLIENT, @@ -644,8 +641,8 @@ describe('ioredis', () => { it('should not create child span for query', async () => { await client.set(testKeyName, 'data'); const result = await client.del(testKeyName); - assert.strictEqual(result, 1); - assert.strictEqual(memoryExporter.getFinishedSpans().length, 0); + strictEqual(result, 1); + strictEqual(memoryExporter.getFinishedSpans().length, 0); }); it('should not create child span for connect', async () => { @@ -653,7 +650,7 @@ describe('ioredis', () => { await lazyClient.connect(); const spans = memoryExporter.getFinishedSpans(); await lazyClient.quit(); - assert.strictEqual(spans.length, 0); + strictEqual(spans.length, 0); }); }); @@ -666,10 +663,10 @@ describe('ioredis', () => { await client.set(testKeyName, 'data'); const result = await client.del(testKeyName); - assert.strictEqual(result, 1); + strictEqual(result, 1); const endedSpans = memoryExporter.getFinishedSpans(); - assert.strictEqual(endedSpans.length, 2); + strictEqual(endedSpans.length, 2); testUtils.assertSpan( endedSpans[0], SpanKind.CLIENT, @@ -691,9 +688,9 @@ describe('ioredis', () => { const lazyClient = new ioredis(REDIS_URL, { lazyConnect: true }); await lazyClient.connect(); const endedSpans = memoryExporter.getFinishedSpans(); - assert.strictEqual(endedSpans.length, 2); - assert.strictEqual(endedSpans[0].name, 'connect'); - assert.strictEqual(endedSpans[1].name, 'info'); + strictEqual(endedSpans.length, 2); + strictEqual(endedSpans[0].name, 'connect'); + strictEqual(endedSpans[1].name, 'info'); await lazyClient.quit(); testUtils.assertSpan( @@ -716,9 +713,9 @@ describe('ioredis', () => { await client.set(testKeyName, 'data'); const result = await client.del(testKeyName); - assert.strictEqual(result, 1); + strictEqual(result, 1); - assert.strictEqual(memoryExporter.getFinishedSpans().length, 0); + strictEqual(memoryExporter.getFinishedSpans().length, 0); }); it('should not instrument connect with requireParentSpan equal true', async () => { @@ -730,7 +727,7 @@ describe('ioredis', () => { const lazyClient = new ioredis(REDIS_URL, { lazyConnect: true }); await lazyClient.connect(); const endedSpans = memoryExporter.getFinishedSpans(); - assert.strictEqual(endedSpans.length, 0); + strictEqual(endedSpans.length, 0); await lazyClient.quit(); }); @@ -760,12 +757,12 @@ describe('ioredis', () => { .startSpan('test span'); context.with(trace.setSpan(context.active(), span), () => { command.method((err, _result) => { - assert.ifError(err); - assert.strictEqual(memoryExporter.getFinishedSpans().length, 1); + ifError(err); + strictEqual(memoryExporter.getFinishedSpans().length, 1); span.end(); const endedSpans = memoryExporter.getFinishedSpans(); - assert.strictEqual(endedSpans.length, 2); - assert.strictEqual(endedSpans[0].name, command.name); + strictEqual(endedSpans.length, 2); + strictEqual(endedSpans[0].name, command.name); testUtils.assertSpan( endedSpans[0], SpanKind.CLIENT, @@ -793,12 +790,12 @@ describe('ioredis', () => { .startSpan('test span'); context.with(trace.setSpan(context.active(), span), () => { operation.method((err, _) => { - assert.ifError(err); - assert.strictEqual(memoryExporter.getFinishedSpans().length, 0); + ifError(err); + strictEqual(memoryExporter.getFinishedSpans().length, 0); span.end(); const endedSpans = memoryExporter.getFinishedSpans(); - assert.strictEqual(endedSpans.length, 1); - assert.strictEqual(endedSpans[0], span); + strictEqual(endedSpans.length, 1); + strictEqual(endedSpans[0], span); done(); }); }); @@ -810,13 +807,13 @@ describe('ioredis', () => { await context.with(trace.setSpan(context.active(), span), async () => { try { await client.hset(hashKeyName, 'random', 'random'); - assert.strictEqual(memoryExporter.getFinishedSpans().length, 0); + strictEqual(memoryExporter.getFinishedSpans().length, 0); span.end(); const endedSpans = memoryExporter.getFinishedSpans(); - assert.strictEqual(endedSpans.length, 1); - assert.strictEqual(endedSpans[0].name, 'test span'); + strictEqual(endedSpans.length, 1); + strictEqual(endedSpans[0].name, 'test span'); } catch (error) { - assert.ifError(error); + ifError(error); } }); }); @@ -831,7 +828,7 @@ describe('ioredis', () => { }); it('should call requestHook when set in config', async () => { - const requestHook = sinon.spy( + const requestHook = spy( (span: Span, requestInfo: IORedisRequestHookInformation) => { span.setAttribute( 'attribute key from request hook', @@ -847,26 +844,26 @@ describe('ioredis', () => { await context.with(trace.setSpan(context.active(), span), async () => { await client.incr('request-hook-test'); const endedSpans = memoryExporter.getFinishedSpans(); - assert.strictEqual(endedSpans.length, 1); - assert.strictEqual( + strictEqual(endedSpans.length, 1); + strictEqual( endedSpans[0].attributes['attribute key from request hook'], 'custom value from request hook' ); }); - sinon.assert.calledOnce(requestHook); + assert.calledOnce(requestHook); const [, requestInfo] = requestHook.firstCall.args; - assert.ok( + ok( /\d{1,4}\.\d{1,4}\.\d{1,5}.*/.test( requestInfo.moduleVersion as string ) ); - assert.strictEqual(requestInfo.cmdName, 'incr'); - assert.deepStrictEqual(requestInfo.cmdArgs, ['request-hook-test']); + strictEqual(requestInfo.cmdName, 'incr'); + deepStrictEqual(requestInfo.cmdArgs, ['request-hook-test']); }); it('should ignore requestHook which throws exception', async () => { - const requestHook = sinon.spy( + const requestHook = spy( (span: Span, _requestInfo: IORedisRequestHookInformation) => { span.setAttribute( 'attribute key BEFORE exception', @@ -883,18 +880,18 @@ describe('ioredis', () => { await context.with(trace.setSpan(context.active(), span), async () => { await client.incr('request-hook-throw-test'); const endedSpans = memoryExporter.getFinishedSpans(); - assert.strictEqual(endedSpans.length, 1); - assert.strictEqual( + strictEqual(endedSpans.length, 1); + strictEqual( endedSpans[0].attributes['attribute key BEFORE exception'], 'this attribute is added to span BEFORE exception is thrown thus we can expect it' ); }); - sinon.assert.threw(requestHook); + assert.threw(requestHook); }); it('should call responseHook when set in config', async () => { - const responseHook = sinon.spy( + const responseHook = spy( ( span: Span, cmdName: string, @@ -915,26 +912,26 @@ describe('ioredis', () => { await context.with(trace.setSpan(context.active(), span), async () => { await client.set('response-hook-test', 'test-value'); const endedSpans = memoryExporter.getFinishedSpans(); - assert.strictEqual(endedSpans.length, 1); - assert.strictEqual( + strictEqual(endedSpans.length, 1); + strictEqual( endedSpans[0].attributes['attribute key from hook'], 'custom value from hook' ); }); - sinon.assert.calledOnce(responseHook); + assert.calledOnce(responseHook); const [, cmdName, , response] = responseHook.firstCall.args as [ Span, string, unknown, Buffer ]; - assert.strictEqual(cmdName, 'set'); - assert.strictEqual(response.toString(), 'OK'); + strictEqual(cmdName, 'set'); + strictEqual(response.toString(), 'OK'); }); it('should ignore responseHook which throws exception', async () => { - const responseHook = sinon.spy( + const responseHook = spy( ( _span: Span, _cmdName: string, @@ -954,10 +951,10 @@ describe('ioredis', () => { const endedSpans = memoryExporter.getFinishedSpans(); // hook throw exception, but span should not be affected - assert.strictEqual(endedSpans.length, 1); + strictEqual(endedSpans.length, 1); }); - sinon.assert.threw(responseHook); + assert.threw(responseHook); }); }); @@ -984,15 +981,15 @@ describe('ioredis', () => { .startSpan('test span'); context.with(trace.setSpan(context.active(), span), () => { operation.method((err, _) => { - assert.ifError(err); + ifError(err); span.end(); const endedSpans = memoryExporter.getFinishedSpans(); - assert.strictEqual(endedSpans.length, 2); + strictEqual(endedSpans.length, 2); const expectedStatement = dbStatementSerializer( operation.name, operation.args ); - assert.strictEqual( + strictEqual( endedSpans[0].attributes[SEMATTRS_DB_STATEMENT], expectedStatement ); @@ -1014,15 +1011,15 @@ describe('ioredis', () => { NODE_NO_WARNINGS: '1', }, checkResult: (err, stdout, stderr) => { - assert.ifError(err); + ifError(err); }, checkCollector: (collector: testUtils.TestCollector) => { const spans = collector.sortedSpans; - assert.strictEqual(spans[0].name, 'manual'); - assert.strictEqual(spans[1].name, 'set'); - assert.strictEqual(spans[1].parentSpanId, spans[0].spanId); - assert.strictEqual(spans[2].name, 'get'); - assert.strictEqual(spans[2].parentSpanId, spans[0].spanId); + strictEqual(spans[0].name, 'manual'); + strictEqual(spans[1].name, 'set'); + strictEqual(spans[1].parentSpanId, spans[0].spanId); + strictEqual(spans[2].name, 'get'); + strictEqual(spans[2].parentSpanId, spans[0].spanId); }, }); }); diff --git a/plugins/node/opentelemetry-instrumentation-knex/src/index.ts b/plugins/node/opentelemetry-instrumentation-knex/src/index.ts index c26f998cff..8f153b21dc 100644 --- a/plugins/node/opentelemetry-instrumentation-knex/src/index.ts +++ b/plugins/node/opentelemetry-instrumentation-knex/src/index.ts @@ -14,5 +14,5 @@ * limitations under the License. */ -export * from './instrumentation'; -export * from './types'; +export { KnexInstrumentation } from './instrumentation'; +export { KnexInstrumentationConfig } from './types'; diff --git a/plugins/node/opentelemetry-instrumentation-koa/src/index.ts b/plugins/node/opentelemetry-instrumentation-koa/src/index.ts index 13de301c07..900ad988da 100644 --- a/plugins/node/opentelemetry-instrumentation-koa/src/index.ts +++ b/plugins/node/opentelemetry-instrumentation-koa/src/index.ts @@ -14,6 +14,11 @@ * limitations under the License. */ -export * from './instrumentation'; -export * from './types'; -export * from './enums/AttributeNames'; +export { KoaInstrumentation } from './instrumentation'; +export { + KoaLayerType, + KoaRequestInfo, + KoaRequestCustomAttributeFunction, + KoaInstrumentationConfig, +} from './types'; +export { AttributeNames } from './enums/AttributeNames'; diff --git a/plugins/node/opentelemetry-instrumentation-koa/test/utils.test.ts b/plugins/node/opentelemetry-instrumentation-koa/test/utils.test.ts index b9a1ab4160..3ac1c803fa 100644 --- a/plugins/node/opentelemetry-instrumentation-koa/test/utils.test.ts +++ b/plugins/node/opentelemetry-instrumentation-koa/test/utils.test.ts @@ -15,27 +15,27 @@ */ import * as utils from '../src/utils'; -import * as assert from 'assert'; +import { strictEqual } from 'assert'; import { KoaInstrumentationConfig, KoaLayerType } from '../src/types'; describe('Utils', () => { describe('isLayerIgnored()', () => { it('should not fail with invalid config', () => { - assert.strictEqual(utils.isLayerIgnored(KoaLayerType.MIDDLEWARE), false); - assert.strictEqual( + strictEqual(utils.isLayerIgnored(KoaLayerType.MIDDLEWARE), false); + strictEqual( utils.isLayerIgnored( KoaLayerType.MIDDLEWARE, {} as KoaInstrumentationConfig ), false ); - assert.strictEqual( + strictEqual( utils.isLayerIgnored(KoaLayerType.MIDDLEWARE, { ignoreLayersType: {}, } as KoaInstrumentationConfig), false ); - assert.strictEqual( + strictEqual( utils.isLayerIgnored(KoaLayerType.ROUTER, { ignoreLayersType: {}, } as KoaInstrumentationConfig), @@ -44,13 +44,13 @@ describe('Utils', () => { }); it('should ignore based on type', () => { - assert.strictEqual( + strictEqual( utils.isLayerIgnored(KoaLayerType.MIDDLEWARE, { ignoreLayersType: [KoaLayerType.MIDDLEWARE], }), true ); - assert.strictEqual( + strictEqual( utils.isLayerIgnored(KoaLayerType.ROUTER, { ignoreLayersType: [KoaLayerType.MIDDLEWARE], }), diff --git a/plugins/node/opentelemetry-instrumentation-memcached/src/index.ts b/plugins/node/opentelemetry-instrumentation-memcached/src/index.ts index c26f998cff..cc97e7391e 100644 --- a/plugins/node/opentelemetry-instrumentation-memcached/src/index.ts +++ b/plugins/node/opentelemetry-instrumentation-memcached/src/index.ts @@ -14,5 +14,5 @@ * limitations under the License. */ -export * from './instrumentation'; -export * from './types'; +export { MemcachedInstrumentation } from './instrumentation'; +export { InstrumentationConfig } from './types'; diff --git a/plugins/node/opentelemetry-instrumentation-memcached/test/index.test.ts b/plugins/node/opentelemetry-instrumentation-memcached/test/index.test.ts index ca6e883cac..1ce7072495 100644 --- a/plugins/node/opentelemetry-instrumentation-memcached/test/index.test.ts +++ b/plugins/node/opentelemetry-instrumentation-memcached/test/index.test.ts @@ -29,7 +29,7 @@ import { SimpleSpanProcessor, } from '@opentelemetry/sdk-trace-base'; import type * as Memcached from 'memcached'; -import * as assert from 'assert'; +import { deepEqual, strictEqual, ok, fail, notStrictEqual } from 'assert'; import { MemcachedInstrumentation } from '../src'; import { DBSYSTEMVALUES_MEMCACHED, @@ -39,6 +39,7 @@ import { SEMATTRS_NET_PEER_PORT, } from '@opentelemetry/semantic-conventions'; import * as util from 'util'; +import assert = require('assert'); const instrumentation = new MemcachedInstrumentation(); const memoryExporter = new InMemorySpanExporter(); @@ -133,7 +134,7 @@ describe('memcached@2.x', () => { await client.setPromise(KEY, VALUE, 10); const value = await client.getPromise(KEY); - assert.strictEqual(value, VALUE); + strictEqual(value, VALUE); const instrumentationSpans = memoryExporter.getFinishedSpans(); assertSpans(instrumentationSpans, [ { @@ -161,9 +162,9 @@ describe('memcached@2.x', () => { async () => { try { await client.appendPromise(KEY, VALUE); - assert.fail(neverError); + fail(neverError); } catch (e) { - assert.notStrictEqual(e, neverError); + notStrictEqual(e, neverError); } const instrumentationSpans = memoryExporter.getFinishedSpans(); @@ -217,7 +218,7 @@ describe('memcached@2.x', () => { client.get(KEY, () => { try { const cbContext = context.active(); - assert.strictEqual(cbContext, parentContext); + strictEqual(cbContext, parentContext); done(); } catch (e) { done(e); @@ -232,7 +233,7 @@ describe('memcached@2.x', () => { }); const value = await client.getPromise(KEY); - assert.strictEqual(value, VALUE); + strictEqual(value, VALUE); const instrumentationSpans = memoryExporter.getFinishedSpans(); assertSpans(instrumentationSpans, [ { @@ -246,7 +247,7 @@ describe('memcached@2.x', () => { it('should not create new spans when disabled', async () => { instrumentation.disable(); await client.getPromise(KEY); - assert.strictEqual(memoryExporter.getFinishedSpans().length, 0); + strictEqual(memoryExporter.getFinishedSpans().length, 0); }); }); @@ -279,7 +280,7 @@ const assertSpans = (actualSpans: any[], expectedSpans: any[]) => { Array.isArray(expectedSpans), 'Expected `expectedSpans` to be an array' ); - assert.strictEqual( + strictEqual( actualSpans.length, expectedSpans.length, 'Expected span count different from actual' @@ -288,30 +289,24 @@ const assertSpans = (actualSpans: any[], expectedSpans: any[]) => { const expected = expectedSpans[idx]; if (expected === null) return; try { - assert.notStrictEqual(span, undefined); - assert.notStrictEqual(expected, undefined); + notStrictEqual(span, undefined); + notStrictEqual(expected, undefined); assertMatch(span.name, new RegExp(expected.op)); assertMatch(span.name, new RegExp('memcached')); - assert.strictEqual(span.kind, SpanKind.CLIENT); - assert.strictEqual(span.attributes['db.statement'], expected.statement); + strictEqual(span.kind, SpanKind.CLIENT); + strictEqual(span.attributes['db.statement'], expected.statement); for (const attr in DEFAULT_ATTRIBUTES) { - assert.strictEqual(span.attributes[attr], DEFAULT_ATTRIBUTES[attr]); + strictEqual(span.attributes[attr], DEFAULT_ATTRIBUTES[attr]); } - assert.strictEqual(span.attributes['db.memcached.key'], expected.key); - assert.strictEqual( + strictEqual(span.attributes['db.memcached.key'], expected.key); + strictEqual( typeof span.attributes['memcached.version'], 'string', 'memcached.version not specified' ); - assert.deepEqual( - span.status, - expected.status || { code: SpanStatusCode.UNSET } - ); - assert.strictEqual(span.attributes['db.operation'], expected.op); - assert.strictEqual( - span.parentSpanId, - expected.parentSpan?.spanContext().spanId - ); + deepEqual(span.status, expected.status || { code: SpanStatusCode.UNSET }); + strictEqual(span.attributes['db.operation'], expected.op); + strictEqual(span.parentSpanId, expected.parentSpan?.spanContext().spanId); } catch (e: any) { e.message = `At span[${idx}]: ${e.message}`; throw e; @@ -320,5 +315,5 @@ const assertSpans = (actualSpans: any[], expectedSpans: any[]) => { }; const assertMatch = (str: string, regexp: RegExp, err?: any) => { - assert.ok(regexp.test(str), err ?? `Expected '${str} to match ${regexp}`); + ok(regexp.test(str), err ?? `Expected '${str} to match ${regexp}`); }; diff --git a/plugins/node/opentelemetry-instrumentation-mongodb/src/index.ts b/plugins/node/opentelemetry-instrumentation-mongodb/src/index.ts index c26f998cff..96a9502c83 100644 --- a/plugins/node/opentelemetry-instrumentation-mongodb/src/index.ts +++ b/plugins/node/opentelemetry-instrumentation-mongodb/src/index.ts @@ -14,5 +14,12 @@ * limitations under the License. */ -export * from './instrumentation'; -export * from './types'; +export { MongoDBInstrumentation } from './instrumentation'; +export { + MongoDBInstrumentationExecutionResponseHook, + DbStatementSerializer, + MongoDBInstrumentationConfig, + MongoResponseHookInformation, + CommandResult, + MongodbCommandType, +} from './types'; diff --git a/plugins/node/opentelemetry-instrumentation-mongodb/test/mongodb-v3.test.ts b/plugins/node/opentelemetry-instrumentation-mongodb/test/mongodb-v3.test.ts index 4a3bd9a6e0..6a0e84ffd8 100644 --- a/plugins/node/opentelemetry-instrumentation-mongodb/test/mongodb-v3.test.ts +++ b/plugins/node/opentelemetry-instrumentation-mongodb/test/mongodb-v3.test.ts @@ -17,7 +17,13 @@ // for testing locally "npm run docker:start" import { context, trace, SpanKind, Span } from '@opentelemetry/api'; -import * as assert from 'assert'; +import { + deepEqual, + strictEqual, + deepStrictEqual, + doesNotThrow, + ifError, +} from 'assert'; import { MongoDBInstrumentation, MongoDBInstrumentationConfig } from '../src'; import { MongoResponseHookInformation } from '../src'; import { @@ -26,6 +32,7 @@ import { resetMemoryExporter, } from '@opentelemetry/contrib-test-utils'; import { lookup } from 'dns'; +import assert = require('assert'); const instrumentation = registerInstrumentationTesting( new MongoDBInstrumentation() @@ -327,7 +334,7 @@ describe('MongoDBInstrumentation-Tracing-v3', () => { const dbStatement = JSON.parse( mongoSpan!.attributes[SEMATTRS_DB_STATEMENT] as string ); - assert.strictEqual(dbStatement[key], '?'); + strictEqual(dbStatement[key], '?'); done(); }) .catch(err => { @@ -362,7 +369,7 @@ describe('MongoDBInstrumentation-Tracing-v3', () => { const dbStatement = JSON.parse( mongoSpan!.attributes[SEMATTRS_DB_STATEMENT] as string ); - assert.deepEqual(dbStatement, { + deepEqual(dbStatement, { aggregate: '?', pipeline: [ { $match: { key: '?' } }, @@ -415,7 +422,7 @@ describe('MongoDBInstrumentation-Tracing-v3', () => { const dbStatement = JSON.parse( mongoSpan!.attributes[SEMATTRS_DB_STATEMENT] as string ); - assert.strictEqual(dbStatement[key], value); + strictEqual(dbStatement[key], value); done(); }) .catch(err => { @@ -485,7 +492,7 @@ describe('MongoDBInstrumentation-Tracing-v3', () => { const spans = getTestSpans(); const insertSpan = spans[0]; - assert.deepStrictEqual( + deepStrictEqual( JSON.parse(insertSpan.attributes[dataAttributeName] as string), (results)?.result ); @@ -513,7 +520,7 @@ describe('MongoDBInstrumentation-Tracing-v3', () => { ); if (results) { - assert.strictEqual( + strictEqual( hookAttributeValue?.cursor?.firstBatch[0]._id, results[0]._id.toString() ); @@ -597,7 +604,7 @@ describe('MongoDBInstrumentation-Tracing-v3', () => { 'find', undefined ); - assert.strictEqual( + strictEqual( mainSpan.spanContext().spanId, spans2[0].parentSpanId ); @@ -646,16 +653,16 @@ describe('MongoDBInstrumentation-Tracing-v3', () => { collection.find({ a: 1 }).toArray((err, results) => { span.end(); const [mongoSpan] = getTestSpans(); - assert.ifError(err); + ifError(err); lookup( process.env.MONGODB_HOST || DEFAULT_MONGO_HOST, (err, address) => { if (err) return done(err); - assert.strictEqual( + strictEqual( mongoSpan.attributes[SEMATTRS_NET_PEER_NAME], address ); - assert.strictEqual( + strictEqual( mongoSpan.attributes[SEMATTRS_NET_PEER_PORT], process.env.MONGODB_PORT ? parseInt(process.env.MONGODB_PORT) @@ -672,7 +679,7 @@ describe('MongoDBInstrumentation-Tracing-v3', () => { /** Should intercept command */ describe('Removing Instrumentation', () => { it('should unpatch plugin', () => { - assert.doesNotThrow(() => { + doesNotThrow(() => { instrumentation.disable(); }); }); @@ -684,7 +691,7 @@ describe('MongoDBInstrumentation-Tracing-v3', () => { .insertMany(insertData) .then(() => { span.end(); - assert.strictEqual(getTestSpans().length, 1); + strictEqual(getTestSpans().length, 1); done(); }) .catch(err => { @@ -699,11 +706,11 @@ describe('MongoDBInstrumentation-Tracing-v3', () => { .toArray() .then(() => { span.end(); - assert.strictEqual(getTestSpans().length, 1); + strictEqual(getTestSpans().length, 1); done(); }) .catch(err => { - assert.ifError(err); + ifError(err); done(err); }); }); @@ -714,7 +721,7 @@ describe('MongoDBInstrumentation-Tracing-v3', () => { .createIndex({ a: 1 }) .then(() => { span.end(); - assert.strictEqual(getTestSpans().length, 1); + strictEqual(getTestSpans().length, 1); done(); }) .catch(err => { diff --git a/plugins/node/opentelemetry-instrumentation-mongodb/test/mongodb-v4-v5-v6.metrics.test.ts b/plugins/node/opentelemetry-instrumentation-mongodb/test/mongodb-v4-v5-v6.metrics.test.ts index 9bb49cb45b..4c3a4f717f 100644 --- a/plugins/node/opentelemetry-instrumentation-mongodb/test/mongodb-v4-v5-v6.metrics.test.ts +++ b/plugins/node/opentelemetry-instrumentation-mongodb/test/mongodb-v4-v5-v6.metrics.test.ts @@ -45,7 +45,8 @@ const instrumentation = registerInstrumentationTesting( import { accessCollection, DEFAULT_MONGO_HOST } from './utils'; import type { MongoClient, Collection } from 'mongodb'; -import * as assert from 'assert'; +import { strictEqual } from 'assert'; +import assert = require('assert'); async function waitForNumberOfExports( exporter: InMemoryMetricExporter, @@ -125,32 +126,29 @@ describe('MongoDBInstrumentation-Metrics', () => { assert.strictEqual(exportedMetrics.length, 1); const metrics = exportedMetrics[0].scopeMetrics[0].metrics; - assert.strictEqual(metrics.length, 1); - assert.strictEqual(metrics[0].dataPointType, DataPointType.SUM); + strictEqual(metrics.length, 1); + strictEqual(metrics[0].dataPointType, DataPointType.SUM); - assert.strictEqual( + strictEqual( metrics[0].descriptor.description, 'The number of connections that are currently in state described by the state attribute.' ); - assert.strictEqual(metrics[0].descriptor.unit, '{connection}'); - assert.strictEqual( - metrics[0].descriptor.name, - 'db.client.connections.usage' - ); + strictEqual(metrics[0].descriptor.unit, '{connection}'); + strictEqual(metrics[0].descriptor.name, 'db.client.connections.usage'); // Checking dataPoints const dataPoints = metrics[0].dataPoints; - assert.strictEqual(dataPoints.length, 2); - assert.strictEqual(dataPoints[0].value, 0); - assert.strictEqual(dataPoints[0].attributes['state'], 'used'); - assert.strictEqual( + strictEqual(dataPoints.length, 2); + strictEqual(dataPoints[0].value, 0); + strictEqual(dataPoints[0].attributes['state'], 'used'); + strictEqual( dataPoints[0].attributes['pool.name'], `mongodb://${HOST}:${PORT}/${DB_NAME}` ); - assert.strictEqual(dataPoints[1].value, 1); - assert.strictEqual(dataPoints[1].attributes['state'], 'idle'); - assert.strictEqual( + strictEqual(dataPoints[1].value, 1); + strictEqual(dataPoints[1].attributes['state'], 'idle'); + strictEqual( dataPoints[1].attributes['pool.name'], `mongodb://${HOST}:${PORT}/${DB_NAME}` ); @@ -163,28 +161,28 @@ describe('MongoDBInstrumentation-Metrics', () => { inMemoryMetricsExporter, 2 ); - assert.strictEqual(exportedMetrics.length, 2); + strictEqual(exportedMetrics.length, 2); const metrics = exportedMetrics[1].scopeMetrics[0].metrics; - assert.strictEqual(metrics.length, 1); - assert.strictEqual(metrics[0].dataPointType, DataPointType.SUM); + strictEqual(metrics.length, 1); + strictEqual(metrics[0].dataPointType, DataPointType.SUM); - assert.strictEqual( + strictEqual( metrics[0].descriptor.description, 'The number of connections that are currently in state described by the state attribute.' ); // Checking dataPoints const dataPoints = metrics[0].dataPoints; - assert.strictEqual(dataPoints.length, 2); - assert.strictEqual(dataPoints[0].value, 0); - assert.strictEqual(dataPoints[0].attributes['state'], 'used'); - assert.strictEqual( + strictEqual(dataPoints.length, 2); + strictEqual(dataPoints[0].value, 0); + strictEqual(dataPoints[0].attributes['state'], 'used'); + strictEqual( dataPoints[0].attributes['pool.name'], `mongodb://${HOST}:${PORT}/${DB_NAME}` ); - assert.strictEqual(dataPoints[1].value, 0); - assert.strictEqual(dataPoints[1].attributes['state'], 'idle'); - assert.strictEqual( + strictEqual(dataPoints[1].value, 0); + strictEqual(dataPoints[1].attributes['state'], 'idle'); + strictEqual( dataPoints[1].attributes['pool.name'], `mongodb://${HOST}:${PORT}/${DB_NAME}` ); diff --git a/plugins/node/opentelemetry-instrumentation-mongodb/test/mongodb-v4.test.ts b/plugins/node/opentelemetry-instrumentation-mongodb/test/mongodb-v4.test.ts index febd901776..320cb4b679 100644 --- a/plugins/node/opentelemetry-instrumentation-mongodb/test/mongodb-v4.test.ts +++ b/plugins/node/opentelemetry-instrumentation-mongodb/test/mongodb-v4.test.ts @@ -17,7 +17,13 @@ // for testing locally "npm run docker:start" import { context, trace, SpanKind, Span } from '@opentelemetry/api'; -import * as assert from 'assert'; +import { + deepEqual, + strictEqual, + deepStrictEqual, + doesNotThrow, + ifError, +} from 'assert'; import { MongoDBInstrumentation, MongoDBInstrumentationConfig, @@ -28,6 +34,7 @@ import { getTestSpans, resetMemoryExporter, } from '@opentelemetry/contrib-test-utils'; +import assert = require('assert'); const instrumentation = registerInstrumentationTesting( new MongoDBInstrumentation() @@ -268,7 +275,7 @@ describe('MongoDBInstrumentation-Tracing-v4', () => { roots.forEach(root => { const rootId = root.spanContext().spanId; const children = spans.filter(s => s.parentSpanId === rootId); - assert.strictEqual(children.length, 1); + strictEqual(children.length, 1); }); done(); }) @@ -362,7 +369,7 @@ describe('MongoDBInstrumentation-Tracing-v4', () => { const dbStatement = JSON.parse( mongoSpan!.attributes[SEMATTRS_DB_STATEMENT] as string ); - assert.strictEqual(dbStatement[key], '?'); + strictEqual(dbStatement[key], '?'); done(); }) .catch(err => { @@ -397,7 +404,7 @@ describe('MongoDBInstrumentation-Tracing-v4', () => { const dbStatement = JSON.parse( mongoSpan!.attributes[SEMATTRS_DB_STATEMENT] as string ); - assert.deepEqual(dbStatement, { + deepEqual(dbStatement, { aggregate: '?', pipeline: [ { $match: { key: '?' } }, @@ -450,7 +457,7 @@ describe('MongoDBInstrumentation-Tracing-v4', () => { const dbStatement = JSON.parse( mongoSpan!.attributes[SEMATTRS_DB_STATEMENT] as string ); - assert.strictEqual(dbStatement[key], value); + strictEqual(dbStatement[key], value); done(); }) .catch(err => { @@ -516,7 +523,7 @@ describe('MongoDBInstrumentation-Tracing-v4', () => { span.end(); const spans = getTestSpans(); const insertSpan = spans[0]; - assert.deepStrictEqual( + deepStrictEqual( JSON.parse(insertSpan.attributes[dataAttributeName] as string) .n, results?.insertedCount @@ -545,7 +552,7 @@ describe('MongoDBInstrumentation-Tracing-v4', () => { ); if (results) { - assert.strictEqual( + strictEqual( hookAttributeValue?.cursor?.firstBatch[0]._id, results[0]._id.toString() ); @@ -622,7 +629,7 @@ describe('MongoDBInstrumentation-Tracing-v4', () => { 'find', URL ); - assert.strictEqual( + strictEqual( mainSpan.spanContext().spanId, spans2[0].parentSpanId ); @@ -642,7 +649,7 @@ describe('MongoDBInstrumentation-Tracing-v4', () => { /** Should intercept command */ describe('Removing Instrumentation', () => { it('should unpatch plugin', () => { - assert.doesNotThrow(() => { + doesNotThrow(() => { instrumentation.disable(); }); }); @@ -654,7 +661,7 @@ describe('MongoDBInstrumentation-Tracing-v4', () => { .insertMany(insertData) .then(() => { span.end(); - assert.strictEqual(getTestSpans().length, 1); + strictEqual(getTestSpans().length, 1); done(); }) .catch(err => { @@ -669,11 +676,11 @@ describe('MongoDBInstrumentation-Tracing-v4', () => { .toArray() .then(() => { span.end(); - assert.strictEqual(getTestSpans().length, 1); + strictEqual(getTestSpans().length, 1); done(); }) .catch(err => { - assert.ifError(err); + ifError(err); done(err); }); }); @@ -684,7 +691,7 @@ describe('MongoDBInstrumentation-Tracing-v4', () => { .createIndex({ a: 1 }) .then(() => { span.end(); - assert.strictEqual(getTestSpans().length, 1); + strictEqual(getTestSpans().length, 1); done(); }) .catch(err => { diff --git a/plugins/node/opentelemetry-instrumentation-mongodb/test/mongodb-v5-v6.test.ts b/plugins/node/opentelemetry-instrumentation-mongodb/test/mongodb-v5-v6.test.ts index debe84dbdc..f76e7f5416 100644 --- a/plugins/node/opentelemetry-instrumentation-mongodb/test/mongodb-v5-v6.test.ts +++ b/plugins/node/opentelemetry-instrumentation-mongodb/test/mongodb-v5-v6.test.ts @@ -17,7 +17,13 @@ // for testing locally "npm run docker:start" import { context, trace, SpanKind, Span } from '@opentelemetry/api'; -import * as assert from 'assert'; +import { + deepEqual, + strictEqual, + deepStrictEqual, + doesNotThrow, + ifError, +} from 'assert'; import { MongoDBInstrumentation, MongoDBInstrumentationConfig, @@ -29,6 +35,7 @@ import { getTestSpans, resetMemoryExporter, } from '@opentelemetry/contrib-test-utils'; +import assert = require('assert'); // Get instrumentation (singleton) let instrumentation: MongoDBInstrumentation; @@ -271,7 +278,7 @@ describe('MongoDBInstrumentation-Tracing-v5', () => { roots.forEach(root => { const rootId = root.spanContext().spanId; const children = spans.filter(s => s.parentSpanId === rootId); - assert.strictEqual(children.length, 1); + strictEqual(children.length, 1); }); done(); }) @@ -365,7 +372,7 @@ describe('MongoDBInstrumentation-Tracing-v5', () => { const dbStatement = JSON.parse( mongoSpan!.attributes[SEMATTRS_DB_STATEMENT] as string ); - assert.strictEqual(dbStatement[key], '?'); + strictEqual(dbStatement[key], '?'); done(); }) .catch(err => { @@ -400,7 +407,7 @@ describe('MongoDBInstrumentation-Tracing-v5', () => { const dbStatement = JSON.parse( mongoSpan!.attributes[SEMATTRS_DB_STATEMENT] as string ); - assert.deepEqual(dbStatement, { + deepEqual(dbStatement, { aggregate: '?', pipeline: [ { $match: { key: '?' } }, @@ -453,7 +460,7 @@ describe('MongoDBInstrumentation-Tracing-v5', () => { const dbStatement = JSON.parse( mongoSpan!.attributes[SEMATTRS_DB_STATEMENT] as string ); - assert.strictEqual(dbStatement[key], value); + strictEqual(dbStatement[key], value); done(); }) .catch(err => { @@ -530,7 +537,7 @@ describe('MongoDBInstrumentation-Tracing-v5', () => { span.end(); const spans = getTestSpans(); const insertSpan = spans[0]; - assert.deepStrictEqual( + deepStrictEqual( insertSpan.attributes['mongodb_insert_count'], results?.insertedCount ); @@ -558,10 +565,7 @@ describe('MongoDBInstrumentation-Tracing-v5', () => { ); if (results) { - assert.strictEqual( - hookAttributeValue?._id, - results[0]._id.toString() - ); + strictEqual(hookAttributeValue?._id, results[0]._id.toString()); } else { throw new Error('Got an unexpected Results: ' + results); } @@ -635,7 +639,7 @@ describe('MongoDBInstrumentation-Tracing-v5', () => { 'find', URL ); - assert.strictEqual( + strictEqual( mainSpan.spanContext().spanId, spans2[0].parentSpanId ); @@ -655,7 +659,7 @@ describe('MongoDBInstrumentation-Tracing-v5', () => { /** Should intercept command */ describe('Removing Instrumentation', () => { it('should unpatch plugin', () => { - assert.doesNotThrow(() => { + doesNotThrow(() => { instrumentation.disable(); }); }); @@ -667,7 +671,7 @@ describe('MongoDBInstrumentation-Tracing-v5', () => { .insertMany(insertData) .then(() => { span.end(); - assert.strictEqual(getTestSpans().length, 1); + strictEqual(getTestSpans().length, 1); done(); }) .catch(err => { @@ -682,11 +686,11 @@ describe('MongoDBInstrumentation-Tracing-v5', () => { .toArray() .then(() => { span.end(); - assert.strictEqual(getTestSpans().length, 1); + strictEqual(getTestSpans().length, 1); done(); }) .catch(err => { - assert.ifError(err); + ifError(err); done(err); }); }); @@ -697,7 +701,7 @@ describe('MongoDBInstrumentation-Tracing-v5', () => { .createIndex({ a: 1 }) .then(() => { span.end(); - assert.strictEqual(getTestSpans().length, 1); + strictEqual(getTestSpans().length, 1); done(); }) .catch(err => { diff --git a/plugins/node/opentelemetry-instrumentation-mongodb/test/utils.ts b/plugins/node/opentelemetry-instrumentation-mongodb/test/utils.ts index 07ce789975..4d161c331d 100644 --- a/plugins/node/opentelemetry-instrumentation-mongodb/test/utils.ts +++ b/plugins/node/opentelemetry-instrumentation-mongodb/test/utils.ts @@ -23,8 +23,9 @@ import { SEMATTRS_NET_PEER_NAME, } from '@opentelemetry/semantic-conventions'; import { ReadableSpan } from '@opentelemetry/sdk-trace-base'; -import * as assert from 'assert'; +import { strictEqual, notStrictEqual } from 'assert'; import type { MongoClient, MongoClientOptions, Collection } from 'mongodb'; +import assert = require('assert'); export const DEFAULT_MONGO_HOST = '127.0.0.1'; @@ -72,7 +73,7 @@ export function accessCollection( /** * Asserts root spans attributes. - * @param spans Readable spans that we need to assert. + * @param spans Readable spans that we need to * @param expectedName The expected name of the first root span. * @param expectedKind The expected kind of the first root span. * @param log Whether should debug print the expected spans. @@ -90,26 +91,23 @@ export function assertSpans( if (log) { console.log(spans); } - assert.strictEqual(spans.length, 2); + strictEqual(spans.length, 2); spans.forEach(span => { assert(span.endTime instanceof Array); assert(span.endTime.length === 2); }); const [mongoSpan] = spans; - assert.strictEqual(mongoSpan.name, expectedName); - assert.strictEqual(mongoSpan.kind, expectedKind); - assert.strictEqual( - mongoSpan.attributes[SEMATTRS_DB_OPERATION], - expectedOperation - ); - assert.strictEqual(mongoSpan.attributes[SEMATTRS_DB_SYSTEM], 'mongodb'); - assert.strictEqual( + strictEqual(mongoSpan.name, expectedName); + strictEqual(mongoSpan.kind, expectedKind); + strictEqual(mongoSpan.attributes[SEMATTRS_DB_OPERATION], expectedOperation); + strictEqual(mongoSpan.attributes[SEMATTRS_DB_SYSTEM], 'mongodb'); + strictEqual( mongoSpan.attributes[SEMATTRS_NET_PEER_NAME], process.env.MONGODB_HOST || DEFAULT_MONGO_HOST ); - assert.strictEqual(mongoSpan.status.code, SpanStatusCode.UNSET); + strictEqual(mongoSpan.status.code, SpanStatusCode.UNSET); if (expectedConnString) { - assert.strictEqual( + strictEqual( mongoSpan.attributes[SEMATTRS_DB_CONNECTION_STRING], expectedConnString ); @@ -120,7 +118,7 @@ export function assertSpans( mongoSpan.attributes[SEMATTRS_DB_STATEMENT] as string ); for (const key in dbStatement) { - assert.notStrictEqual(dbStatement[key], '?'); + notStrictEqual(dbStatement[key], '?'); } } } diff --git a/plugins/node/opentelemetry-instrumentation-mysql/src/index.ts b/plugins/node/opentelemetry-instrumentation-mysql/src/index.ts index c26f998cff..c1df2e0706 100644 --- a/plugins/node/opentelemetry-instrumentation-mysql/src/index.ts +++ b/plugins/node/opentelemetry-instrumentation-mysql/src/index.ts @@ -14,5 +14,5 @@ * limitations under the License. */ -export * from './instrumentation'; -export * from './types'; +export { MySQLInstrumentation } from './instrumentation'; +export { MySQLInstrumentationConfig } from './types'; diff --git a/plugins/node/opentelemetry-instrumentation-mysql2/src/index.ts b/plugins/node/opentelemetry-instrumentation-mysql2/src/index.ts index c26f998cff..bf50741d78 100644 --- a/plugins/node/opentelemetry-instrumentation-mysql2/src/index.ts +++ b/plugins/node/opentelemetry-instrumentation-mysql2/src/index.ts @@ -14,5 +14,8 @@ * limitations under the License. */ -export * from './instrumentation'; -export * from './types'; +export { MySQL2Instrumentation } from './instrumentation'; +export { + MySQL2ResponseHookInformation, + MySQL2InstrumentationConfig, +} from './types'; diff --git a/plugins/node/opentelemetry-instrumentation-nestjs-core/src/index.ts b/plugins/node/opentelemetry-instrumentation-nestjs-core/src/index.ts index c464af622c..812058a1ca 100644 --- a/plugins/node/opentelemetry-instrumentation-nestjs-core/src/index.ts +++ b/plugins/node/opentelemetry-instrumentation-nestjs-core/src/index.ts @@ -14,5 +14,5 @@ * limitations under the License. */ -export * from './instrumentation'; -export * from './enums/AttributeNames'; +export { NestInstrumentation } from './instrumentation'; +export { AttributeNames } from './enums/AttributeNames'; diff --git a/plugins/node/opentelemetry-instrumentation-net/src/index.ts b/plugins/node/opentelemetry-instrumentation-net/src/index.ts index c26f998cff..ea5305656a 100644 --- a/plugins/node/opentelemetry-instrumentation-net/src/index.ts +++ b/plugins/node/opentelemetry-instrumentation-net/src/index.ts @@ -14,5 +14,5 @@ * limitations under the License. */ -export * from './instrumentation'; -export * from './types'; +export { NetInstrumentation } from './instrumentation'; +export { TLSAttributes } from './types'; diff --git a/plugins/node/opentelemetry-instrumentation-net/test/connect.test.ts b/plugins/node/opentelemetry-instrumentation-net/test/connect.test.ts index 55849289ee..c05f6c570f 100644 --- a/plugins/node/opentelemetry-instrumentation-net/test/connect.test.ts +++ b/plugins/node/opentelemetry-instrumentation-net/test/connect.test.ts @@ -22,7 +22,7 @@ import { import { SEMATTRS_NET_TRANSPORT } from '@opentelemetry/semantic-conventions'; import { NodeTracerProvider } from '@opentelemetry/sdk-trace-node'; import * as net from 'net'; -import * as assert from 'assert'; +import { throws, equal, strictEqual } from 'assert'; import { NetInstrumentation } from '../src'; import { SocketEvent } from '../src/internal-types'; import { assertIpcSpan, assertTcpSpan, IPC_PATH, HOST, PORT } from './utils'; @@ -33,7 +33,7 @@ provider.addSpanProcessor(new SimpleSpanProcessor(memoryExporter)); function getSpan() { const spans = memoryExporter.getFinishedSpans(); - assert.strictEqual(spans.length, 1); + strictEqual(spans.length, 1); const [span] = spans; return span; } @@ -171,12 +171,12 @@ describe('NetInstrumentation', () => { describe('invalid input', () => { it('should produce an error span when connect throws', done => { - assert.throws(() => { + throws(() => { // Invalid cast on purpose to avoid compiler errors. socket.connect({ port: {} } as { port: number }); }); - assert.strictEqual(getSpan().status.code, SpanStatusCode.ERROR); + strictEqual(getSpan().status.code, SpanStatusCode.ERROR); done(); }); @@ -185,11 +185,8 @@ describe('NetInstrumentation', () => { const assertSpan = () => { try { const span = getSpan(); - assert.strictEqual( - span.attributes[SEMATTRS_NET_TRANSPORT], - undefined - ); - assert.strictEqual(span.status.code, SpanStatusCode.ERROR); + strictEqual(span.attributes[SEMATTRS_NET_TRANSPORT], undefined); + strictEqual(span.status.code, SpanStatusCode.ERROR); done(); } catch (e) { done(e); @@ -202,7 +199,7 @@ describe('NetInstrumentation', () => { } catch (e: any) { // socket.connect() will throw in node@16 socket.removeListener(SocketEvent.CLOSE, assertSpan); - assert.strictEqual( + strictEqual( e.message, 'The "options" or "port" or "path" argument must be specified' ); @@ -219,7 +216,7 @@ describe('NetInstrumentation', () => { SocketEvent.CONNECT, SocketEvent.ERROR, ]) { - assert.equal(events.has(event), false); + equal(events.has(event), false); } } @@ -244,7 +241,7 @@ describe('NetInstrumentation', () => { socket.destroy(); socket.connect(PORT, () => { const spans = memoryExporter.getFinishedSpans(); - assert.strictEqual(spans.length, 2); + strictEqual(spans.length, 2); done(); }); }); diff --git a/plugins/node/opentelemetry-instrumentation-net/test/instrument.test.ts b/plugins/node/opentelemetry-instrumentation-net/test/instrument.test.ts index 09319a5808..198b94e3f0 100644 --- a/plugins/node/opentelemetry-instrumentation-net/test/instrument.test.ts +++ b/plugins/node/opentelemetry-instrumentation-net/test/instrument.test.ts @@ -19,7 +19,7 @@ import { SimpleSpanProcessor, } from '@opentelemetry/sdk-trace-base'; import { isWrapped } from '@opentelemetry/instrumentation'; -import * as assert from 'assert'; +import { strictEqual } from 'assert'; import { NodeTracerProvider } from '@opentelemetry/sdk-trace-node'; import { NetInstrumentation } from '../src'; import * as Sinon from 'sinon'; @@ -40,7 +40,7 @@ describe('NetInstrumentation', () => { instrumentation = new NetInstrumentation(); instrumentation.setTracerProvider(provider); require('net'); - assert.strictEqual(isWrapped(net.Socket.prototype.connect), true); + strictEqual(isWrapped(net.Socket.prototype.connect), true); }); before(done => { @@ -66,9 +66,9 @@ describe('NetInstrumentation', () => { instrumentation.disable(); socket = net.connect(PORT, HOST, () => { const spans = memoryExporter.getFinishedSpans(); - assert.strictEqual(spans.length, 0); - assert.strictEqual(isWrapped(net.Socket.prototype.connect), false); - assert.strictEqual((tracer.startSpan as sinon.SinonSpy).called, false); + strictEqual(spans.length, 0); + strictEqual(isWrapped(net.Socket.prototype.connect), false); + strictEqual((tracer.startSpan as sinon.SinonSpy).called, false); done(); }); }); diff --git a/plugins/node/opentelemetry-instrumentation-net/test/tls.test.ts b/plugins/node/opentelemetry-instrumentation-net/test/tls.test.ts index 0052a4787c..ee40dee387 100644 --- a/plugins/node/opentelemetry-instrumentation-net/test/tls.test.ts +++ b/plugins/node/opentelemetry-instrumentation-net/test/tls.test.ts @@ -21,7 +21,7 @@ import { } from '@opentelemetry/sdk-trace-base'; import { NodeTracerProvider } from '@opentelemetry/sdk-trace-node'; import { AsyncHooksContextManager } from '@opentelemetry/context-async-hooks'; -import * as assert from 'assert'; +import { equal, strictEqual } from 'assert'; import * as tls from 'tls'; import { NetInstrumentation } from '../src'; import { SocketEvent } from '../src/internal-types'; @@ -39,7 +39,7 @@ provider.addSpanProcessor(new SimpleSpanProcessor(memoryExporter)); function getTLSSpans() { const spans = memoryExporter.getFinishedSpans(); - assert.strictEqual(spans.length, 2); + strictEqual(spans.length, 2); const [netSpan, tlsSpan] = spans; return { netSpan, @@ -133,8 +133,8 @@ describe('NetInstrumentation', () => { ); tlsSocket.on('error', error => { const { tlsSpan } = getTLSSpans(); - assert.strictEqual(tlsSpan.status.message, error.message); - assert.strictEqual(tlsSpan.status.code, SpanStatusCode.ERROR); + strictEqual(tlsSpan.status.message, error.message); + strictEqual(tlsSpan.status.code, SpanStatusCode.ERROR); done(); }); }); @@ -149,9 +149,9 @@ describe('NetInstrumentation', () => { SocketEvent.SECURE_CONNECT, SocketEvent.ERROR, ]) { - assert.equal(events.has(event), false); + equal(events.has(event), false); } - assert.strictEqual(tlsSocket.listenerCount(SocketEvent.CLOSE), 1); + strictEqual(tlsSocket.listenerCount(SocketEvent.CLOSE), 1); } it('should clean up listeners for tls.connect', done => { diff --git a/plugins/node/opentelemetry-instrumentation-net/test/utils.ts b/plugins/node/opentelemetry-instrumentation-net/test/utils.ts index 7d3651d2df..acb2a124fb 100644 --- a/plugins/node/opentelemetry-instrumentation-net/test/utils.ts +++ b/plugins/node/opentelemetry-instrumentation-net/test/utils.ts @@ -24,8 +24,8 @@ import { SEMATTRS_NET_PEER_PORT, SEMATTRS_NET_TRANSPORT, } from '@opentelemetry/semantic-conventions'; -import * as assert from 'assert'; -import * as path from 'path'; +import { strictEqual } from 'assert'; +import { resolve, join } from 'path'; import * as os from 'os'; import { Socket } from 'net'; import { IPC_TRANSPORT } from '../src/utils'; @@ -36,7 +36,7 @@ export const PORT = 42123; export const HOST = 'localhost'; export const IPC_PATH = os.platform() !== 'win32' - ? path.join(os.tmpdir(), 'otel-js-net-test-ipc') + ? join(os.tmpdir(), 'otel-js-net-test-ipc') : '\\\\.\\pipe\\otel-js-net-test-ipc'; export function assertTcpSpan(span: ReadableSpan, socket: Socket) { @@ -98,28 +98,28 @@ export function assertTLSSpan( } export function assertSpanKind(span: ReadableSpan) { - assert.strictEqual(span.kind, SpanKind.INTERNAL); + strictEqual(span.kind, SpanKind.INTERNAL); } export function assertAttrib(span: ReadableSpan, attrib: string, value: any) { - assert.strictEqual(span.attributes[attrib], value); + strictEqual(span.attributes[attrib], value); } export function assertParentChild( parentSpan: ReadableSpan, childSpan: ReadableSpan ) { - assert.strictEqual( + strictEqual( childSpan.spanContext().traceId, parentSpan.spanContext().traceId ); - assert.strictEqual(childSpan.parentSpanId, parentSpan.spanContext().spanId); + strictEqual(childSpan.parentSpanId, parentSpan.spanContext().spanId); } export const TLS_SERVER_CERT = fs - .readFileSync(path.resolve(__dirname, './fixtures/tls.crt')) + .readFileSync(resolve(__dirname, './fixtures/tls.crt')) .toString(); export const TLS_SERVER_KEY = fs - .readFileSync(path.resolve(__dirname, './fixtures/tls.key')) + .readFileSync(resolve(__dirname, './fixtures/tls.key')) .toString(); diff --git a/plugins/node/opentelemetry-instrumentation-pg/src/index.ts b/plugins/node/opentelemetry-instrumentation-pg/src/index.ts index 13de301c07..58ef1a985f 100644 --- a/plugins/node/opentelemetry-instrumentation-pg/src/index.ts +++ b/plugins/node/opentelemetry-instrumentation-pg/src/index.ts @@ -14,6 +14,12 @@ * limitations under the License. */ -export * from './instrumentation'; -export * from './types'; -export * from './enums/AttributeNames'; +export { PgInstrumentation } from './instrumentation'; +export { + PgResponseHookInformation, + PgInstrumentationExecutionResponseHook, + PgRequestHookInformation, + PgInstrumentationExecutionRequestHook, + PgInstrumentationConfig, +} from './types'; +export { AttributeNames } from './enums/AttributeNames'; diff --git a/plugins/node/opentelemetry-instrumentation-pino/src/index.ts b/plugins/node/opentelemetry-instrumentation-pino/src/index.ts index c26f998cff..5387e2c04d 100644 --- a/plugins/node/opentelemetry-instrumentation-pino/src/index.ts +++ b/plugins/node/opentelemetry-instrumentation-pino/src/index.ts @@ -14,5 +14,5 @@ * limitations under the License. */ -export * from './instrumentation'; -export * from './types'; +export { PinoInstrumentation } from './instrumentation'; +export { LogHookFunction, PinoInstrumentationConfig } from './types'; diff --git a/plugins/node/opentelemetry-instrumentation-pino/test/pino.test.ts b/plugins/node/opentelemetry-instrumentation-pino/test/pino.test.ts index 6f03e197cd..a6beb712a1 100644 --- a/plugins/node/opentelemetry-instrumentation-pino/test/pino.test.ts +++ b/plugins/node/opentelemetry-instrumentation-pino/test/pino.test.ts @@ -14,11 +14,18 @@ * limitations under the License. */ -import * as assert from 'assert'; +import { + strictEqual, + deepStrictEqual, + ok, + equal, + deepEqual, + ifError, +} from 'assert'; import { Writable } from 'stream'; import * as semver from 'semver'; -import * as sinon from 'sinon'; +import { spy, SinonSpy, assert } from 'sinon'; import { INVALID_SPAN_CONTEXT, context, trace, Span } from '@opentelemetry/api'; import { diag, DiagLogLevel } from '@opentelemetry/api'; import { hrTimeToMilliseconds } from '@opentelemetry/core'; @@ -68,13 +75,13 @@ describe('PinoInstrumentation', () => { describe('disabled instrumentation', () => { let logger: Pino.Logger; let stream: Writable; - let writeSpy: sinon.SinonSpy; + let writeSpy: SinonSpy; beforeEach(() => { instrumentation.disable(); stream = new Writable(); stream._write = () => {}; - writeSpy = sinon.spy(stream, 'write'); + writeSpy = spy(stream, 'write'); logger = pino(stream); }); @@ -87,12 +94,12 @@ describe('PinoInstrumentation', () => { logger.info('a message'); span.end(); - sinon.assert.calledOnce(writeSpy); + assert.calledOnce(writeSpy); const record = JSON.parse(writeSpy.firstCall.args[0].toString()); - assert.strictEqual(record['msg'], 'a message'); - assert.strictEqual(record['trace_id'], undefined); - assert.strictEqual(record['span_id'], undefined); - assert.strictEqual(record['trace_flags'], undefined); + strictEqual(record['msg'], 'a message'); + strictEqual(record['trace_id'], undefined); + strictEqual(record['span_id'], undefined); + strictEqual(record['trace_flags'], undefined); }); }); @@ -107,9 +114,9 @@ describe('PinoInstrumentation', () => { logger.info('a message'); span.end(); - sinon.assert.calledOnce(writeSpy); + assert.calledOnce(writeSpy); const record = JSON.parse(writeSpy.firstCall.args[0].toString()); - assert.strictEqual(record['resource.service.name'], undefined); + strictEqual(record['resource.service.name'], undefined); }); }); @@ -119,7 +126,7 @@ describe('PinoInstrumentation', () => { logger.info('a message'); span.end(); - sinon.assert.calledOnce(writeSpy); + assert.calledOnce(writeSpy); const record = JSON.parse(writeSpy.firstCall.args[0].toString()); assertRecord(record, span); }); @@ -129,14 +136,14 @@ describe('PinoInstrumentation', () => { describe('log correlation', () => { let logger: Pino.Logger; let stream: Writable; - let writeSpy: sinon.SinonSpy; + let writeSpy: SinonSpy; beforeEach(() => { instrumentation.setConfig({}); // reset to defaults memExporter.getFinishedLogRecords().length = 0; // clear stream = new Writable(); stream._write = () => {}; - writeSpy = sinon.spy(stream, 'write'); + writeSpy = spy(stream, 'write'); logger = pino(stream); }); @@ -145,10 +152,10 @@ describe('PinoInstrumentation', () => { logger.info('a message'); span.end(); - sinon.assert.calledOnce(writeSpy); + assert.calledOnce(writeSpy); const record = JSON.parse(writeSpy.firstCall.args[0].toString()); assertRecord(record, span); - assert.strictEqual(record['msg'], 'a message'); + strictEqual(record['msg'], 'a message'); }); }); @@ -163,13 +170,13 @@ describe('PinoInstrumentation', () => { logger.info('a message'); span.end(); - sinon.assert.calledOnce(writeSpy); + assert.calledOnce(writeSpy); const record = JSON.parse(writeSpy.firstCall.args[0].toString()); assertRecord(record, span, logKeys); - assert.strictEqual(record['trace_id'], undefined); - assert.strictEqual(record['span_id'], undefined); - assert.strictEqual(record['trace_flags'], undefined); - assert.strictEqual(record['msg'], 'a message'); + strictEqual(record['trace_id'], undefined); + strictEqual(record['span_id'], undefined); + strictEqual(record['trace_flags'], undefined); + strictEqual(record['msg'], 'a message'); }); }); @@ -179,24 +186,24 @@ describe('PinoInstrumentation', () => { child.info('a message'); span.end(); - sinon.assert.calledOnce(writeSpy); + assert.calledOnce(writeSpy); const record = JSON.parse(writeSpy.firstCall.args[0].toString()); assertRecord(record, span); - assert.strictEqual(record['msg'], 'a message'); - assert.strictEqual(record['childField'], 42); + strictEqual(record['msg'], 'a message'); + strictEqual(record['childField'], 42); }); }); it('does not inject span context if no span is active', () => { - assert.strictEqual(trace.getSpan(context.active()), undefined); + strictEqual(trace.getSpan(context.active()), undefined); logger.info('a message'); - sinon.assert.calledOnce(writeSpy); + assert.calledOnce(writeSpy); const record = JSON.parse(writeSpy.firstCall.args[0].toString()); - assert.strictEqual(record['trace_id'], undefined); - assert.strictEqual(record['span_id'], undefined); - assert.strictEqual(record['trace_flags'], undefined); + strictEqual(record['trace_id'], undefined); + strictEqual(record['span_id'], undefined); + strictEqual(record['trace_flags'], undefined); }); it('does not inject span context if span context is invalid', () => { @@ -204,11 +211,11 @@ describe('PinoInstrumentation', () => { context.with(trace.setSpan(context.active(), span), () => { logger.info('a message'); - sinon.assert.calledOnce(writeSpy); + assert.calledOnce(writeSpy); const record = JSON.parse(writeSpy.firstCall.args[0].toString()); - assert.strictEqual(record['trace_id'], undefined); - assert.strictEqual(record['span_id'], undefined); - assert.strictEqual(record['trace_flags'], undefined); + strictEqual(record['trace_id'], undefined); + strictEqual(record['span_id'], undefined); + strictEqual(record['trace_flags'], undefined); }); }); @@ -217,7 +224,7 @@ describe('PinoInstrumentation', () => { logHook: (_span, record, level) => { record['resource.service.name'] = 'test-service'; if (semver.satisfies(pino.version, '>=7.9.0')) { - assert.strictEqual(level, 30); + strictEqual(level, 30); } }, }); @@ -226,10 +233,10 @@ describe('PinoInstrumentation', () => { logger.info('a message'); span.end(); - sinon.assert.calledOnce(writeSpy); + assert.calledOnce(writeSpy); const record = JSON.parse(writeSpy.firstCall.args[0].toString()); assertRecord(record, span); - assert.strictEqual(record['resource.service.name'], 'test-service'); + strictEqual(record['resource.service.name'], 'test-service'); }); }); @@ -243,7 +250,7 @@ describe('PinoInstrumentation', () => { logger.info('a message'); span.end(); - sinon.assert.calledOnce(writeSpy); + assert.calledOnce(writeSpy); const record = JSON.parse(writeSpy.firstCall.args[0].toString()); assertRecord(record, span); }); @@ -260,13 +267,13 @@ describe('PinoInstrumentation', () => { logger.info('foo'); span.end(); - sinon.assert.calledOnce(writeSpy); + assert.calledOnce(writeSpy); const record = JSON.parse(writeSpy.firstCall.args[0].toString()); - assert.strictEqual('foo', record['msg']); - assert.strictEqual(record['trace_id'], undefined); - assert.strictEqual(record['span_id'], undefined); - assert.strictEqual(record['trace_flags'], undefined); - assert.strictEqual(record['resource.service.name'], undefined); + strictEqual('foo', record['msg']); + strictEqual(record['trace_id'], undefined); + strictEqual(record['span_id'], undefined); + strictEqual(record['trace_flags'], undefined); + strictEqual(record['resource.service.name'], undefined); }); }); @@ -281,10 +288,10 @@ describe('PinoInstrumentation', () => { span.end(); const { traceId, spanId } = span.spanContext(); - sinon.assert.calledOnce(writeSpy); + assert.calledOnce(writeSpy); const record = JSON.parse(writeSpy.firstCall.args[0].toString()); - assert.strictEqual(record['trace_id'], traceId); - assert.strictEqual(record['span_id'], spanId); + strictEqual(record['trace_id'], traceId); + strictEqual(record['span_id'], spanId); }); }); @@ -299,20 +306,20 @@ describe('PinoInstrumentation', () => { span.end(); const { traceId, spanId } = span.spanContext(); - sinon.assert.calledOnce(writeSpy); + assert.calledOnce(writeSpy); const record = JSON.parse(writeSpy.firstCall.args[0].toString()); - assert.strictEqual(record['trace_id'], traceId); - assert.strictEqual(record['span_id'], spanId); + strictEqual(record['trace_id'], traceId); + strictEqual(record['span_id'], spanId); }); }); }); describe('logger construction', () => { - let stdoutSpy: sinon.SinonSpy; + let stdoutSpy: SinonSpy; beforeEach(() => { instrumentation.setConfig({}); // reset to defaults - stdoutSpy = sinon.spy(process.stdout, 'write'); + stdoutSpy = spy(process.stdout, 'write'); }); afterEach(() => { @@ -338,7 +345,7 @@ describe('PinoInstrumentation', () => { const record = JSON.parse(stdoutSpy.firstCall.args[0].toString()); assertRecord(record, span); - assert.strictEqual(record['name'], 'LogLog'); + strictEqual(record['name'], 'LogLog'); }); }); @@ -364,9 +371,9 @@ describe('PinoInstrumentation', () => { const record = JSON.parse(stdoutSpy.firstCall.args[0].toString()); assertRecord(record, span); - assert.strictEqual(record['a'], 2); - assert.strictEqual(record['b'], 'bar'); - assert.strictEqual(record['name'], 'LogLog'); + strictEqual(record['a'], 2); + strictEqual(record['b'], 'bar'); + strictEqual(record['name'], 'LogLog'); }); }); @@ -385,8 +392,8 @@ describe('PinoInstrumentation', () => { const { spanId } = span.spanContext(); const record = JSON.parse(stdoutSpy.firstCall.args[0].toString()); - assert.strictEqual(record['trace_id'], '123'); - assert.strictEqual(record['span_id'], spanId); + strictEqual(record['trace_id'], '123'); + strictEqual(record['span_id'], spanId); }); }); }); @@ -394,7 +401,7 @@ describe('PinoInstrumentation', () => { describe('log sending', () => { let logger: Pino.Logger; let stream: Writable; - let writeSpy: sinon.SinonSpy; + let writeSpy: SinonSpy; before(function () { if (typeof pino.multistream !== 'function') { @@ -407,7 +414,7 @@ describe('PinoInstrumentation', () => { memExporter.getFinishedLogRecords().length = 0; // clear stream = new Writable(); stream._write = () => {}; - writeSpy = sinon.spy(stream, 'write'); + writeSpy = spy(stream, 'write'); logger = pino( { name: 'test-logger-name', @@ -428,33 +435,33 @@ describe('PinoInstrumentation', () => { logger.warn('at warn level'); logger.error('at error level'); logger.fatal('at fatal level'); - assert.strictEqual(logRecords.length, 5); - assert.strictEqual(logRecords[0].severityNumber, SeverityNumber.DEBUG); - assert.strictEqual(logRecords[0].severityText, 'debug'); - assert.strictEqual(logRecords[1].severityNumber, SeverityNumber.INFO); - assert.strictEqual(logRecords[1].severityText, 'info'); - assert.strictEqual(logRecords[2].severityNumber, SeverityNumber.WARN); - assert.strictEqual(logRecords[2].severityText, 'warn'); - assert.strictEqual(logRecords[3].severityNumber, SeverityNumber.ERROR); - assert.strictEqual(logRecords[3].severityText, 'error'); - assert.strictEqual(logRecords[4].severityNumber, SeverityNumber.FATAL); - assert.strictEqual(logRecords[4].severityText, 'fatal'); + strictEqual(logRecords.length, 5); + strictEqual(logRecords[0].severityNumber, SeverityNumber.DEBUG); + strictEqual(logRecords[0].severityText, 'debug'); + strictEqual(logRecords[1].severityNumber, SeverityNumber.INFO); + strictEqual(logRecords[1].severityText, 'info'); + strictEqual(logRecords[2].severityNumber, SeverityNumber.WARN); + strictEqual(logRecords[2].severityText, 'warn'); + strictEqual(logRecords[3].severityNumber, SeverityNumber.ERROR); + strictEqual(logRecords[3].severityText, 'error'); + strictEqual(logRecords[4].severityNumber, SeverityNumber.FATAL); + strictEqual(logRecords[4].severityText, 'fatal'); // attributes, resource, instrumentationScope, etc. logger.info({ foo: 'bar' }, 'a message'); const rec = logRecords[logRecords.length - 1]; - assert.strictEqual(rec.body, 'a message'); - assert.deepStrictEqual(rec.attributes, { + strictEqual(rec.body, 'a message'); + deepStrictEqual(rec.attributes, { name: 'test-logger-name', foo: 'bar', }); - assert.strictEqual( + strictEqual( rec.resource.attributes['service.name'], 'test-instrumentation-pino' ); - assert.strictEqual(rec.instrumentationScope.name, PACKAGE_NAME); - assert.strictEqual(rec.instrumentationScope.version, PACKAGE_VERSION); - assert.strictEqual(rec.spanContext, undefined); + strictEqual(rec.instrumentationScope.name, PACKAGE_NAME); + strictEqual(rec.instrumentationScope.version, PACKAGE_VERSION); + strictEqual(rec.spanContext, undefined); // spanContext tracer.startActiveSpan('abc', span => { @@ -463,14 +470,14 @@ describe('PinoInstrumentation', () => { const { traceId, spanId, traceFlags } = span.spanContext(); const rec = logRecords[logRecords.length - 1]; - assert.strictEqual(rec.spanContext?.traceId, traceId); - assert.strictEqual(rec.spanContext?.spanId, spanId); - assert.strictEqual(rec.spanContext?.traceFlags, traceFlags); + strictEqual(rec.spanContext?.traceId, traceId); + strictEqual(rec.spanContext?.spanId, spanId); + strictEqual(rec.spanContext?.traceFlags, traceFlags); // This rec should *NOT* have the `trace_id` et al attributes. - assert.strictEqual(rec.attributes.trace_id, undefined); - assert.strictEqual(rec.attributes.span_id, undefined); - assert.strictEqual(rec.attributes.trace_flags, undefined); + strictEqual(rec.attributes.trace_id, undefined); + strictEqual(rec.attributes.span_id, undefined); + strictEqual(rec.attributes.trace_flags, undefined); }); }); @@ -486,15 +493,15 @@ describe('PinoInstrumentation', () => { logger.info('foo'); span.end(); - assert.strictEqual(memExporter.getFinishedLogRecords().length, 0); + strictEqual(memExporter.getFinishedLogRecords().length, 0); // Test log correlation still works. const { traceId, spanId } = span.spanContext(); - sinon.assert.calledOnce(writeSpy); + assert.calledOnce(writeSpy); const record = JSON.parse(writeSpy.firstCall.args[0].toString()); - assert.strictEqual('foo', record['msg']); - assert.strictEqual(record['trace_id'], traceId); - assert.strictEqual(record['span_id'], spanId); + strictEqual('foo', record['msg']); + strictEqual(record['trace_id'], traceId); + strictEqual(record['span_id'], spanId); }); }); @@ -507,11 +514,11 @@ describe('PinoInstrumentation', () => { // would be nice to maintain that "time" attribute if possible. logger.info({ time: 'miller' }, 'hi'); const rec = logRecords[logRecords.length - 1]; - assert.deepEqual( + deepEqual( rec.hrTime.map(n => typeof n), ['number', 'number'] ); - assert.strictEqual(rec.attributes.time, 'miller'); + strictEqual(rec.attributes.time, 'miller'); }); it('edge case: custom "timestamp" option', () => { @@ -522,32 +529,29 @@ describe('PinoInstrumentation', () => { logger.info('using false'); otelRec = logRecords[logRecords.length - 1]; pinoRec = JSON.parse(writeSpy.lastCall.args[0].toString()); - assert.deepEqual( + deepEqual( otelRec.hrTime.map(n => typeof n), ['number', 'number'] ); - assert.strictEqual(pinoRec.time, undefined); + strictEqual(pinoRec.time, undefined); logger = pino({ timestamp: pino.stdTimeFunctions.epochTime }, stream); logger.info('using epochTime'); otelRec = logRecords[logRecords.length - 1]; pinoRec = JSON.parse(writeSpy.lastCall.args[0].toString()); - assert.strictEqual(hrTimeToMilliseconds(otelRec.hrTime), pinoRec.time); + strictEqual(hrTimeToMilliseconds(otelRec.hrTime), pinoRec.time); logger = pino({ timestamp: pino.stdTimeFunctions.unixTime }, stream); logger.info('using unixTime'); otelRec = logRecords[logRecords.length - 1]; pinoRec = JSON.parse(writeSpy.lastCall.args[0].toString()); - assert.strictEqual( - hrTimeToMilliseconds(otelRec.hrTime), - pinoRec.time * 1e3 - ); + strictEqual(hrTimeToMilliseconds(otelRec.hrTime), pinoRec.time * 1e3); logger = pino({ timestamp: pino.stdTimeFunctions.isoTime }, stream); logger.info('using isoTime'); otelRec = logRecords[logRecords.length - 1]; pinoRec = JSON.parse(writeSpy.lastCall.args[0].toString()); - assert.strictEqual( + strictEqual( hrTimeToMilliseconds(otelRec.hrTime), new Date(pinoRec.time).getTime() ); @@ -556,12 +560,12 @@ describe('PinoInstrumentation', () => { logger.info('using custom timestamp fn'); otelRec = logRecords[logRecords.length - 1]; pinoRec = JSON.parse(writeSpy.lastCall.args[0].toString()); - assert.deepEqual( + deepEqual( otelRec.hrTime.map(n => typeof n), ['number', 'number'] ); - assert.strictEqual(pinoRec.time, 'quittin'); - assert.strictEqual(otelRec.attributes.time, 'quittin'); + strictEqual(pinoRec.time, 'quittin'); + strictEqual(otelRec.attributes.time, 'quittin'); }); // A custom 'timestamp' fn that returns invalid data will result in a Pino @@ -587,10 +591,10 @@ describe('PinoInstrumentation', () => { logger = pino({ timestamp: () => 'invalid JSON' }, stream); logger.info('using custom timestamp fn returning bogus result'); - assert.strictEqual(logRecords.length, 0); - assert.ok(writeSpy.lastCall.args[0].toString().includes('invalid JSON')); - assert.equal(diagWarns.length, 1); - assert.ok(diagWarns[0][1].includes('could not send pino log line')); + strictEqual(logRecords.length, 0); + ok(writeSpy.lastCall.args[0].toString().includes('invalid JSON')); + equal(diagWarns.length, 1); + ok(diagWarns[0][1].includes('could not send pino log line')); }); it('edge case: customLevels', () => { @@ -610,18 +614,18 @@ describe('PinoInstrumentation', () => { (logger as any).foo('foomsg'); rec = logRecords[logRecords.length - 1]; - assert.strictEqual(rec.severityNumber, SeverityNumber.WARN); - assert.strictEqual(rec.severityText, 'foo'); + strictEqual(rec.severityNumber, SeverityNumber.WARN); + strictEqual(rec.severityText, 'foo'); (logger as any).bar('barmsg'); rec = logRecords[logRecords.length - 1]; - assert.strictEqual(rec.severityNumber, SeverityNumber.INFO4); - assert.strictEqual(rec.severityText, 'bar'); + strictEqual(rec.severityNumber, SeverityNumber.INFO4); + strictEqual(rec.severityText, 'bar'); (logger as any).baz('bazmsg'); rec = logRecords[logRecords.length - 1]; - assert.strictEqual(rec.severityNumber, SeverityNumber.WARN2); - assert.strictEqual(rec.severityText, 'baz'); + strictEqual(rec.severityNumber, SeverityNumber.WARN2); + strictEqual(rec.severityText, 'baz'); }); it('edge case: customLevels and formatters.level', () => { @@ -643,12 +647,12 @@ describe('PinoInstrumentation', () => { const logRecords = memExporter.getFinishedLogRecords(); (logger as any).foo('foomsg'); const otelRec = logRecords[logRecords.length - 1]; - assert.strictEqual(otelRec.severityNumber, SeverityNumber.WARN); - assert.strictEqual(otelRec.severityText, 'foo'); + strictEqual(otelRec.severityNumber, SeverityNumber.WARN); + strictEqual(otelRec.severityText, 'foo'); - sinon.assert.calledOnce(writeSpy); + assert.calledOnce(writeSpy); const pinoRec = JSON.parse(writeSpy.firstCall.args[0].toString()); - assert.equal((pinoRec as any).level, 'foo'); + equal((pinoRec as any).level, 'foo'); }); it('edge case: customLevels and useOnlyCustomLevels', () => { @@ -669,13 +673,13 @@ describe('PinoInstrumentation', () => { (logger as any).foo('foomsg'); rec = logRecords[logRecords.length - 1]; - assert.strictEqual(rec.severityNumber, SeverityNumber.WARN); - assert.strictEqual(rec.severityText, 'foo'); + strictEqual(rec.severityNumber, SeverityNumber.WARN); + strictEqual(rec.severityText, 'foo'); (logger as any).bar('barmsg'); rec = logRecords[logRecords.length - 1]; - assert.strictEqual(rec.severityNumber, SeverityNumber.INFO4); - assert.strictEqual(rec.severityText, 'bar'); + strictEqual(rec.severityNumber, SeverityNumber.INFO4); + strictEqual(rec.severityText, 'bar'); }); // We use multistream internally to write to the OTel SDK. This test ensures @@ -685,7 +689,7 @@ describe('PinoInstrumentation', () => { const stream2 = new Writable(); stream2._write = () => {}; - const writeSpy2 = sinon.spy(stream2, 'write'); + const writeSpy2 = spy(stream2, 'write'); logger = pino( {}, @@ -694,15 +698,15 @@ describe('PinoInstrumentation', () => { logger.info('using multistream'); const otelRec = logRecords[logRecords.length - 1]; - assert.equal(otelRec.body, 'using multistream'); + equal(otelRec.body, 'using multistream'); - sinon.assert.calledOnce(writeSpy); + assert.calledOnce(writeSpy); const pinoRec = JSON.parse(writeSpy.firstCall.args[0].toString()); - assert.equal((pinoRec as any).msg, 'using multistream'); + equal((pinoRec as any).msg, 'using multistream'); - sinon.assert.calledOnce(writeSpy2); + assert.calledOnce(writeSpy2); const pinoRec2 = JSON.parse(writeSpy2.firstCall.args[0].toString()); - assert.equal((pinoRec2 as any).msg, 'using multistream'); + equal((pinoRec2 as any).msg, 'using multistream'); }); it('edge case: messageKey', () => { @@ -711,11 +715,11 @@ describe('PinoInstrumentation', () => { const logRecords = memExporter.getFinishedLogRecords(); const otelRec = logRecords[logRecords.length - 1]; - assert.equal(otelRec.body, 'using messageKey'); + equal(otelRec.body, 'using messageKey'); - sinon.assert.calledOnce(writeSpy); + assert.calledOnce(writeSpy); const pinoRec = JSON.parse(writeSpy.firstCall.args[0].toString()); - assert.equal((pinoRec as any).mymsg, 'using messageKey'); + equal((pinoRec as any).mymsg, 'using messageKey'); }); }); @@ -731,20 +735,20 @@ describe('PinoInstrumentation', () => { NODE_NO_WARNINGS: '1', }, checkResult: (err, stdout, _stderr) => { - assert.ifError(err); + ifError(err); logRecords = stdout .trim() .split('\n') .map(ln => JSON.parse(ln)); - assert.strictEqual(logRecords.length, 1); + strictEqual(logRecords.length, 1); }, checkCollector: (collector: TestCollector) => { // Check that both log records had the trace-context of the span injected. const spans = collector.sortedSpans; - assert.strictEqual(spans.length, 1); + strictEqual(spans.length, 1); logRecords.forEach(rec => { - assert.strictEqual(rec.trace_id, spans[0].traceId); - assert.strictEqual(rec.span_id, spans[0].spanId); + strictEqual(rec.trace_id, spans[0].traceId); + strictEqual(rec.span_id, spans[0].spanId); }); }, }); @@ -765,20 +769,20 @@ describe('PinoInstrumentation', () => { NODE_NO_WARNINGS: '1', }, checkResult: (err, stdout, _stderr) => { - assert.ifError(err); + ifError(err); logRecords = stdout .trim() .split('\n') .map(ln => JSON.parse(ln)); - assert.strictEqual(logRecords.length, 1); + strictEqual(logRecords.length, 1); }, checkCollector: (collector: TestCollector) => { // Check that both log records had the trace-context of the span injected. const spans = collector.sortedSpans; - assert.strictEqual(spans.length, 1); + strictEqual(spans.length, 1); logRecords.forEach(rec => { - assert.strictEqual(rec.trace_id, spans[0].traceId); - assert.strictEqual(rec.span_id, spans[0].spanId); + strictEqual(rec.trace_id, spans[0].traceId); + strictEqual(rec.span_id, spans[0].spanId); }); }, }); @@ -793,9 +797,9 @@ function assertRecord( expectedKeys?: PinoInstrumentationConfig['logKeys'] ) { const { traceId, spanId, traceFlags } = span.spanContext(); - assert.strictEqual(record[expectedKeys?.traceId ?? 'trace_id'], traceId); - assert.strictEqual(record[expectedKeys?.spanId ?? 'span_id'], spanId); - assert.strictEqual( + strictEqual(record[expectedKeys?.traceId ?? 'trace_id'], traceId); + strictEqual(record[expectedKeys?.spanId ?? 'span_id'], spanId); + strictEqual( record[expectedKeys?.traceFlags ?? 'trace_flags'], `0${traceFlags.toString(16)}` ); diff --git a/plugins/node/opentelemetry-instrumentation-redis-4/src/index.ts b/plugins/node/opentelemetry-instrumentation-redis-4/src/index.ts index c26f998cff..bf64b57896 100644 --- a/plugins/node/opentelemetry-instrumentation-redis-4/src/index.ts +++ b/plugins/node/opentelemetry-instrumentation-redis-4/src/index.ts @@ -14,5 +14,9 @@ * limitations under the License. */ -export * from './instrumentation'; -export * from './types'; +export { RedisInstrumentation } from './instrumentation'; +export { + DbStatementSerializer, + RedisResponseCustomAttributeFunction, + RedisInstrumentationConfig, +} from './types'; diff --git a/plugins/node/opentelemetry-instrumentation-redis-4/test/redis.test.ts b/plugins/node/opentelemetry-instrumentation-redis-4/test/redis.test.ts index 14b439e797..381cb83232 100644 --- a/plugins/node/opentelemetry-instrumentation-redis-4/test/redis.test.ts +++ b/plugins/node/opentelemetry-instrumentation-redis-4/test/redis.test.ts @@ -21,7 +21,7 @@ import { } from '@opentelemetry/contrib-test-utils'; import { RedisInstrumentation } from '../src'; import type { MultiErrorReply } from '../src/internal-types'; -import * as assert from 'assert'; +import { strictEqual, ok, rejects, deepStrictEqual, fail } from 'assert'; import { redisTestConfig, @@ -94,48 +94,48 @@ describe('redis@^4.0.0', () => { it('simple set and get', async () => { await client.set('key', 'value'); const value = await client.get('key'); - assert.strictEqual(value, 'value'); // verify we did not screw up the normal functionality + strictEqual(value, 'value'); // verify we did not screw up the normal functionality const spans = getTestSpans(); - assert.strictEqual(spans.length, 2); + strictEqual(spans.length, 2); const setSpan = spans.find(s => s.name.includes('SET')); - assert.ok(setSpan); - assert.strictEqual(setSpan?.kind, SpanKind.CLIENT); - assert.strictEqual(setSpan?.name, 'redis-SET'); - assert.strictEqual(setSpan?.attributes[SEMATTRS_DB_SYSTEM], 'redis'); - assert.strictEqual( + ok(setSpan); + strictEqual(setSpan?.kind, SpanKind.CLIENT); + strictEqual(setSpan?.name, 'redis-SET'); + strictEqual(setSpan?.attributes[SEMATTRS_DB_SYSTEM], 'redis'); + strictEqual( setSpan?.attributes[SEMATTRS_DB_STATEMENT], 'SET key [1 other arguments]' ); - assert.strictEqual( + strictEqual( setSpan?.attributes[SEMATTRS_NET_PEER_NAME], redisTestConfig.host ); - assert.strictEqual( + strictEqual( setSpan?.attributes[SEMATTRS_NET_PEER_PORT], redisTestConfig.port ); - assert.strictEqual( + strictEqual( setSpan?.attributes[SEMATTRS_DB_CONNECTION_STRING], redisTestUrl ); const getSpan = spans.find(s => s.name.includes('GET')); - assert.ok(getSpan); - assert.strictEqual(getSpan?.kind, SpanKind.CLIENT); - assert.strictEqual(getSpan?.name, 'redis-GET'); - assert.strictEqual(getSpan?.attributes[SEMATTRS_DB_SYSTEM], 'redis'); - assert.strictEqual(getSpan?.attributes[SEMATTRS_DB_STATEMENT], 'GET key'); - assert.strictEqual( + ok(getSpan); + strictEqual(getSpan?.kind, SpanKind.CLIENT); + strictEqual(getSpan?.name, 'redis-GET'); + strictEqual(getSpan?.attributes[SEMATTRS_DB_SYSTEM], 'redis'); + strictEqual(getSpan?.attributes[SEMATTRS_DB_STATEMENT], 'GET key'); + strictEqual( getSpan?.attributes[SEMATTRS_NET_PEER_NAME], redisTestConfig.host ); - assert.strictEqual( + strictEqual( getSpan?.attributes[SEMATTRS_NET_PEER_PORT], redisTestConfig.port ); - assert.strictEqual( + strictEqual( getSpan?.attributes[SEMATTRS_DB_CONNECTION_STRING], redisTestUrl ); @@ -143,20 +143,20 @@ describe('redis@^4.0.0', () => { it('send general command', async () => { const res = await client.sendCommand(['SET', 'key', 'value']); - assert.strictEqual(res, 'OK'); // verify we did not screw up the normal functionality + strictEqual(res, 'OK'); // verify we did not screw up the normal functionality const [setSpan] = getTestSpans(); - assert.ok(setSpan); - assert.strictEqual( + ok(setSpan); + strictEqual( setSpan?.attributes[SEMATTRS_DB_STATEMENT], 'SET key [1 other arguments]' ); - assert.strictEqual( + strictEqual( setSpan?.attributes[SEMATTRS_NET_PEER_NAME], redisTestConfig.host ); - assert.strictEqual( + strictEqual( setSpan?.attributes[SEMATTRS_NET_PEER_PORT], redisTestConfig.port ); @@ -164,13 +164,13 @@ describe('redis@^4.0.0', () => { it('command with error', async () => { await client.set('string-key', 'string-value'); - await assert.rejects(async () => await client.incr('string-key')); + await rejects(async () => await client.incr('string-key')); const [_setSpan, incrSpan] = getTestSpans(); - assert.ok(incrSpan); - assert.strictEqual(incrSpan?.status.code, SpanStatusCode.ERROR); - assert.strictEqual( + ok(incrSpan); + strictEqual(incrSpan?.status.code, SpanStatusCode.ERROR); + strictEqual( incrSpan?.status.message, 'ERR value is not an integer or out of range' ); @@ -178,8 +178,8 @@ describe('redis@^4.0.0', () => { const exceptions = incrSpan.events.filter( event => event.name === 'exception' ); - assert.strictEqual(exceptions.length, 1); - assert.strictEqual( + strictEqual(exceptions.length, 1); + strictEqual( exceptions?.[0].attributes?.[SEMATTRS_EXCEPTION_MESSAGE], 'ERR value is not an integer or out of range' ); @@ -200,21 +200,18 @@ describe('redis@^4.0.0', () => { const [span] = getTestSpans(); - assert.strictEqual(span.name, 'redis-connect'); + strictEqual(span.name, 'redis-connect'); - assert.strictEqual(span.attributes[SEMATTRS_DB_SYSTEM], 'redis'); - assert.strictEqual( + strictEqual(span.attributes[SEMATTRS_DB_SYSTEM], 'redis'); + strictEqual( span.attributes[SEMATTRS_NET_PEER_NAME], redisTestConfig.host ); - assert.strictEqual( + strictEqual( span.attributes[SEMATTRS_NET_PEER_PORT], redisTestConfig.port ); - assert.strictEqual( - span.attributes[SEMATTRS_DB_CONNECTION_STRING], - redisTestUrl - ); + strictEqual(span.attributes[SEMATTRS_DB_CONNECTION_STRING], redisTestUrl); }); it('sets error status on connection failure', async () => { @@ -225,16 +222,13 @@ describe('redis@^4.0.0', () => { url: redisURL, }); - await assert.rejects(newClient.connect()); + await rejects(newClient.connect()); const [span] = getTestSpans(); - assert.strictEqual(span.name, 'redis-connect'); - assert.strictEqual(span.status.code, SpanStatusCode.ERROR); - assert.strictEqual( - span.attributes[SEMATTRS_DB_CONNECTION_STRING], - redisURL - ); + strictEqual(span.name, 'redis-connect'); + strictEqual(span.status.code, SpanStatusCode.ERROR); + strictEqual(span.attributes[SEMATTRS_DB_CONNECTION_STRING], redisURL); }); it('omits basic auth from DB_CONNECTION_STRING span attribute', async () => { @@ -248,17 +242,17 @@ describe('redis@^4.0.0', () => { url: redisURL, }); - await assert.rejects(newClient.connect()); + await rejects(newClient.connect()); const [span] = getTestSpans(); - assert.strictEqual(span.name, 'redis-connect'); - assert.strictEqual(span.status.code, SpanStatusCode.ERROR); - assert.strictEqual( + strictEqual(span.name, 'redis-connect'); + strictEqual(span.status.code, SpanStatusCode.ERROR); + strictEqual( span.attributes[SEMATTRS_NET_PEER_NAME], redisTestConfig.host ); - assert.strictEqual( + strictEqual( span.attributes[SEMATTRS_DB_CONNECTION_STRING], expectAttributeConnString ); @@ -275,17 +269,17 @@ describe('redis@^4.0.0', () => { url: redisURL, }); - await assert.rejects(newClient.connect()); + await rejects(newClient.connect()); const [span] = getTestSpans(); - assert.strictEqual(span.name, 'redis-connect'); - assert.strictEqual(span.status.code, SpanStatusCode.ERROR); - assert.strictEqual( + strictEqual(span.name, 'redis-connect'); + strictEqual(span.status.code, SpanStatusCode.ERROR); + strictEqual( span.attributes[SEMATTRS_NET_PEER_NAME], redisTestConfig.host ); - assert.strictEqual( + strictEqual( span.attributes[SEMATTRS_DB_CONNECTION_STRING], expectAttributeConnString ); @@ -317,8 +311,8 @@ describe('redis@^4.0.0', () => { await newClient.disconnect(); const [span] = getTestSpans(); - assert.strictEqual(span.name, 'redis-connect'); - assert.strictEqual(diagErrors.length, 0, "no diag.error's"); + strictEqual(span.name, 'redis-connect'); + strictEqual(diagErrors.length, 0, "no diag.error's"); }); }); @@ -331,47 +325,47 @@ describe('redis@^4.0.0', () => { .get('another-key') .exec(); // ['OK', 'another-value'] - assert.strictEqual(setKeyReply, 'OK'); // verify we did not screw up the normal functionality - assert.strictEqual(otherKeyValue, 'another-value'); // verify we did not screw up the normal functionality + strictEqual(setKeyReply, 'OK'); // verify we did not screw up the normal functionality + strictEqual(otherKeyValue, 'another-value'); // verify we did not screw up the normal functionality const [setSpan, multiSetSpan, multiGetSpan] = getTestSpans(); - assert.ok(setSpan); + ok(setSpan); - assert.ok(multiSetSpan); - assert.strictEqual(multiSetSpan.name, 'redis-SET'); - assert.strictEqual( + ok(multiSetSpan); + strictEqual(multiSetSpan.name, 'redis-SET'); + strictEqual( multiSetSpan.attributes[SEMATTRS_DB_STATEMENT], 'SET key [1 other arguments]' ); - assert.strictEqual( + strictEqual( multiSetSpan?.attributes[SEMATTRS_NET_PEER_NAME], redisTestConfig.host ); - assert.strictEqual( + strictEqual( multiSetSpan?.attributes[SEMATTRS_NET_PEER_PORT], redisTestConfig.port ); - assert.strictEqual( + strictEqual( multiSetSpan?.attributes[SEMATTRS_DB_CONNECTION_STRING], redisTestUrl ); - assert.ok(multiGetSpan); - assert.strictEqual(multiGetSpan.name, 'redis-GET'); - assert.strictEqual( + ok(multiGetSpan); + strictEqual(multiGetSpan.name, 'redis-GET'); + strictEqual( multiGetSpan.attributes[SEMATTRS_DB_STATEMENT], 'GET another-key' ); - assert.strictEqual( + strictEqual( multiGetSpan?.attributes[SEMATTRS_NET_PEER_NAME], redisTestConfig.host ); - assert.strictEqual( + strictEqual( multiGetSpan?.attributes[SEMATTRS_NET_PEER_PORT], redisTestConfig.port ); - assert.strictEqual( + strictEqual( multiGetSpan?.attributes[SEMATTRS_DB_CONNECTION_STRING], redisTestUrl ); @@ -382,23 +376,23 @@ describe('redis@^4.0.0', () => { .multi() .addCommand(['SET', 'key', 'value']) .exec(); - assert.strictEqual(setReply, 'OK'); // verify we did not screw up the normal functionality + strictEqual(setReply, 'OK'); // verify we did not screw up the normal functionality const [multiSetSpan] = getTestSpans(); - assert.ok(multiSetSpan); - assert.strictEqual( + ok(multiSetSpan); + strictEqual( multiSetSpan.attributes[SEMATTRS_DB_STATEMENT], 'SET key [1 other arguments]' ); - assert.strictEqual( + strictEqual( multiSetSpan?.attributes[SEMATTRS_NET_PEER_NAME], redisTestConfig.host ); - assert.strictEqual( + strictEqual( multiSetSpan?.attributes[SEMATTRS_NET_PEER_PORT], redisTestConfig.port ); - assert.strictEqual( + strictEqual( multiSetSpan?.attributes[SEMATTRS_DB_CONNECTION_STRING], redisTestUrl ); @@ -415,17 +409,17 @@ describe('redis@^4.0.0', () => { } const [setReply, incrReply] = replies; - assert.strictEqual(setReply, 'OK'); // verify we did not screw up the normal functionality - assert.ok(incrReply instanceof Error); // verify we did not screw up the normal functionality + strictEqual(setReply, 'OK'); // verify we did not screw up the normal functionality + ok(incrReply instanceof Error); // verify we did not screw up the normal functionality const [multiSetSpan, multiIncrSpan] = getTestSpans(); - assert.ok(multiSetSpan); - assert.strictEqual(multiSetSpan.status.code, SpanStatusCode.UNSET); + ok(multiSetSpan); + strictEqual(multiSetSpan.status.code, SpanStatusCode.UNSET); - assert.ok(multiIncrSpan); - assert.strictEqual(multiIncrSpan.status.code, SpanStatusCode.ERROR); - assert.strictEqual( + ok(multiIncrSpan); + strictEqual(multiIncrSpan.status.code, SpanStatusCode.ERROR); + strictEqual( multiIncrSpan.status.message, 'ERR value is not an integer or out of range' ); @@ -437,15 +431,15 @@ describe('redis@^4.0.0', () => { await client.set(watchedKey, 'a different value'); try { await client.multi().get(watchedKey).exec(); - assert.fail('expected WatchError to be thrown and caught in try/catch'); + fail('expected WatchError to be thrown and caught in try/catch'); } catch (error) { - assert.ok(error instanceof WatchError); + ok(error instanceof WatchError); } // All the multi spans' status are set to ERROR. const [_watchSpan, _setSpan, multiGetSpan] = getTestSpans(); - assert.strictEqual(multiGetSpan?.status.code, SpanStatusCode.ERROR); - assert.strictEqual( + strictEqual(multiGetSpan?.status.code, SpanStatusCode.ERROR); + strictEqual( multiGetSpan?.status.message, 'One (or more) of the watched keys has been changed' ); @@ -461,8 +455,8 @@ describe('redis@^4.0.0', () => { commands = commands.get('another-key'); const [setKeyReply, otherKeyValue] = await commands.exec(); // ['OK', 'another-value'] - assert.strictEqual(setKeyReply, 'OK'); // verify we did not screw up the normal functionality - assert.strictEqual(otherKeyValue, 'another-value'); // verify we did not screw up the normal functionality + strictEqual(setKeyReply, 'OK'); // verify we did not screw up the normal functionality + strictEqual(otherKeyValue, 'another-value'); // verify we did not screw up the normal functionality const [_setSpan, multiSetSpan, multiGetSpan] = getTestSpans(); // verify that commands span started when it was added to multi and not when "sent". @@ -471,7 +465,7 @@ describe('redis@^4.0.0', () => { const startTimeDiff = hrTimeToMilliseconds(multiGetSpan.startTime) - hrTimeToMilliseconds(multiSetSpan.startTime); - assert.ok( + ok( startTimeDiff >= 9, `diff of start time should be >= 10 and it's ${startTimeDiff}` ); @@ -479,7 +473,7 @@ describe('redis@^4.0.0', () => { const endTimeDiff = hrTimeToMilliseconds(multiGetSpan.endTime) - hrTimeToMilliseconds(multiSetSpan.endTime); - assert.ok(endTimeDiff < 10); // spans should all end together when multi response arrives from redis server + ok(endTimeDiff < 10); // spans should all end together when multi response arrives from redis server }); it('response hook for multi commands', async () => { @@ -501,28 +495,25 @@ describe('redis@^4.0.0', () => { .set('key', 'value') .get('another-key') .exec(); // ['OK', 'another-value'] - assert.strictEqual(setKeyReply, 'OK'); // verify we did not screw up the normal functionality - assert.strictEqual(otherKeyValue, 'another-value'); // verify we did not screw up the normal functionality + strictEqual(setKeyReply, 'OK'); // verify we did not screw up the normal functionality + strictEqual(otherKeyValue, 'another-value'); // verify we did not screw up the normal functionality const [_setSpan, multiSetSpan, multiGetSpan] = getTestSpans(); - assert.ok(multiSetSpan); - assert.strictEqual(multiSetSpan.attributes['test.cmd.name'], 'SET'); - assert.deepStrictEqual(multiSetSpan.attributes['test.cmd.args'], [ + ok(multiSetSpan); + strictEqual(multiSetSpan.attributes['test.cmd.name'], 'SET'); + deepStrictEqual(multiSetSpan.attributes['test.cmd.args'], [ 'key', 'value', ]); - assert.strictEqual(multiSetSpan.attributes['test.db.response'], 'OK'); + strictEqual(multiSetSpan.attributes['test.db.response'], 'OK'); - assert.ok(multiGetSpan); - assert.strictEqual(multiGetSpan.attributes['test.cmd.name'], 'GET'); - assert.deepStrictEqual(multiGetSpan.attributes['test.cmd.args'], [ + ok(multiGetSpan); + strictEqual(multiGetSpan.attributes['test.cmd.name'], 'GET'); + deepStrictEqual(multiGetSpan.attributes['test.cmd.args'], [ 'another-key', ]); - assert.strictEqual( - multiGetSpan.attributes['test.db.response'], - 'another-value' - ); + strictEqual(multiGetSpan.attributes['test.db.response'], 'another-value'); }); }); @@ -539,10 +530,7 @@ describe('redis@^4.0.0', () => { instrumentation.setConfig({ dbStatementSerializer }); await client.set('key', 'value'); const [span] = getTestSpans(); - assert.strictEqual( - span.attributes[SEMATTRS_DB_STATEMENT], - 'SET key value' - ); + strictEqual(span.attributes[SEMATTRS_DB_STATEMENT], 'SET key value'); }); it('dbStatementSerializer throws', async () => { @@ -553,8 +541,8 @@ describe('redis@^4.0.0', () => { instrumentation.setConfig({ dbStatementSerializer }); await client.set('key', 'value'); const [span] = getTestSpans(); - assert.ok(span); - assert.ok(!(SEMATTRS_DB_STATEMENT in span.attributes)); + ok(span); + ok(!(SEMATTRS_DB_STATEMENT in span.attributes)); }); }); @@ -573,13 +561,10 @@ describe('redis@^4.0.0', () => { instrumentation.setConfig({ responseHook }); await client.set('key', 'value'); const [span] = getTestSpans(); - assert.ok(span); - assert.strictEqual(span.attributes['test.cmd.name'], 'SET'); - assert.deepStrictEqual(span.attributes['test.cmd.args'], [ - 'key', - 'value', - ]); - assert.strictEqual(span.attributes['test.db.response'], 'OK'); + ok(span); + strictEqual(span.attributes['test.cmd.name'], 'SET'); + deepStrictEqual(span.attributes['test.cmd.args'], ['key', 'value']); + strictEqual(span.attributes['test.db.response'], 'OK'); }); it('responseHook throws', async () => { @@ -588,9 +573,9 @@ describe('redis@^4.0.0', () => { }; instrumentation.setConfig({ responseHook }); const res = await client.set('key', 'value'); - assert.strictEqual(res, 'OK'); // package is still functional + strictEqual(res, 'OK'); // package is still functional const [span] = getTestSpans(); - assert.ok(span); + ok(span); }); }); @@ -600,15 +585,15 @@ describe('redis@^4.0.0', () => { // no parent span => no redis span const res = await client.set('key', 'value'); - assert.strictEqual(res, 'OK'); // verify we did not screw up the normal functionality - assert.ok(getTestSpans().length === 0); + strictEqual(res, 'OK'); // verify we did not screw up the normal functionality + ok(getTestSpans().length === 0); // has ambient span => redis span const span = trace.getTracer('test').startSpan('test span'); await context.with(trace.setSpan(context.active(), span), async () => { const res = await client.set('key', 'value'); - assert.strictEqual(res, 'OK'); // verify we did not screw up the normal functionality - assert.ok(getTestSpans().length === 1); + strictEqual(res, 'OK'); // verify we did not screw up the normal functionality + ok(getTestSpans().length === 1); }); span.end(); }); diff --git a/plugins/node/opentelemetry-instrumentation-redis/src/index.ts b/plugins/node/opentelemetry-instrumentation-redis/src/index.ts index c26f998cff..2c72b0b752 100644 --- a/plugins/node/opentelemetry-instrumentation-redis/src/index.ts +++ b/plugins/node/opentelemetry-instrumentation-redis/src/index.ts @@ -14,5 +14,10 @@ * limitations under the License. */ -export * from './instrumentation'; -export * from './types'; +export { RedisInstrumentation } from './instrumentation'; +export { + RedisCommand, + DbStatementSerializer, + RedisResponseCustomAttributeFunction, + RedisInstrumentationConfig, +} from './types'; diff --git a/plugins/node/opentelemetry-instrumentation-restify/src/index.ts b/plugins/node/opentelemetry-instrumentation-restify/src/index.ts index 45cd8db559..f911c003f0 100644 --- a/plugins/node/opentelemetry-instrumentation-restify/src/index.ts +++ b/plugins/node/opentelemetry-instrumentation-restify/src/index.ts @@ -14,6 +14,11 @@ * limitations under the License. */ -export * from './instrumentation'; -export * from './enums/AttributeNames'; -export * from './types'; +export { RestifyInstrumentation } from './instrumentation'; +export { AttributeNames } from './enums/AttributeNames'; +export { + LayerType, + RestifyRequestInfo, + RestifyCustomAttributeFunction, + RestifyInstrumentationConfig, +} from './types'; diff --git a/plugins/node/opentelemetry-instrumentation-restify/test/restify.test.ts b/plugins/node/opentelemetry-instrumentation-restify/test/restify.test.ts index ee7e6c524e..a1df3a6638 100644 --- a/plugins/node/opentelemetry-instrumentation-restify/test/restify.test.ts +++ b/plugins/node/opentelemetry-instrumentation-restify/test/restify.test.ts @@ -30,15 +30,16 @@ import { RestifyRequestInfo } from '../src/types'; const plugin = new RestifyInstrumentation(); import * as semver from 'semver'; -import * as assert from 'assert'; +import { deepEqual, strictEqual, notStrictEqual } from 'assert'; import * as http from 'http'; import { AddressInfo } from 'net'; +import assert = require('assert'); import * as restify from 'restify'; const LIB_VERSION = require('restify/package.json').version; const assertIsVersion = (str: any) => { - assert.strictEqual(typeof str, 'string'); + strictEqual(typeof str, 'string'); assert(/^[0-9]+\.[0-9]+\.[0-9]+$/.test(str)); }; @@ -142,7 +143,7 @@ describe('Restify Instrumentation', () => { server = await createServer(); port = (server.address() as AddressInfo).port; - assert.strictEqual(memoryExporter.getFinishedSpans().length, 0); + strictEqual(memoryExporter.getFinishedSpans().length, 0); }); afterEach(() => { @@ -160,39 +161,36 @@ describe('Restify Instrumentation', () => { async () => { await httpRequest.get(`http://localhost:${port}/route/foo`); rootSpan.end(); - assert.strictEqual(memoryExporter.getFinishedSpans().length, 4); + strictEqual(memoryExporter.getFinishedSpans().length, 4); { // span from pre const span = memoryExporter.getFinishedSpans()[0]; - assert.notStrictEqual(span, undefined); - assert.strictEqual(span.attributes['http.route'], undefined); - assert.strictEqual(span.attributes['restify.method'], 'pre'); - assert.strictEqual(span.attributes['restify.type'], 'middleware'); - assert.strictEqual(span.attributes['restify.name'], undefined); + notStrictEqual(span, undefined); + strictEqual(span.attributes['http.route'], undefined); + strictEqual(span.attributes['restify.method'], 'pre'); + strictEqual(span.attributes['restify.type'], 'middleware'); + strictEqual(span.attributes['restify.name'], undefined); assertIsVersion(span.attributes['restify.version']); } { // span from use const span = memoryExporter.getFinishedSpans()[1]; - assert.notStrictEqual(span, undefined); - assert.strictEqual(span.attributes['http.route'], '/route/:param'); - assert.strictEqual(span.attributes['restify.method'], 'use'); - assert.strictEqual(span.attributes['restify.type'], 'middleware'); - assert.strictEqual(span.attributes['restify.name'], 'useHandler'); + notStrictEqual(span, undefined); + strictEqual(span.attributes['http.route'], '/route/:param'); + strictEqual(span.attributes['restify.method'], 'use'); + strictEqual(span.attributes['restify.type'], 'middleware'); + strictEqual(span.attributes['restify.name'], 'useHandler'); assertIsVersion(span.attributes['restify.version']); } { // span from get const span = memoryExporter.getFinishedSpans()[2]; - assert.notStrictEqual(span, undefined); - assert.strictEqual(span.attributes['http.route'], '/route/:param'); - assert.strictEqual(span.attributes['restify.method'], 'get'); - assert.strictEqual( - span.attributes['restify.type'], - 'request_handler' - ); - assert.strictEqual(span.attributes['restify.name'], 'getHandler'); + notStrictEqual(span, undefined); + strictEqual(span.attributes['http.route'], '/route/:param'); + strictEqual(span.attributes['restify.method'], 'get'); + strictEqual(span.attributes['restify.type'], 'request_handler'); + strictEqual(span.attributes['restify.name'], 'getHandler'); assertIsVersion(span.attributes['restify.version']); } } @@ -209,19 +207,19 @@ describe('Restify Instrumentation', () => { `http://localhost:${port}/not-found` ); rootSpan.end(); - assert.strictEqual(memoryExporter.getFinishedSpans().length, 2); + strictEqual(memoryExporter.getFinishedSpans().length, 2); { // span from pre const span = memoryExporter.getFinishedSpans()[0]; - assert.notStrictEqual(span, undefined); - assert.strictEqual(span.attributes['http.route'], undefined); - assert.strictEqual(span.attributes['restify.method'], 'pre'); - assert.strictEqual(span.attributes['restify.type'], 'middleware'); - assert.strictEqual(span.attributes['restify.name'], undefined); + notStrictEqual(span, undefined); + strictEqual(span.attributes['http.route'], undefined); + strictEqual(span.attributes['restify.method'], 'pre'); + strictEqual(span.attributes['restify.type'], 'middleware'); + strictEqual(span.attributes['restify.name'], undefined); assertIsVersion(span.attributes['restify.version']); } - assert.strictEqual( + strictEqual( res, '{"code":"ResourceNotFound","message":"/not-found does not exist"}' ); @@ -239,54 +237,47 @@ describe('Restify Instrumentation', () => { `http://localhost:${port}/erroring` ); rootSpan.end(); - assert.strictEqual(memoryExporter.getFinishedSpans().length, 4); + strictEqual(memoryExporter.getFinishedSpans().length, 4); - if (semver.satisfies(LIB_VERSION, '>=8.2.0')) { - // Error handling changed slightly in v8.2.0 (https://github.com/restify/node-restify/pull/1757). - assert.deepEqual( - result, - '{"code":"Internal","message":"Error: NOK"}' - ); - } else if (semver.satisfies(LIB_VERSION, '>=7 <8.2.0')) { - assert.deepEqual( + if (semver.satisfies(LIB_VERSION, '>=8')) { + deepEqual(result, '{"code":"Internal","message":"Error: NOK"}'); + } else if (semver.satisfies(LIB_VERSION, '>=7 <8')) { + deepEqual( result, '{"code":"Internal","message":"caused by Error: NOK"}' ); } else { - assert.deepEqual(result, '{"message":"NOK"}'); + deepEqual(result, '{"message":"NOK"}'); } { // span from pre const span = memoryExporter.getFinishedSpans()[0]; - assert.notStrictEqual(span, undefined); - assert.strictEqual(span.attributes['http.route'], undefined); - assert.strictEqual(span.attributes['restify.method'], 'pre'); - assert.strictEqual(span.attributes['restify.type'], 'middleware'); - assert.strictEqual(span.attributes['restify.name'], undefined); + notStrictEqual(span, undefined); + strictEqual(span.attributes['http.route'], undefined); + strictEqual(span.attributes['restify.method'], 'pre'); + strictEqual(span.attributes['restify.type'], 'middleware'); + strictEqual(span.attributes['restify.name'], undefined); assertIsVersion(span.attributes['restify.version']); } { // span from use const span = memoryExporter.getFinishedSpans()[1]; - assert.notStrictEqual(span, undefined); - assert.strictEqual(span.attributes['http.route'], '/erroring'); - assert.strictEqual(span.attributes['restify.method'], 'use'); - assert.strictEqual(span.attributes['restify.type'], 'middleware'); - assert.strictEqual(span.attributes['restify.name'], 'useHandler'); + notStrictEqual(span, undefined); + strictEqual(span.attributes['http.route'], '/erroring'); + strictEqual(span.attributes['restify.method'], 'use'); + strictEqual(span.attributes['restify.type'], 'middleware'); + strictEqual(span.attributes['restify.name'], 'useHandler'); assertIsVersion(span.attributes['restify.version']); } { // span from get const span = memoryExporter.getFinishedSpans()[2]; - assert.notStrictEqual(span, undefined); - assert.strictEqual(span.attributes['http.route'], '/erroring'); - assert.strictEqual(span.attributes['restify.method'], 'get'); - assert.strictEqual( - span.attributes['restify.type'], - 'request_handler' - ); - assert.strictEqual(span.attributes['restify.name'], 'returnError'); + notStrictEqual(span, undefined); + strictEqual(span.attributes['http.route'], '/erroring'); + strictEqual(span.attributes['restify.method'], 'get'); + strictEqual(span.attributes['restify.type'], 'request_handler'); + strictEqual(span.attributes['restify.name'], 'returnError'); assertIsVersion(span.attributes['restify.version']); } } @@ -320,9 +311,9 @@ describe('Restify Instrumentation', () => { `http://localhost:${testLocalPort}/route/hello` ); httpSpan.end(); - assert.strictEqual(memoryExporter.getFinishedSpans().length, 3); - assert.strictEqual(rpcMetadata.route, '/route/:param'); - assert.strictEqual(res, '{"route":"hello"}'); + strictEqual(memoryExporter.getFinishedSpans().length, 3); + strictEqual(rpcMetadata.route, '/route/:param'); + strictEqual(res, '{"route":"hello"}'); } finally { testLocalServer.close(); } @@ -343,21 +334,18 @@ describe('Restify Instrumentation', () => { const res = await httpRequest.get( `http://localhost:${testLocalPort}/route/hello` ); - assert.strictEqual(memoryExporter.getFinishedSpans().length, 1); + strictEqual(memoryExporter.getFinishedSpans().length, 1); { // span from get const span = memoryExporter.getFinishedSpans()[0]; - assert.notStrictEqual(span, undefined); - assert.strictEqual(span.attributes['http.route'], '/route/:param'); - assert.strictEqual(span.attributes['restify.method'], 'get'); - assert.strictEqual( - span.attributes['restify.type'], - 'request_handler' - ); - assert.strictEqual(span.attributes['restify.name'], 'getHandler'); + notStrictEqual(span, undefined); + strictEqual(span.attributes['http.route'], '/route/:param'); + strictEqual(span.attributes['restify.method'], 'get'); + strictEqual(span.attributes['restify.type'], 'request_handler'); + strictEqual(span.attributes['restify.name'], 'getHandler'); assertIsVersion(span.attributes['restify.version']); } - assert.strictEqual(res, '{"route":"hello"}'); + strictEqual(res, '{"route":"hello"}'); } finally { testLocalServer.close(); } @@ -385,34 +373,31 @@ describe('Restify Instrumentation', () => { .get(`http://localhost:${testLocalPort}/route/hello`) .then(res => { // assert request results - assert.strictEqual(res, '{"route":"hello"}'); + strictEqual(res, '{"route":"hello"}'); }); // assert pre request state - assert.strictEqual(status, 'uninit'); + strictEqual(status, 'uninit'); await started; // assert started state - assert.strictEqual(status, 'started'); - assert.strictEqual(memoryExporter.getFinishedSpans().length, 0); + strictEqual(status, 'started'); + strictEqual(memoryExporter.getFinishedSpans().length, 0); resolveWork(); await requestPromise; // assert done state - assert.strictEqual(status, 'done'); - assert.strictEqual(memoryExporter.getFinishedSpans().length, 1); + strictEqual(status, 'done'); + strictEqual(memoryExporter.getFinishedSpans().length, 1); { // span from get const span = memoryExporter.getFinishedSpans()[0]; - assert.notStrictEqual(span, undefined); - assert.strictEqual(span.attributes['http.route'], '/route/:param'); - assert.strictEqual(span.attributes['restify.method'], 'get'); - assert.strictEqual( - span.attributes['restify.type'], - 'request_handler' - ); - assert.strictEqual(span.attributes['restify.name'], 'asyncHandler'); + notStrictEqual(span, undefined); + strictEqual(span.attributes['http.route'], '/route/:param'); + strictEqual(span.attributes['restify.method'], 'get'); + strictEqual(span.attributes['restify.type'], 'request_handler'); + strictEqual(span.attributes['restify.name'], 'asyncHandler'); assertIsVersion(span.attributes['restify.version']); } } finally { @@ -447,34 +432,31 @@ describe('Restify Instrumentation', () => { .get(`http://localhost:${testLocalPort}/route/hello`) .then(res => { // assert request results - assert.strictEqual(res, '{"route":"hello"}'); + strictEqual(res, '{"route":"hello"}'); }); // assert pre request state - assert.strictEqual(status, 'uninit'); + strictEqual(status, 'uninit'); await started; // assert started state - assert.strictEqual(status, 'started'); - assert.strictEqual(memoryExporter.getFinishedSpans().length, 0); + strictEqual(status, 'started'); + strictEqual(memoryExporter.getFinishedSpans().length, 0); resolveWork(); await requestPromise; // assert done state - assert.strictEqual(status, 'done'); - assert.strictEqual(memoryExporter.getFinishedSpans().length, 1); + strictEqual(status, 'done'); + strictEqual(memoryExporter.getFinishedSpans().length, 1); { // span from get const span = memoryExporter.getFinishedSpans()[0]; - assert.notStrictEqual(span, undefined); - assert.strictEqual(span.attributes['http.route'], '/route/:param'); - assert.strictEqual(span.attributes['restify.method'], 'get'); - assert.strictEqual( - span.attributes['restify.type'], - 'request_handler' - ); - assert.strictEqual( + notStrictEqual(span, undefined); + strictEqual(span.attributes['http.route'], '/route/:param'); + strictEqual(span.attributes['restify.method'], 'get'); + strictEqual(span.attributes['restify.type'], 'request_handler'); + strictEqual( span.attributes['restify.name'], 'promiseReturningHandler' ); @@ -487,8 +469,8 @@ describe('Restify Instrumentation', () => { it('should create spans even if there is no parent', async () => { const res = await httpRequest.get(`http://localhost:${port}/route/bar`); - assert.strictEqual(memoryExporter.getFinishedSpans().length, 3); - assert.strictEqual(res, '{"route":"bar"}'); + strictEqual(memoryExporter.getFinishedSpans().length, 3); + strictEqual(res, '{"route":"bar"}'); }); describe('using requestHook in config', () => { @@ -510,17 +492,14 @@ describe('Restify Instrumentation', () => { async () => { await httpRequest.get(`http://localhost:${port}/route/foo`); rootSpan.end(); - assert.strictEqual(memoryExporter.getFinishedSpans().length, 4); + strictEqual(memoryExporter.getFinishedSpans().length, 4); { // span from get const span = memoryExporter.getFinishedSpans()[2]; - assert.notStrictEqual(span, undefined); - assert.strictEqual(span.attributes[SEMATTRS_HTTP_METHOD], 'GET'); - assert.strictEqual( - span.attributes['restify.layer'], - 'request_handler' - ); + notStrictEqual(span, undefined); + strictEqual(span.attributes[SEMATTRS_HTTP_METHOD], 'GET'); + strictEqual(span.attributes['restify.layer'], 'request_handler'); } } ); @@ -545,13 +524,13 @@ describe('Restify Instrumentation', () => { async () => { await httpRequest.get(`http://localhost:${port}/route/foo`); rootSpan.end(); - assert.strictEqual(memoryExporter.getFinishedSpans().length, 4); + strictEqual(memoryExporter.getFinishedSpans().length, 4); { // span from get const span = memoryExporter.getFinishedSpans()[2]; - assert.notStrictEqual(span, undefined); - assert.strictEqual(span.attributes[SEMATTRS_HTTP_METHOD], 'GET'); + notStrictEqual(span, undefined); + strictEqual(span.attributes[SEMATTRS_HTTP_METHOD], 'GET'); } } ); @@ -567,16 +546,13 @@ describe('Restify Instrumentation', () => { await context.with( trace.setSpan(context.active(), rootSpan), async () => { - assert.strictEqual( + strictEqual( await httpRequest.get(`http://localhost:${port}/route/foo`), '{"route":"foo"}' ); rootSpan.end(); - assert.strictEqual(memoryExporter.getFinishedSpans().length, 1); - assert.notStrictEqual( - memoryExporter.getFinishedSpans()[0], - undefined - ); + strictEqual(memoryExporter.getFinishedSpans().length, 1); + notStrictEqual(memoryExporter.getFinishedSpans()[0], undefined); } ); }); diff --git a/plugins/node/opentelemetry-instrumentation-restify/test/utils.test.ts b/plugins/node/opentelemetry-instrumentation-restify/test/utils.test.ts index 1b2421e01c..787f4f7dc9 100644 --- a/plugins/node/opentelemetry-instrumentation-restify/test/utils.test.ts +++ b/plugins/node/opentelemetry-instrumentation-restify/test/utils.test.ts @@ -14,47 +14,47 @@ * limitations under the License. */ import { isAsyncFunction, isPromise } from '../src/utils'; -import * as assert from 'assert'; +import { strictEqual } from 'assert'; describe('utils', () => { describe('isPromise', () => { it('should be able to validate a promise to be true', () => { - assert.strictEqual(isPromise(Promise.resolve()), true); + strictEqual(isPromise(Promise.resolve()), true); }); it('should be able to validate non-promise to be false', () => { - assert.strictEqual(isPromise(), false); - assert.strictEqual(isPromise(null), false); - assert.strictEqual(isPromise({}), false); - assert.strictEqual(isPromise('string'), false); - assert.strictEqual(isPromise(123), false); - assert.strictEqual( + strictEqual(isPromise(), false); + strictEqual(isPromise(null), false); + strictEqual(isPromise({}), false); + strictEqual(isPromise('string'), false); + strictEqual(isPromise(123), false); + strictEqual( isPromise(() => {}), false ); - assert.strictEqual(isPromise((async () => {}) as any), false); + strictEqual(isPromise((async () => {}) as any), false); }); }); describe('isAsyncFunction', () => { it('should be able to validate an async function to be true', () => { - assert.strictEqual( + strictEqual( isAsyncFunction(async () => {}), true ); }); it('should be able to validate non async function to be false', () => { - assert.strictEqual(isAsyncFunction(), false); - assert.strictEqual(isAsyncFunction(null), false); - assert.strictEqual(isAsyncFunction({}), false); - assert.strictEqual(isAsyncFunction('string'), false); - assert.strictEqual(isAsyncFunction(123), false); - assert.strictEqual( + strictEqual(isAsyncFunction(), false); + strictEqual(isAsyncFunction(null), false); + strictEqual(isAsyncFunction({}), false); + strictEqual(isAsyncFunction('string'), false); + strictEqual(isAsyncFunction(123), false); + strictEqual( isAsyncFunction(() => {}), false ); - assert.strictEqual(isAsyncFunction(Promise.resolve()), false); + strictEqual(isAsyncFunction(Promise.resolve()), false); }); }); }); diff --git a/plugins/node/opentelemetry-instrumentation-router/src/index.ts b/plugins/node/opentelemetry-instrumentation-router/src/index.ts index c464af622c..eabf3927a8 100644 --- a/plugins/node/opentelemetry-instrumentation-router/src/index.ts +++ b/plugins/node/opentelemetry-instrumentation-router/src/index.ts @@ -14,5 +14,5 @@ * limitations under the License. */ -export * from './instrumentation'; -export * from './enums/AttributeNames'; +export { RouterInstrumentation } from './instrumentation'; +export { AttributeNames } from './enums/AttributeNames'; diff --git a/plugins/node/opentelemetry-instrumentation-winston/src/index.ts b/plugins/node/opentelemetry-instrumentation-winston/src/index.ts index c26f998cff..dcc8fe1422 100644 --- a/plugins/node/opentelemetry-instrumentation-winston/src/index.ts +++ b/plugins/node/opentelemetry-instrumentation-winston/src/index.ts @@ -14,5 +14,5 @@ * limitations under the License. */ -export * from './instrumentation'; -export * from './types'; +export { WinstonInstrumentation } from './instrumentation'; +export { LogHookFunction, WinstonInstrumentationConfig } from './types'; diff --git a/plugins/web/opentelemetry-instrumentation-document-load/src/index.ts b/plugins/web/opentelemetry-instrumentation-document-load/src/index.ts index 45cd8db559..b5a7ee1fe4 100644 --- a/plugins/web/opentelemetry-instrumentation-document-load/src/index.ts +++ b/plugins/web/opentelemetry-instrumentation-document-load/src/index.ts @@ -14,6 +14,10 @@ * limitations under the License. */ -export * from './instrumentation'; -export * from './enums/AttributeNames'; -export * from './types'; +export { DocumentLoadInstrumentation } from './instrumentation'; +export { AttributeNames } from './enums/AttributeNames'; +export { + DocumentLoadCustomAttributeFunction, + ResourceFetchCustomAttributeFunction, + DocumentLoadInstrumentationConfig, +} from './types'; diff --git a/plugins/web/opentelemetry-instrumentation-long-task/src/index.ts b/plugins/web/opentelemetry-instrumentation-long-task/src/index.ts index c26f998cff..5f151947d9 100644 --- a/plugins/web/opentelemetry-instrumentation-long-task/src/index.ts +++ b/plugins/web/opentelemetry-instrumentation-long-task/src/index.ts @@ -14,5 +14,11 @@ * limitations under the License. */ -export * from './instrumentation'; -export * from './types'; +export { LongTaskInstrumentation } from './instrumentation'; +export { + PerformanceLongTaskTiming, + TaskAttributionTiming, + ObserverCallbackInformation, + ObserverCallback, + LongtaskInstrumentationConfig, +} from './types'; diff --git a/plugins/web/opentelemetry-instrumentation-user-interaction/src/index.ts b/plugins/web/opentelemetry-instrumentation-user-interaction/src/index.ts index 13de301c07..3050c84409 100644 --- a/plugins/web/opentelemetry-instrumentation-user-interaction/src/index.ts +++ b/plugins/web/opentelemetry-instrumentation-user-interaction/src/index.ts @@ -14,6 +14,10 @@ * limitations under the License. */ -export * from './instrumentation'; -export * from './types'; -export * from './enums/AttributeNames'; +export { UserInteractionInstrumentation } from './instrumentation'; +export { + EventName, + ShouldPreventSpanCreation, + UserInteractionInstrumentationConfig, +} from './types'; +export { AttributeNames } from './enums/AttributeNames'; diff --git a/plugins/web/opentelemetry-instrumentation-user-interaction/src/instrumentation.ts b/plugins/web/opentelemetry-instrumentation-user-interaction/src/instrumentation.ts index 4bd38efbe7..4397cb8c6e 100644 --- a/plugins/web/opentelemetry-instrumentation-user-interaction/src/instrumentation.ts +++ b/plugins/web/opentelemetry-instrumentation-user-interaction/src/instrumentation.ts @@ -18,7 +18,7 @@ import { isWrapped, InstrumentationBase } from '@opentelemetry/instrumentation'; -import * as api from '@opentelemetry/api'; +import { trace, context, Span, HrTime, Context } from '@opentelemetry/api'; import { hrTime } from '@opentelemetry/core'; import { getElementXPath } from '@opentelemetry/sdk-trace-web'; import { AttributeNames } from './enums/AttributeNames'; @@ -52,7 +52,7 @@ function defaultShouldPreventSpanCreation() { export class UserInteractionInstrumentation extends InstrumentationBase { readonly version = PACKAGE_VERSION; readonly moduleName: string = 'user-interaction'; - private _spansData = new WeakMap(); + private _spansData = new WeakMap(); private _zonePatched?: boolean; // for addEventListener/removeEventListener state private _wrappedListeners = new WeakMap< @@ -60,10 +60,7 @@ export class UserInteractionInstrumentation extends InstrumentationBase> >(); // for event bubbling - private _eventsSpanMap: WeakMap = new WeakMap< - Event, - api.Span - >(); + private _eventsSpanMap: WeakMap = new WeakMap(); private _eventNames: Set; private _shouldPreventSpanCreation: ShouldPreventSpanCreation; @@ -86,7 +83,7 @@ export class UserInteractionInstrumentation extends InstrumentationBase { - const result = plugin._invokeListener(listener, this, args); - // no zone so end span immediately - span.end(); - return result; - } - ); + return context.with(trace.setSpan(context.active(), span), () => { + const result = plugin._invokeListener(listener, this, args); + // no zone so end span immediately + span.end(); + return result; + }); } else { return plugin._invokeListener(listener, this, args); } @@ -420,7 +412,7 @@ export class UserInteractionInstrumentation extends InstrumentationBase { try { - return api.context.with( - api.trace.setSpan(api.context.active(), span!), + return context.with( + trace.setSpan(context.active(), span!), () => { const currentZone = Zone.current; task._zone = currentZone; @@ -512,7 +504,7 @@ export class UserInteractionInstrumentation extends InstrumentationBase { document.body.addEventListener('bodyEvent2', listener); document.addEventListener('docEvent', listener); document.body.dispatchEvent(new Event('bodyEvent')); - assert.strictEqual(called, true); + strictEqual(called, true); called = false; // Remove first callback, second type should still fire document.body.removeEventListener('bodyEvent', listener); document.body.dispatchEvent(new Event('bodyEvent')); - assert.strictEqual(called, false); + strictEqual(called, false); document.body.dispatchEvent(new Event('bodyEvent2')); - assert.strictEqual(called, true); + strictEqual(called, true); called = false; // Remove doc callback, body 2 should still fire document.removeEventListener('docEvent', listener); document.dispatchEvent(new Event('docEvent')); - assert.strictEqual(called, false); + strictEqual(called, false); document.body.dispatchEvent(new Event('bodyEvent2')); - assert.strictEqual(called, true); + strictEqual(called, true); called = false; // Finally, remove the last one and nothing should fire document.body.removeEventListener('bodyEvent2', listener); document.body.dispatchEvent(new Event('bodyEvent')); document.body.dispatchEvent(new Event('bodyEvent2')); document.dispatchEvent(new Event('docEvent')); - assert.strictEqual(called, false); + strictEqual(called, false); }); it('should not double-register a listener', () => { @@ -155,12 +155,12 @@ describe('UserInteractionInstrumentation', () => { document.body.addEventListener('bodyEvent', listener); document.body.addEventListener('bodyEvent', listener); document.body.dispatchEvent(new Event('bodyEvent')); - assert.strictEqual(callCount, 1); + strictEqual(callCount, 1); // now ensure remove still works callCount = 0; document.body.removeEventListener('bodyEvent', listener); document.body.dispatchEvent(new Event('bodyEvent')); - assert.strictEqual(callCount, 0); + strictEqual(callCount, 0); }); it('should handle once-only callbacks', () => { @@ -172,16 +172,16 @@ describe('UserInteractionInstrumentation', () => { document.body.addEventListener('bodyEvent', listener, { once: true }); document.body.addEventListener('bodyEvent', listener); // considered a double-register document.body.dispatchEvent(new Event('bodyEvent')); - assert.strictEqual(callCount, 1); + strictEqual(callCount, 1); // now that it's been dispatched once, it's been removed document.body.dispatchEvent(new Event('bodyEvent')); - assert.strictEqual(callCount, 1); + strictEqual(callCount, 1); // should be able to re-add document.body.addEventListener('bodyEvent', listener); document.body.dispatchEvent(new Event('bodyEvent')); - assert.strictEqual(callCount, 2); + strictEqual(callCount, 2); document.body.dispatchEvent(new Event('bodyEvent')); - assert.strictEqual(callCount, 3); + strictEqual(callCount, 3); }); it('should handle EventListener callbacks', () => { @@ -195,16 +195,16 @@ describe('UserInteractionInstrumentation', () => { }; document.body.addEventListener('EventListenerEvent', listener); document.body.dispatchEvent(new Event('EventListenerEvent')); - assert.strictEqual(callCount, 1); + strictEqual(callCount, 1); callCount = 0; document.body.removeEventListener('EventListenerEvent', listener); document.body.dispatchEvent(new Event('EventListenerEvent')); - assert.strictEqual(callCount, 0); + strictEqual(callCount, 0); }); it('should handle task without async operation', () => { fakeClickInteraction(); - assert.equal(exportSpy.args.length, 1, 'should export one span'); + equal(exportSpy.args.length, 1, 'should export one span'); const spanClick = exportSpy.args[0][0][0]; assertClickSpan(spanClick); }); @@ -214,7 +214,7 @@ describe('UserInteractionInstrumentation', () => { originalSetTimeout(() => { const spanClick: tracing.ReadableSpan = exportSpy.args[0][0][0]; - assert.equal(exportSpy.args.length, 1, 'should export one span'); + equal(exportSpy.args.length, 1, 'should export one span'); assertClickSpan(spanClick); done(); }); @@ -234,7 +234,7 @@ describe('UserInteractionInstrumentation', () => { }; fakeClickInteraction(() => { originalSetTimeout(() => { - assert.equal(exportSpy.args.length, 0, 'should NOT export any span'); + equal(exportSpy.args.length, 0, 'should NOT export any span'); done(); }); }, btn); @@ -257,7 +257,7 @@ describe('UserInteractionInstrumentation', () => { }; fakeClickInteraction(() => { originalSetTimeout(() => { - assert.equal(exportSpy.args.length, 0, 'should NOT export any span'); + equal(exportSpy.args.length, 0, 'should NOT export any span'); done(); }); }, btn); @@ -271,7 +271,7 @@ describe('UserInteractionInstrumentation', () => { fakeClickInteraction(() => { originalSetTimeout(() => { - assert.equal(exportSpy.args.length, 0, 'should NOT export any span'); + equal(exportSpy.args.length, 0, 'should NOT export any span'); done(); }); }); @@ -289,24 +289,21 @@ describe('UserInteractionInstrumentation', () => { sandbox.clock.tick(1000); }).then(() => { originalSetTimeout(() => { - assert.equal(exportSpy.args.length, 2, 'should export 2 spans'); + equal(exportSpy.args.length, 2, 'should export 2 spans'); const spanXhr: tracing.ReadableSpan = exportSpy.args[0][0][0]; const spanClick: tracing.ReadableSpan = exportSpy.args[1][0][0]; - assert.equal( + equal( spanXhr.parentSpanId, spanClick.spanContext().spanId, 'xhr span has wrong parent' ); - assert.equal( - spanClick.name, - `Navigation: ${location.pathname}#foo=bar1` - ); + equal(spanClick.name, `Navigation: ${location.pathname}#foo=bar1`); const attributes = spanClick.attributes; - assert.equal(attributes.event_type, 'click'); - assert.equal(attributes.target_element, 'BUTTON'); - assert.equal(attributes.target_xpath, '//*[@id="testBtn"]'); + equal(attributes.event_type, 'click'); + equal(attributes.target_element, 'BUTTON'); + equal(attributes.target_xpath, '//*[@id="testBtn"]'); done(); }); @@ -320,11 +317,11 @@ describe('UserInteractionInstrumentation', () => { sandbox.clock.tick(1000); }).then(() => { originalSetTimeout(() => { - assert.equal(exportSpy.args.length, 2, 'should export 2 spans'); + equal(exportSpy.args.length, 2, 'should export 2 spans'); const spanXhr: tracing.ReadableSpan = exportSpy.args[0][0][0]; const spanClick: tracing.ReadableSpan = exportSpy.args[1][0][0]; - assert.equal( + equal( spanXhr.parentSpanId, spanClick.spanContext().spanId, 'xhr span has wrong parent' @@ -332,7 +329,7 @@ describe('UserInteractionInstrumentation', () => { assertClickSpan(spanClick); const attributes = spanXhr.attributes; - assert.equal( + equal( attributes['http.url'], 'https://raw.githubusercontent.com/open-telemetry/opentelemetry-js/main/package.json' ); @@ -362,13 +359,13 @@ describe('UserInteractionInstrumentation', () => { // remove added listener so we don't pollute other tests document.body.removeEventListener('click', listener1); } - assert.strictEqual(callCount, 2); - assert.strictEqual(exportSpy.args.length, 2); - assert.strictEqual( + strictEqual(callCount, 2); + strictEqual(exportSpy.args.length, 2); + strictEqual( exportSpy.args[0][0][0].traceId, exportSpy.args[1][0][0].traceId ); - assert.strictEqual( + strictEqual( exportSpy.args[0][0][0].spanId, exportSpy.args[1][0][0].spanContext().parentSpanId ); @@ -398,7 +395,7 @@ describe('UserInteractionInstrumentation', () => { }, btn3); sandbox.clock.tick(1000); originalSetTimeout(() => { - assert.equal(exportSpy.args.length, 6, 'should export 6 spans'); + equal(exportSpy.args.length, 6, 'should export 6 spans'); const span1: tracing.ReadableSpan = exportSpy.args[0][0][0]; const span2: tracing.ReadableSpan = exportSpy.args[1][0][0]; @@ -411,17 +408,17 @@ describe('UserInteractionInstrumentation', () => { assertClickSpan(span2, 'btn2'); assertClickSpan(span3, 'btn3'); - assert.strictEqual( + strictEqual( span1.spanContext().spanId, span4.parentSpanId, 'span4 has wrong parent' ); - assert.strictEqual( + strictEqual( span2.spanContext().spanId, span5.parentSpanId, 'span5 has wrong parent' ); - assert.strictEqual( + strictEqual( span3.spanContext().spanId, span6.parentSpanId, 'span6 has wrong parent' @@ -466,7 +463,7 @@ describe('UserInteractionInstrumentation', () => { sandbox.clock.tick(1000); originalSetTimeout(() => { - assert.equal(exportSpy.args.length, 4, 'should export 4 spans'); + equal(exportSpy.args.length, 4, 'should export 4 spans'); const span1: tracing.ReadableSpan = exportSpy.args[0][0][0]; const span2: tracing.ReadableSpan = exportSpy.args[1][0][0]; @@ -476,12 +473,12 @@ describe('UserInteractionInstrumentation', () => { assertClickSpan(span1, 'btn1'); assertClickSpan(span2, 'btn2'); - assert.strictEqual( + strictEqual( span1.spanContext().spanId, span3.parentSpanId, 'span3 has wrong parent' ); - assert.strictEqual( + strictEqual( span2.spanContext().spanId, span4.parentSpanId, 'span4 has wrong parent' @@ -526,18 +523,18 @@ describe('UserInteractionInstrumentation', () => { sandbox.clock.tick(1000); originalSetTimeout(() => { - assert.strictEqual( + strictEqual( listenerThis[0], root, 'this inside event listener matches listened target (0)' ); - assert.strictEqual( + strictEqual( listenerThis[1], root, 'this inside event listener matches listened target (1)' ); - assert.equal(exportSpy.args.length, 4, 'should export 4 spans'); + equal(exportSpy.args.length, 4, 'should export 4 spans'); const span1: tracing.ReadableSpan = exportSpy.args[0][0][0]; const span2: tracing.ReadableSpan = exportSpy.args[1][0][0]; @@ -547,12 +544,12 @@ describe('UserInteractionInstrumentation', () => { assertClickSpan(span1, 'btn1'); assertClickSpan(span2, 'btn2'); - assert.strictEqual( + strictEqual( span1.spanContext().spanId, span3.parentSpanId, 'span3 has wrong parent' ); - assert.strictEqual( + strictEqual( span2.spanContext().spanId, span4.parentSpanId, 'span4 has wrong parent' @@ -564,11 +561,7 @@ describe('UserInteractionInstrumentation', () => { it('should not create spans from unknown events', () => { fakeEventInteraction('play'); - assert.strictEqual( - exportSpy.args.length, - 0, - 'should not export any spans' - ); + strictEqual(exportSpy.args.length, 0, 'should not export any spans'); }); it('should export spans for configured event types', () => { @@ -577,7 +570,7 @@ describe('UserInteractionInstrumentation', () => { }); fakeEventInteraction('play'); - assert.strictEqual(exportSpy.args.length, 1, 'should export one span'); + strictEqual(exportSpy.args.length, 1, 'should export one span'); const span = exportSpy.args[0][0][0]; assertInteractionSpan(span, { name: 'play' }); }); @@ -588,11 +581,7 @@ describe('UserInteractionInstrumentation', () => { }); fakeClickInteraction(); - assert.strictEqual( - exportSpy.args.length, - 0, - 'should not export any spans' - ); + strictEqual(exportSpy.args.length, 0, 'should not export any spans'); }); it('should call shouldPreventSpanCreation with proper arguments', () => { @@ -606,7 +595,7 @@ describe('UserInteractionInstrumentation', () => { element.click(); const span = exportSpy.args[0][0][0]; - assert.deepStrictEqual(shouldPreventSpanCreation.args, [ + deepStrictEqual(shouldPreventSpanCreation.args, [ ['click', element, span], ]); }); @@ -622,11 +611,7 @@ describe('UserInteractionInstrumentation', () => { element.addEventListener('click', () => {}); element.click(); - assert.strictEqual( - exportSpy.args.length, - 0, - 'should not export any spans' - ); + strictEqual(exportSpy.args.length, 0, 'should not export any spans'); }); }); @@ -641,7 +626,7 @@ describe('UserInteractionInstrumentation', () => { element.addEventListener('click', () => {}); element.click(); - assert.strictEqual(exportSpy.args.length, 1, 'should export one span'); + strictEqual(exportSpy.args.length, 1, 'should export one span'); }); }); @@ -663,77 +648,65 @@ describe('UserInteractionInstrumentation', () => { }); it('should handle disable', () => { - assert.strictEqual( + strictEqual( isWrapped(HTMLElement.prototype.addEventListener), true, 'addEventListener should be wrapped' ); - assert.strictEqual( + strictEqual( isWrapped(HTMLElement.prototype.removeEventListener), true, 'removeEventListener should be wrapped' ); - assert.strictEqual( + strictEqual( isWrapped(history.replaceState), true, 'replaceState should be wrapped' ); - assert.strictEqual( + strictEqual( isWrapped(history.pushState), true, 'pushState should be wrapped' ); - assert.strictEqual( - isWrapped(history.back), - true, - 'back should be wrapped' - ); - assert.strictEqual( + strictEqual(isWrapped(history.back), true, 'back should be wrapped'); + strictEqual( isWrapped(history.forward), true, 'forward should be wrapped' ); - assert.strictEqual(isWrapped(history.go), true, 'go should be wrapped'); + strictEqual(isWrapped(history.go), true, 'go should be wrapped'); userInteractionInstrumentation.disable(); - assert.strictEqual( + strictEqual( isWrapped(HTMLElement.prototype.addEventListener), false, 'addEventListener should be unwrapped' ); - assert.strictEqual( + strictEqual( isWrapped(HTMLElement.prototype.removeEventListener), false, 'removeEventListener should be unwrapped' ); - assert.strictEqual( + strictEqual( isWrapped(history.replaceState), false, 'replaceState should be unwrapped' ); - assert.strictEqual( + strictEqual( isWrapped(history.pushState), false, 'pushState should be unwrapped' ); - assert.strictEqual( - isWrapped(history.back), - false, - 'back should be unwrapped' - ); - assert.strictEqual( + strictEqual(isWrapped(history.back), false, 'back should be unwrapped'); + strictEqual( isWrapped(history.forward), false, 'forward should be unwrapped' ); - assert.strictEqual( - isWrapped(history.go), - false, - 'go should be unwrapped' - ); + strictEqual(isWrapped(history.go), false, 'go should be unwrapped'); }); describe('simulate IE', () => { @@ -767,7 +740,7 @@ describe('UserInteractionInstrumentation', () => { */ fakeClickInteraction(); - assert.equal(exportSpy.args.length, 1, 'should export one span'); + equal(exportSpy.args.length, 1, 'should export one span'); const spanClick = exportSpy.args[0][0][0]; assertClickSpan(spanClick); }); diff --git a/plugins/web/opentelemetry-instrumentation-user-interaction/test/userInteraction.test.ts b/plugins/web/opentelemetry-instrumentation-user-interaction/test/userInteraction.test.ts index 792387e8c5..57d17e9df7 100644 --- a/plugins/web/opentelemetry-instrumentation-user-interaction/test/userInteraction.test.ts +++ b/plugins/web/opentelemetry-instrumentation-user-interaction/test/userInteraction.test.ts @@ -23,7 +23,7 @@ import { import { XMLHttpRequestInstrumentation } from '@opentelemetry/instrumentation-xml-http-request'; import * as tracing from '@opentelemetry/sdk-trace-base'; import { WebTracerProvider } from '@opentelemetry/sdk-trace-web'; -import * as assert from 'assert'; +import { strictEqual, ok, equal, deepStrictEqual } from 'assert'; import * as sinon from 'sinon'; import 'zone.js'; import { UserInteractionInstrumentation } from '../src'; @@ -124,7 +124,7 @@ describe('UserInteractionInstrumentation', () => { it('should handle task without async operation', () => { fakeClickInteraction(); - assert.equal(exportSpy.args.length, 1, 'should export one span'); + equal(exportSpy.args.length, 1, 'should export one span'); const spanClick = exportSpy.args[0][0][0]; assertClickSpan(spanClick); }); @@ -134,7 +134,7 @@ describe('UserInteractionInstrumentation', () => { originalSetTimeout(() => { const spanClick: tracing.ReadableSpan = exportSpy.args[0][0][0]; - assert.equal(exportSpy.args.length, 1, 'should export one span'); + equal(exportSpy.args.length, 1, 'should export one span'); assertClickSpan(spanClick); done(); }); @@ -146,7 +146,7 @@ describe('UserInteractionInstrumentation', () => { fakeClickInteraction(() => { const interval = setInterval(() => {}, 1); originalSetTimeout(() => { - assert.equal( + equal( exportSpy.args.length, 1, 'should not export more then one span' @@ -173,24 +173,21 @@ describe('UserInteractionInstrumentation', () => { sandbox.clock.tick(1000); }).then(() => { originalSetTimeout(() => { - assert.equal(exportSpy.args.length, 2, 'should export 2 spans'); + equal(exportSpy.args.length, 2, 'should export 2 spans'); const spanXhr: tracing.ReadableSpan = exportSpy.args[0][0][0]; const spanClick: tracing.ReadableSpan = exportSpy.args[1][0][0]; - assert.equal( + equal( spanXhr.parentSpanId, spanClick.spanContext().spanId, 'xhr span has wrong parent' ); - assert.equal( - spanClick.name, - `Navigation: ${location.pathname}#foo=bar1` - ); + equal(spanClick.name, `Navigation: ${location.pathname}#foo=bar1`); const attributes = spanClick.attributes; - assert.equal(attributes.event_type, 'click'); - assert.equal(attributes.target_element, 'BUTTON'); - assert.equal(attributes.target_xpath, '//*[@id="testBtn"]'); + equal(attributes.event_type, 'click'); + equal(attributes.target_element, 'BUTTON'); + equal(attributes.target_xpath, '//*[@id="testBtn"]'); done(); }); @@ -204,11 +201,11 @@ describe('UserInteractionInstrumentation', () => { sandbox.clock.tick(1000); }).then(() => { originalSetTimeout(() => { - assert.equal(exportSpy.args.length, 2, 'should export 2 spans'); + equal(exportSpy.args.length, 2, 'should export 2 spans'); const spanXhr: tracing.ReadableSpan = exportSpy.args[0][0][0]; const spanClick: tracing.ReadableSpan = exportSpy.args[1][0][0]; - assert.equal( + equal( spanXhr.parentSpanId, spanClick.spanContext().spanId, 'xhr span has wrong parent' @@ -216,7 +213,7 @@ describe('UserInteractionInstrumentation', () => { assertClickSpan(spanClick); const attributes = spanXhr.attributes; - assert.equal( + equal( attributes['http.url'], 'https://raw.githubusercontent.com/open-telemetry/opentelemetry-js/main/package.json' ); @@ -230,11 +227,7 @@ describe('UserInteractionInstrumentation', () => { it('should not create spans from unknown events', () => { fakeEventInteraction('play'); - assert.strictEqual( - exportSpy.args.length, - 0, - 'should not export any spans' - ); + strictEqual(exportSpy.args.length, 0, 'should not export any spans'); }); it('should export spans for configured event types', () => { @@ -243,7 +236,7 @@ describe('UserInteractionInstrumentation', () => { }); fakeEventInteraction('play'); - assert.strictEqual(exportSpy.args.length, 1, 'should export one span'); + strictEqual(exportSpy.args.length, 1, 'should export one span'); const span = exportSpy.args[0][0][0]; assertInteractionSpan(span, { name: 'play' }); }); @@ -254,11 +247,7 @@ describe('UserInteractionInstrumentation', () => { }); fakeClickInteraction(); - assert.strictEqual( - exportSpy.args.length, - 0, - 'should not export any spans' - ); + strictEqual(exportSpy.args.length, 0, 'should not export any spans'); }); it('should call shouldPreventSpanCreation with proper arguments', () => { @@ -272,7 +261,7 @@ describe('UserInteractionInstrumentation', () => { element.click(); const span = exportSpy.args[0][0][0]; - assert.deepStrictEqual(shouldPreventSpanCreation.args, [ + deepStrictEqual(shouldPreventSpanCreation.args, [ ['click', element, span], ]); }); @@ -288,11 +277,7 @@ describe('UserInteractionInstrumentation', () => { element.addEventListener('click', () => {}); element.click(); - assert.strictEqual( - exportSpy.args.length, - 0, - 'should not export any spans' - ); + strictEqual(exportSpy.args.length, 0, 'should not export any spans'); }); }); @@ -307,7 +292,7 @@ describe('UserInteractionInstrumentation', () => { element.addEventListener('click', () => {}); element.click(); - assert.strictEqual(exportSpy.args.length, 1, 'should export one span'); + strictEqual(exportSpy.args.length, 1, 'should export one span'); }); }); @@ -324,23 +309,20 @@ describe('UserInteractionInstrumentation', () => { const element = createButton(); element.addEventListener('click', () => { - assert.ok( + ok( Zone.current !== newZone, 'Current zone for 2nd listener click is wrong' ); - assert.ok( + ok( Zone.current.parent === rootZone, 'Parent Zone for 2nd listener click is wrong' ); }); newZone.run(() => { - assert.ok(Zone.current === newZone, 'New zone is wrong'); + ok(Zone.current === newZone, 'New zone is wrong'); fakeClickInteraction(() => { - assert.ok( - Zone.current.parent === newZone, - 'Parent zone for click is wrong' - ); + ok(Zone.current.parent === newZone, 'Parent zone for click is wrong'); const spanClick: tracing.ReadableSpan = exportSpy.args[0][0][0]; assertClickSpan(spanClick); @@ -358,7 +340,7 @@ describe('UserInteractionInstrumentation', () => { fakeClickInteraction(callback, btn); sandbox.clock.tick(1000); originalSetTimeout(() => { - assert.equal(called, false, 'callback should not be called'); + equal(called, false, 'callback should not be called'); done(); }); }); @@ -387,7 +369,7 @@ describe('UserInteractionInstrumentation', () => { }, btn3); sandbox.clock.tick(1000); originalSetTimeout(() => { - assert.equal(exportSpy.args.length, 6, 'should export 6 spans'); + equal(exportSpy.args.length, 6, 'should export 6 spans'); const span1: tracing.ReadableSpan = exportSpy.args[0][0][0]; const span2: tracing.ReadableSpan = exportSpy.args[1][0][0]; @@ -400,17 +382,17 @@ describe('UserInteractionInstrumentation', () => { assertClickSpan(span2, 'btn2'); assertClickSpan(span3, 'btn3'); - assert.strictEqual( + strictEqual( span1.spanContext().spanId, span4.parentSpanId, 'span4 has wrong parent' ); - assert.strictEqual( + strictEqual( span2.spanContext().spanId, span5.parentSpanId, 'span5 has wrong parent' ); - assert.strictEqual( + strictEqual( span3.spanContext().spanId, span6.parentSpanId, 'span6 has wrong parent' @@ -455,7 +437,7 @@ describe('UserInteractionInstrumentation', () => { sandbox.clock.tick(1000); originalSetTimeout(() => { - assert.equal(exportSpy.args.length, 4, 'should export 4 spans'); + equal(exportSpy.args.length, 4, 'should export 4 spans'); const span1: tracing.ReadableSpan = exportSpy.args[0][0][0]; const span2: tracing.ReadableSpan = exportSpy.args[1][0][0]; @@ -465,12 +447,12 @@ describe('UserInteractionInstrumentation', () => { assertClickSpan(span1, 'btn1'); assertClickSpan(span2, 'btn2'); - assert.strictEqual( + strictEqual( span1.spanContext().spanId, span3.parentSpanId, 'span3 has wrong parent' ); - assert.strictEqual( + strictEqual( span2.spanContext().spanId, span4.parentSpanId, 'span4 has wrong parent' @@ -511,7 +493,7 @@ describe('UserInteractionInstrumentation', () => { sandbox.clock.tick(1000); originalSetTimeout(() => { - assert.equal(exportSpy.args.length, 4, 'should export 4 spans'); + equal(exportSpy.args.length, 4, 'should export 4 spans'); const span1: tracing.ReadableSpan = exportSpy.args[0][0][0]; const span2: tracing.ReadableSpan = exportSpy.args[1][0][0]; @@ -521,12 +503,12 @@ describe('UserInteractionInstrumentation', () => { assertClickSpan(span1, 'btn1'); assertClickSpan(span2, 'btn2'); - assert.strictEqual( + strictEqual( span1.spanContext().spanId, span3.parentSpanId, 'span3 has wrong parent' ); - assert.strictEqual( + strictEqual( span2.spanContext().spanId, span4.parentSpanId, 'span4 has wrong parent' @@ -539,87 +521,75 @@ describe('UserInteractionInstrumentation', () => { it('should handle unpatch', () => { const _window: WindowWithZone = window as unknown as WindowWithZone; const ZoneWithPrototype = _window.Zone; - assert.strictEqual( + strictEqual( isWrapped(ZoneWithPrototype.prototype.runTask), true, 'runTask should be wrapped' ); - assert.strictEqual( + strictEqual( isWrapped(ZoneWithPrototype.prototype.scheduleTask), true, 'scheduleTask should be wrapped' ); - assert.strictEqual( + strictEqual( isWrapped(ZoneWithPrototype.prototype.cancelTask), true, 'cancelTask should be wrapped' ); - assert.strictEqual( + strictEqual( isWrapped(history.replaceState), true, 'replaceState should be wrapped' ); - assert.strictEqual( + strictEqual( isWrapped(history.pushState), true, 'pushState should be wrapped' ); - assert.strictEqual( - isWrapped(history.back), - true, - 'back should be wrapped' - ); - assert.strictEqual( + strictEqual(isWrapped(history.back), true, 'back should be wrapped'); + strictEqual( isWrapped(history.forward), true, 'forward should be wrapped' ); - assert.strictEqual(isWrapped(history.go), true, 'go should be wrapped'); + strictEqual(isWrapped(history.go), true, 'go should be wrapped'); userInteractionInstrumentation.disable(); - assert.strictEqual( + strictEqual( isWrapped(ZoneWithPrototype.prototype.runTask), false, 'runTask should be unwrapped' ); - assert.strictEqual( + strictEqual( isWrapped(ZoneWithPrototype.prototype.scheduleTask), false, 'scheduleTask should be unwrapped' ); - assert.strictEqual( + strictEqual( isWrapped(ZoneWithPrototype.prototype.cancelTask), false, 'cancelTask should be unwrapped' ); - assert.strictEqual( + strictEqual( isWrapped(history.replaceState), false, 'replaceState should be unwrapped' ); - assert.strictEqual( + strictEqual( isWrapped(history.pushState), false, 'pushState should be unwrapped' ); - assert.strictEqual( - isWrapped(history.back), - false, - 'back should be unwrapped' - ); - assert.strictEqual( + strictEqual(isWrapped(history.back), false, 'back should be unwrapped'); + strictEqual( isWrapped(history.forward), false, 'forward should be unwrapped' ); - assert.strictEqual( - isWrapped(history.go), - false, - 'go should be unwrapped' - ); + strictEqual(isWrapped(history.go), false, 'go should be unwrapped'); }); }); }); diff --git a/plugins/web/opentelemetry-plugin-react-load/src/BaseOpenTelemetryComponent.ts b/plugins/web/opentelemetry-plugin-react-load/src/BaseOpenTelemetryComponent.ts index fa7b007d0a..6fce56e6d2 100644 --- a/plugins/web/opentelemetry-plugin-react-load/src/BaseOpenTelemetryComponent.ts +++ b/plugins/web/opentelemetry-plugin-react-load/src/BaseOpenTelemetryComponent.ts @@ -14,7 +14,14 @@ * limitations under the License. */ -import * as api from '@opentelemetry/api'; +import { + trace, + context, + Tracer, + Span, + DiagLogger, + diag, +} from '@opentelemetry/api'; import { isWrapped } from '@opentelemetry/core'; import * as shimmer from 'shimmer'; import { AttributeNames } from './enums/AttributeNames'; @@ -37,16 +44,16 @@ import { export class BaseOpenTelemetryComponent extends React.Component { readonly component: string = 'react-load'; moduleName = this.component; - private _parentSpanMap: WeakMap; - private static _tracer: api.Tracer; - private static _logger: api.DiagLogger = api.diag; + private _parentSpanMap: WeakMap; + private static _tracer: Tracer; + private static _logger: DiagLogger = diag; /** * @param props Props of the React component */ constructor(props: Readonly) { super(props); - this._parentSpanMap = new WeakMap(); + this._parentSpanMap = new WeakMap(); this.patch(); } @@ -56,7 +63,7 @@ export class BaseOpenTelemetryComponent extends React.Component { * @param version Version of tracer, this is optional. When not provided it will use the latest. */ static setTracer(name: string, version?: string): void { - BaseOpenTelemetryComponent._tracer = api.trace.getTracer( + BaseOpenTelemetryComponent._tracer = trace.getTracer( name, version ? version : PACKAGE_VERSION ); @@ -66,8 +73,8 @@ export class BaseOpenTelemetryComponent extends React.Component { * Sets the logger for all components being instrumented * @param logger */ - static setLogger(logger: api.DiagLogger): void { - api.diag.setLogger(logger); + static setLogger(logger: DiagLogger): void { + diag.setLogger(logger); BaseOpenTelemetryComponent._logger = logger; } @@ -81,16 +88,14 @@ export class BaseOpenTelemetryComponent extends React.Component { private _createSpanWithParent( react: React.Component, name: string, - parentSpan: api.Span - ): api.Span { + parentSpan: Span + ): Span { return BaseOpenTelemetryComponent._tracer.startSpan( name, { attributes: this._getAttributes(react), }, - parentSpan - ? api.trace.setSpan(api.context.active(), parentSpan) - : undefined + parentSpan ? trace.setSpan(context.active(), parentSpan) : undefined ); } @@ -99,7 +104,7 @@ export class BaseOpenTelemetryComponent extends React.Component { * @param react React component currently being instrumented * @param name Name of span */ - private _createSpan(react: React.Component, name: string): api.Span { + private _createSpan(react: React.Component, name: string): Span { return BaseOpenTelemetryComponent._tracer.startSpan(name, { attributes: this._getAttributes(react), }); @@ -115,18 +120,15 @@ export class BaseOpenTelemetryComponent extends React.Component { private _instrumentFunction( react: React.Component, spanName: string, - parent: api.Span, + parent: Span, original: any ) { const span = this._createSpanWithParent(react, spanName, parent); let wasError = false; try { - return api.context.with( - api.trace.setSpan(api.context.active(), span), - () => { - return original(); - } - ); + return context.with(trace.setSpan(context.active(), span), () => { + return original(); + }); } catch (err: any) { span.setAttribute(AttributeNames.REACT_ERROR, err.stack); wasError = true; @@ -174,8 +176,8 @@ export class BaseOpenTelemetryComponent extends React.Component { * exist, the function creates one * @param react React component parent span belongs to. */ - private _getParentSpan(react: React.Component, parentName: string): api.Span { - const parentSpan: api.Span | undefined = this._parentSpanMap.get(react); + private _getParentSpan(react: React.Component, parentName: string): Span { + const parentSpan: Span | undefined = this._parentSpanMap.get(react); if (!parentSpan) { const span = this._createSpan(react, parentName); this._parentSpanMap.set(react, span); @@ -194,7 +196,7 @@ export class BaseOpenTelemetryComponent extends React.Component { ...args ): React.ReactNode { // Render is the first method in the mounting flow, if a parent span wasn't created already then we're in the mounting flow - let parentSpan: api.Span; + let parentSpan: Span; if (!plugin._parentSpanMap.get(this)) { parentSpan = plugin._getParentSpan( this, @@ -551,6 +553,6 @@ export class BaseOpenTelemetryComponent extends React.Component { shimmer.unwrap(this, 'componentWillUnmount'); - this._parentSpanMap = new WeakMap(); + this._parentSpanMap = new WeakMap(); } } diff --git a/plugins/web/opentelemetry-plugin-react-load/src/index.ts b/plugins/web/opentelemetry-plugin-react-load/src/index.ts index 5c898a23d4..41e77870db 100644 --- a/plugins/web/opentelemetry-plugin-react-load/src/index.ts +++ b/plugins/web/opentelemetry-plugin-react-load/src/index.ts @@ -14,5 +14,5 @@ * limitations under the License. */ -export * from './BaseOpenTelemetryComponent'; -export * from './enums/AttributeNames'; +export { BaseOpenTelemetryComponent } from './BaseOpenTelemetryComponent'; +export { AttributeNames } from './enums/AttributeNames'; diff --git a/plugins/web/opentelemetry-plugin-react-load/test/BaseOpenTelemetryComponent.test.ts b/plugins/web/opentelemetry-plugin-react-load/test/BaseOpenTelemetryComponent.test.ts index 2636e20338..9efe7e01ea 100644 --- a/plugins/web/opentelemetry-plugin-react-load/test/BaseOpenTelemetryComponent.test.ts +++ b/plugins/web/opentelemetry-plugin-react-load/test/BaseOpenTelemetryComponent.test.ts @@ -29,7 +29,7 @@ import { ReadableSpan, } from '@opentelemetry/sdk-trace-base'; import { StackContextManager } from '@opentelemetry/sdk-trace-web'; -import * as assert from 'assert'; +import { strictEqual, ok, equal } from 'assert'; import * as sinon from 'sinon'; import AllLifecycles from './test-react-components/AllLifecycles'; import MissingRender from './test-react-components/MissingRender'; @@ -132,145 +132,139 @@ describe('ReactLoad Instrumentation', () => { }); it('should always have defined lifecycle methods', () => { - assert.ok(constructed.render, 'render is not defined'); - assert.ok( - constructed.componentDidMount, - 'componentDidMount is not defined' - ); + ok(constructed.render, 'render is not defined'); + ok(constructed.componentDidMount, 'componentDidMount is not defined'); - assert.ok( + ok( constructed.shouldComponentUpdate, 'shouldComponentUpdate is not defined' ); - assert.ok( + ok( constructed.getSnapshotBeforeUpdate, 'getSnapshotBeforeUpdate is not defined' ); - assert.ok( - constructed.componentDidUpdate, - 'componentDidUpdate is not defined' - ); + ok(constructed.componentDidUpdate, 'componentDidUpdate is not defined'); }); it('should wrap functions', () => { - assert.ok( + ok( isWrapped(constructed.render), 'render function is not wrapped before' ); - assert.ok( + ok( isWrapped(constructed.componentDidMount), 'componentDidMount function is not wrapped before' ); - assert.ok( + ok( isWrapped(constructed.shouldComponentUpdate), 'shouldComponentUpdate function is not wrapped before' ); - assert.ok( + ok( isWrapped(constructed.getSnapshotBeforeUpdate), 'getSnapshotBeforeUpdate function is not wrapped before' ); - assert.ok( + ok( isWrapped(constructed.componentDidUpdate), 'componentDidUpdate function is not wrapped before' ); - assert.ok( + ok( isWrapped(constructed.setState), 'setState function is not wrapped before' ); - assert.ok( + ok( isWrapped(constructed.forceUpdate), 'forceUpdate function is not wrapped before' ); constructed.patch(); - assert.ok( + ok( isWrapped(constructed.render), 'render function is not wrapped after' ); - assert.ok( + ok( isWrapped(constructed.componentDidMount), 'componentDidMount function is not wrapped after' ); - assert.ok( + ok( isWrapped(constructed.shouldComponentUpdate), 'shouldComponentUpdate function is not wrapped after' ); - assert.ok( + ok( isWrapped(constructed.getSnapshotBeforeUpdate), 'getSnapshotBeforeUpdate function is not wrapped after' ); - assert.ok( + ok( isWrapped(constructed.componentDidUpdate), 'componentDidUpdate function is not wrapped after' ); - assert.ok( + ok( isWrapped(constructed.setState), 'setState function is not wrapped after' ); - assert.ok( + ok( isWrapped(constructed.forceUpdate), 'forceUpdate function is not wrapped after' ); }); it('should unwrap functions', () => { - assert.ok( + ok( isWrapped(constructed.render), 'render function is not wrapped before' ); - assert.ok( + ok( isWrapped(constructed.componentDidMount), 'componentDidMount function is not wrapped before' ); - assert.ok( + ok( isWrapped(constructed.shouldComponentUpdate), 'shouldComponentUpdate function is not wrapped before' ); - assert.ok( + ok( isWrapped(constructed.getSnapshotBeforeUpdate), 'getSnapshotBeforeUpdate function is not wrapped before' ); - assert.ok( + ok( isWrapped(constructed.componentDidUpdate), 'componentDidUpdate function is not wrapped before' ); - assert.ok( + ok( isWrapped(constructed.setState), 'setState function is not wrapped before' ); - assert.ok( + ok( isWrapped(constructed.forceUpdate), 'forceUpdate function is not wrapped before' ); constructed.unpatch(); - assert.ok( + ok( !isWrapped(constructed.render), 'render function is not unwrapped after' ); - assert.ok( + ok( !isWrapped(constructed.componentDidMount), 'componentDidMount function is not unwrapped after' ); - assert.ok( + ok( !isWrapped(constructed.shouldComponentUpdate), 'shouldComponentUpdate function is not unwrapped after' ); - assert.ok( + ok( !isWrapped(constructed.getSnapshotBeforeUpdate), 'getSnapshotBeforeUpdate function is not unwrapped after' ); - assert.ok( + ok( !isWrapped(constructed.componentDidUpdate), 'componentDidUpdate function is not unwrapped after' ); - assert.ok( + ok( !isWrapped(constructed.setState), 'setState function is not unwrapped after' ); - assert.ok( + ok( !isWrapped(constructed.forceUpdate), 'forceUpdate function is not unwrapped after' ); @@ -296,23 +290,23 @@ describe('ReactLoad Instrumentation', () => { const componentDidMountSpan: ReadableSpan = exportSpy.args[1][0][0]; const mountingSpan: ReadableSpan = exportSpy.args[2][0][0]; - assert.equal( + equal( mountingSpan.parentSpanId, undefined, 'mounting span is should not have a parent' ); - assert.equal( + equal( renderSpan.parentSpanId, mountingSpan.spanContext().spanId, 'render span is not a child of the mounting span' ); - assert.equal( + equal( componentDidMountSpan.parentSpanId, mountingSpan.spanContext().spanId, 'componentDidMount span is not a child of the mounting span' ); - assert.strictEqual( + strictEqual( exportSpy.args.length, 3, 'total number of spans is wrong' @@ -324,13 +318,13 @@ describe('ReactLoad Instrumentation', () => { const componentDidMountSpan: ReadableSpan = exportSpy.args[1][0][0]; const mountingSpan: ReadableSpan = exportSpy.args[2][0][0]; - assert.equal( + equal( mountingSpan.name, 'reactLoad: mounting', 'mounting span has wrong name' ); - assert.equal(renderSpan.name, 'render', 'render span has wrong name'); - assert.equal( + equal(renderSpan.name, 'render', 'render span has wrong name'); + equal( componentDidMountSpan.name, 'componentDidMount', 'componentDidMount span has wrong name' @@ -339,7 +333,7 @@ describe('ReactLoad Instrumentation', () => { it('spans should have correct attributes', () => { const spans: [] = exportSpy.args; - assert.strictEqual(spans.length, 3, 'number of spans is wrong'); + strictEqual(spans.length, 3, 'number of spans is wrong'); spans.forEach(element => { const span: ReadableSpan = element[0][0]; ensureSpanAttributesAreCorrect(span); @@ -373,38 +367,38 @@ describe('ReactLoad Instrumentation', () => { const componentDidUpdateSpan: ReadableSpan = exportSpy.args[7][0][0]; const updatingSpan: ReadableSpan = exportSpy.args[8][0][0]; - assert.equal( + equal( updatingSpan.parentSpanId, undefined, 'updating span is should not have a parent' ); - assert.equal( + equal( setStateSpan.parentSpanId, updatingSpan.spanContext().spanId, 'setState span is not a child of the updating span' ); - assert.equal( + equal( shouldComponentUpdateSpan.parentSpanId, updatingSpan.spanContext().spanId, 'shouldComponentUpdate span is not a child of the updating span' ); - assert.equal( + equal( renderSpan.parentSpanId, updatingSpan.spanContext().spanId, 'render span is not a child of the updating span' ); - assert.equal( + equal( getSnapshotBeforeUpdateSpan.parentSpanId, updatingSpan.spanContext().spanId, 'getSnapshotBeforeUpdate span is not a child of the updating span' ); - assert.equal( + equal( componentDidUpdateSpan.parentSpanId, updatingSpan.spanContext().spanId, 'componentDidUpdate span is not a child of the updating span' ); - assert.strictEqual( + strictEqual( exportSpy.args.length, 9, 'total number of spans is wrong' @@ -421,28 +415,28 @@ describe('ReactLoad Instrumentation', () => { const componentDidUpdateSpan: ReadableSpan = exportSpy.args[7][0][0]; const updatingSpan: ReadableSpan = exportSpy.args[8][0][0]; - assert.equal( + equal( updatingSpan.name, 'reactLoad: updating', 'updating span has wrong name' ); - assert.equal( + equal( setStateSpan.name, 'setState()', 'setState span has wrong name' ); - assert.equal( + equal( shouldComponentUpdateSpan.name, 'shouldComponentUpdate', 'shouldComponentUpdate span has wrong name' ); - assert.equal(renderSpan.name, 'render', 'render span has wrong name'); - assert.equal( + equal(renderSpan.name, 'render', 'render span has wrong name'); + equal( getSnapshotBeforeUpdateSpan.name, 'getSnapshotBeforeUpdate', 'getSnapshotBeforeUpdate span has wrong name' ); - assert.equal( + equal( componentDidUpdateSpan.name, 'componentDidUpdate', 'componentDidUpdate span has wrong name' @@ -451,7 +445,7 @@ describe('ReactLoad Instrumentation', () => { it('spans should have correct attributes', () => { const spans: [] = exportSpy.args; - assert.strictEqual(spans.length, 9, 'number of spans is wrong'); + strictEqual(spans.length, 9, 'number of spans is wrong'); spans.forEach(element => { const span: ReadableSpan = element[0][0]; ensureSpanAttributesAreCorrect(span); @@ -483,33 +477,33 @@ describe('ReactLoad Instrumentation', () => { const componentDidUpdateSpan: ReadableSpan = exportSpy.args[6][0][0]; const updatingSpan: ReadableSpan = exportSpy.args[7][0][0]; - assert.equal( + equal( updatingSpan.parentSpanId, undefined, 'updating span is should not have a parent' ); - assert.equal( + equal( forceUpdateSpan.parentSpanId, updatingSpan.spanContext().spanId, 'forceUpdate span is not a child of the updating span' ); - assert.equal( + equal( renderSpan.parentSpanId, updatingSpan.spanContext().spanId, 'render span is not a child of the updating span' ); - assert.equal( + equal( getSnapshotBeforeUpdateSpan.parentSpanId, updatingSpan.spanContext().spanId, 'getSnapshotBeforeUpdate span is not a child of the updating span' ); - assert.equal( + equal( componentDidUpdateSpan.parentSpanId, updatingSpan.spanContext().spanId, 'componentDidUpdate span is not a child of the updating span' ); - assert.strictEqual( + strictEqual( exportSpy.args.length, 8, 'total number of spans is wrong' @@ -524,23 +518,23 @@ describe('ReactLoad Instrumentation', () => { const componentDidUpdateSpan: ReadableSpan = exportSpy.args[6][0][0]; const updatingSpan: ReadableSpan = exportSpy.args[7][0][0]; - assert.equal( + equal( updatingSpan.name, 'reactLoad: updating', 'updating span has wrong name' ); - assert.equal( + equal( forceUpdateSpan.name, 'forceUpdate()', 'forceUpdate span has wrong name' ); - assert.equal(renderSpan.name, 'render', 'render span has wrong name'); - assert.equal( + equal(renderSpan.name, 'render', 'render span has wrong name'); + equal( getSnapshotBeforeUpdateSpan.name, 'getSnapshotBeforeUpdate', 'getSnapshotBeforeUpdate span has wrong name' ); - assert.equal( + equal( componentDidUpdateSpan.name, 'componentDidUpdate', 'componentDidUpdate span has wrong name' @@ -549,7 +543,7 @@ describe('ReactLoad Instrumentation', () => { it('spans should have correct attributes', () => { const spans: [] = exportSpy.args; - assert.strictEqual(spans.length, 8, 'number of spans is wrong'); + strictEqual(spans.length, 8, 'number of spans is wrong'); spans.forEach(element => { const span: ReadableSpan = element[0][0]; ensureSpanAttributesAreCorrect(span); @@ -578,18 +572,18 @@ describe('ReactLoad Instrumentation', () => { exportSpy.args[3][0][0]; const unmountingSpan: ReadableSpan = exportSpy.args[4][0][0]; - assert.equal( + equal( unmountingSpan.parentSpanId, undefined, 'unmounting span is should not have a parent' ); - assert.equal( + equal( componentWillUnmountSpan.parentSpanId, unmountingSpan.spanContext().spanId, 'componentWillUnmount span is not a child of the unmounting span' ); - assert.strictEqual( + strictEqual( exportSpy.args.length, 5, 'total number of spans is wrong' @@ -601,12 +595,12 @@ describe('ReactLoad Instrumentation', () => { exportSpy.args[3][0][0]; const unmountingSpan: ReadableSpan = exportSpy.args[4][0][0]; - assert.equal( + equal( unmountingSpan.name, 'reactLoad: unmounting', 'unmounting span has wrong name' ); - assert.equal( + equal( componentWillUnmountSpan.name, 'componentWillUnmount', 'componentWillUnmount span has wrong name' @@ -615,7 +609,7 @@ describe('ReactLoad Instrumentation', () => { it('spans should have correct attributes', () => { const spans: [] = exportSpy.args; - assert.strictEqual(spans.length, 5, 'number of spans is wrong'); + strictEqual(spans.length, 5, 'number of spans is wrong'); spans.forEach(element => { const span: ReadableSpan = element[0][0]; ensureSpanAttributesAreCorrect(span); @@ -650,27 +644,23 @@ describe('ReactLoad Instrumentation', () => { const shouldComponentUpdateSpan: ReadableSpan = exportSpy.args[4][0][0]; const updatingSpan: ReadableSpan = exportSpy.args[5][0][0]; - assert.equal( + equal( updatingSpan.parentSpanId, undefined, 'updating span is should not have a parent' ); - assert.equal( + equal( setStateSpan.parentSpanId, updatingSpan.spanContext().spanId, 'setState span is not a child of the updating span' ); - assert.equal( + equal( shouldComponentUpdateSpan.parentSpanId, updatingSpan.spanContext().spanId, 'shouldComponentUpdate span is not a child of the updating span' ); - assert.strictEqual( - exportSpy.args.length, - 6, - 'total number of spans is wrong' - ); + strictEqual(exportSpy.args.length, 6, 'total number of spans is wrong'); }); it('spans should have correct name', () => { @@ -678,17 +668,13 @@ describe('ReactLoad Instrumentation', () => { const shouldComponentUpdateSpan: ReadableSpan = exportSpy.args[4][0][0]; const updatingSpan: ReadableSpan = exportSpy.args[5][0][0]; - assert.equal( + equal( updatingSpan.name, 'reactLoad: updating', 'updating span has wrong name' ); - assert.equal( - setStateSpan.name, - 'setState()', - 'setState span has wrong name' - ); - assert.equal( + equal(setStateSpan.name, 'setState()', 'setState span has wrong name'); + equal( shouldComponentUpdateSpan.name, 'shouldComponentUpdate', 'shouldComponentUpdate span has wrong name' @@ -709,21 +695,21 @@ function ensureSpanAttributesAreCorrect(span: ReadableSpan) { const attributes = span.attributes; const keys = Object.keys(attributes); - assert.ok( + ok( attributes[keys[0]] !== '', `attributes ${AttributeNames.LOCATION_URL} is not defined for span "${span.name}"` ); - assert.ok( + ok( attributes[keys[1]] !== '', `attributes ${AttributeNames.REACT_NAME} is not defined for span "${span.name}"` ); - assert.ok( + ok( attributes[keys[2]] !== '', `attributes ${AttributeNames.REACT_STATE} is not defined for span "${span.name}"` ); - assert.strictEqual( + strictEqual( keys.length, 3, `number of attributes is wrong for span "${span.name}"` diff --git a/propagators/opentelemetry-propagator-instana/test/InstanaPropagator.test.ts b/propagators/opentelemetry-propagator-instana/test/InstanaPropagator.test.ts index 102cb30a40..b6a630a6dd 100644 --- a/propagators/opentelemetry-propagator-instana/test/InstanaPropagator.test.ts +++ b/propagators/opentelemetry-propagator-instana/test/InstanaPropagator.test.ts @@ -24,7 +24,7 @@ import { TraceFlags, ROOT_CONTEXT, } from '@opentelemetry/api'; -import * as assert from 'assert'; +import { strictEqual, deepStrictEqual } from 'assert'; import { InstanaPropagator, INSTANA_TRACE_ID_HEADER, @@ -54,12 +54,12 @@ describe('InstanaPropagator', () => { defaultTextMapSetter ); - assert.strictEqual( + strictEqual( carrier[INSTANA_TRACE_ID_HEADER], '80f198ee56343ba864fe8b2a57d3eff7' ); - assert.strictEqual(carrier[INSTANA_SPAN_ID_HEADER], 'e457b5a2e4d86bd1'); - assert.strictEqual(carrier[INSTANA_LEVEL_HEADER], '1'); + strictEqual(carrier[INSTANA_SPAN_ID_HEADER], 'e457b5a2e4d86bd1'); + strictEqual(carrier[INSTANA_LEVEL_HEADER], '1'); }); it('translates sampled flag into level header', () => { @@ -75,12 +75,12 @@ describe('InstanaPropagator', () => { defaultTextMapSetter ); - assert.strictEqual( + strictEqual( carrier[INSTANA_TRACE_ID_HEADER], '80f198ee56343ba864fe8b2a57d3eff7' ); - assert.strictEqual(carrier[INSTANA_SPAN_ID_HEADER], 'e457b5a2e4d86bd1'); - assert.strictEqual(carrier[INSTANA_LEVEL_HEADER], '0'); + strictEqual(carrier[INSTANA_SPAN_ID_HEADER], 'e457b5a2e4d86bd1'); + strictEqual(carrier[INSTANA_LEVEL_HEADER], '0'); }); it('correctly reads sampled flags, even if other flags are set', () => { @@ -98,12 +98,12 @@ describe('InstanaPropagator', () => { defaultTextMapSetter ); - assert.strictEqual( + strictEqual( carrier[INSTANA_TRACE_ID_HEADER], '80f198ee56343ba864fe8b2a57d3eff7' ); - assert.strictEqual(carrier[INSTANA_SPAN_ID_HEADER], 'e457b5a2e4d86bd1'); - assert.strictEqual(carrier[INSTANA_LEVEL_HEADER], '1'); + strictEqual(carrier[INSTANA_SPAN_ID_HEADER], 'e457b5a2e4d86bd1'); + strictEqual(carrier[INSTANA_LEVEL_HEADER], '1'); }); it('does nothing if the trace ID is invalid', () => { @@ -119,9 +119,9 @@ describe('InstanaPropagator', () => { defaultTextMapSetter ); - assert.strictEqual(carrier[INSTANA_TRACE_ID_HEADER], undefined); - assert.strictEqual(carrier[INSTANA_SPAN_ID_HEADER], undefined); - assert.strictEqual(carrier[INSTANA_LEVEL_HEADER], undefined); + strictEqual(carrier[INSTANA_TRACE_ID_HEADER], undefined); + strictEqual(carrier[INSTANA_SPAN_ID_HEADER], undefined); + strictEqual(carrier[INSTANA_LEVEL_HEADER], undefined); }); it('does nothing if the span ID is invalid', () => { @@ -137,9 +137,9 @@ describe('InstanaPropagator', () => { defaultTextMapSetter ); - assert.strictEqual(carrier[INSTANA_TRACE_ID_HEADER], undefined); - assert.strictEqual(carrier[INSTANA_SPAN_ID_HEADER], undefined); - assert.strictEqual(carrier[INSTANA_LEVEL_HEADER], undefined); + strictEqual(carrier[INSTANA_TRACE_ID_HEADER], undefined); + strictEqual(carrier[INSTANA_SPAN_ID_HEADER], undefined); + strictEqual(carrier[INSTANA_LEVEL_HEADER], undefined); }); }); @@ -162,7 +162,7 @@ describe('InstanaPropagator', () => { const extractedSpanContext = trace.getSpan(context)?.spanContext(); - assert.deepStrictEqual(extractedSpanContext, { + deepStrictEqual(extractedSpanContext, { traceId: '80f198ee56343ba864fe8b2a57d3eff7', spanId: 'e457b5a2e4d86bd1', isRemote: true, @@ -187,7 +187,7 @@ describe('InstanaPropagator', () => { const extractedSpanContext = trace.getSpan(context)?.spanContext(); - assert.deepStrictEqual(extractedSpanContext, { + deepStrictEqual(extractedSpanContext, { traceId: '80f198ee56343ba864fe8b2a57d3eff7', spanId: 'e457b5a2e4d86bd1', isRemote: true, @@ -210,7 +210,7 @@ describe('InstanaPropagator', () => { const extractedSpanContext = trace.getSpan(context)?.spanContext(); - assert.deepStrictEqual(extractedSpanContext, { + deepStrictEqual(extractedSpanContext, { traceId: '80f198ee56343ba864fe8b2a57d3eff7', spanId: 'e457b5a2e4d86bd1', isRemote: true, @@ -234,7 +234,7 @@ describe('InstanaPropagator', () => { const extractedSpanContext = trace.getSpan(context)?.spanContext(); - assert.deepStrictEqual(extractedSpanContext, { + deepStrictEqual(extractedSpanContext, { traceId: '80f198ee56343ba864fe8b2a57d3eff7', spanId: 'e457b5a2e4d86bd1', isRemote: true, @@ -255,7 +255,7 @@ describe('InstanaPropagator', () => { const extractedSpanContext = trace.getSpan(context)?.spanContext(); - assert.deepStrictEqual(extractedSpanContext, { + deepStrictEqual(extractedSpanContext, { traceId: INVALID_TRACEID, spanId: INVALID_SPANID, isRemote: true, @@ -277,7 +277,7 @@ describe('InstanaPropagator', () => { ); const extractedSpanContext = trace.getSpan(context)?.spanContext(); - assert.deepStrictEqual(extractedSpanContext, { + deepStrictEqual(extractedSpanContext, { traceId: '00000000000000004aaba1a52cf8ee09', spanId: 'e457b5a2e4d86bd1', isRemote: true, @@ -300,7 +300,7 @@ describe('InstanaPropagator', () => { ); const extractedSpanContext = trace.getSpan(context)?.spanContext(); - assert.deepStrictEqual(extractedSpanContext, { + deepStrictEqual(extractedSpanContext, { traceId: '80f198ee56343ba864fe8b2a57d3eff7', spanId: '0007b5a2e4d86bd1', isRemote: true, @@ -323,7 +323,7 @@ describe('InstanaPropagator', () => { ); const extractedSpanContext = trace.getSpan(context)?.spanContext(); - assert.deepStrictEqual(undefined, extractedSpanContext); + deepStrictEqual(undefined, extractedSpanContext); }); it('handles malformed span ID', () => { @@ -341,7 +341,7 @@ describe('InstanaPropagator', () => { ); const extractedSpanContext = trace.getSpan(context)?.spanContext(); - assert.deepStrictEqual(undefined, extractedSpanContext); + deepStrictEqual(undefined, extractedSpanContext); }); it('handles invalid trace ID', () => { @@ -358,7 +358,7 @@ describe('InstanaPropagator', () => { ); const extractedSpanContext = trace.getSpan(context)?.spanContext(); - assert.deepStrictEqual(undefined, extractedSpanContext); + deepStrictEqual(undefined, extractedSpanContext); }); it('handles invalid span ID', () => { @@ -376,13 +376,13 @@ describe('InstanaPropagator', () => { ); const extractedSpanContext = trace.getSpan(context)?.spanContext(); - assert.deepStrictEqual(undefined, extractedSpanContext); + deepStrictEqual(undefined, extractedSpanContext); }); }); describe('.fields', () => { it('provides all fields', () => { - assert.deepStrictEqual( + deepStrictEqual( [INSTANA_TRACE_ID_HEADER, INSTANA_SPAN_ID_HEADER, INSTANA_LEVEL_HEADER], propagator.fields() ); diff --git a/propagators/opentelemetry-propagator-ot-trace/src/index.ts b/propagators/opentelemetry-propagator-ot-trace/src/index.ts index 116d438fa3..cefc208c30 100644 --- a/propagators/opentelemetry-propagator-ot-trace/src/index.ts +++ b/propagators/opentelemetry-propagator-ot-trace/src/index.ts @@ -14,4 +14,4 @@ * limitations under the License. */ -export * from './OTTracePropagator'; +export { OTTracePropagator } from './OTTracePropagator'; diff --git a/propagators/opentelemetry-propagator-ot-trace/test/OTTracePropagator.test.ts b/propagators/opentelemetry-propagator-ot-trace/test/OTTracePropagator.test.ts index d07b3d3eb2..95e8970228 100644 --- a/propagators/opentelemetry-propagator-ot-trace/test/OTTracePropagator.test.ts +++ b/propagators/opentelemetry-propagator-ot-trace/test/OTTracePropagator.test.ts @@ -26,7 +26,7 @@ import { Baggage, ROOT_CONTEXT, } from '@opentelemetry/api'; -import * as assert from 'assert'; +import assert = require('assert'); import { OTTracePropagator, OT_TRACE_ID_HEADER,