-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathplaywright-check.ts
More file actions
361 lines (323 loc) · 11.6 KB
/
playwright-check.ts
File metadata and controls
361 lines (323 loc) · 11.6 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
import { createReadStream } from 'node:fs'
import fs from 'node:fs/promises'
import type { AxiosResponse } from 'axios'
import { checklyStorage } from '../rest/api'
import {
bundlePlayWrightProject, cleanup,
} from '../services/util'
import { RuntimeCheck, RuntimeCheckProps } from './check'
import {
ConflictingPropertyDiagnostic,
DeprecatedPropertyDiagnostic,
InvalidPropertyValueDiagnostic,
UnsupportedPropertyDiagnostic,
} from './construct-diagnostics'
import { Diagnostics } from './diagnostics'
import { PlaywrightCheckBundle } from './playwright-check-bundle'
import { Session } from './project'
import { Ref } from './ref'
import { ConfigDefaultsGetter, makeConfigDefaultsGetter } from './check-config'
export interface PlaywrightCheckProps extends Omit<RuntimeCheckProps, 'retryStrategy' | 'doubleCheck'> {
/**
* Path to the Playwright configuration file (playwright.config.js/ts).
* This file defines test settings, browser configurations, and project structure.
*
* @example "playwright.config.ts"
*/
playwrightConfigPath: string
/**
* Command to install dependencies before running tests.
* Useful for ensuring test dependencies are available in the runtime environment.
*
* @example "npm ci"
* @example "yarn install --frozen-lockfile"
*/
installCommand?: string
/**
* Command to execute Playwright tests.
* The check will automatically append configuration, project, and tag arguments.
*
* @defaultValue "npx playwright test"
* @example "npx playwright test --grep@checkly --config=playwright.foo.config.ts"
* @example "yarn playwright test"
*/
testCommand?: string
/**
* Specific Playwright projects to run from your configuration.
* Projects let you run tests in different browsers or with different settings.
*
* @example "chromium"
* @example ["chromium", "firefox"]
* @see {@link https://playwright.dev/docs/test-projects | Playwright Projects}
*/
pwProjects?: string | string[]
/**
* Tags to filter which tests to run using Playwright's grep functionality.
* Tests matching any of these tags will be executed.
*
* @example "@smoke"
* @example ["@smoke", "@critical"]
* @see {@link https://playwright.dev/docs/test-annotations#tag-tests | Playwright Test Tags}
*/
pwTags?: string | string[]
/**
* File patterns to include when bundling the test project.
* Use this to include test files, utilities, and other assets.
*
* @example "tests/**\/*"
* @example ["tests/**\/*", "utils/**\/*", "fixtures/**\/*"]
*/
include?: string | string[]
/**
* Name of the check group to assign this check to.
* The group must exist in your project configuration.
*
* @deprecated Use {@link group} instead. Depending on load order, group
* defaults may not work correctly when using {@link groupName} to attach the
* check to a group.
* @example "E2E Tests"
* @example "Critical User Flows"
*/
groupName?: string
}
/**
* Creates a Playwright Check to run end-to-end tests using Playwright Test.
*
* Playwright check suites allow you to monitor complex user interactions and workflows
* by running your existing Playwright test suites as monitoring checks. They support
* multiple browsers, test filtering, and custom test commands.
*
* @example
* ```typescript
* // Basic Playwright check
* new PlaywrightCheck('e2e-login', {
* name: 'Login Flow E2E Test',
* playwrightConfigPath: '../playwright.config.js',
* frequency: Frequency.EVERY_10M,
* locations: ['us-east-1', 'eu-west-1']
* })
*
* // Advanced check with projects and tags
* new PlaywrightCheck('critical-flows', {
* name: 'Critical User Flows',
* playwrightConfigPath: '../playwright.config.js',
* installCommand: 'npm ci',
* pwProjects: ['chromium', 'firefox'],
* pwTags: ['@smoke', '@critical'],
* include: ['tests/**\/*', 'utils/**\/*'],
* groupName: 'E2E Tests',
* frequency: Frequency.EVERY_5M
* })
* ```
*
* @see {@link https://www.checklyhq.com/docs/constructs/playwright-check/ | PlaywrightCheck API Reference}
* @see {@link https://www.checklyhq.com/docs/detect/synthetic-monitoring/playwright-checks/overview/
* Playwright Checks Documentation}
* @see {@link https://playwright.dev/ | Playwright Documentation}
*/
export class PlaywrightCheck extends RuntimeCheck {
installCommand?: string
testCommand: string
playwrightConfigPath: string
pwProjects: string[]
pwTags: string[]
include: string[]
/** @deprecated Use {@link groupId} instead. Kept for compatibility with earlier versions. */
groupName?: string
constructor (logicalId: string, props: PlaywrightCheckProps) {
super(logicalId, props)
const config = this.applyConfigDefaults(props)
this.installCommand = config.installCommand
this.pwProjects = config.pwProjects
? (Array.isArray(config.pwProjects) ? config.pwProjects : [config.pwProjects])
: []
this.pwTags = config.pwTags
? (Array.isArray(config.pwTags) ? config.pwTags : [config.pwTags])
: []
this.include = config.include
? (Array.isArray(config.include) ? config.include : [config.include])
: []
this.testCommand = config.testCommand ?? 'npx playwright test'
this.groupName = config.groupName
this.playwrightConfigPath = this.resolveContentFilePath(config.playwrightConfigPath)
Session.registerConstruct(this)
this.addSubscriptions()
this.addPrivateLocationCheckAssignments()
}
describe (): string {
return `PlaywrightCheck:${this.logicalId}`
}
protected configDefaultsGetter (props: PlaywrightCheckProps): ConfigDefaultsGetter {
const group = PlaywrightCheck.#resolveGroupFromProps(props)
return makeConfigDefaultsGetter(
group?.getCheckDefaults(),
{
...Session.checkDefaults,
// Not supported by Playwright checks; exclude from defaults.
retryStrategy: undefined,
// Not supported by Playwright checks; exclude from defaults.
doubleCheck: undefined,
},
)
}
static #resolveGroupFromProps (props: PlaywrightCheckProps) {
// Check the preferred 'group' property first
if (props.group) {
return props.group
}
// Fall back to deprecated groupId
if (props.groupId) {
return PlaywrightCheck.#findGroupByRef(props.groupId)
}
// Fall back to deprecated groupName
if (props.groupName) {
return PlaywrightCheck.#findGroupByName(props.groupName)
}
return undefined
}
static #findGroupByRef (groupRef: Ref | string) {
const ref = typeof groupRef === 'string' ? groupRef : groupRef.ref
return Session.project?.data?.['check-group']?.[ref]
}
static #findGroupByName (groupName: string) {
return Object.values(Session.project?.data?.['check-group'] ?? {})
.find(group => group.name === groupName)
}
// eslint-disable-next-line require-await
protected async validateDoubleCheck (diagnostics: Diagnostics): Promise<void> {
if (this.doubleCheck !== undefined) {
diagnostics.add(new UnsupportedPropertyDiagnostic(
'doubleCheck',
new Error(
`This property is not available in Playwright checks.`
+ `\n\n`
+ `Playwright tests have their own built-in retry mechanism that `
+ `should be configured in your Playwright configuration file `
+ `instead.`,
),
))
}
}
// eslint-disable-next-line require-await
protected async validateRetryStrategy (diagnostics: Diagnostics): Promise<void> {
// Check if retryStrategy was passed (even though TypeScript should prevent it)
if (this.retryStrategy) {
diagnostics.add(new UnsupportedPropertyDiagnostic(
'retryStrategy',
new Error(
`This property is not available in Playwright checks.`
+ `\n\n`
+ `Playwright tests have their own built-in retry mechanism that `
+ `should be configured in your Playwright configuration file `
+ `instead.`,
),
))
}
}
async validate (diagnostics: Diagnostics): Promise<void> {
await super.validate(diagnostics)
await this.validateRetryStrategy(diagnostics)
try {
await fs.access(this.playwrightConfigPath, fs.constants.R_OK)
} catch (err: any) {
diagnostics.add(new InvalidPropertyValueDiagnostic(
'playwrightConfigPath',
new Error(`Playwright config "${this.playwrightConfigPath}" does not exist: ${err.message}`, { cause: err }),
))
}
this.#validateGroupReferences(diagnostics)
}
#validateGroupReferences (diagnostics: Diagnostics): void {
if (this.groupName) {
diagnostics.add(new DeprecatedPropertyDiagnostic(
'groupName',
new Error(
`Use the "group" property instead. Depending on load order, `
+ 'group defaults may not work correctly when using "groupName".',
),
))
if (this.groupId) {
diagnostics.add(new ConflictingPropertyDiagnostic(
'groupName',
'group',
new Error(`Prefer the "group" property over "groupName".`),
))
}
const checkGroup = PlaywrightCheck.#findGroupByName(this.groupName)
if (!checkGroup) {
diagnostics.add(new InvalidPropertyValueDiagnostic(
'groupName',
new Error(`No such group "${this.groupName}".`),
))
}
}
}
getSourceFile () {
return this.__checkFilePath
}
static buildTestCommand (
testCommand: string, playwrightConfigPath: string, playwrightProject?: string[], playwrightTag?: string[],
) {
const quotedPath = `"${playwrightConfigPath}"`
const projectArg = playwrightProject?.length ? ' --project ' + playwrightProject.map(p => `"${p}"`).join(' ') : ''
const tagArg = playwrightTag?.length ? ' --grep "' + playwrightTag.join('|').replace(/"/g, '\\"') + '"' : ''
return `${testCommand} --config ${quotedPath}${projectArg}${tagArg}`
}
static async bundleProject (playwrightConfigPath: string, include: string[]) {
let dir = ''
try {
const {
outputFile, browsers, relativePlaywrightConfigPath, cacheHash, playwrightVersion,
} = await bundlePlayWrightProject(playwrightConfigPath, include)
dir = outputFile
const { data: { key } } = await PlaywrightCheck.uploadPlaywrightProject(dir)
return { key, browsers, relativePlaywrightConfigPath, cacheHash, playwrightVersion }
} finally {
await cleanup(dir)
}
}
static async uploadPlaywrightProject (dir: string): Promise<AxiosResponse> {
const { size } = await fs.stat(dir)
const stream = createReadStream(dir)
stream.on('error', err => {
throw new Error(`Failed to read Playwright project file: ${err.message}`)
})
return checklyStorage.uploadCodeBundle(stream, size)
}
async bundle (): Promise<PlaywrightCheckBundle> {
// Prefer the standard groupId but fall back to the deprecated groupName
// if available.
const groupId = this.groupName && !this.groupId
? PlaywrightCheck.#findGroupByName(this.groupName)?.ref()
: this.groupId
const {
key: codeBundlePath,
browsers,
cacheHash,
playwrightVersion,
relativePlaywrightConfigPath,
} = await PlaywrightCheck.bundleProject(this.playwrightConfigPath, this.include ?? [])
const testCommand = PlaywrightCheck.buildTestCommand(
this.testCommand,
relativePlaywrightConfigPath,
this.pwProjects,
this.pwTags,
)
return new PlaywrightCheckBundle(this, {
groupId,
codeBundlePath,
browsers,
cacheHash,
playwrightVersion,
testCommand,
installCommand: this.installCommand,
})
}
synthesize () {
return {
...super.synthesize(),
checkType: 'PLAYWRIGHT',
doubleCheck: false,
}
}
}