Skip to content

Commit

Permalink
Port applyCustomAttributesOnSpan tests
Browse files Browse the repository at this point in the history
  • Loading branch information
chancancode committed Dec 25, 2024
1 parent 43db151 commit 3a013bf
Show file tree
Hide file tree
Showing 2 changed files with 157 additions and 8 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,11 @@ import * as tracing from '@opentelemetry/sdk-trace-base';
import { WebTracerProvider } from '@opentelemetry/sdk-trace-web';
import * as assert from 'assert';
import * as sinon from 'sinon';
import { FetchInstrumentation, FetchInstrumentationConfig } from '../src';
import {
FetchCustomAttributeFunction,
FetchInstrumentation,
FetchInstrumentationConfig,
} from '../src';
import { AttributeNames } from '../src/enums/AttributeNames';
import {
SEMATTRS_HTTP_HOST,
Expand Down Expand Up @@ -974,16 +978,161 @@ describe('fetch', () => {
config: { measureRequestSize: true },
});
const { request } = await response.json();
debugger;
assert.strictEqual(
request.headers['content-type'],
'application/x-www-form-urlencoded'
);
assert.deepStrictEqual(request.body, 'hello=world');
assert.strictEqual(request.body, 'hello=world');
assertHasRequestContentLength('hello=world');
});
});
});
});

describe('secure requests', () => {
// TODO: come back to events later
});

describe('`applyCustomAttributesOnSpan` hook', () => {
async function tracedFetch({
handlers = [
msw.http.get('/api/project-headers.json', ({ request }) => {
const headers = new Headers();

for (const [key, value] of request.headers) {
headers.set(`x-request-${key}`, value);
}

return msw.HttpResponse.json({ ok: true }, { headers });
}),
msw.http.get('/api/fail.json', () => {
return msw.HttpResponse.json({ fail: true }, { status: 500 });
}),
],
callback = () => fetch('/api/project-headers.json'),
config,
}: {
handlers?: msw.RequestHandler[];
callback?: () => Promise<Response>;
config: FetchInstrumentationConfig &
Required<
Pick<FetchInstrumentationConfig, 'applyCustomAttributesOnSpan'>
>;
}): Promise<{ rootSpan: api.Span; response: Response }> {
let rootSpan: api.Span;
let response: Response | undefined;

await startWorker(...handlers);

// The current implementation doesn't call this hook until the body has
// been fully read, this ensures that timing is met before returning to
// the test so we don't have to deal with it in every test. Plus it
// checks that the hook is definitely called which is important here.
const appliedCustomAttributes = new Promise<void>(resolve => {
const originalHook = config.applyCustomAttributesOnSpan;

const applyCustomAttributesOnSpan = (
...args: Parameters<FetchCustomAttributeFunction>
) => {
resolve();
originalHook(...args);
};

config = { ...config, applyCustomAttributesOnSpan };
});

rootSpan = await trace(async () => {
response = await callback();
}, config);

await appliedCustomAttributes;

assert.ok(response instanceof Response);
assert.strictEqual(exportedSpans.length, 1);

return { rootSpan, response };
}

it('can apply arbitrary attributes to the span indiscriminantly', async () => {
await tracedFetch({
config: {
applyCustomAttributesOnSpan: span => {
span.setAttribute('custom.foo', 'bar');
},
},
});

const span: tracing.ReadableSpan = exportedSpans[0][0];
assert.strictEqual(span.attributes['custom.foo'], 'bar');
});

describe('successful request', () => {
it('has access to the request and response objects', async () => {
await tracedFetch({
callback: () =>
fetch(
new Request('/api/project-headers.json', {
headers: new Headers({
foo: 'bar',
}),
})
),
config: {
applyCustomAttributesOnSpan: (span, request, response) => {
assert.ok(request.headers instanceof Headers);
assert.ok(response instanceof Response);
assert.ok(response.headers instanceof Headers);

assert.strictEqual(
request.headers.get('foo'),
response.headers.get('x-request-foo')
);

span.setAttribute(
'custom.foo',
response.headers.get('x-request-foo')!
);
},
},
});

const span: tracing.ReadableSpan = exportedSpans[0][0];
assert.strictEqual(span.attributes['custom.foo'], 'bar');
});

// https://github.com/open-telemetry/opentelemetry-js/pull/5281
it('will not be able to access the response body if already consumed by the application', async () => {
await tracedFetch({
callback: async () => {
const response = await fetch(
new Request('/api/project-headers.json')
);

// body consumed here by the application
await response.json();

return response;
},
config: {
applyCustomAttributesOnSpan: (span, _request, response) => {
assert.ok(response instanceof Response);

span.setAttribute(
'custom.body-used',
String(response.bodyUsed)
);
},
},
});

const span: tracing.ReadableSpan = exportedSpans[0][0];
assert.strictEqual(
span.attributes['custom.body-used'],
// Flip this to 'true' after #5281 is merged
'false'
);
});
});
});
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -880,7 +880,7 @@ describe('fetch', () => {
});
});

describe('applyCustomAttributesOnSpan option', () => {
xdescribe('applyCustomAttributesOnSpan option', () => {
const prepare = async (
url: string,
applyCustomAttributesOnSpan: FetchCustomAttributeFunction
Expand All @@ -897,7 +897,7 @@ describe('fetch', () => {
clearData();
});

it('applies attributes when the request is successful', async () => {
xit('applies attributes when the request is successful', async () => {
await prepare(url, span => {
span.setAttribute(CUSTOM_ATTRIBUTE_KEY, 'custom value');
});
Expand All @@ -907,7 +907,7 @@ describe('fetch', () => {
assert.ok(attributes[CUSTOM_ATTRIBUTE_KEY] === 'custom value');
});

it('applies custom attributes when the request fails', async () => {
xit('applies custom attributes when the request fails', async () => {
await prepare(badUrl, span => {
span.setAttribute(CUSTOM_ATTRIBUTE_KEY, 'custom value');
});
Expand All @@ -917,7 +917,7 @@ describe('fetch', () => {
assert.ok(attributes[CUSTOM_ATTRIBUTE_KEY] === 'custom value');
});

it('has request and response objects in callback arguments', async () => {
xit('has request and response objects in callback arguments', async () => {
let request: any;
let response: any;
const applyCustomAttributes: FetchCustomAttributeFunction = (
Expand All @@ -934,7 +934,7 @@ describe('fetch', () => {
assert.ok(response.status === 200);
});

it('get response body from callback arguments response', async () => {
xit('get response body from callback arguments response', async () => {
let response: any;
const applyCustomAttributes: FetchCustomAttributeFunction = async (
span,
Expand Down

0 comments on commit 3a013bf

Please sign in to comment.