forked from microsoft/vscode-python-environments
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtestUtils.ts
More file actions
261 lines (234 loc) · 7.72 KB
/
testUtils.ts
File metadata and controls
261 lines (234 loc) · 7.72 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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
/**
* Test utilities for E2E and smoke tests.
*
* These utilities are designed to work with REAL VS Code APIs,
* not the mocked APIs used in unit tests.
*/
import type { Disposable, Event } from 'vscode';
/**
* Sleep for a specified number of milliseconds.
* Use sparingly - prefer waitForCondition() for most cases.
*/
export function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
/**
* Wait for a condition to become true within a timeout.
*
* This is the PRIMARY utility for smoke/E2E tests. Use this instead of sleep()
* for any async assertion that depends on VS Code state.
*
* @param condition - Async function that returns true when condition is met
* @param timeoutMs - Maximum time to wait (default: 10 seconds)
* @param errorMessage - Error message if condition is not met
* @param pollIntervalMs - How often to check condition (default: 100ms)
*
* @example
* // Wait for extension to activate
* await waitForCondition(
* () => extension.isActive,
* 10_000,
* 'Extension did not activate within 10 seconds'
* );
*
* @example
* // Wait for file to exist
* await waitForCondition(
* async () => fs.pathExists(outputFile),
* 30_000,
* `Output file ${outputFile} was not created`
* );
*/
export async function waitForCondition(
condition: () => boolean | Promise<boolean>,
timeoutMs: number = 10_000,
errorMessage: string | (() => string) = 'Condition not met within timeout',
pollIntervalMs: number = 100,
): Promise<void> {
return new Promise<void>((resolve, reject) => {
const startTime = Date.now();
const checkCondition = async () => {
try {
const result = await condition();
if (result) {
resolve();
return;
}
} catch {
// Condition threw - keep waiting
}
if (Date.now() - startTime >= timeoutMs) {
const msg = typeof errorMessage === 'function' ? errorMessage() : errorMessage;
reject(new Error(`${msg} (waited ${timeoutMs}ms)`));
return;
}
setTimeout(checkCondition, pollIntervalMs);
};
checkCondition();
});
}
/**
* Retry an async function until it succeeds or timeout is reached.
*
* Similar to waitForCondition but captures the return value.
*
* @example
* const envs = await retryUntilSuccess(
* () => api.getEnvironments(),
* (envs) => envs.length > 0,
* 10_000,
* 'No environments discovered'
* );
*/
export async function retryUntilSuccess<T>(
fn: () => T | Promise<T>,
validate: (result: T) => boolean = () => true,
timeoutMs: number = 10_000,
errorMessage: string = 'Operation did not succeed within timeout',
): Promise<T> {
const startTime = Date.now();
let lastError: Error | undefined;
while (Date.now() - startTime < timeoutMs) {
try {
const result = await fn();
if (validate(result)) {
return result;
}
} catch (e) {
lastError = e as Error;
}
await sleep(100);
}
throw new Error(`${errorMessage}: ${lastError?.message || 'validation failed'}`);
}
/**
* Result of waiting for API readiness.
*/
export interface ApiReadyResult {
/** Whether the API is ready and managers have registered */
ready: boolean;
/** Error message if not ready */
error?: string;
}
/**
* Wait for the API to be fully ready, including manager registration.
*
* This waits for the async initialization that happens in setImmediate() after
* extension.activate() returns. Without this, calls to getEnvironments() may
* hang waiting for managers that haven't registered yet.
*
* @param api - The Python environment API
* @param timeoutMs - Maximum time to wait (default: 30 seconds)
* @returns Result indicating if API is ready
*
* @example
* const result = await waitForApiReady(api, 30_000);
* if (!result.ready) {
* this.skip(); // Skip test if managers not available
* }
*/
export async function waitForApiReady(
api: { getEnvironments: (scope: 'all' | 'global') => Promise<unknown[]> },
timeoutMs: number = 30_000,
): Promise<ApiReadyResult> {
// Race the getEnvironments call against a timeout
// This ensures managers have registered before we proceed
const timeoutPromise = new Promise<never>((_, reject) => {
setTimeout(
() => reject(new Error(`API not ready within ${timeoutMs}ms - managers may not have registered`)),
timeoutMs,
);
});
try {
// If getEnvironments completes, managers are ready
await Promise.race([api.getEnvironments('all'), timeoutPromise]);
return { ready: true };
} catch (error) {
// Return error info instead of throwing
return {
ready: false,
error: error instanceof Error ? error.message : String(error),
};
}
}
/**
* Helper class to test events.
*
* Captures events and provides assertion helpers.
*
* @example
* const handler = new TestEventHandler(api.onDidChangeEnvironments, 'onDidChangeEnvironments');
* // ... trigger some action that fires events ...
* await handler.assertFiredAtLeast(1, 5000);
* assert.strictEqual(handler.first.type, 'add');
* handler.dispose();
*/
export class TestEventHandler<T> implements Disposable {
private readonly handledEvents: T[] = [];
private readonly disposable: Disposable;
constructor(
event: Event<T>,
private readonly eventName: string = 'event',
) {
this.disposable = event((e) => this.handledEvents.push(e));
}
/** Whether any events have been fired */
get fired(): boolean {
return this.handledEvents.length > 0;
}
/** The first event fired (throws if none) */
get first(): T {
if (this.handledEvents.length === 0) {
throw new Error(`No ${this.eventName} events fired yet`);
}
return this.handledEvents[0];
}
/** The last event fired (throws if none) */
get last(): T {
if (this.handledEvents.length === 0) {
throw new Error(`No ${this.eventName} events fired yet`);
}
return this.handledEvents[this.handledEvents.length - 1];
}
/** Number of events fired */
get count(): number {
return this.handledEvents.length;
}
/** All events fired */
get all(): T[] {
return [...this.handledEvents];
}
/** Get event at specific index */
at(index: number): T {
return this.handledEvents[index];
}
/** Reset captured events */
reset(): void {
this.handledEvents.length = 0;
}
/** Wait for at least one event to fire */
async assertFired(waitMs: number = 1000): Promise<void> {
await waitForCondition(() => this.fired, waitMs, `${this.eventName} was not fired`);
}
/** Wait for exactly N events to fire */
async assertFiredExactly(count: number, waitMs: number = 2000): Promise<void> {
await waitForCondition(
() => this.count === count,
waitMs,
`Expected ${this.eventName} to fire ${count} times, but fired ${this.count} times`,
);
}
/** Wait for at least N events to fire */
async assertFiredAtLeast(count: number, waitMs: number = 2000): Promise<void> {
await waitForCondition(
() => this.count >= count,
waitMs,
`Expected ${this.eventName} to fire at least ${count} times, but fired ${this.count} times`,
);
}
dispose(): void {
this.disposable.dispose();
}
}