Repository navigation
Expand file tree
/
Copy pathtestHubModule.deferredFinish.test.ts
More file actions
408 lines (338 loc) · 19.4 KB
/
Copy pathtestHubModule.deferredFinish.test.ts
File metadata and controls
408 lines (338 loc) · 19.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
import TestHubModule from '../../../src/cli/modules/testHubModule.js'
import TestFramework from '../../../src/cli/frameworks/testFramework.js'
import { TestFrameworkState } from '../../../src/cli/states/testFrameworkState.js'
import { HookState } from '../../../src/cli/states/hookState.js'
import { GrpcClient } from '../../../src/cli/grpcClient.js'
import { TestFrameworkConstants } from '../../../src/cli/frameworks/constants/testFrameworkConstants.js'
import type { Frameworks } from '@wdio/types'
vi.mock('../../../src/cli/frameworks/testFramework.js', () => ({
default: {
registerObserver: vi.fn(),
getTrackedInstance: vi.fn(),
getState: vi.fn(),
setState: vi.fn(),
hasState: vi.fn()
}
}))
vi.mock('../../../src/cli/frameworks/automationFramework.js', () => ({
default: { getTrackedInstance: vi.fn(), getState: vi.fn(), getDriver: vi.fn() }
}))
vi.mock('../../../src/cli/grpcClient.js', () => ({
GrpcClient: { getInstance: vi.fn() }
}))
vi.mock('../../../src/cli/frameworks/wdioMochaTestFramework.js', () => ({
default: { getLogEntries: vi.fn(), clearLogs: vi.fn() }
}))
vi.mock('../../../src/cli/cliLogger.js', () => ({
BStackLogger: { debug: vi.fn(), info: vi.fn(), error: vi.fn(), warn: vi.fn() }
}))
// Build a mock TestFrameworkInstance sitting at mocha TEST/POST (a finished test whose
// TestRunFinished the module defers past the after-each window).
function makeMochaTestInstance(uuid: string) {
return {
__uuid: uuid,
getContext: () => ({
getId: () => 'ctx',
getThreadId: () => 'thread-1',
getProcessId: () => 'proc-1'
}),
getAllData: () => new Map<string, unknown>([
[TestFrameworkConstants.KEY_TEST_FRAMEWORK_NAME, 'WebdriverIO-mocha'],
[TestFrameworkConstants.KEY_TEST_FRAMEWORK_VERSION, '9.33.1'],
[TestFrameworkConstants.KEY_TEST_STARTED_AT, '2026-08-10T20:53:00Z'],
[TestFrameworkConstants.KEY_TEST_ENDED_AT, '2026-08-10T20:53:02Z']
]),
getRef: () => `ref-${uuid}`,
getCurrentTestState: () => TestFrameworkState.TEST,
getCurrentHookState: () => HookState.POST
}
}
describe('TestHubModule — deferred last-test-finish delivery (SDK-7265)', () => {
let testHubModule: TestHubModule
let mockGrpcClient: { testFrameworkEvent: ReturnType<typeof vi.fn> }
beforeEach(() => {
vi.clearAllMocks()
process.env.WDIO_WORKER_ID = '0-1'
mockGrpcClient = { testFrameworkEvent: vi.fn().mockResolvedValue({ success: true }) }
vi.mocked(GrpcClient.getInstance).mockReturnValue(mockGrpcClient as never)
// KEY_TEST_RESULT_AT present (so onAllTestEvents does not take the "no results" path);
// framework name resolves to mocha; uuid echoes the instance.
vi.mocked(TestFramework.hasState).mockReturnValue(true)
vi.mocked(TestFramework.getState).mockImplementation((instance: any, key: unknown) => {
if (key === TestFrameworkConstants.KEY_TEST_FRAMEWORK_NAME) {
return 'WebdriverIO-mocha'
}
if (key === TestFrameworkConstants.KEY_TEST_DEFERRED) {
return false
}
if (key === TestFrameworkConstants.KEY_TEST_UUID) {
return instance?.__uuid
}
return ''
})
testHubModule = new TestHubModule({ enabled: true, hubUrl: 'https://hub.browserstack.com' })
Object.defineProperty(testHubModule, 'config', {
value: { hubUrl: 'https://hub.browserstack.com' },
writable: true
})
})
afterEach(() => {
vi.resetAllMocks()
delete process.env.WDIO_WORKER_ID
})
it('defers a mocha TEST/POST instead of sending it immediately', () => {
const inst = makeMochaTestInstance('t1')
testHubModule.onAllTestEvents({ instance: inst, test: { title: 't1' } as Frameworks.Test })
// Held for the after-each window — not yet on the wire.
expect(mockGrpcClient.testFrameworkEvent).not.toHaveBeenCalled()
})
it('delivers the deferred finish when the flush send succeeds', async () => {
const inst = makeMochaTestInstance('t1')
testHubModule.onAllTestEvents({ instance: inst, test: { title: 't1' } as Frameworks.Test })
await testHubModule.flushPendingTestFinishEvent()
expect(mockGrpcClient.testFrameworkEvent).toHaveBeenCalledTimes(1)
expect(mockGrpcClient.testFrameworkEvent).toHaveBeenCalledWith(
expect.objectContaining({ testFrameworkState: 'TEST', testHookState: 'POST', uuid: 't1' })
)
})
// REPRODUCTION: the worker's last test relies on this single best-effort flush (service.after()).
// A transient gRPC failure was swallowed with no retry, so the TestRunFinished never reached the
// binary/backend. The test then stays "in progress" and is reaped by Test Hub's ~60-min per-test
// timeout (TEST_TIMED_OUT_WITH_BUILD_SUCCESS), which stamps the whole build `timeout`.
it('does not drop the last-test finish on a transient send failure — retries the SAME finish until delivered', async () => {
const inst = makeMochaTestInstance('last')
testHubModule.onAllTestEvents({ instance: inst, test: { title: 'last' } as Frameworks.Test })
// First attempt fails transiently, second succeeds.
mockGrpcClient.testFrameworkEvent
.mockRejectedValueOnce(new Error('transient gRPC failure'))
.mockResolvedValueOnce({ success: true })
await testHubModule.flushPendingTestFinishEvent()
// Retried (not a single fixed attempt) AND every attempt re-sends the same test's finish —
// distinguishes a real retry-until-delivered from a regressed single-shot send.
expect(mockGrpcClient.testFrameworkEvent).toHaveBeenCalledTimes(2)
for (const call of mockGrpcClient.testFrameworkEvent.mock.calls) {
expect(call[0]).toMatchObject({ uuid: 'last', testFrameworkState: 'TEST', testHookState: 'POST' })
}
})
it('drives the retry budget to exhaustion on sustained failure, then gives up cleanly without re-stashing', async () => {
const inst = makeMochaTestInstance('exhaust')
testHubModule.onAllTestEvents({ instance: inst, test: { title: 'exhaust' } as Frameworks.Test })
mockGrpcClient.testFrameworkEvent.mockRejectedValue(new Error('sustained gRPC outage'))
await expect(testHubModule.flushPendingTestFinishEvent()).resolves.toBeUndefined()
// All three attempts ran, each re-sending the same finish.
expect(mockGrpcClient.testFrameworkEvent).toHaveBeenCalledTimes(3)
for (const call of mockGrpcClient.testFrameworkEvent.mock.calls) {
expect(call[0]).toMatchObject({ uuid: 'exhaust' })
}
// An exhausted event must NOT be re-stashed — re-stashing races the fire-and-forget
// flush call sites and can drop a newer test's finish (SDK-7265 review #1).
// SDK-7493: the single `pendingTestFinish` slot is now a uuid-keyed map, so "not
// re-stashed" means the map is empty rather than the slot being null.
expect((testHubModule as unknown as { pendingTestFinishes: Map<string, unknown> }).pendingTestFinishes.size).toBe(0)
expect(testHubModule.logger.error).toHaveBeenCalledWith(
expect.stringContaining('failed after all retries')
)
})
it('concurrent flushes each deliver their own finish — a retrying older flush never drops a newer test', async () => {
let aAttempts = 0
mockGrpcClient.testFrameworkEvent.mockImplementation((payload: { uuid: string }) => {
if (payload.uuid === 'A') {
aAttempts += 1
if (aAttempts === 1) {
return Promise.reject(new Error('transient on A'))
}
}
return Promise.resolve({ success: true })
})
// Test A finishes, is deferred, then flushed fire-and-forget (as the next-test boundary does).
testHubModule.onAllTestEvents({ instance: makeMochaTestInstance('A'), test: { title: 'A' } as Frameworks.Test })
const flushA = testHubModule.flushPendingTestFinishEvent() // not awaited — A is retrying
// While A retries, test B finishes, is deferred and flushed.
testHubModule.onAllTestEvents({ instance: makeMochaTestInstance('B'), test: { title: 'B' } as Frameworks.Test })
await testHubModule.flushPendingTestFinishEvent() // B
await flushA
const sent = mockGrpcClient.testFrameworkEvent.mock.calls.map((c: unknown[]) => (c[0] as { uuid: string }).uuid)
expect(sent.filter((u) => u === 'A').length).toBe(2) // 1 transient fail + 1 retry success
expect(sent.filter((u) => u === 'B').length).toBe(1) // delivered once, never dropped
})
it('clears the pending finish after a flush so it is never sent twice', async () => {
const inst = makeMochaTestInstance('t1')
testHubModule.onAllTestEvents({ instance: inst, test: { title: 't1' } as Frameworks.Test })
await testHubModule.flushPendingTestFinishEvent()
await testHubModule.flushPendingTestFinishEvent() // second flush is a no-op
expect(mockGrpcClient.testFrameworkEvent).toHaveBeenCalledTimes(1)
})
// SDK-7493 — the two hardenings that replaced the single `pendingTestFinish` slot.
// The queue-and-drain in skipReporter is the primary fix; these guard the deferral itself
// so a future interleave degrades into a late send rather than a silently lost finish.
it('two finishes stashed against the SAME instance under different uuids both survive', async () => {
// The exact shape the single slot lost: an interleave presents one tracked instance
// whose uuid has moved on, so the old `instance !== instance` guard never fired and the
// second stash silently evicted the first.
const shared = makeMochaTestInstance('first')
testHubModule.onAllTestEvents({ instance: shared, test: { title: 'first' } as Frameworks.Test })
// Same object, uuid rewritten — as an interleaved skip report would leave it.
shared.__uuid = 'second'
testHubModule.onAllTestEvents({ instance: shared, test: { title: 'second' } as Frameworks.Test })
expect((testHubModule as unknown as { pendingTestFinishes: Map<string, unknown> }).pendingTestFinishes.size).toBe(2)
await testHubModule.flushPendingTestFinishEvent()
const sent = mockGrpcClient.testFrameworkEvent.mock.calls.map((c: unknown[]) => (c[0] as { uuid: string }).uuid)
expect(sent).toHaveLength(2)
expect(new Set(sent)).toEqual(new Set(['first', 'second']))
})
it('flushes the uuid captured at DEFER time, not the instance uuid at send time', async () => {
const inst = makeMochaTestInstance('at-defer')
testHubModule.onAllTestEvents({ instance: inst, test: { title: 't' } as Frameworks.Test })
// The instance's live uuid is rewritten before the flush runs. Reading it here would
// close the wrong test_run and leave this one open until Test Hub's idle reap — the
// binary keys closure on the request's top-level `uuid` field.
inst.__uuid = 'rewritten-after-defer'
await testHubModule.flushPendingTestFinishEvent()
expect(mockGrpcClient.testFrameworkEvent).toHaveBeenCalledTimes(1)
expect(mockGrpcClient.testFrameworkEvent.mock.calls[0][0]).toMatchObject({ uuid: 'at-defer' })
})
it('pins the uuid INSIDE event_json too — the binary routes on that, not the top-level field', async () => {
// `webdriverio/index.js` does `const event = JSON.parse(eventJson)` and the mocha
// handler builds the run with `uuid: event.test_uuid`. A stale test_uuid in the blob
// closes the wrong run, so pinning only the top-level field is not enough.
const inst = makeMochaTestInstance('pinned')
testHubModule.onAllTestEvents({ instance: inst, test: { title: 't' } as Frameworks.Test })
inst.__uuid = 'rewritten-after-defer'
await testHubModule.flushPendingTestFinishEvent()
const payload = mockGrpcClient.testFrameworkEvent.mock.calls[0][0] as { uuid: string, eventJson: Buffer }
expect(payload.uuid).toBe('pinned')
expect(JSON.parse(payload.eventJson.toString()).test_uuid).toBe('pinned')
})
it('re-stashing the SAME uuid replaces rather than duplicating (LOG_REPORT re-entry)', async () => {
// onAllTestEvents re-enters for one test via the LOG_REPORT/POST recovery path; that
// must not send the same finish twice.
const inst = makeMochaTestInstance('same')
testHubModule.onAllTestEvents({ instance: inst, test: { title: 'same' } as Frameworks.Test })
testHubModule.onAllTestEvents({ instance: inst, test: { title: 'same' } as Frameworks.Test })
expect((testHubModule as unknown as { pendingTestFinishes: Map<string, unknown> }).pendingTestFinishes.size).toBe(1)
await testHubModule.flushPendingTestFinishEvent()
expect(mockGrpcClient.testFrameworkEvent).toHaveBeenCalledTimes(1)
})
})
describe('TestHubModule — finish held until the TEST/POST observers end (cucumber)', () => {
let testHubModule: TestHubModule
let mockGrpcClient: { testFrameworkEvent: ReturnType<typeof vi.fn> }
const cucumberInstance = (uuid: string) => ({
...makeMochaTestInstance(uuid),
getAllData: () => new Map<string, unknown>([
[TestFrameworkConstants.KEY_TEST_FRAMEWORK_NAME, 'WebdriverIO-cucumber'],
[TestFrameworkConstants.KEY_TEST_ENDED_AT, '2026-08-10T20:53:02Z']
])
})
beforeEach(() => {
vi.clearAllMocks()
process.env.WDIO_WORKER_ID = '0-1'
mockGrpcClient = { testFrameworkEvent: vi.fn().mockResolvedValue({ success: true }) }
vi.mocked(GrpcClient.getInstance).mockReturnValue(mockGrpcClient as never)
vi.mocked(TestFramework.hasState).mockReturnValue(true)
vi.mocked(TestFramework.getState).mockImplementation((instance: any, key: unknown) => {
if (key === TestFrameworkConstants.KEY_TEST_FRAMEWORK_NAME) {
return 'WebdriverIO-cucumber'
}
if (key === TestFrameworkConstants.KEY_TEST_UUID) {
return instance?.__uuid
}
return ''
})
testHubModule = new TestHubModule({ enabled: true, hubUrl: 'https://hub.browserstack.com' })
})
afterEach(() => {
vi.resetAllMocks()
delete process.env.WDIO_WORKER_ID
})
it('holds the finish and hands back a release that sends it once', async () => {
const args: Record<string, unknown> = { instance: cucumberInstance('s1'), holdFinishUntilHooksEnd: true }
testHubModule.onAllTestEvents(args)
expect(mockGrpcClient.testFrameworkEvent).not.toHaveBeenCalled()
expect(typeof args.releaseHeldFinish).toBe('function')
await (args.releaseHeldFinish as () => Promise<void>)()
await (args.releaseHeldFinish as () => Promise<void>)()
expect(mockGrpcClient.testFrameworkEvent).toHaveBeenCalledTimes(1)
expect(mockGrpcClient.testFrameworkEvent).toHaveBeenCalledWith(
expect.objectContaining({ testFrameworkState: 'TEST', testHookState: 'POST', uuid: 's1' })
)
await testHubModule.flushPendingTestFinishEvent()
expect(mockGrpcClient.testFrameworkEvent).toHaveBeenCalledTimes(1)
})
it('still sends immediately when the framework does not ask to hold', () => {
testHubModule.onAllTestEvents({ instance: cucumberInstance('s2') })
expect(mockGrpcClient.testFrameworkEvent).toHaveBeenCalledTimes(1)
})
it('sends a held finish from the worker-end flush if it was never released', async () => {
testHubModule.onAllTestEvents({ instance: cucumberInstance('s3'), holdFinishUntilHooksEnd: true })
await testHubModule.flushPendingTestFinishEvent()
expect(mockGrpcClient.testFrameworkEvent).toHaveBeenCalledTimes(1)
expect(mockGrpcClient.testFrameworkEvent).toHaveBeenCalledWith(expect.objectContaining({ uuid: 's3' }))
})
})
describe('TestHubModule — finish uses the dispatched state, not the shared instance state', () => {
let testHubModule: TestHubModule
let mockGrpcClient: { testFrameworkEvent: ReturnType<typeof vi.fn>, logCreatedEvent: ReturnType<typeof vi.fn> }
// A mocha test whose instance was moved to LOG/POST by console output from the user's
// afterTest while an earlier TEST/POST observer (the Automate session rename after a
// mid-test reload) was still awaiting.
function makeInstanceOverwrittenByLog(uuid: string) {
return {
...makeMochaTestInstance(uuid),
getCurrentTestState: () => TestFrameworkState.LOG,
getCurrentHookState: () => HookState.POST
}
}
function registeredObserver(state: unknown, hook: unknown) {
const call = vi.mocked(TestFramework.registerObserver).mock.calls.find(([s, h]) => s === state && h === hook)
return call?.[2] as (args: Record<string, unknown>) => void
}
beforeEach(() => {
vi.clearAllMocks()
process.env.WDIO_WORKER_ID = '0-1'
mockGrpcClient = {
testFrameworkEvent: vi.fn().mockResolvedValue({ success: true }),
logCreatedEvent: vi.fn().mockResolvedValue({ success: true })
}
vi.mocked(GrpcClient.getInstance).mockReturnValue(mockGrpcClient as never)
vi.mocked(TestFramework.hasState).mockReturnValue(true)
vi.mocked(TestFramework.getState).mockImplementation((instance: any, key: unknown) => {
if (key === TestFrameworkConstants.KEY_TEST_FRAMEWORK_NAME) {
return 'WebdriverIO-mocha'
}
if (key === TestFrameworkConstants.KEY_TEST_DEFERRED) {
return false
}
if (key === TestFrameworkConstants.KEY_TEST_UUID) {
return instance?.__uuid
}
return ''
})
testHubModule = new TestHubModule({ enabled: true, hubUrl: 'https://hub.browserstack.com' })
Object.defineProperty(testHubModule, 'config', {
value: { hubUrl: 'https://hub.browserstack.com' },
writable: true
})
})
afterEach(() => {
vi.resetAllMocks()
delete process.env.WDIO_WORKER_ID
})
it('queues and sends the finish when a LOG event overwrote the instance state first', async () => {
const observer = registeredObserver(TestFrameworkState.TEST, HookState.POST)
expect(observer).toBeTypeOf('function')
observer({ instance: makeInstanceOverwrittenByLog('reload'), test: { title: 'reload' } as Frameworks.Test })
await testHubModule.flushPendingTestFinishEvent()
expect(mockGrpcClient.testFrameworkEvent).toHaveBeenCalledTimes(1)
expect(mockGrpcClient.testFrameworkEvent).toHaveBeenCalledWith(
expect.objectContaining({ testFrameworkState: 'TEST', testHookState: 'POST', uuid: 'reload' })
)
})
it('still handles a LOG/POST dispatch as a log', () => {
const observer = registeredObserver(TestFrameworkState.LOG, HookState.POST)
observer({ instance: makeInstanceOverwrittenByLog('log'), test: { title: 'log' } as Frameworks.Test })
expect(testHubModule.flushPendingTestFinishEvent()).toBeUndefined()
expect(mockGrpcClient.testFrameworkEvent).not.toHaveBeenCalled()
})
})