codeceptjs 4.0.0-beta.4 → 4.0.0-beta.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (150) hide show
  1. package/README.md +134 -119
  2. package/bin/codecept.js +12 -2
  3. package/bin/test-server.js +53 -0
  4. package/docs/webapi/clearCookie.mustache +1 -1
  5. package/lib/actor.js +66 -102
  6. package/lib/ai.js +130 -121
  7. package/lib/assert/empty.js +3 -5
  8. package/lib/assert/equal.js +4 -7
  9. package/lib/assert/include.js +4 -6
  10. package/lib/assert/throws.js +2 -4
  11. package/lib/assert/truth.js +2 -2
  12. package/lib/codecept.js +139 -87
  13. package/lib/command/check.js +201 -0
  14. package/lib/command/configMigrate.js +2 -4
  15. package/lib/command/definitions.js +8 -26
  16. package/lib/command/generate.js +10 -14
  17. package/lib/command/gherkin/snippets.js +75 -73
  18. package/lib/command/gherkin/steps.js +1 -1
  19. package/lib/command/info.js +42 -8
  20. package/lib/command/init.js +13 -12
  21. package/lib/command/interactive.js +10 -2
  22. package/lib/command/list.js +1 -1
  23. package/lib/command/run-multiple/chunk.js +48 -45
  24. package/lib/command/run-multiple.js +12 -35
  25. package/lib/command/run-workers.js +21 -58
  26. package/lib/command/utils.js +5 -6
  27. package/lib/command/workers/runTests.js +262 -220
  28. package/lib/container.js +386 -238
  29. package/lib/data/context.js +10 -13
  30. package/lib/data/dataScenarioConfig.js +8 -8
  31. package/lib/data/dataTableArgument.js +6 -6
  32. package/lib/data/table.js +5 -11
  33. package/lib/effects.js +223 -0
  34. package/lib/element/WebElement.js +327 -0
  35. package/lib/els.js +158 -0
  36. package/lib/event.js +21 -17
  37. package/lib/heal.js +88 -80
  38. package/lib/helper/AI.js +2 -1
  39. package/lib/helper/ApiDataFactory.js +3 -6
  40. package/lib/helper/Appium.js +47 -51
  41. package/lib/helper/FileSystem.js +3 -3
  42. package/lib/helper/GraphQLDataFactory.js +3 -3
  43. package/lib/helper/JSONResponse.js +75 -37
  44. package/lib/helper/Mochawesome.js +31 -9
  45. package/lib/helper/Nightmare.js +35 -53
  46. package/lib/helper/Playwright.js +262 -267
  47. package/lib/helper/Protractor.js +54 -77
  48. package/lib/helper/Puppeteer.js +246 -260
  49. package/lib/helper/REST.js +5 -17
  50. package/lib/helper/TestCafe.js +21 -44
  51. package/lib/helper/WebDriver.js +151 -170
  52. package/lib/helper/extras/Popup.js +22 -22
  53. package/lib/helper/testcafe/testcafe-utils.js +26 -27
  54. package/lib/listener/emptyRun.js +55 -0
  55. package/lib/listener/exit.js +7 -10
  56. package/lib/listener/{retry.js → globalRetry.js} +5 -5
  57. package/lib/listener/globalTimeout.js +165 -0
  58. package/lib/listener/helpers.js +15 -15
  59. package/lib/listener/mocha.js +1 -1
  60. package/lib/listener/result.js +12 -0
  61. package/lib/listener/retryEnhancer.js +85 -0
  62. package/lib/listener/steps.js +32 -18
  63. package/lib/listener/store.js +20 -0
  64. package/lib/mocha/asyncWrapper.js +231 -0
  65. package/lib/{interfaces → mocha}/bdd.js +3 -3
  66. package/lib/mocha/cli.js +308 -0
  67. package/lib/mocha/factory.js +104 -0
  68. package/lib/{interfaces → mocha}/featureConfig.js +32 -12
  69. package/lib/{interfaces → mocha}/gherkin.js +26 -28
  70. package/lib/mocha/hooks.js +112 -0
  71. package/lib/mocha/index.js +12 -0
  72. package/lib/mocha/inject.js +29 -0
  73. package/lib/{interfaces → mocha}/scenarioConfig.js +31 -7
  74. package/lib/mocha/suite.js +82 -0
  75. package/lib/mocha/test.js +181 -0
  76. package/lib/mocha/types.d.ts +42 -0
  77. package/lib/mocha/ui.js +232 -0
  78. package/lib/output.js +82 -62
  79. package/lib/pause.js +160 -138
  80. package/lib/plugin/analyze.js +396 -0
  81. package/lib/plugin/auth.js +435 -0
  82. package/lib/plugin/autoDelay.js +8 -8
  83. package/lib/plugin/autoLogin.js +3 -338
  84. package/lib/plugin/commentStep.js +6 -1
  85. package/lib/plugin/coverage.js +10 -19
  86. package/lib/plugin/customLocator.js +3 -3
  87. package/lib/plugin/customReporter.js +52 -0
  88. package/lib/plugin/eachElement.js +1 -1
  89. package/lib/plugin/fakerTransform.js +1 -1
  90. package/lib/plugin/heal.js +36 -9
  91. package/lib/plugin/htmlReporter.js +1947 -0
  92. package/lib/plugin/pageInfo.js +140 -0
  93. package/lib/plugin/retryFailedStep.js +17 -18
  94. package/lib/plugin/retryTo.js +2 -113
  95. package/lib/plugin/screenshotOnFail.js +17 -58
  96. package/lib/plugin/selenoid.js +15 -35
  97. package/lib/plugin/standardActingHelpers.js +4 -1
  98. package/lib/plugin/stepByStepReport.js +56 -17
  99. package/lib/plugin/stepTimeout.js +5 -12
  100. package/lib/plugin/subtitles.js +4 -4
  101. package/lib/plugin/tryTo.js +3 -102
  102. package/lib/plugin/wdio.js +8 -10
  103. package/lib/recorder.js +155 -124
  104. package/lib/rerun.js +43 -42
  105. package/lib/result.js +161 -0
  106. package/lib/secret.js +1 -1
  107. package/lib/step/base.js +239 -0
  108. package/lib/step/comment.js +10 -0
  109. package/lib/step/config.js +50 -0
  110. package/lib/step/func.js +46 -0
  111. package/lib/step/helper.js +50 -0
  112. package/lib/step/meta.js +99 -0
  113. package/lib/step/record.js +74 -0
  114. package/lib/step/retry.js +11 -0
  115. package/lib/step/section.js +55 -0
  116. package/lib/step.js +21 -332
  117. package/lib/steps.js +50 -0
  118. package/lib/store.js +37 -5
  119. package/lib/template/heal.js +2 -11
  120. package/lib/test-server.js +323 -0
  121. package/lib/timeout.js +66 -0
  122. package/lib/utils.js +351 -218
  123. package/lib/within.js +75 -55
  124. package/lib/workerStorage.js +2 -1
  125. package/lib/workers.js +386 -276
  126. package/package.json +76 -70
  127. package/translations/de-DE.js +4 -3
  128. package/translations/fr-FR.js +4 -3
  129. package/translations/index.js +1 -0
  130. package/translations/it-IT.js +4 -3
  131. package/translations/ja-JP.js +4 -3
  132. package/translations/nl-NL.js +76 -0
  133. package/translations/pl-PL.js +4 -3
  134. package/translations/pt-BR.js +4 -3
  135. package/translations/ru-RU.js +4 -3
  136. package/translations/utils.js +9 -0
  137. package/translations/zh-CN.js +4 -3
  138. package/translations/zh-TW.js +4 -3
  139. package/typings/index.d.ts +188 -186
  140. package/typings/promiseBasedTypes.d.ts +18 -705
  141. package/typings/types.d.ts +301 -804
  142. package/lib/cli.js +0 -256
  143. package/lib/helper/ExpectHelper.js +0 -391
  144. package/lib/helper/SoftExpectHelper.js +0 -381
  145. package/lib/listener/artifacts.js +0 -19
  146. package/lib/listener/timeout.js +0 -109
  147. package/lib/mochaFactory.js +0 -113
  148. package/lib/plugin/debugErrors.js +0 -67
  149. package/lib/scenario.js +0 -224
  150. package/lib/ui.js +0 -236
@@ -0,0 +1,396 @@
1
+ const debug = require('debug')('codeceptjs:analyze')
2
+ const { isMainThread } = require('node:worker_threads')
3
+ const { arrowRight } = require('figures')
4
+ const container = require('../container')
5
+ const store = require('../store')
6
+ const ai = require('../ai')
7
+ const colors = require('chalk')
8
+ const ora = require('ora-classic')
9
+ const event = require('../event')
10
+ const output = require('../output')
11
+ const { ansiRegExp, base64EncodeFile, markdownToAnsi } = require('../utils')
12
+
13
+ const MAX_DATA_LENGTH = 5000
14
+
15
+ const defaultConfig = {
16
+ clusterize: 5,
17
+ analyze: 2,
18
+ vision: false,
19
+ categories: [
20
+ 'Browser connection error / browser crash',
21
+ 'Network errors (server error, timeout, etc)',
22
+ 'HTML / page elements (not found, not visible, etc)',
23
+ 'Navigation errors (404, etc)',
24
+ 'Code errors (syntax error, JS errors, etc)',
25
+ 'Library & framework errors (CodeceptJS internal errors, user-defined libraries, etc)',
26
+ 'Data errors (password incorrect, no options in select, invalid format, etc)',
27
+ 'Assertion failures',
28
+ 'Other errors',
29
+ ],
30
+ prompts: {
31
+ clusterize: (tests, config) => {
32
+ const serializedFailedTests = tests
33
+ .map((test, index) => {
34
+ if (!test || !test.err) return
35
+ return `
36
+ #${index + 1}: ${serializeTest(test)}
37
+ ${serializeError(test.err).slice(0, MAX_DATA_LENGTH / tests.length)}`.trim()
38
+ })
39
+ .join('\n\n--------\n\n')
40
+
41
+ const messages = [
42
+ {
43
+ role: 'user',
44
+ content: `
45
+ I am test analyst analyzing failed tests in CodeceptJS testing framework.
46
+
47
+ Please analyze the following failed tests and classify them into groups by their cause.
48
+ If there is no groups detected, say: "No common groups found".
49
+
50
+ Provide a short description of the group and a list of failed tests that belong to this group.
51
+ Use percent sign to indicate the percentage of failed tests in the group if this percentage is greater than 30%.
52
+
53
+ Here are failed tests:
54
+
55
+ ${serializedFailedTests}
56
+
57
+ Common categories of failures by order of priority:
58
+
59
+ ${config.categories.join('\n- ')}
60
+
61
+ If there is no groups of tests, say: "No patterns found"
62
+ Preserve error messages but cut them if they are too long.
63
+ Respond clearly and directly, without introductory words or phrases like 'Of course,' 'Here is the answer,' etc.
64
+ Do not list more than 3 errors in the group.
65
+ If you identify that all tests in the group have the same tag, add this tag to the group report, otherwise ignore TAG section.
66
+ If you identify that all tests in the group have the same suite, add this suite to the group report, otherwise ignore SUITE section.
67
+ Pick different emojis for each group.
68
+ Order groups by the number of tests in the group.
69
+ If group has one test, skip that group.
70
+
71
+ Provide list of groups in following format:
72
+
73
+ _______________________________
74
+
75
+ ## Group <group_number> <emoji>
76
+
77
+ * SUMMARY <summary_of_errors>
78
+ * CATEGORY <category_of_failure>
79
+ * URL <url_of_failure_if_any>
80
+ * ERROR <error_message_1>, <error_message_2>, ...
81
+ * STEP <step_of_failure> (use CodeceptJS format I.click(), I.see(), etc; if all failures happend on the same step)
82
+ * SUITE <suite_title>, <suite_title> (if SUITE is present, and if all tests in the group have the same suite or suites)
83
+ * TAG <tag> (if TAG is present, and if all tests in the group have the same tag)
84
+ * AFFECTED TESTS (<total number of tests>):
85
+ x <test1 title>
86
+ x <test2 title>
87
+ x <test3 title>
88
+ x ...
89
+ `,
90
+ },
91
+ ]
92
+ return messages
93
+ },
94
+ analyze: (test, config) => {
95
+ const testMessage = serializeTest(test)
96
+ const errorMessage = serializeError(test.err)
97
+
98
+ const messages = [
99
+ {
100
+ role: 'user',
101
+ content: [
102
+ {
103
+ type: 'text',
104
+ text: `
105
+ I am qa engineer analyzing failed tests in CodeceptJS testing framework.
106
+ Please analyze the following failed test and error its error and explain it.
107
+
108
+ Pick one of the categories of failures and explain it.
109
+
110
+ Categories of failures in order of priority:
111
+
112
+ ${config.categories.join('\n- ')}
113
+
114
+ Here is the test and error:
115
+
116
+ ------- TEST -------
117
+ ${testMessage}
118
+
119
+ ------- ERROR -------
120
+ ${errorMessage}
121
+
122
+ ------ INSTRUCTIONS ------
123
+
124
+ Do not get to details, be concise.
125
+ If there is failed step, just write it in STEPS section.
126
+ If you have suggestions for the test, write them in SUMMARY section.
127
+ Do not be too technical in SUMMARY section.
128
+ Inside SUMMARY write exact values, if you have suggestions, explain which information you used to suggest.
129
+ Be concise, each section should not take more than one sentence.
130
+
131
+ Response format:
132
+
133
+ * SUMMARY <explanation_of_failure>
134
+ * ERROR <error_message_1>, <error_message_2>, ...
135
+ * CATEGORY <category_of_failure>
136
+ * STEPS <step_of_failure>
137
+ * URL <url_of_failure_if_any>
138
+
139
+ Do not add any other sections or explanations. Only CATEGORY, SUMMARY, STEPS.
140
+ ${config.vision ? 'Also a screenshot of the page is attached to the prompt.' : ''}
141
+ `,
142
+ },
143
+ ],
144
+ },
145
+ ]
146
+
147
+ if (config.vision && test.artifacts.screenshot) {
148
+ debug('Adding screenshot to prompt')
149
+ messages[0].content.push({
150
+ type: 'image_url',
151
+ image_url: {
152
+ url: 'data:image/png;base64,' + base64EncodeFile(test.artifacts.screenshot),
153
+ },
154
+ })
155
+ }
156
+
157
+ return messages
158
+ },
159
+ },
160
+ }
161
+
162
+ /**
163
+ *
164
+ * Uses AI to analyze test failures and provide insights
165
+ *
166
+ * This plugin analyzes failed tests using AI to provide detailed explanations and group similar failures.
167
+ * When enabled with --ai flag, it generates reports after test execution.
168
+ *
169
+ * #### Usage
170
+ *
171
+ * ```js
172
+ * // in codecept.conf.js
173
+ * exports.config = {
174
+ * plugins: {
175
+ * analyze: {
176
+ * enabled: true,
177
+ * clusterize: 5,
178
+ * analyze: 2,
179
+ * vision: false
180
+ * }
181
+ * }
182
+ * }
183
+ * ```
184
+ *
185
+ * #### Configuration
186
+ *
187
+ * * `clusterize` (number) - minimum number of failures to trigger clustering analysis. Default: 5
188
+ * * `analyze` (number) - maximum number of individual test failures to analyze in detail. Default: 2
189
+ * * `vision` (boolean) - enables visual analysis of test screenshots. Default: false
190
+ * * `categories` (array) - list of failure categories for classification. Defaults to:
191
+ * - Browser connection error / browser crash
192
+ * - Network errors (server error, timeout, etc)
193
+ * - HTML / page elements (not found, not visible, etc)
194
+ * - Navigation errors (404, etc)
195
+ * - Code errors (syntax error, JS errors, etc)
196
+ * - Library & framework errors
197
+ * - Data errors (password incorrect, invalid format, etc)
198
+ * - Assertion failures
199
+ * - Other errors
200
+ * * `prompts` (object) - customize AI prompts for analysis
201
+ * - `clusterize` - prompt for clustering analysis
202
+ * - `analyze` - prompt for individual test analysis
203
+ *
204
+ * #### Features
205
+ *
206
+ * * Groups similar failures when number of failures >= clusterize value
207
+ * * Provides detailed analysis of individual failures
208
+ * * Analyzes screenshots if vision=true and screenshots are available
209
+ * * Classifies failures into predefined categories
210
+ * * Suggests possible causes and solutions
211
+ *
212
+ * @param {Object} config - Plugin configuration
213
+ * @returns {void}
214
+ */
215
+ module.exports = function (config = {}) {
216
+ config = Object.assign(defaultConfig, config)
217
+
218
+ event.dispatcher.on(event.workers.before, () => {
219
+ if (!ai.isEnabled) return
220
+ console.log('Enabled AI analysis')
221
+ })
222
+
223
+ event.dispatcher.on(event.all.result, async result => {
224
+ if (!isMainThread) return // run only on main thread
225
+ if (!ai.isEnabled) {
226
+ console.log('AI is disabled, no analysis will be performed. Run tests with --ai flag to enable it.')
227
+ return
228
+ }
229
+
230
+ printReport(result)
231
+ })
232
+
233
+ event.dispatcher.on(event.workers.result, async result => {
234
+ if (!result.hasFailed) {
235
+ console.log('Everything is fine, skipping AI analysis')
236
+ return
237
+ }
238
+
239
+ if (!ai.isEnabled) {
240
+ console.log('AI is disabled, no analysis will be performed. Run tests with --ai flag to enable it.')
241
+ return
242
+ }
243
+
244
+ printReport(result)
245
+ })
246
+
247
+ async function printReport(result) {
248
+ const failedTestsAndErrors = result.tests.filter(t => t.err)
249
+
250
+ if (!failedTestsAndErrors.length) return
251
+
252
+ debug(failedTestsAndErrors.map(t => serializeTest(t) + '\n' + serializeError(t.err)))
253
+
254
+ try {
255
+ if (failedTestsAndErrors.length >= config.clusterize) {
256
+ const response = await clusterize(failedTestsAndErrors)
257
+ printHeader()
258
+ console.log(response)
259
+ return
260
+ }
261
+
262
+ output.plugin('analyze', `Analyzing first ${config.analyze} failed tests...`)
263
+
264
+ // we pick only unique errors to not repeat answers
265
+ const uniqueErrors = failedTestsAndErrors.filter((item, index, array) => {
266
+ return array.findIndex(t => t.err?.message === item.err?.message) === index
267
+ })
268
+
269
+ for (let i = 0; i < config.analyze; i++) {
270
+ if (!uniqueErrors[i]) break
271
+
272
+ const response = await analyze(uniqueErrors[i])
273
+ if (!response) {
274
+ break
275
+ }
276
+
277
+ printHeader()
278
+ console.log()
279
+ console.log('--------------------------------')
280
+ console.log(arrowRight, colors.bold.white(uniqueErrors[i].fullTitle()), config.vision ? '👀' : '')
281
+ console.log()
282
+ console.log()
283
+ console.log(response)
284
+ console.log()
285
+ }
286
+ } catch (err) {
287
+ console.error('Error analyzing failed tests', err)
288
+ }
289
+
290
+ if (!Object.keys(container.plugins()).includes('pageInfo')) {
291
+ console.log('To improve analysis, enable pageInfo plugin to get more context for failed tests.')
292
+ }
293
+ }
294
+
295
+ let hasPrintedHeader = false
296
+
297
+ function printHeader() {
298
+ if (!hasPrintedHeader) {
299
+ console.log()
300
+ console.log(colors.bold.white('🪄 AI REPORT:'))
301
+ hasPrintedHeader = true
302
+ }
303
+ }
304
+
305
+ async function clusterize(failedTestsAndErrors) {
306
+ const spinner = ora('Clusterizing failures...').start()
307
+ const prompt = config.prompts.clusterize(failedTestsAndErrors, config)
308
+ try {
309
+ const response = await ai.createCompletion(prompt)
310
+ spinner.stop()
311
+ return formatResponse(response)
312
+ } catch (err) {
313
+ spinner.stop()
314
+ console.error('Error clusterizing failures', err.message)
315
+ }
316
+ }
317
+
318
+ async function analyze(failedTestAndError) {
319
+ const spinner = ora('Analyzing failure...').start()
320
+ const prompt = config.prompts.analyze(failedTestAndError, config)
321
+ try {
322
+ const response = await ai.createCompletion(prompt)
323
+ spinner.stop()
324
+ return formatResponse(response)
325
+ } catch (err) {
326
+ spinner.stop()
327
+ console.error('Error analyzing failure:', err.message)
328
+ }
329
+ }
330
+ }
331
+
332
+ function serializeError(error) {
333
+ if (typeof error === 'string') {
334
+ return error
335
+ }
336
+
337
+ if (!error) return
338
+
339
+ let errorMessage = 'ERROR: ' + error.message
340
+
341
+ if (error.inspect) {
342
+ errorMessage = 'ERROR: ' + error.inspect()
343
+ }
344
+
345
+ if (error.stack) {
346
+ errorMessage +=
347
+ '\n' +
348
+ error.stack
349
+ .replace(global.codecept_dir || '', '.')
350
+ .split('\n')
351
+ .map(line => line.replace(ansiRegExp(), ''))
352
+ .slice(0, 5)
353
+ .join('\n')
354
+ }
355
+ if (error.steps) {
356
+ errorMessage += '\n STEPS: ' + error.steps.map(s => s.toCode()).join('\n')
357
+ }
358
+ return errorMessage
359
+ }
360
+
361
+ function serializeTest(test) {
362
+ if (!test.uid) return
363
+
364
+ let testMessage = 'TEST TITLE: ' + test.title
365
+
366
+ if (test.suite) {
367
+ testMessage += '\n SUITE: ' + test.suite.title
368
+ }
369
+ if (test.parent) {
370
+ testMessage += '\n SUITE: ' + test.parent.title
371
+ }
372
+
373
+ if (test.steps?.length) {
374
+ const failedSteps = test.steps
375
+ if (failedSteps.length) testMessage += '\n STEP: ' + failedSteps.map(s => s.toCode()).join('; ')
376
+ }
377
+
378
+ const pageInfo = test.notes.find(n => n.type === 'pageInfo')
379
+ if (pageInfo) {
380
+ testMessage += '\n PAGE INFO: ' + pageInfo.text
381
+ }
382
+
383
+ return testMessage
384
+ }
385
+
386
+ function formatResponse(response) {
387
+ return response
388
+ .replace(/<think>([\s\S]*?)<\/think>/g, store.debugMode ? colors.cyan('$1') : '')
389
+ .split('\n')
390
+ .map(line => line.trim())
391
+ .filter(line => !/^[A-Z\s]+$/.test(line))
392
+ .map(line => markdownToAnsi(line))
393
+ .map(line => line.replace(/^x /gm, ` ${colors.red.bold('x')} `))
394
+ .join('\n')
395
+ .trim()
396
+ }