-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexpectRetrying.ts
503 lines (459 loc) · 14.1 KB
/
expectRetrying.ts
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
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
import { assert } from "./assert.ts";
import type { ANSI_COLORS } from "./colors.ts";
import {
DEFAULT_RETRY_OPTIONS,
type ExpectConfig,
type RetryConfig,
} from "./config.ts";
import { captureExecutionContext } from "./execution.ts";
import {
ExpectedReceivedMatcherRenderer,
type LineGroup,
type MatcherErrorInfo,
MatcherErrorRendererRegistry,
ReceivedOnlyMatcherRenderer,
} from "./render.ts";
import { parseStackTrace } from "./stacktrace.ts";
import type { Locator } from "https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/refs/heads/master/types/k6/browser/index.d.ts";
/**
* RetryingExpectation is an interface that defines the methods that can be used to create a retrying expectation.
*
* Retrying expectations are used to assert that a condition is met within a given timeout.
* The provided assertion function is called repeatedly until the condition is met or the timeout is reached.
*
* The RetryingExpectation interface is implemented by the createExpectation function.
*/
export interface RetryingExpectation {
/**
* Ensures the Locator points to a checked input.
*/
toBeChecked(options: Partial<RetryConfig>): Promise<void>;
/**
* Ensures the Locator points to a disabled element.
* Element is disabled if it has "disabled" attribute or is disabled via 'aria-disabled'.
*
* Note that only native control elements such as HTML button, input, select, textarea, option, optgroup can be disabled by setting "disabled" attribute.
* "disabled" attribute on other elements is ignored by the browser.
*/
toBeDisabled(options: Partial<RetryConfig>): Promise<void>;
/**
* Ensures the Locator points to an editable element.
*/
toBeEditable(options: Partial<RetryConfig>): Promise<void>;
/**
* Ensures the Locator points to an enabled element.
*/
toBeEnabled(options: Partial<RetryConfig>): Promise<void>;
/**
* Ensures that Locator either does not resolve to any DOM node, or resolves to a non-visible one.
*/
toBeHidden(options: Partial<RetryConfig>): Promise<void>;
/**
* Ensures that Locator points to an attached and visible DOM node.
*/
toBeVisible(options: Partial<RetryConfig>): Promise<void>;
/**
* Ensures the Locator points to an element with the given input value. You can use regular expressions for the value as well.
*
* @param value {string} the expected value of the input
*/
toHaveValue(value: string, options: Partial<RetryConfig>): Promise<void>;
}
/**
* createExpectation is a factory function that creates an expectation object for a given value.
*
* Note that although the browser `is` prefixed methods are used, and return boolean values, we
* throw errors if the condition is not met. This is to ensure that we align with playwright's
* API, and have matchers return `Promise<void>`, as opposed to `Promise<boolean>`.
*
* @param locator the value to create an expectation for
* @param isSoft whether the expectation should be a soft assertion
* @param assertFn optional custom assertion function
* @returns an expectation object over the given value exposing the Expectation set of methods
*/
export function createExpectation(
locator: Locator,
config: ExpectConfig,
): RetryingExpectation {
// In order to facilitate testing, we support passing in a custom assert function.
// As a result, we need to make sure that the assert function is always available, and
// if not, we need to use the default assert function.
//
// From this point forward, we will use the `usedAssert` variable to refer to the assert function.
const usedAssert = config.assertFn ?? assert;
const isSoft = config.soft ?? false;
const retryConfig: RetryConfig = {
timeout: config.timeout,
interval: config.interval,
};
// Configure the renderer with the colorize option.
MatcherErrorRendererRegistry.configure({
colorize: config.colorize,
display: config.display,
});
// Register renderers specific to each matchers at initialization time.
MatcherErrorRendererRegistry.register(
"toBeChecked",
new ToBeCheckedErrorRenderer(),
);
MatcherErrorRendererRegistry.register(
"toBeDisabled",
new ToBeDisabledErrorRenderer(),
);
MatcherErrorRendererRegistry.register(
"toBeEditable",
new ToBeEditableErrorRenderer(),
);
MatcherErrorRendererRegistry.register(
"toBeEnabled",
new ToBeEnabledErrorRenderer(),
);
MatcherErrorRendererRegistry.register(
"toBeHidden",
new ToBeHiddenErrorRenderer(),
);
MatcherErrorRendererRegistry.register(
"toBeVisible",
new ToBeVisibleErrorRenderer(),
);
MatcherErrorRendererRegistry.register(
"toHaveValue",
new ToHaveValueErrorRenderer(),
);
const matcherConfig = {
locator,
retryConfig,
usedAssert,
isSoft,
};
return {
async toBeChecked(
options: Partial<RetryConfig> = retryConfig,
): Promise<void> {
await createMatcher(
"toBeChecked",
async () => await locator.isChecked(),
"checked",
"unchecked",
{ ...matcherConfig, options },
);
},
async toBeDisabled(
options: Partial<RetryConfig> = retryConfig,
): Promise<void> {
await createMatcher(
"toBeDisabled",
async () => await locator.isDisabled(),
"disabled",
"enabled",
{ ...matcherConfig, options },
);
},
async toBeEditable(
options: Partial<RetryConfig> = retryConfig,
): Promise<void> {
await createMatcher(
"toBeEditable",
async () => await locator.isEditable(),
"editable",
"uneditable",
{ ...matcherConfig, options },
);
},
async toBeEnabled(
options: Partial<RetryConfig> = retryConfig,
): Promise<void> {
await createMatcher(
"toBeEnabled",
async () => await locator.isEnabled(),
"enabled",
"disabled",
{ ...matcherConfig, options },
);
},
async toBeHidden(
options: Partial<RetryConfig> = retryConfig,
): Promise<void> {
await createMatcher(
"toBeHidden",
async () => await locator.isHidden(),
"hidden",
"visible",
{ ...matcherConfig, options },
);
},
async toBeVisible(
options: Partial<RetryConfig> = retryConfig,
): Promise<void> {
await createMatcher(
"toBeVisible",
async () => await locator.isVisible(),
"visible",
"hidden",
{ ...matcherConfig, options },
);
},
async toHaveValue(
expectedValue: string,
options: Partial<RetryConfig> = retryConfig,
): Promise<void> {
const stacktrace = parseStackTrace(new Error().stack);
const executionContext = captureExecutionContext(stacktrace);
if (!executionContext) {
throw new Error("k6 failed to capture execution context");
}
const info: MatcherErrorInfo = {
executionContext,
matcherName: "toHaveValue",
expected: expectedValue,
received: "unknown",
};
try {
await withRetry(async () => {
const actualValue = await locator.inputValue();
usedAssert(
expectedValue === actualValue,
MatcherErrorRendererRegistry.getRenderer("toHaveValue").render(
info,
MatcherErrorRendererRegistry.getConfig(),
),
isSoft,
);
}, { ...retryConfig, ...options });
} catch (_) {
usedAssert(
false,
MatcherErrorRendererRegistry.getRenderer("toHaveValue").render(
info,
MatcherErrorRendererRegistry.getConfig(),
),
isSoft,
);
}
},
};
}
// Helper function to create common matcher error info
function createMatcherInfo(
matcherName: string,
expected: string,
received: string,
additionalInfo = {},
): MatcherErrorInfo {
const stacktrace = parseStackTrace(new Error().stack);
const executionContext = captureExecutionContext(stacktrace);
if (!executionContext) {
throw new Error("k6 failed to capture execution context");
}
return {
executionContext,
matcherName,
expected,
received,
...additionalInfo,
};
}
// Helper function to handle common matcher logic
async function createMatcher(
matcherName: string,
checkFn: () => Promise<boolean>,
expected: string,
received: string,
{
locator,
retryConfig,
usedAssert,
isSoft,
options = {},
}: {
locator: Locator;
retryConfig: RetryConfig;
usedAssert: typeof assert;
isSoft: boolean;
options?: Partial<RetryConfig>;
},
): Promise<void> {
const info = createMatcherInfo(matcherName, expected, received, {
matcherSpecific: {
locator,
timeout: options.timeout,
},
});
try {
await withRetry(async () => {
const result = await checkFn();
if (!result) {
throw new Error("matcher failed");
}
usedAssert(
result,
MatcherErrorRendererRegistry.getRenderer(matcherName).render(
info,
MatcherErrorRendererRegistry.getConfig(),
),
isSoft,
);
}, { ...retryConfig, ...options });
} catch (_) {
usedAssert(
false,
MatcherErrorRendererRegistry.getRenderer(matcherName).render(
info,
MatcherErrorRendererRegistry.getConfig(),
),
isSoft,
);
}
}
/**
* Base class for boolean state matchers (checked, disabled, etc.)
*/
export abstract class BooleanStateErrorRenderer
extends ReceivedOnlyMatcherRenderer {
protected abstract state: string;
protected abstract oppositeState: string;
protected getMatcherName(): string {
return `toBe${this.state[0].toUpperCase()}${this.state.slice(1)}`;
}
protected override getReceivedPlaceholder(): string {
return "locator";
}
protected override getSpecificLines(
info: MatcherErrorInfo,
maybeColorize: (text: string, color: keyof typeof ANSI_COLORS) => string,
): LineGroup[] {
return [
{ label: "Expected", value: this.state, group: 3 },
{ label: "Received", value: this.oppositeState, group: 3 },
{ label: "Call log", value: "", group: 3 },
{
label: "",
value: maybeColorize(
` - expect.toBe${this.state[0].toUpperCase()}${
this.state.slice(1)
} with timeout ${info.matcherSpecific?.timeout}ms`,
"darkGrey",
),
group: 3,
raw: true,
},
{
label: "",
value: maybeColorize(` - waiting for locator`, "darkGrey"),
group: 3,
raw: true,
},
];
}
}
export class ToBeCheckedErrorRenderer extends BooleanStateErrorRenderer {
protected state = "checked";
protected oppositeState = "unchecked";
}
/**
* A matcher error renderer for the `toBeDisabled` matcher.
*/
export class ToBeDisabledErrorRenderer extends BooleanStateErrorRenderer {
protected state = "disabled";
protected oppositeState = "enabled";
}
export class ToBeEditableErrorRenderer extends BooleanStateErrorRenderer {
protected state = "editable";
protected oppositeState = "uneditable";
}
export class ToBeEnabledErrorRenderer extends BooleanStateErrorRenderer {
protected state = "enabled";
protected oppositeState = "disabled";
}
export class ToBeHiddenErrorRenderer extends BooleanStateErrorRenderer {
protected state = "hidden";
protected oppositeState = "visible";
}
export class ToBeVisibleErrorRenderer extends BooleanStateErrorRenderer {
protected state = "visible";
protected oppositeState = "hidden";
}
export class ToHaveValueErrorRenderer extends ExpectedReceivedMatcherRenderer {
protected getMatcherName(): string {
return "toHaveValue";
}
protected override getSpecificLines(
info: MatcherErrorInfo,
maybeColorize: (text: string, color: keyof typeof ANSI_COLORS) => string,
): LineGroup[] {
return [
// FIXME (@oleiade): When k6/#4210 is fixed, we can use the locator here.
// { label: "Locator", value: maybeColorize(`locator('${info.matcherSpecific?.locator}')`, "white"), group: 3 },
{
label: "Expected",
value: maybeColorize(info.expected, "green"),
group: 3,
},
{
label: "Received",
value: maybeColorize(info.received, "red"),
group: 3,
},
{ label: "Call log", value: "", group: 3 },
{
label: "",
value: maybeColorize(
` - expect.toHaveValue with timeout ${info.matcherSpecific?.timeout}ms`,
"darkGrey",
),
group: 3,
raw: true,
},
// FIXME (@oleiade): When k6/#4210 is fixed, we can use the locator's selector here.
{
label: "",
value: maybeColorize(` - waiting for locator`, "darkGrey"),
group: 3,
raw: true,
},
];
}
}
/**
* Implements retry logic for async assertions.
*
* @param assertion Function that performs the actual check
* @param options Retry configuration
* @returns Promise that resolves when assertion passes or rejects if timeout is reached
*/
export async function withRetry(
assertion: () => Promise<void>,
options: RetryConfig & {
// Optional test hooks - only used in testing
_now?: () => number;
_sleep?: (ms: number) => Promise<void>;
} = {},
): Promise<boolean> {
const timeout: number = options.timeout ?? DEFAULT_RETRY_OPTIONS.timeout;
const interval: number = options.interval ?? DEFAULT_RETRY_OPTIONS.interval;
const getNow = options._now ?? (() => Date.now());
const sleep = options._sleep ??
((ms: number) => new Promise((resolve) => setTimeout(resolve, ms)));
const startTime: number = getNow();
while (getNow() - startTime < timeout) {
try {
await assertion();
return true;
} catch (_error) {
// Ignore error and continue retrying
}
await sleep(interval);
}
throw new RetryTimeoutError(
`Expect condition not met within ${timeout}ms timeout`,
);
}
/**
* RetryTimeoutError is an error that is thrown when an expectation is not met within a provided timeout.
*/
export class RetryTimeoutError extends Error {
constructor(message: string) {
super(message);
this.name = "RetryTimeoutError";
}
}