@testomatio/reporter 1.0.17 → 1.1.0-beta-2

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.
@@ -3,16 +3,18 @@ const fs = require('fs');
3
3
  const path = require('path');
4
4
  const os = require('os');
5
5
  const { join } = require('path');
6
- const JestReporter = require('./adapter/jest');
7
- const { TESTOMAT_TMP_STORAGE } = require('./constants');
8
- const { fileSystem } = require('./utils/utils');
9
- const getTestIdFromTestTitle = require('./utils/utils').parseTest;
6
+ const { TESTOMAT_TMP_STORAGE_DIR } = require('../constants');
7
+ const { fileSystem, jestHelpers, parseTest } = require('../utils/utils');
8
+
9
+ const getTestIdFromTestTitle = parseTest;
10
10
 
11
11
  class DataStorage {
12
12
  /**
13
13
  * Creates data storage instance for specific data type.
14
14
  * Stores data to global variable or to file depending on what is applicable for current test runner
15
15
  * (running environment).
16
+ * Recommend to use composition while using this class (instead of inheritance).
17
+ * ! Also the class which will use data storage should be singleton (to avoid data loss).
16
18
  * @param {*} dataType storage type (like 'log', 'artifact'); could be any string, used only to define file path
17
19
  */
18
20
  constructor(dataType) {
@@ -20,8 +22,35 @@ class DataStorage {
20
22
  this.isFileStorage = true;
21
23
  this.#refreshStorageType();
22
24
 
23
- this.dataDirPath = path.join(TESTOMAT_TMP_STORAGE.mainDir, this.dataType);
24
- fileSystem.createDir(this.dataDirPath);
25
+ this.dataDirPath = path.join(TESTOMAT_TMP_STORAGE_DIR, this.dataType);
26
+
27
+ // set test title for mocha (could not be moved to adapter)
28
+ // it does not override existing hook, just add new one
29
+ try {
30
+ // @ts-ignore
31
+ if (!beforeEach) return;
32
+ // @ts-ignore-next-line
33
+ beforeEach(function () {
34
+ if (this.currentTest?.__mocha_id__) {
35
+ global.testTitle = this.currentTest.fullTitle();
36
+ }
37
+ });
38
+ } catch (e) {
39
+ // ignore
40
+ }
41
+
42
+ // set test title for playwright
43
+ try {
44
+ // eslint-disable-next-line import/no-extraneous-dependencies, import/no-unresolved
45
+ const { test } = require('@playwright/test');
46
+ // eslint-disable-next-line no-empty-pattern
47
+ test.beforeEach(async ({}, testInfo) => {
48
+ global.testTitle = testInfo.title;
49
+ global.testomatioRunningEnvironment = 'playwright';
50
+ });
51
+ } catch (e) {
52
+ // ignore
53
+ }
25
54
  }
26
55
 
27
56
  /**
@@ -44,15 +73,18 @@ class DataStorage {
44
73
  }
45
74
 
46
75
  /**
47
- * Puts any data to storage (file or global variable)
48
- * @param {*} data anything you want to store
76
+ * Puts any data to storage (file or global variable).
77
+ * If file: stores data as text, if global variable – stores as array of data.
78
+ * @param {*} data anything you want to store (string, object, array, etc)
49
79
  * @param {*} context could be testId or any context (test, suite, etc) which is used to define testId
50
80
  * @returns
51
81
  */
52
82
  putData(data, context = null) {
53
- this.#refreshStorageType();
83
+ fileSystem.createDir(this.dataDirPath);
54
84
 
55
- let testId = this.#tryToRetrieveTestId(context) || null;
85
+ this.#refreshStorageType();
86
+ context = context ?? global.testTitle ?? null;
87
+ let testId = this.#tryToRetrieveTestId(context) || context || null;
56
88
 
57
89
  if (this.runningEnvironment === 'codeceptjs') {
58
90
  this.isFileStorage = false;
@@ -60,7 +92,7 @@ class DataStorage {
60
92
  }
61
93
 
62
94
  if (this.runningEnvironment === 'jest') {
63
- testId = testId ?? JestReporter.getIdOfCurrentlyRunningTest();
95
+ testId = testId ?? jestHelpers.getIdOfCurrentlyRunningTest();
64
96
  }
65
97
 
66
98
  // logs in playwright are gathered by pw framework itself
@@ -74,7 +106,7 @@ class DataStorage {
74
106
  testId = this.#tryToRetrieveTestId(global.currentlyRunningTestTitle);
75
107
 
76
108
  if (!testId) {
77
- debug(`No test id provided for ${this.dataType} data: ${data}`);
109
+ debug(`No test id provided for "${this.dataType}" data:`, data);
78
110
  return;
79
111
  }
80
112
 
@@ -87,12 +119,10 @@ class DataStorage {
87
119
 
88
120
  /**
89
121
  * Returns data, stored for specific testId (or data which was stored without test id specified).
90
- * This method will get data from global variable. But if it is not available, it will try to get data from file.
91
- * Thus, good approach is to remove file storage folder before each test run (and after, for sure).
122
+ * This method will get data from global variable and/or from from file (previosly saved with put method).
92
123
  *
93
- * Defining the execution environment is not guaranteed! Is used only as additional check.
94
- * @param {*} context could be testId or any context (test, suite, etc) which is used to define testId
95
- * @returns
124
+ * @param {*} context could be testId or any context (test title, suite, etc) which is used to define testId
125
+ * @returns array of data (any type), null (if no data found for test) or string (if data type is log)
96
126
  */
97
127
  getData(context) {
98
128
  this.#refreshStorageType();
@@ -100,9 +130,6 @@ class DataStorage {
100
130
  let testId = null;
101
131
  if (typeof context === 'string') {
102
132
  testId = this.#tryToRetrieveTestId(context) || context;
103
- } else {
104
- // TODO: derive testId from context
105
- // testId = context...
106
133
  }
107
134
 
108
135
  if (!testId) {
@@ -110,12 +137,20 @@ class DataStorage {
110
137
  return null;
111
138
  }
112
139
 
113
- let testData = '';
140
+ let testDataFromFile = [];
141
+ let testDataFromGlobalVar = [];
114
142
 
115
143
  if (global?.testomatioDataStore) {
116
- testData = this.#getDataFromGlobalVar(testId);
144
+ testDataFromGlobalVar = this.#getDataFromGlobalVar(testId);
117
145
  // these frameworks use global variable storage
118
- if (testData && ['cucumber', 'codeceptjs'].includes(this.runningEnvironment)) return testData;
146
+ // if (testDataFromGlobalVar && ['cucumber', 'codeceptjs'].includes(this.runningEnvironment)) {
147
+ if (testDataFromGlobalVar) {
148
+ // return as string if its log data
149
+ if (this.dataType === 'log' && testDataFromGlobalVar.length) return testDataFromGlobalVar.join('\n');
150
+ // return as array for other data types
151
+ if (testDataFromGlobalVar.length) return testDataFromGlobalVar;
152
+ }
153
+ // don't return nothing if no data in global variable
119
154
  }
120
155
 
121
156
  /* condition is removed for mocha
@@ -126,11 +161,16 @@ class DataStorage {
126
161
  // if (testData) return testData;
127
162
  // }
128
163
 
129
- const testDataFromFile = this.#getDataFromFile(testId);
130
- testData += testDataFromFile || '';
164
+ testDataFromFile = this.#getDataFromFile(testId);
131
165
 
132
- debug(`No ${this.dataType} data for test id ${testId} in both file and global variable`);
133
- return testData || '';
166
+ if (testDataFromFile.length) {
167
+ if (this.dataType === 'log') return testDataFromFile.join('\n');
168
+ return testDataFromFile;
169
+ }
170
+ debug(`No "${this.dataType}" data for test id ${testId} in both file and global variable`);
171
+
172
+ // in case no data found for test
173
+ return null;
134
174
  }
135
175
 
136
176
  /**
@@ -166,46 +206,63 @@ class DataStorage {
166
206
  this.runningEnvironment = this.getRunningEnviroment();
167
207
 
168
208
  // some test frameworks do not persist global variables, thus file storage is used for them (by default)
169
- if (['playwright', 'codeceptjs'].includes(this.runningEnvironment)) this.isFileStorage = false;
209
+ if (this.runningEnvironment === 'codeceptjs') this.isFileStorage = false;
210
+ // playwrigth stores logs by itself; but file storage is used for other data types for playwright
211
+ if (this.runningEnvironment === 'playwright' && this.dataType === 'log') this.isFileStorage = false;
170
212
  }
171
213
 
214
+ /**
215
+ * @param {*} testId
216
+ * @returns aray of data (any type)
217
+ */
172
218
  #getDataFromGlobalVar(testId) {
173
219
  try {
174
220
  if (global?.testomatioDataStore[this.dataType]) {
175
221
  const testData = global.testomatioDataStore[this.dataType][testId];
176
- debug(`Data for test id ${testId}:\n${testData}`);
177
- return testData || '';
222
+ if (testData) debug(`"${this.dataType}" data for test id ${testId}:`, testData.join(', '));
223
+ return testData || [];
178
224
  }
179
- debug(`No ${this.dataType} data for test id ${testId} in <global> storage`);
180
- return '';
225
+ // debug(`No ${this.dataType} data for test id ${testId} in <global> storage`);
226
+ return [];
181
227
  } catch (e) {
182
228
  // there could be no data, ignore
183
229
  }
184
230
  }
185
231
 
232
+ /**
233
+ *
234
+ * @param {*} testId
235
+ * @returns array of data (any type)
236
+ */
186
237
  #getDataFromFile(testId) {
187
238
  try {
188
239
  const filepath = join(this.dataDirPath, `${this.dataType}_${testId}`);
189
240
  if (fs.existsSync(filepath)) {
190
- const testData = fs.readFileSync(filepath, 'utf-8');
191
- debug(`Data for test id ${testId}:\n${testData}`);
192
- return testData || '';
241
+ const testDataAsText = fs.readFileSync(filepath, 'utf-8');
242
+ if (testDataAsText) debug(`"${this.dataType}" data for test id ${testId}:`, testDataAsText);
243
+ const testDataArr = testDataAsText?.split(os.EOL) || [];
244
+ return testDataArr;
193
245
  }
194
- debug(`No ${this.dataType} data for test id ${testId} in <file> storage`);
195
- return '';
246
+ // debug(`No ${this.dataType} data for test id ${testId} in <file> storage`);
247
+ return [];
196
248
  } catch (e) {
197
249
  // there could be no data, ignore
198
250
  }
199
- return '';
251
+ return [];
200
252
  }
201
253
 
254
+ /**
255
+ * Puts data to global variable. Unlike the file storage, stores data in array (file storage just append as string).
256
+ * @param {*} data
257
+ * @param {*} testId
258
+ */
202
259
  #putDataToGlobalVar(data, testId) {
203
- debug('Saving data to global variable for test', testId, ':\n', data, '\n');
260
+ debug(`Saving data to global variable for test ${testId}:`, data);
204
261
  if (!global.testomatioDataStore) global.testomatioDataStore = {};
205
262
  if (!global.testomatioDataStore?.[this.dataType]) global.testomatioDataStore[this.dataType] = {};
206
- global.testomatioDataStore?.[this.dataType][testId] // eslint-disable-line no-unused-expressions
207
- ? (global.testomatioDataStore[this.dataType][testId] += `\n${data}`)
208
- : (global.testomatioDataStore[this.dataType][testId] = data);
263
+
264
+ if (!global.testomatioDataStore?.[this.dataType][testId]) global.testomatioDataStore[this.dataType][testId] = [];
265
+ global.testomatioDataStore[this.dataType][testId].push(data);
209
266
  }
210
267
 
211
268
  #putDataToFile(data, testId) {
@@ -215,18 +272,36 @@ class DataStorage {
215
272
  if (!fs.existsSync(this.dataDirPath)) fileSystem.createDir(this.dataDirPath);
216
273
  debug('Saving data to file for test', testId, 'to', filepath, ':\n', data, '\n');
217
274
 
218
- // TODO: handle multiple invocations of JSON.stringify.
219
- // UPD: not actual because decided not to use it - it created extra wrapping quotes "" and // (escaped slashes)
220
- fs.appendFileSync(filepath, data + os.EOL, 'utf-8');
275
+ // append new line if file already exists (in this case its definitely includes some data)
276
+ if (fs.existsSync(filepath)) {
277
+ fs.appendFileSync(filepath, os.EOL + data, 'utf-8');
278
+ } else {
279
+ fs.writeFileSync(filepath, data, 'utf-8');
280
+ }
221
281
  }
222
282
  }
223
283
 
224
- module.exports.DataStorage = DataStorage;
284
+ module.exports = DataStorage;
225
285
 
226
286
  // TODO: consider using fs promises instead of writeSync/appendFileSync to
227
287
  // prevent blocking and improve performance (probably queue usage will be required)
228
288
 
229
289
  // TODO: rewrite client - everything regarding storing artifacts
230
290
  // TODO: try to define adapter inside client
231
- // TODO: use .env
232
291
  // TODO: ability to intercept multiple loggers (upd: no need)
292
+
293
+ /* does not work for Playwright
294
+ try {
295
+ const { test } = require('@playwright/test');
296
+ test.beforeEach(async ({}, testInfo) => {
297
+ global.testTitle = testInfo.title;
298
+ global.testomatioRunningEnvironment = 'playwright';
299
+ });
300
+ } catch (e) {
301
+ // ignore
302
+ }
303
+ // Playwright storage works fine only when running tests from a single file;
304
+ // otherwise it is not possible to define test id/title, it is overwritten
305
+ TODO: the only way implementation for Pw for now is to pass testInfo inside test
306
+ // (and process this testInfo inside "put" function)
307
+ */
@@ -0,0 +1,58 @@
1
+ const debug = require('debug')('@testomatio/reporter:key-value-storage');
2
+ const DataStorage = require('./data-storage');
3
+
4
+ class KeyValueStorage {
5
+ constructor() {
6
+ this.dataStorage = new DataStorage('keyvalue');
7
+
8
+ // singleton
9
+ if (!KeyValueStorage.instance) {
10
+ KeyValueStorage.instance = this;
11
+ }
12
+ }
13
+
14
+ /**
15
+ * Stores key-value pair and passes it to reporter
16
+ * @param {{key: string}} keyValue - key-value pair(s) as object
17
+ * @param {*} context testId or test title
18
+ */
19
+ put(keyValue, context = null) {
20
+ if (!keyValue) return;
21
+ this.dataStorage.putData(keyValue, context);
22
+ }
23
+
24
+ #isKeyValueObject(smth) {
25
+ return smth && typeof smth === 'object' && !Array.isArray(smth) && smth !== null;
26
+ }
27
+
28
+ /**
29
+ * Returns key-values pairs for the test as object
30
+ * @param {*} context testId or test context from test runner
31
+ * @returns {Object} key-values pairs as object
32
+ */
33
+ get(context) {
34
+ if (!context) return null;
35
+
36
+ const keyValuesList = this.dataStorage.getData(context);
37
+ if (!keyValuesList || !keyValuesList?.length) return null;
38
+
39
+ const keyValues = {};
40
+ for (const keyValue of keyValuesList) {
41
+ if (this.#isKeyValueObject(keyValue)) {
42
+ Object.assign(keyValues, keyValue);
43
+ } else if (typeof keyValue === 'string') {
44
+ try {
45
+ Object.assign(keyValues, JSON.parse(keyValue));
46
+ } catch (e) {
47
+ debug(`Error parsing key-values for test ${context}`, keyValue);
48
+ }
49
+ }
50
+ }
51
+
52
+ return Object.keys(keyValues).length ? keyValues : null;
53
+ }
54
+ }
55
+
56
+ KeyValueStorage.instance = null;
57
+
58
+ module.exports = new KeyValueStorage();
@@ -1,6 +1,6 @@
1
1
  const chalk = require('chalk');
2
2
  const debug = require('debug')('@testomatio/reporter:logger');
3
- const { DataStorage } = require('./dataStorage');
3
+ const DataStorage = require('./data-storage');
4
4
 
5
5
  const LOG_METHODS = ['assert', 'debug', 'error', 'info', 'log', 'trace', 'warn'];
6
6
  const LEVELS = {
@@ -38,20 +38,6 @@ class Logger {
38
38
  if (!Logger.instance) {
39
39
  Logger.instance = this;
40
40
  }
41
-
42
- // add beforeEach hook for mocha. it does not override existing hook, just add new one
43
- try {
44
- // @ts-ignore
45
- if (!beforeEach) return;
46
- // @ts-ignore-next-line
47
- beforeEach(function () {
48
- if (this.currentTest?.__mocha_id__) {
49
- global.testTitle = this.currentTest.fullTitle();
50
- }
51
- });
52
- } catch (e) {
53
- // ignore
54
- }
55
41
  }
56
42
 
57
43
  /**
@@ -61,9 +47,6 @@ class Logger {
61
47
  * @param {...any} values
62
48
  */
63
49
  step(strings, ...values) {
64
- // get testId for mocha
65
- const context = global.testTitle ?? null;
66
-
67
50
  let logs = '';
68
51
  for (let i = 0; i < strings.length; i++) {
69
52
  logs += strings[i];
@@ -72,7 +55,7 @@ class Logger {
72
55
  }
73
56
  }
74
57
  logs = chalk.blue(`> ${logs}`);
75
- this.#dataStorage.putData(logs, context);
58
+ this.#dataStorage.putData(logs);
76
59
  }
77
60
 
78
61
  /**
@@ -117,11 +100,6 @@ class Logger {
117
100
  templateLiteralLog(strings, ...args) {
118
101
  if (Array.isArray(strings)) strings = strings.filter(item => item !== '').map(item => item.trim());
119
102
  if (Array.isArray(args)) args = args.filter(item => item !== '');
120
- // entity which is used to define testId
121
- let context = null;
122
-
123
- // get testId for mocha
124
- context = global.testTitle ?? null;
125
103
 
126
104
  let logs;
127
105
  // this block means tagged template is used (syntax like $`text ${someVar}`)
@@ -146,7 +124,7 @@ class Logger {
146
124
  logs = this.#stringifyLogs(strings, ...args);
147
125
  }
148
126
  this.#originalUserLogger.log(logs);
149
- this.#dataStorage.putData(logs, context);
127
+ this.#dataStorage.putData(logs);
150
128
  }
151
129
 
152
130
  /**
@@ -158,18 +136,12 @@ class Logger {
158
136
  #logWrapper(argsArray, level) {
159
137
  if (!argsArray.length) return;
160
138
 
161
- // entity which is used to define testId
162
- let context = null;
163
-
164
- // get context for mocha
165
- context = global.testTitle ?? null;
166
-
167
139
  const severity = LEVELS[level].severity;
168
140
  if (severity < LEVELS[this.logLevel]?.severity) return;
169
141
 
170
142
  const logs = this.#stringifyLogs(...argsArray);
171
143
  const colorizedLogs = chalk[LEVELS[level].color](logs);
172
- this.#dataStorage.putData(colorizedLogs, context);
144
+ this.#dataStorage.putData(colorizedLogs);
173
145
  try {
174
146
  // level.toLowerCase() represents method name (log, warn, error, etc)
175
147
  this.#originalUserLogger[level.toLowerCase()](colorizedLogs);
@@ -269,7 +241,6 @@ class Logger {
269
241
 
270
242
  Logger.instance = null;
271
243
 
272
- // module.exports.Logger = Logger;
273
244
  const logger = new Logger();
274
245
 
275
246
  module.exports = logger;
@@ -290,6 +290,19 @@ function removeColorCodes(input) {
290
290
  return input.replace(/\x1b\[[0-9;]*m/g, '');
291
291
  }
292
292
 
293
+ const jestHelpers = {
294
+ getIdOfCurrentlyRunningTest: () => {
295
+ if (!process.env.JEST_WORKER_ID) return null;
296
+ try {
297
+ // @ts-expect-error "expect" could only be defined inside Jest environement (forbidden to import it outside)
298
+ // eslint-disable-next-line no-undef
299
+ if (expect && expect?.getState()?.currentTestName) return parseTest(expect?.getState()?.currentTestName);
300
+ } catch (e) {
301
+ return null;
302
+ }
303
+ },
304
+ };
305
+
293
306
  module.exports = {
294
307
  isSameTest,
295
308
  fetchSourceCode,
@@ -299,6 +312,7 @@ module.exports = {
299
312
  fetchFilesFromStackTrace,
300
313
  fileSystem,
301
314
  getCurrentDateTime,
315
+ jestHelpers,
302
316
  specificTestInfo,
303
317
  isValidUrl,
304
318
  ansiRegExp,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@testomatio/reporter",
3
- "version": "1.0.17",
3
+ "version": "1.1.0-beta-2",
4
4
  "description": "Testomatio Reporter Client",
5
5
  "main": "./lib/reporter.js",
6
6
  "typings": "typings/index.d.ts",