Skip to content

Commit

Permalink
broken test
Browse files Browse the repository at this point in the history
  • Loading branch information
mhennoch committed Sep 4, 2024
1 parent 8c08c93 commit ada939c
Show file tree
Hide file tree
Showing 4 changed files with 139 additions and 107 deletions.
66 changes: 42 additions & 24 deletions test/options.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,16 @@

import * as api from '@opentelemetry/api';
import { W3CBaggagePropagator } from '@opentelemetry/core';
import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-grpc';
import { OTLPTraceExporter as OTLPHttpTraceExporter } from '@opentelemetry/exporter-trace-otlp-proto';
import { InstrumentationBase } from '@opentelemetry/instrumentation';
import { Resource } from '@opentelemetry/resources';
import {
ConsoleSpanExporter,
InMemorySpanExporter,
SimpleSpanProcessor,
SpanExporter,
} from '@opentelemetry/sdk-trace-base';
import {
SEMRESATTRS_CONTAINER_ID,
SEMRESATTRS_HOST_ARCH,
Expand All @@ -30,19 +38,10 @@ import {
SEMRESATTRS_PROCESS_RUNTIME_VERSION,
SEMRESATTRS_SERVICE_NAME,
} from '@opentelemetry/semantic-conventions';
import {
ConsoleSpanExporter,
SimpleSpanProcessor,
SpanExporter,
InMemorySpanExporter,
} from '@opentelemetry/sdk-trace-base';
import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-grpc';
import { OTLPTraceExporter as OTLPHttpTraceExporter } from '@opentelemetry/exporter-trace-otlp-proto';

import { strict as assert } from 'assert';
import { describe, it, beforeEach, afterEach, mock } from 'node:test';
import { Mock } from 'node:test';
import * as fs from 'fs';
import { afterEach, beforeEach, describe, it, mock } from 'node:test';
import * as os from 'os';

import * as instrumentations from '../src/instrumentations';
Expand Down Expand Up @@ -195,12 +194,29 @@ describe('options', () => {

assert(exporter instanceof OTLPTraceExporter);

// sinon.assert.calledWithMatch(logger.warn, MATCH_SERVICE_NAME_WARNING);
//FIXME finish
const logMsg = logger.warn.mock.calls[0].arguments[0];
console.log(logMsg);
assert(MATCH_SERVICE_NAME_WARNING.test(logMsg));
});

it('reads the container when setting default options', (t) => {
// Stub `os.platform` to return 'linux'
mock.method(os, 'platform', () => 'linux');

// Stub `fs.readFileSync` to simulate reading the file
mock.method(fs, 'readFileSync', (path, encoding) => {
if (path === '/proc/self/cgroup' && encoding === 'utf8') {
return '1:blkio:/docker/a4d00c9dd675d67f866c786181419e1b44832d4696780152e61afd44a3e02856\n';
}
return ''; // Default return if different path or encoding
});

const options = _setDefaultOptions();
assertContainerId(
options.tracerConfig.resource?.attributes[SEMRESATTRS_CONTAINER_ID]
);
});
// TODO left for debugging

// it('reads the container when setting default options', () => {
// sandbox.stub(os, 'platform').returns('linux');
// sandbox
Expand Down Expand Up @@ -254,11 +270,7 @@ describe('options', () => {
propagatorFactory: testPropagatorFactory,
});

sinon.assert.neverCalledWithMatch(logger.warn, MATCH_SERVICE_NAME_WARNING);
sinon.assert.neverCalledWithMatch(
logger.warn,
MATCH_NO_INSTRUMENTATIONS_WARNING
);
assert(logger.warn.mock.calls.length === 0);
});

describe('OTEL_TRACES_EXPORTER', () => {
Expand Down Expand Up @@ -358,10 +370,12 @@ describe('options', () => {
exporter.url,
'https://ingest.us0.signalfx.com/v2/trace/otlp'
);
sinon.assert.calledWith(
logger.warn,
`OTLP span exporter factory: defaulting protocol to 'http/protobuf' instead of grpc due to realm being defined.`
const oneLogMatches = logger.warn.mock.calls.some((call) =>
call.arguments[0].includes(
`OTLP span exporter factory: defaulting protocol to 'http/protobuf' instead of grpc due to realm being defined.`
)
);
assert(oneLogMatches);
});

it('warns when realm and endpoint are both set', () => {
Expand All @@ -373,10 +387,14 @@ describe('options', () => {
const exporters = options.spanExporterFactory(options);
assert(Array.isArray(exporters));
const [exporter] = exporters;
sinon.assert.calledWith(
logger.warn,
'OTLP span exporter factory: Realm value ignored (full endpoint URL has been specified).'

const oneLogMatches = logger.warn.mock.calls.some((call) =>
call.arguments[0].includes(
`OTLP span exporter factory: Realm value ignored (full endpoint URL has been specified).`
)
);
assert(oneLogMatches);

assert(
exporter instanceof OTLPTraceExporter,
'Expected exporter to be instance of OTLPTraceExporter'
Expand Down
14 changes: 7 additions & 7 deletions test/propagation.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,26 +14,26 @@
* limitations under the License.
*/

import * as assert from 'assert';
import * as util from 'util';

import {
propagation,
trace,
context,
defaultTextMapSetter,
defaultTextMapGetter,
propagation,
trace,
} from '@opentelemetry/api';
import { startTracing, stopTracing } from '../src/tracing';
import { CompositePropagator, RandomIdGenerator } from '@opentelemetry/core';
import { RandomIdGenerator } from '@opentelemetry/core';
import {
InMemorySpanExporter,
SpanProcessor,
} from '@opentelemetry/sdk-trace-base';
import { parseOptionsAndConfigureInstrumentations } from '../src/instrumentations';
import { startTracing, stopTracing } from '../src/tracing';
import { SYNTHETIC_RUN_ID_FIELD } from '../src/tracing/SplunkBatchSpanProcessor';
import { defaultSpanProcessorFactory } from '../src/tracing/options';
import * as utils from './utils';
import { parseOptionsAndConfigureInstrumentations } from '../src/instrumentations';
import { strict as assert } from 'assert';
import { describe, it, beforeEach, afterEach } from 'node:test';

function assertIncludes(arr: string[], item: string) {
assert(Array.isArray(arr), `Expected an array got ${util.inspect(arr)}`);
Expand Down
26 changes: 8 additions & 18 deletions test/resource.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,31 +14,21 @@
* limitations under the License.
*/

import * as assert from 'assert';
import { strict as assert } from 'assert';
import { beforeEach, describe, it, mock } from 'node:test';

import { SEMRESATTRS_CONTAINER_ID } from '@opentelemetry/semantic-conventions';
import * as fs from 'fs';
import { ContainerDetector } from '../src/detectors/ContainerDetector';
import { detect } from '../src/resource';
import * as fs from 'fs';
import * as sinon from 'sinon';
import * as utils from './utils';
import { SEMRESATTRS_CONTAINER_ID } from '@opentelemetry/semantic-conventions';

describe('resource detector', () => {
beforeEach(() => {
utils.cleanEnvironment();
});

describe('ContainerDetector', () => {
let sandbox: sinon.SinonSandbox;

before(() => {
sandbox = sinon.createSandbox();
});

after(() => {
sandbox.restore();
});

const invalidCases = [
'13:name=systemd:/podruntime/docker/kubepods/ac679f8a8319c8cf7d38e1adf263bc08d23zzzz',
];
Expand Down Expand Up @@ -84,20 +74,20 @@ describe('resource detector', () => {
it('parses all the known test cases correctly', () => {
const detector = new ContainerDetector();
testCases.forEach(([testCase, result]) => {
const stub = sinon.stub(fs, 'readFileSync').returns(testCase);
mock.method(fs, 'readFileSync', () => testCase);

assert.strictEqual(
detector.detect().attributes[SEMRESATTRS_CONTAINER_ID],
result
);
stub.restore();
});
invalidCases.forEach(([testCase, result]) => {
const stub = sinon.stub(fs, 'readFileSync').returns(testCase);
mock.method(fs, 'readFileSync', () => testCase);

assert.strictEqual(
detector.detect().attributes[SEMRESATTRS_CONTAINER_ID],
undefined
);
stub.restore();
});
});
});
Expand Down
140 changes: 82 additions & 58 deletions test/servertiming.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,14 @@
* limitations under the License.
*/

import * as assert from 'assert';
import { strict as assert } from 'assert';
import { beforeEach, describe, it, afterEach } from 'node:test';

import { context, trace } from '@opentelemetry/api';
import { HttpInstrumentation } from '@opentelemetry/instrumentation-http';
import { parseOptionsAndConfigureInstrumentations } from '../src/instrumentations';
import { startTracing, stopTracing } from '../src/tracing';
import * as utils from './utils';
import { parseOptionsAndConfigureInstrumentations } from '../src/instrumentations';

const PORT = 9111;
const SERVER_URL = `http://localhost:${PORT}`;
Expand All @@ -40,86 +42,108 @@ describe('servertiming', () => {
let server;

beforeEach(utils.cleanEnvironment);
afterEach(() => {
afterEach(async () => {
console.log('closing server');
// if (server) {
// // Await server closing to ensure it's fully stopped
// await new Promise<void>((resolve, reject) => {
// server.close((err) => {
// if (err) reject(err);
// else resolve();
// });
// });
// }
server.close();
stopTracing();
});

function testHeadersAdded(done) {
async function testHeadersAdded() {
let spanContext;
const http = require('http');
server = http.createServer((req, res) => {
spanContext = trace.getSpanContext(context.active());
console.log('got request', spanContext);
res.end('ok');
});
server.listen(PORT);
http.get(SERVER_URL, (res) => {
assertHeaders(spanContext, res);
done();
// await new Promise((resolve) => server.listen(PORT, resolve));

await new Promise<void>((resolve) => {
http.get(SERVER_URL, (res) => {
console.log('got response', spanContext);
assertHeaders(spanContext, res);
resolve();
});
});
}

it('injects server timing by default', (done) => {
it('injects server timing by default', async () => {
const { tracingOptions } = parseOptionsAndConfigureInstrumentations();
startTracing(tracingOptions);
testHeadersAdded(done);
await testHeadersAdded();
console.log('test 1 done');
});

it('can be enabled via environment variables', (done) => {
it('can be enabled via environment variables', async () => {
process.env.SPLUNK_TRACE_RESPONSE_HEADER_ENABLED = 'true';
const { tracingOptions } = parseOptionsAndConfigureInstrumentations();
startTracing(tracingOptions);
testHeadersAdded(() => {
done();
});
// await new Promise((resolve) => setTimeout(resolve, 500));
await testHeadersAdded();
console.log('test 2 done');
});

it('injects server timing header with current context', (done) => {
const { tracingOptions } = parseOptionsAndConfigureInstrumentations({
tracing: { serverTimingEnabled: true },
});
startTracing(tracingOptions);
testHeadersAdded(done);
});
// it('injects server timing header with current context', async () => {
// const { tracingOptions } = parseOptionsAndConfigureInstrumentations({
// tracing: { serverTimingEnabled: true },
// });
// startTracing(tracingOptions);
// await testHeadersAdded();
// });

it('works with user provided http instrumentation config', (done) => {
const { tracingOptions } = parseOptionsAndConfigureInstrumentations({
tracing: {
serverTimingEnabled: true,
instrumentations: [new HttpInstrumentation({})],
},
});
startTracing(tracingOptions);
testHeadersAdded(done);
});
// it('works with user provided http instrumentation config', async () => {
// const { tracingOptions } = parseOptionsAndConfigureInstrumentations({
// tracing: {
// serverTimingEnabled: true,
// instrumentations: [new HttpInstrumentation({})],
// },
// });
// startTracing(tracingOptions);
// await testHeadersAdded();
// });

it('leaves user hooks unchanged', (done) => {
let userHookCalled = false;
const { tracingOptions } = parseOptionsAndConfigureInstrumentations({
tracing: {
serverTimingEnabled: true,
instrumentations: [
new HttpInstrumentation({
responseHook: (span, response) => {
userHookCalled = true;
},
}),
],
},
});
startTracing(tracingOptions);
// it('leaves user hooks unchanged', async () => {
// let userHookCalled = false;
// const { tracingOptions } = parseOptionsAndConfigureInstrumentations({
// tracing: {
// serverTimingEnabled: true,
// instrumentations: [
// new HttpInstrumentation({
// responseHook: (span, response) => {
// userHookCalled = true;
// },
// }),
// ],
// },
// });
// startTracing(tracingOptions);

const http = require('http');
let spanContext;
server = http.createServer((req, res) => {
spanContext = trace.getSpanContext(context.active());
res.end('ok');
});
server.listen(PORT);
http.get(SERVER_URL, (res) => {
assertHeaders(spanContext, res);
assert.ok(userHookCalled);
done();
});
});
// const http = require('http');
// let spanContext;

// server = http.createServer((req, res) => {
// spanContext = trace.getSpanContext(context.active());
// res.end('ok');
// });

// server.listen(PORT);

// await new Promise<void>((resolve) => {
// http.get(SERVER_URL, (res) => {
// assertHeaders(spanContext, res);
// assert.ok(userHookCalled);
// resolve();
// });
// });
// });
});

0 comments on commit ada939c

Please sign in to comment.