Skip to content

improvement: integration tests #1050

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Mar 20, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .size-limit.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ module.exports = [

{
name: 'artifacts/splunk-otel-web.js',
limit: '42 kB',
limit: '43 kB',
path: './packages/web/dist/artifacts/splunk-otel-web.js',
},

Expand Down
4 changes: 2 additions & 2 deletions packages/integration-tests/src/pages/record-page.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,8 @@ export class RecordPage {

async flushData() {
await this.page.evaluate(() => {
if (window.SplunkRum) {
window.SplunkRum._processor.forceFlush()
if ((window as any).SplunkRum) {
;(window as any).SplunkRum._processor.forceFlush()
}
})
}
Expand Down
12 changes: 7 additions & 5 deletions packages/integration-tests/src/server/render-agent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,14 +20,16 @@ export const RENDER_AGENT_TEMPLATE = `
<script src="<%= otelApiGlobalsFile -%>" crossorigin="anonymous"></script>
<script>
const options = <%- options -%>;
const customOptions = <%- customOptions -%>;

const samplingRatioRaw = (new URL(document.location)).searchParams.get('samplingRatio');
console.log('samplingRatioRaw', samplingRatioRaw);
if (samplingRatioRaw != null) {
console.log('setting sampling ration:', samplingRatioRaw);
if (typeof customOptions.forceSessionId === 'string') {
window.__splunkRumIntegrationTestSessionId = customOptions.forceSessionId;
}

if (typeof customOptions.samplingRatio === 'number') {
options['tracer'] = {
sampler: new SplunkRum.SessionBasedSampler({
ratio: parseFloat(samplingRatioRaw),
ratio: customOptions.samplingRatio,
})
}
}
Expand Down
20 changes: 15 additions & 5 deletions packages/integration-tests/src/server/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,8 +100,11 @@ fastify.get('/', (request, reply) => {

fastify.get<{
Querystring: {
_experimental_longtaskNoStartSession?: string
beaconEndpoint?: string
disableInstrumentation?: string
forceSessionId?: string
samplingRatio?: string
}
}>('*', async (request, reply) => {
const beaconUrl = new URL(`http://${request.headers.host}/api/v2/spans`)
Expand All @@ -110,23 +113,29 @@ fastify.get<{
const parsedUrl = new URL(request.url, `http://${request.host}`)
const filePath = path.join(__dirname, '../tests', parsedUrl.pathname)

const _experimental_longtaskNoStartSession = JSON.parse(
request.query['_experimental_longtaskNoStartSession'] ?? 'null',
)

if (fs.existsSync(filePath)) {
if (parsedUrl.pathname.endsWith('.ejs')) {
return reply.viewAsync(parsedUrl.pathname, {
renderAgent(userOpts = {}, noInit = false, file = defaultFile, cdnVersion = null) {
const options: Record<string, unknown> = {
_experimental_longtaskNoStartSession,
_experimental_longtaskNoStartSession:
request.query._experimental_longtaskNoStartSession === 'true',
beaconEndpoint: beaconUrl.toString(),
applicationName: 'splunk-otel-js-dummy-app',
debug: true,
bufferTimeout: GLOBAL_TEST_BUFFER_TIMEOUT,
...userOpts,
}

const customOptions: Record<string, unknown> = {}
if (typeof request.query.samplingRatio === 'string') {
customOptions['samplingRatio'] = parseFloat(request.query.samplingRatio)
}

if (typeof request.query.forceSessionId === 'string') {
customOptions['forceSessionId'] = request.query.forceSessionId
}

if (typeof request.query.disableInstrumentation === 'string') {
if (!options.instrumentations) {
options.instrumentations = {}
Expand All @@ -149,6 +158,7 @@ fastify.get<{
file,
noInit,
options: JSON.stringify(options),
customOptions: JSON.stringify(customOptions),
otelApiGlobalsFile: '/artifacts/otel-api-globals.js',
})
},
Expand Down
6 changes: 3 additions & 3 deletions packages/integration-tests/src/tests/errors/errors.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -131,9 +131,9 @@ test.describe('errors', () => {
expect(errorSpans[0].tags['error.message']).toBe(errorMessages[browserName])

const errorStackMap = {
chromium: `TypeError: Cannot set properties of null (setting 'anyField')\n at ${url}:76:25`,
firefox: `@${url}:76:7\n`,
webkit: `global code@${url}:76:15`,
chromium: `TypeError: Cannot set properties of null (setting 'anyField')\n at ${url}:78:25`,
firefox: `@${url}:78:7\n`,
webkit: `global code@${url}:78:15`,
}

expect(errorSpans[0].tags['error.stack']).toBe(errorStackMap[browserName])
Expand Down
21 changes: 21 additions & 0 deletions packages/integration-tests/src/tests/extend-activity/all.ejs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>All spans extend session</title>

<%- renderAgent({ _experimental_allSpansExtendSession: true }) %>
</head>
<body>
<h1>All spans extend session to true</h1>
<pre id="scenarioDisplay"></pre>
<button type="button" id="btnSpan">Produce a span</button>
<pre id="scenarioDisplay"></pre>
<script id="scenario">
document.querySelector('#btnSpan').addEventListener('click', () => {
SplunkRum.provider.getTracer('guard').startSpan('guard-span').end();
});
</script>
<script>scenarioDisplay.innerHTML = scenario.innerHTML;</script>
</body>
</html>
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
/**
*
* Copyright 2020-2025 Splunk Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
import { expect } from '@playwright/test'
import { test } from '../../utils/test'

test.describe('extend-activity', () => {
test('only user activity extends session', async ({ recordPage }) => {
await recordPage.goTo('/extend-activity/some.ejs')

const sessionCookie1 = await recordPage.getCookie('_splunk_rum_sid')

expect(sessionCookie1).toBeTruthy()

const sessionCookie1Parsed = JSON.parse(decodeURIComponent(sessionCookie1.value))

await recordPage.waitForTimeout(1500)

await recordPage.evaluate(() => {
;(window as any).SplunkRum.provider.getTracer('guard').startSpan('guard-span').end()
})

await recordPage.waitForTimeout(1500)

const sessionCookie2 = await recordPage.getCookie('_splunk_rum_sid')

expect(sessionCookie2).toBeTruthy()

const sessionCookie2Parsed = JSON.parse(decodeURIComponent(sessionCookie2.value))

expect(sessionCookie1Parsed.expiresAt).toBe(sessionCookie2Parsed.expiresAt)

expect(recordPage.receivedSpans.filter((s) => s.name === 'guard-span')).toHaveLength(1)
})

test('all spans extend session', async ({ recordPage }) => {
await recordPage.goTo('/extend-activity/all.ejs')

const sessionCookie1 = await recordPage.getCookie('_splunk_rum_sid')

expect(sessionCookie1).toBeTruthy()

const sessionCookie1Parsed = JSON.parse(decodeURIComponent(sessionCookie1.value))

await recordPage.waitForTimeout(1500)

await recordPage.evaluate(() => {
;(window as any).SplunkRum.provider.getTracer('guard').startSpan('guard-span').end()
})

await recordPage.waitForTimeout(1500)

const sessionCookie2 = await recordPage.getCookie('_splunk_rum_sid')

expect(sessionCookie2).toBeTruthy()

const sessionCookie2Parsed = JSON.parse(decodeURIComponent(sessionCookie2.value))

expect(sessionCookie1Parsed.expiresAt).toBeLessThan(sessionCookie2Parsed.expiresAt)

expect(recordPage.receivedSpans.filter((s) => s.name === 'guard-span')).toHaveLength(1)
})
})
20 changes: 20 additions & 0 deletions packages/integration-tests/src/tests/extend-activity/some.ejs
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>All spans extend session</title>

<%- renderAgent() %>
</head>
<body>
<h1>All spans extend session to false</h1>
<button type="button" id="btnSpan">Produce a span</button>
<pre id="scenarioDisplay"></pre>
<script id="scenario">
document.querySelector('#btnSpan').addEventListener('click', () => {
SplunkRum.provider.getTracer('guard').startSpan('guard-span').end();
});
</script>
<script>scenarioDisplay.innerHTML = scenario.innerHTML;</script>
</body>
</html>
2 changes: 1 addition & 1 deletion packages/integration-tests/src/tests/long-task/index.ejs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
};

document.querySelector('#btnLongtask').addEventListener('click', () => {
window.testing = true;
window.testing = true;
generateLongTask();
window.testing = false;
});
Expand Down
107 changes: 107 additions & 0 deletions packages/integration-tests/src/tests/long-task/long-task.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,4 +87,111 @@ test.describe('long task', () => {

expect(longTaskSpans).toHaveLength(0)
})

test('longtask will spawn new session', async ({ recordPage, browserName }) => {
if (browserName === 'webkit' || browserName === 'firefox') {
test.skip()
}

await recordPage.goTo(
'/long-task/index.ejs?_experimental_longtaskNoStartSession=false&disableInstrumentation=connectivity,document,errors,fetch,interactions,postload,socketio,visibility,websocket,webvitals,xhr',
)

await recordPage.locator('#btnLongtask').click()

const sessionCookie1 = await recordPage.getCookie('_splunk_rum_sid')
expect(sessionCookie1).toBeTruthy()

const sessionCookie1Parsed = JSON.parse(decodeURIComponent(sessionCookie1.value))

await recordPage.waitForTimeoutAndFlushData(1000)

const allSpans1 = recordPage.receivedSpans

expect(allSpans1).toHaveLength(1)

// Set session as expired using expiresAt
await recordPage.evaluate(
([expiresAt, id, startTime]) => {
globalThis[Symbol.for('opentelemetry.js.api.1')]['splunk.rum']['store'].set({
expiresAt,
id,
startTime,
})
},
[Date.now(), sessionCookie1Parsed.id, sessionCookie1Parsed.startTime],
)

await recordPage.locator('#btnLongtask').click()

await recordPage.waitForTimeoutAndFlushData(1000)

const sessionCookie3 = await recordPage.getCookie('_splunk_rum_sid')
expect(sessionCookie3).toBeTruthy()

const allSpans2 = recordPage.receivedSpans
expect(allSpans2).toHaveLength(2)

const sessionCookie3Parsed = JSON.parse(decodeURIComponent(sessionCookie3.value))

expect(sessionCookie1Parsed.id).not.toBe(sessionCookie3Parsed.id)
})

test('longtask will not spawn new session', async ({ recordPage, browserName }) => {
if (browserName === 'webkit' || browserName === 'firefox') {
test.skip()
}

await recordPage.goTo(
'/long-task/index.ejs?_experimental_longtaskNoStartSession=true&disableInstrumentation=connectivity,document,errors,fetch,interactions,postload,socketio,visibility,websocket,webvitals,xhr',
)

await recordPage.locator('#btnLongtask').click()

const sessionCookie1 = await recordPage.getCookie('_splunk_rum_sid')

expect(sessionCookie1).toBeTruthy()

const sessionCookie1Parsed = JSON.parse(decodeURIComponent(sessionCookie1.value))

await recordPage.waitForTimeoutAndFlushData(1000)

const allSpans1 = recordPage.receivedSpans

expect(allSpans1).toHaveLength(1)

const onlyLongTask = allSpans1[0]

// Set session as expired using expiresAt
await recordPage.evaluate(
([expiresAt, id, startTime]) => {
globalThis[Symbol.for('opentelemetry.js.api.1')]['splunk.rum']['store'].set({
expiresAt,
id,
startTime,
})
},
[Date.now(), sessionCookie1Parsed.id, sessionCookie1Parsed.startTime],
)

await recordPage.waitForTimeout(1000)

await recordPage.locator('#btnLongtask').click()

await recordPage.waitForTimeoutAndFlushData(1000)

const allSpans2 = recordPage.receivedSpans

expect(allSpans2).toHaveLength(1)

expect(allSpans2[0].id).toBe(onlyLongTask.id)

const sessionCookie2 = await recordPage.getCookie('_splunk_rum_sid')

expect(sessionCookie2).toBeTruthy()

const sessionCookie2Parsed = JSON.parse(decodeURIComponent(sessionCookie1.value))

expect(sessionCookie2Parsed.id).toBe(sessionCookie1Parsed.id)
})
})
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,6 @@
<head>
<meta charset="UTF-8">
<title>Session sampling</title>
<script>
window.__integrationTestSessionId = new URL(document.location).searchParams.get('forceSessionId');
</script>
<%- renderAgent() %>
</head>
<body>
Expand Down
Loading
Loading