Repository navigation
Expand file tree
/
Copy pathtest-utils.ts
More file actions
485 lines (426 loc) · 13 KB
/
Copy pathtest-utils.ts
File metadata and controls
485 lines (426 loc) · 13 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
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
import { expect, type Page } from "@playwright/test"
/**
* Utility functions for complex testing scenarios
*/
/**
* Simulates a complex network operation by waiting for a specific duration
*/
export async function simulateNetworkDelay(
page: Page,
baseMs: number,
spread: number
): Promise<void> {
const delay = baseMs + Math.random() * spread
await page.waitForTimeout(delay)
}
/**
* Performs CPU-intensive operations to simulate workload
*/
export async function simulateHeavyComputation(
iterations: number
): Promise<void> {
for (let i = 0; i < iterations; i++) {
// Create large arrays and perform operations on them
const arraySize = 10_000
const array = Array.from({ length: arraySize }, () => Math.random())
// Sort the array (CPU intensive)
array.sort()
// Calculate sum (another CPU operation)
array.reduce((sum, current) => sum + current, 0)
}
}
/**
* Simulates complex DOM interactions and validations
*/
export async function performComplexDOMOperations(
page: Page,
elementCount: number
): Promise<void> {
// Execute complex DOM operations in the browser context
await page.evaluate((count) => {
// Create many DOM elements dynamically
const container = document.createElement("div")
container.id = "test-container"
container.style.position = "fixed"
container.style.top = "0"
container.style.left = "0"
container.style.width = "10px"
container.style.height = "10px"
container.style.opacity = "0.1"
container.style.pointerEvents = "none"
for (let i = 0; i < count; i++) {
const element = document.createElement("div")
element.id = `dynamic-element-${i}`
element.textContent = `Element ${i}`
element.style.margin = "5px"
element.style.padding = "5px"
container.appendChild(element)
}
document.body.appendChild(container)
// Trigger layout operations
container.getBoundingClientRect()
// Perform style manipulations
for (let i = 0; i < count; i++) {
const element = document.getElementById(`dynamic-element-${i}`)
if (element) {
element.style.color = i % 2 === 0 ? "red" : "blue"
element.style.backgroundColor = i % 3 === 0 ? "yellow" : "white"
element.style.border = i % 5 === 0 ? "1px solid black" : "none"
element.getBoundingClientRect() // Force layout recalculation
}
}
return container.id
}, elementCount)
// Clean up after test
await page.evaluate(() => {
const container = document.getElementById("test-container")
if (container) {
container.remove()
}
})
}
/**
* Simulates form filling with validations
*/
export async function fillFormWithValidation(
page: Page,
fieldCount: number
): Promise<void> {
await page.evaluate((count) => {
// Create a complex form
const form = document.createElement("form")
form.id = "complex-form"
form.style.position = "fixed"
form.style.top = "0"
form.style.left = "0"
form.style.opacity = "0.1"
form.style.pointerEvents = "none"
for (let i = 0; i < count; i++) {
const fieldContainer = document.createElement("div")
const label = document.createElement("label")
label.textContent = `Field ${i}:`
label.setAttribute("for", `field-${i}`)
const input = document.createElement("input")
input.id = `field-${i}`
input.name = `field-${i}`
input.type = i % 5 === 0 ? "number" : i % 4 === 0 ? "email" : "text"
const validationMessage = document.createElement("span")
validationMessage.id = `validation-${i}`
validationMessage.style.color = "red"
validationMessage.style.display = "none"
fieldContainer.appendChild(label)
fieldContainer.appendChild(input)
fieldContainer.appendChild(validationMessage)
form.appendChild(fieldContainer)
}
document.body.appendChild(form)
return form.id
}, fieldCount)
// Fill the form with values and perform validations
for (let i = 0; i < fieldCount; i++) {
const fieldType = i % 5 === 0 ? "number" : i % 4 === 0 ? "email" : "text"
let value = ""
// Create appropriate test values based on field type
if (fieldType === "number") {
value = String(Math.floor(Math.random() * 1000))
} else if (fieldType === "email") {
value = `test-${i}@example.com`
} else {
value = `Test value ${i} ${Math.random().toString(36).substring(2, 8)}`
}
// Fill the field
await page.evaluate(
([fieldId, fieldValue]) => {
const input = document.getElementById(fieldId) as HTMLInputElement
if (input) {
input.value = fieldValue
// Trigger validation
const event = new Event("input", { bubbles: true })
input.dispatchEvent(event)
// Simple validation logic
const validationElem = document.getElementById(
`validation-${fieldId.split("-")[1]}`
)
if (validationElem) {
if (input.type === "email" && !fieldValue.includes("@")) {
validationElem.textContent = "Invalid email"
validationElem.style.display = "block"
} else if (
input.type === "number" &&
Number.isNaN(Number(fieldValue))
) {
validationElem.textContent = "Invalid number"
validationElem.style.display = "block"
} else {
validationElem.style.display = "none"
}
}
}
},
[`field-${i}`, value] as const
)
// Add brief delay between fields to simulate user input
await page.waitForTimeout(50)
}
// Cleanup
await page.evaluate(() => {
const form = document.getElementById("complex-form")
if (form) {
form.remove()
}
})
}
/**
* Simulate complex API requests and processing responses
*/
export async function simulateApiRequests(
page: Page,
requestCount: number
): Promise<void> {
// Set up response interception for test data
await page.route("**/api/test-data/**", async (route) => {
await simulateNetworkDelay(page, 150, 100)
const data = Array.from({ length: 100 }, (_, i) => ({
id: i,
name: `Item ${i}`,
value: Math.random() * 1000,
timestamp: new Date().toISOString(),
complex: {
nested: {
data: Array.from({ length: 20 }, (_, j) => ({
subId: j,
value: Math.random(),
})),
},
},
}))
await route.fulfill({ json: data })
})
// Perform multiple API requests
for (let i = 0; i < requestCount; i++) {
await page.evaluate(async (index) => {
const response = await fetch(`/api/test-data/${index}`)
if (!response.ok) {
const text = await response.text()
console.error(`Failed to fetch data: ${response.statusText} ${text}`)
} else {
const data = await response.json()
console.log(data)
}
}, i)
// Add processing time between requests
await simulateHeavyComputation(1)
}
}
/**
* Simulates complex rendering scenarios with canvas operations
*/
export async function performCanvasOperations(
page: Page,
complexity: number
): Promise<void> {
await page.evaluate((level) => {
const canvas = document.createElement("canvas")
canvas.id = "test-canvas"
canvas.width = 800
canvas.height = 600
canvas.style.position = "fixed"
canvas.style.top = "0"
canvas.style.left = "0"
canvas.style.opacity = "0.1"
canvas.style.pointerEvents = "none"
document.body.appendChild(canvas)
const ctx = canvas.getContext("2d")
if (!ctx) return
// Draw complex shapes based on complexity level
for (let i = 0; i < 100 * level; i++) {
// Random colors
ctx.fillStyle = `rgb(${Math.floor(Math.random() * 255)}, ${Math.floor(
Math.random() * 255
)}, ${Math.floor(Math.random() * 255)})`
ctx.strokeStyle = `rgb(${Math.floor(Math.random() * 255)}, ${Math.floor(
Math.random() * 255
)}, ${Math.floor(Math.random() * 255)})`
// Random positions
const x = Math.random() * canvas.width
const y = Math.random() * canvas.height
// Draw different types of shapes
const shapeType = i % 4
if (shapeType === 0) {
// Rectangle
ctx.fillRect(x, y, Math.random() * 50 + 10, Math.random() * 50 + 10)
} else if (shapeType === 1) {
// Circle
ctx.beginPath()
ctx.arc(x, y, Math.random() * 30 + 5, 0, Math.PI * 2)
ctx.fill()
} else if (shapeType === 2) {
// Line
ctx.beginPath()
ctx.moveTo(x, y)
ctx.lineTo(x + Math.random() * 100 - 50, y + Math.random() * 100 - 50)
ctx.stroke()
} else {
// Path
ctx.beginPath()
ctx.moveTo(x, y)
for (let j = 0; j < 5; j++) {
ctx.lineTo(x + Math.random() * 100 - 50, y + Math.random() * 100 - 50)
}
ctx.closePath()
ctx.fill()
ctx.stroke()
}
}
return canvas.id
}, complexity)
// Cleanup
await page.evaluate(() => {
const canvas = document.getElementById("test-canvas")
if (canvas) {
canvas.remove()
}
})
}
/**
* Simulates scrolling and interaction with a large dataset
*/
export async function simulateLargeDataInteraction(
page: Page,
itemCount: number
): Promise<void> {
// Create a large virtual list
await page.evaluate((count) => {
const container = document.createElement("div")
container.id = "large-data-container"
container.style.position = "fixed"
container.style.top = "0"
container.style.left = "0"
container.style.width = "100%"
container.style.height = "100%"
container.style.overflow = "auto"
container.style.opacity = "0.1"
container.style.backgroundColor = "#f0f0f0"
container.style.pointerEvents = "none"
// Create a large number of items
for (let i = 0; i < count; i++) {
const item = document.createElement("div")
item.id = `item-${i}`
item.textContent = `Item ${i} - ${Math.random()
.toString(36)
.substring(2, 12)}`
item.style.padding = "20px"
item.style.margin = "5px"
item.style.backgroundColor = "#fff"
item.style.border = "1px solid #ddd"
container.appendChild(item)
}
document.body.appendChild(container)
return container.id
}, itemCount)
// Perform various scrolling operations
const scrollSteps = Math.min(20, Math.floor(itemCount / 10))
for (let i = 0; i < scrollSteps; i++) {
const targetPosition = itemCount * 30 * (i / scrollSteps)
// Scroll to position
await page.evaluate((position) => {
const container = document.getElementById("large-data-container")
if (container) {
container.scrollTop = position
}
}, targetPosition)
// Wait briefly to simulate looking at content
await page.waitForTimeout(100)
// Interact with some elements
if (i % 3 === 0) {
const targetItem = Math.floor(targetPosition / 30 + Math.random() * 5)
await page.evaluate((itemId) => {
const item = document.getElementById(`item-${itemId}`)
if (item) {
item.style.backgroundColor = "#f0f8ff"
item.innerHTML += ' <span style="color: blue">[Selected]</span>'
}
}, targetItem)
}
}
// Cleanup
await page.evaluate(() => {
const container = document.getElementById("large-data-container")
if (container) {
container.remove()
}
})
}
/**
* Load resources that take some time
*/
export async function loadHeavyResources(
page: Page,
resourceCount: number
): Promise<void> {
await page.evaluate((count) => {
const container = document.createElement("div")
container.id = "resource-container"
container.style.position = "fixed"
container.style.top = "0"
container.style.left = "0"
container.style.opacity = "0"
document.body.appendChild(container)
// Create scripts that simulate resource loading
for (let i = 0; i < count; i++) {
const loadTime = 50 + Math.random() * 300
// Create a promise that resolves after the load time
window.setTimeout(() => {
const element = document.createElement("div")
element.id = `resource-${i}`
element.textContent = `Resource ${i} loaded after ${loadTime}ms`
container.appendChild(element)
}, loadTime)
}
return container.id
}, resourceCount)
// Wait for all resources to be loaded in parallel
await Promise.all(
Array.from({ length: resourceCount }, (_, i) =>
page.waitForSelector(`#resource-${i}`, { timeout: 10000 })
)
)
// Cleanup
await page.evaluate(() => {
const container = document.getElementById("resource-container")
if (container) {
container.remove()
}
})
}
/**
* Generate complex test scenario that will take between 10-40 seconds
*/
export async function runComplexTestScenario(
page: Page,
complexityFactor: number
): Promise<void> {
// Step 1: Navigate to a page and wait for it to load
await page.goto("https://playwright.dev/")
await expect(page).toHaveTitle(/Playwright/)
// Step 2: Perform DOM manipulations
await performComplexDOMOperations(page, 12 * complexityFactor)
// Step 3: Simulate network delays and API calls
await simulateApiRequests(page, 1 + complexityFactor)
// Step 4: Perform CPU-intensive operations
await simulateHeavyComputation(complexityFactor)
// Step 5: Interact with form elements
await fillFormWithValidation(page, 3 + complexityFactor)
// Step 6: Canvas operations for visual rendering load
await performCanvasOperations(page, Math.ceil(complexityFactor / 4))
// Step 7: Simulate scrolling through large datasets
await simulateLargeDataInteraction(page, 25 * complexityFactor)
// Step 8: Load heavy resources
await loadHeavyResources(page, Math.ceil(complexityFactor / 4))
// Additional network delay to ensure total test time is adequate
await simulateNetworkDelay(
page,
100 * complexityFactor,
200 * complexityFactor
)
}