@amanat-qa/utils-frontend 1.0.0

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.
package/package.json ADDED
@@ -0,0 +1,37 @@
1
+ {
2
+ "name": "@amanat-qa/utils-frontend",
3
+ "version": "1.0.0",
4
+ "publishConfig": {
5
+ "access": "public"
6
+ },
7
+ "type": "commonjs",
8
+ "files": [
9
+ "src"
10
+ ],
11
+ "keywords": [],
12
+ "license": "MIT",
13
+ "exports": {
14
+ ".": "./src/index.js",
15
+ "./baseAPI": "./src/API/baseAPI.js",
16
+ "./baseDB": "./src/DB/baseDB.js",
17
+ "./JSONLoader": "./src/data/JSONLoader.js",
18
+ "./dataUtils": "./src/data/dataUtils.js",
19
+ "./filesParser": "./src/data/filesParser.js",
20
+ "./gitlabCIGenerator": "./src/data/gitlabCIGenerator.js",
21
+ "./index": "./src/index.js",
22
+ "./logger": "./src/log/logger.js",
23
+ "./randomizer": "./src/random/randomizer.js",
24
+ "./strUtils": "./src/str/strUtils.js",
25
+ "./timeUtils": "./src/time/timeUtils.js"
26
+ },
27
+ "dependencies": {
28
+ "axios": "*",
29
+ "mysql2": "*",
30
+ "moment": "*",
31
+ "xml2js": "*",
32
+ "fs": "*",
33
+ "path": "*",
34
+ "dotenv": "*",
35
+ "js-yaml": "*"
36
+ }
37
+ }
@@ -0,0 +1,76 @@
1
+ const axios = require('axios');
2
+
3
+ class BaseAPI {
4
+ #baseURL;
5
+
6
+ #logString;
7
+
8
+ #timeout;
9
+
10
+ #headers;
11
+
12
+ #logBaseURL;
13
+
14
+ #axiosInstance;
15
+
16
+ constructor(options) {
17
+ this.#baseURL = options.baseURL;
18
+ this.#logString = options.logString;
19
+ this.#timeout = options.timeout;
20
+ this.#headers = options.headers;
21
+ this.#axiosInstance = this.createInstance();
22
+ }
23
+
24
+ createInstance() {
25
+ if (this.#logString) this.#logBaseURL = `${this.#logString} ${this.#baseURL}`;
26
+ return axios.create({
27
+ baseURL: this.#baseURL,
28
+ timeout: this.#timeout,
29
+ headers: this.#headers,
30
+ });
31
+ }
32
+
33
+ async get(endpoint, params) {
34
+ const logs = [`[req] ▶ get ${JSON.stringify(params || {})} from ${endpoint}:`];
35
+ if (this.#logBaseURL) logs.unshift(this.#logBaseURL);
36
+ try {
37
+ const response = await this.#axiosInstance.get(`/${endpoint}`, { params });
38
+ logs.push(`[res] status code: ${response.status}`);
39
+ return { data: response.data, status: response.status, logs };
40
+ } catch (error) {
41
+ logs.push(`[res] status code: ${error.response.status}`);
42
+ logs.push(`[res] body: ${JSON.stringify(error.response.data)}`);
43
+ return { data: error.response.data, status: error.response.status, logs };
44
+ }
45
+ }
46
+
47
+ async post(endpoint, params) {
48
+ const logs = [`[req] ▶ post ${JSON.stringify(params || {})} to ${endpoint}:`];
49
+ if (this.#logBaseURL) logs.unshift(this.#logBaseURL);
50
+ try {
51
+ const response = await this.#axiosInstance.post(`/${endpoint}`, params);
52
+ logs.push(`[res] status code: ${response.status}`);
53
+ return { data: response.data, status: response.status, logs };
54
+ } catch (error) {
55
+ logs.push(`[res] status code: ${error.response.status}`);
56
+ logs.push(`[res] body: ${JSON.stringify(error.response.data)}`);
57
+ return { data: error.response.data, status: error.response.status, logs };
58
+ }
59
+ }
60
+
61
+ async patch(endpoint, params) {
62
+ const logs = [`[req] ▶ patch ${JSON.stringify(params || {})} to ${endpoint}:`];
63
+ if (this.#logBaseURL) logs.unshift(this.#logBaseURL);
64
+ try {
65
+ const response = await this.#axiosInstance.patch(`/${endpoint}`, params);
66
+ logs.push(`[res] status code: ${response.status}`);
67
+ return { data: response.data, status: response.status, logs };
68
+ } catch (error) {
69
+ logs.push(`[res] status code: ${error.response.status}`);
70
+ logs.push(`[res] body: ${JSON.stringify(error.response.data)}`);
71
+ return { data: error.response.data, status: error.response.status, logs };
72
+ }
73
+ }
74
+ }
75
+
76
+ module.exports = BaseAPI;
@@ -0,0 +1,62 @@
1
+ const mysql = require('mysql2/promise');
2
+
3
+ class BaseDB {
4
+ #host;
5
+
6
+ #user;
7
+
8
+ #port;
9
+
10
+ #password;
11
+
12
+ #database;
13
+
14
+ #connection;
15
+
16
+ constructor(host, user, password, database, port) {
17
+ this.#host = host;
18
+ this.#user = user;
19
+ this.#password = password;
20
+ this.#database = database;
21
+ this.#port = port;
22
+ }
23
+
24
+ async createConnection() {
25
+ const logs = [`[inf] ▶ connect to ${this.#database} database`];
26
+ this.#connection = await mysql.createConnection({
27
+ host: this.#host,
28
+ user: this.#user,
29
+ password: this.#password,
30
+ database: this.#database,
31
+ port: this.#port,
32
+ });
33
+ return { logs };
34
+ }
35
+
36
+ async closeConnection() {
37
+ const logs = [`[inf] ▶ close connection to ${this.#database} database`];
38
+ await this.#connection.end();
39
+ return { logs };
40
+ }
41
+
42
+ async sqlQuery(query, values) {
43
+ const [rows] = await this.#connection.query(query, values);
44
+ return rows;
45
+ }
46
+
47
+ async sqlSelect(
48
+ tableName,
49
+ target = '*',
50
+ conditions = '',
51
+ values = [],
52
+ options = { hasLogger: true },
53
+ ) {
54
+ const logs = [];
55
+ if (options.hasLogger) logs.push(`[inf] ▶ select ${target} from ${tableName} table`);
56
+ const query = `SELECT ${target} FROM ${tableName} ${conditions};`;
57
+ const rows = await this.sqlQuery(query, values);
58
+ return { rows, logs };
59
+ }
60
+ }
61
+
62
+ module.exports = BaseDB;
@@ -0,0 +1,8 @@
1
+ let JSONLoader;
2
+ try {
3
+ JSONLoader = require('../../../../../test/main/utils/data/JSONLoader');
4
+ } catch (e) {
5
+ throw new Error('[err] JSONLoader require error!');
6
+ }
7
+
8
+ module.exports = JSONLoader;
@@ -0,0 +1,317 @@
1
+ const moment = require('moment');
2
+ const { parseStringPromise } = require('xml2js');
3
+ const JSONLoader = require('./JSONLoader');
4
+ const StrUtils = require('../str/strUtils');
5
+ const TimeUtils = require('../time/timeUtils');
6
+ const Randomizer = require('../random/randomizer');
7
+
8
+ class DataUtils {
9
+ static async XMLToJSON(xml) {
10
+ return (await parseStringPromise(xml)).response;
11
+ }
12
+
13
+ static getFromRequests(url1, alias1, url2, alias2) {
14
+ cy.intercept(url1).as(alias1);
15
+ cy.intercept(url2).as(alias2);
16
+ return cy.wait([`@${alias1}`, `@${alias2}`]).then(([interception1, interception2]) => [interception1.response.body, interception2.response.body]);
17
+ }
18
+
19
+ static interceptPolicyList({
20
+ url,
21
+ sortColumn,
22
+ sortValue,
23
+ searchColumn,
24
+ searchValue,
25
+ page,
26
+ perPage,
27
+ alias,
28
+ raw = false,
29
+ } = {}) {
30
+ if (raw) {
31
+ cy.intercept('GET', url).as(alias);
32
+ return;
33
+ }
34
+
35
+ const query = {};
36
+
37
+ if (sortColumn) query['sort[column]'] = sortColumn;
38
+ if (sortValue) query['sort[value]'] = sortValue;
39
+
40
+ if (searchColumn && searchValue) {
41
+ query['search[column]'] = searchColumn;
42
+ query['search[value]'] = searchValue;
43
+ }
44
+
45
+ if (page) query.page = String(page);
46
+ if (perPage) query.per_page = String(perPage);
47
+
48
+ cy.intercept({
49
+ method: 'GET',
50
+ url,
51
+ query,
52
+ }).as(alias);
53
+ }
54
+
55
+ static extractDataArray(interception) {
56
+ return interception.response.body.data || [];
57
+ }
58
+
59
+ static isSorted(arr, order = 'asc') {
60
+ const sorted = [...arr].sort((a, b) => (order === 'asc' ? a - b : b - a));
61
+ return JSON.stringify(arr) === JSON.stringify(sorted);
62
+ }
63
+
64
+ static waitForPolicyList(alias, path) {
65
+ return cy.wait(`@${alias}`).then((interception) => {
66
+ const parts = ['response', 'body', ...path.split('.')];
67
+ const result = parts.reduce((acc, key) => (acc && typeof acc === 'object' ? acc[key] : {}), interception);
68
+ return result;
69
+ });
70
+ }
71
+
72
+ static getFromRequest(url, alias) {
73
+ cy.intercept(url).as(alias);
74
+ return cy.wait(`@${alias}`).then((interception) => interception.response.body);
75
+ }
76
+
77
+ /**
78
+ * requires one mandatory argument: clients.
79
+ * options contain optional parameters:
80
+ * residency,
81
+ * type of document being passport,
82
+ * having driver license
83
+ * and being under 60 years old:
84
+ * @param {string[]} clients
85
+ * @param {Object} options
86
+ * @param {boolean} options.isResident
87
+ * @param {boolean} options.hasPassport
88
+ * @param {boolean} options.hasDriverLicence
89
+ * @param {boolean} options.isUnderSixtyYearsOld
90
+ */
91
+ static filterClients(clients, options = {}) {
92
+ const { isResident } = options;
93
+ const { hasPassport } = options;
94
+ const { hasDriverLicence } = options;
95
+ const { isUnderSixtyYearsOld } = options;
96
+ const { isJuridical } = options;
97
+ let filteredClients = [...clients];
98
+
99
+ filteredClients = filteredClients.filter((client) => {
100
+ if (isResident !== undefined) {
101
+ return isResident ? client.resident_bool : !client.resident_bool;
102
+ }
103
+
104
+ return true;
105
+ });
106
+
107
+ filteredClients = filteredClients.filter((client) => {
108
+ if (hasDriverLicence !== undefined) {
109
+ return hasDriverLicence ? client.driving_license : !client.driving_license;
110
+ }
111
+
112
+ return true;
113
+ });
114
+
115
+ filteredClients = filteredClients.filter((client) => {
116
+ if (hasPassport !== undefined) {
117
+ const hasLetter = /[a-zA-Z]/.test(client.document_number);
118
+ return hasPassport
119
+ ? client.document_type_id === 11 && hasLetter
120
+ : client.document_type_id !== 11;
121
+ }
122
+
123
+ return true;
124
+ });
125
+
126
+ filteredClients = filteredClients.filter((client) => {
127
+ if (isUnderSixtyYearsOld !== undefined) {
128
+ return isUnderSixtyYearsOld
129
+ ? moment(client.born) > moment().subtract(60, 'years')
130
+ : moment(client.born) <= moment().subtract(60, 'years');
131
+ }
132
+
133
+ return true;
134
+ });
135
+
136
+ filteredClients = filteredClients.filter((client) => {
137
+ if (isJuridical !== undefined) {
138
+ return isJuridical ? !client.natural_person_bool : client.natural_person_bool;
139
+ }
140
+
141
+ return true;
142
+ });
143
+
144
+ return filteredClients;
145
+ }
146
+
147
+ static createRandomCarStructure(carsArr) {
148
+ const randomCarIndex = Randomizer.getRandomInteger(carsArr.length - 1);
149
+ const tempCar = carsArr[randomCarIndex];
150
+ const resultCar = { ...tempCar };
151
+
152
+ resultCar.dt_reg_cert = {};
153
+ resultCar.dt_reg_cert.YMD = tempCar.dt_reg_cert;
154
+ resultCar.dt_reg_cert.DMY = TimeUtils.reformatDateFromYMDToDMY(tempCar.dt_reg_cert);
155
+
156
+ resultCar.year = tempCar.year.toString();
157
+ resultCar.engine_volume = tempCar.engine_volume.toString();
158
+
159
+ resultCar.model = {};
160
+ resultCar.model.OGPO = tempCar.model;
161
+ resultCar.model.KASKO = {};
162
+ resultCar.model.KASKO.get = tempCar.model;
163
+ resultCar.model.KASKO.set = tempCar.id !== 1
164
+ ? StrUtils.toTitleCase(tempCar.model)
165
+ : '5 серия';
166
+
167
+ resultCar.mark = {};
168
+ resultCar.mark.OGPO = tempCar.mark;
169
+ resultCar.mark.KASKO = {};
170
+ resultCar.mark.KASKO.get = tempCar.mark;
171
+ resultCar.mark.KASKO.set = tempCar.id !== 1 ? StrUtils.toTitleCase(tempCar.mark) : tempCar.mark;
172
+
173
+ resultCar.region_id = JSONLoader.testData.carRegion;
174
+ resultCar.type_id = JSONLoader.testData.carType;
175
+
176
+ return resultCar;
177
+ }
178
+
179
+ static createRandomClientsStructures(clientsArr) {
180
+ let randomHolderIndex = 0;
181
+ let randomInsuredIndex = 0;
182
+ let randomBeneficiaryIndex = 0;
183
+
184
+ if (clientsArr.length > 1) {
185
+ randomHolderIndex = Randomizer.getRandomInteger(clientsArr.length - 1);
186
+
187
+ do {
188
+ randomInsuredIndex = Randomizer.getRandomInteger(clientsArr.length - 1);
189
+ } while (randomInsuredIndex === randomHolderIndex);
190
+
191
+ do {
192
+ randomBeneficiaryIndex = Randomizer.getRandomInteger(clientsArr.length - 1);
193
+ } while (randomBeneficiaryIndex === randomHolderIndex
194
+ || randomBeneficiaryIndex === randomInsuredIndex);
195
+ }
196
+
197
+ const tempHolder = clientsArr[randomHolderIndex];
198
+ const tempInsured = clientsArr[randomInsuredIndex];
199
+ const tempBeneficiary = clientsArr[randomBeneficiaryIndex];
200
+
201
+ const resultHolder = { ...tempHolder };
202
+ const resultInsured = { ...tempInsured };
203
+ const resultBeneficiary = { ...tempBeneficiary };
204
+
205
+ resultHolder.document_gived_date = {};
206
+ resultHolder.document_gived_date.YMD = tempHolder.document_gived_date;
207
+ resultHolder.document_gived_date.DMY = TimeUtils
208
+ .reformatDateFromYMDToDMY(tempHolder.document_gived_date);
209
+ resultHolder.born = {};
210
+ resultHolder.born.YMD = tempHolder.born;
211
+ resultHolder.born.DMY = TimeUtils.reformatDateFromYMDToDMY(tempHolder.born);
212
+ resultHolder.date_issue_license = {};
213
+ resultHolder.date_issue_license.YMD = tempHolder.date_issue_license;
214
+ resultHolder.date_issue_license.DMY = TimeUtils
215
+ .reformatDateFromYMDToDMY(tempHolder.date_issue_license);
216
+
217
+ resultHolder.iin = tempHolder.iin.toString();
218
+ resultHolder.document_type = JSONLoader
219
+ .dictDocumentType[tempHolder.document_type_id.toString()];
220
+
221
+ resultHolder.sex = JSONLoader.dictSexID[tempHolder.sex_id];
222
+ resultHolder.address = JSONLoader.testData.holderAddress;
223
+ resultHolder.email = JSONLoader.testData.holderEmail;
224
+ resultHolder.document_gived_by = JSONLoader.testData.holderDocumentGivedBy;
225
+ resultHolder.document_gived_by_quote = JSONLoader.testData.holderDocumentGivedByQuote;
226
+ resultHolder.pdl = JSONLoader.testData.holderIsPDL;
227
+ resultHolder.driver_certificate_type_id = JSONLoader.testData.holderDriverLicenceType;
228
+ resultHolder.invalid_bool = JSONLoader.testData.holderIsInvalid;
229
+ resultHolder.pensioner_bool = JSONLoader.testData.holderIsPensioner;
230
+ resultHolder.country = JSONLoader.testData.holderCountry;
231
+ resultHolder.region = JSONLoader.testData.holderRegion;
232
+ resultHolder.phone = JSONLoader.testData.holderPhone;
233
+ resultHolder.phoneTrimmed = JSONLoader.testData.holderPhoneTrimmed;
234
+ resultHolder.phoneFormatted = JSONLoader.testData.holderPhoneFormatted;
235
+
236
+ resultInsured.document_gived_date = {};
237
+ resultInsured.document_gived_date.YMD = tempInsured.document_gived_date;
238
+ resultInsured.document_gived_date.DMY = TimeUtils
239
+ .reformatDateFromYMDToDMY(tempInsured.document_gived_date);
240
+ resultInsured.born = {};
241
+ resultInsured.born.YMD = tempInsured.born;
242
+ resultInsured.born.DMY = TimeUtils.reformatDateFromYMDToDMY(tempInsured.born);
243
+ resultInsured.date_issue_license = {};
244
+ resultInsured.date_issue_license.YMD = tempInsured.date_issue_license;
245
+ resultInsured.date_issue_license.DMY = TimeUtils
246
+ .reformatDateFromYMDToDMY(tempInsured.date_issue_license);
247
+
248
+ resultInsured.iin = tempInsured.iin.toString();
249
+ resultInsured.document_type = JSONLoader
250
+ .dictDocumentType[tempInsured.document_type_id.toString()];
251
+
252
+ resultInsured.sex = JSONLoader.dictSexID[tempInsured.sex_id];
253
+ resultInsured.address = JSONLoader.testData.insuredAddress;
254
+ resultInsured.email = JSONLoader.testData.insuredEmail;
255
+ resultInsured.document_gived_by = JSONLoader.testData.insuredDocumentGivedBy;
256
+ resultInsured.pdl = JSONLoader.testData.insuredIsPDL;
257
+ resultInsured.driver_certificate_type_id = JSONLoader.testData.insuredDriverLicenceType;
258
+ resultInsured.invalid_bool = JSONLoader.testData.insuredIsInvalid;
259
+ resultInsured.pensioner_bool = JSONLoader.testData.insuredIsPensioner;
260
+
261
+ resultBeneficiary.document_gived_date = {};
262
+ resultBeneficiary.document_gived_date.YMD = tempBeneficiary.document_gived_date;
263
+ resultBeneficiary.document_gived_date.DMY = TimeUtils
264
+ .reformatDateFromYMDToDMY(tempBeneficiary.document_gived_date);
265
+ resultBeneficiary.born = {};
266
+ resultBeneficiary.born.YMD = tempBeneficiary.born;
267
+ resultBeneficiary.born.DMY = TimeUtils.reformatDateFromYMDToDMY(tempBeneficiary.born);
268
+ resultBeneficiary.date_issue_license = {};
269
+ resultBeneficiary.date_issue_license.YMD = tempBeneficiary.date_issue_license;
270
+ resultBeneficiary.date_issue_license.DMY = TimeUtils
271
+ .reformatDateFromYMDToDMY(tempBeneficiary.date_issue_license);
272
+
273
+ resultBeneficiary.iin = tempBeneficiary.iin.toString();
274
+ resultBeneficiary.document_type = JSONLoader
275
+ .dictDocumentType[tempBeneficiary.document_type_id.toString()];
276
+ resultBeneficiary.sex = JSONLoader.dictSexID[tempBeneficiary.sex_id];
277
+ resultBeneficiary.address = JSONLoader.testData.beneficiaryAddress;
278
+ resultBeneficiary.email = JSONLoader.testData.beneficiaryEmail;
279
+ resultBeneficiary.document_gived_by = JSONLoader.testData.beneficiaryDocumentGivedBy;
280
+ resultBeneficiary.document_gived_by_quote = JSONLoader.testData.beneficiaryDocumentGivedByQuote;
281
+ resultBeneficiary.pdl = JSONLoader.testData.beneficiaryIsPDL;
282
+ resultBeneficiary.driver_certificate_type_id = JSONLoader.testData.beneficiaryDriverLicenceType;
283
+ resultBeneficiary.invalid_bool = JSONLoader.testData.beneficiaryIsInvalid;
284
+ resultBeneficiary.pensioner_bool = JSONLoader.testData.beneficiaryIsPensioner;
285
+
286
+ return { holder: resultHolder, insured: resultInsured, beneficiary: resultBeneficiary };
287
+ }
288
+
289
+ static prepareSetClientRequestBody(getClientResponse, client) {
290
+ const requestBody = { ...getClientResponse.data.data };
291
+ requestBody.first_name = client.first_name;
292
+ requestBody.middle_name = client.middle_name;
293
+ requestBody.last_name = client.last_name;
294
+ requestBody.first_name_eng = client.first_name_eng;
295
+ requestBody.last_name_eng = client.last_name_eng;
296
+ requestBody.natural_person_bool = client.natural_person_bool;
297
+ requestBody.sex_id = client.sex_id;
298
+ requestBody.born = requestBody.natural_person_bool ? client.born.DMY : null;
299
+ requestBody.resident_bool = client.resident_bool;
300
+ requestBody.document_number = client.document_number;
301
+ requestBody.document_gived_date = client.document_gived_date.DMY;
302
+ requestBody.document_type_id = client.document_type_id;
303
+ requestBody.verify_bool = requestBody.natural_person_bool
304
+ ? Number(JSONLoader.configData.verification) : 0;
305
+ requestBody.verify_type_id = requestBody.verify_bool ? 1 : 3;
306
+ requestBody.activity_kind_id = requestBody.natural_person_bool
307
+ ? 250 : client.activity_kind_id;
308
+ requestBody.economics_sector_id = requestBody.natural_person_bool
309
+ ? 10 : client.economics_sector_id;
310
+ requestBody.juridical_person_name = requestBody.natural_person_bool
311
+ ? '' : client.juridical_person_name;
312
+
313
+ return requestBody;
314
+ }
315
+ }
316
+
317
+ module.exports = DataUtils;
@@ -0,0 +1,107 @@
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+ require('dotenv').config({ path: path.join(__dirname, '../../../../../', '.env.test'), override: true });
4
+
5
+ const envDirectory = path.join(__dirname, '../../../../../');
6
+ const loaderFileLocation = path.join(__dirname, 'JSONLoader.js');
7
+ const testClientsFileLocation = path.join(envDirectory, './test/resources/data/testClients.json');
8
+ const testCarsFileLocation = path.join(envDirectory, './test/resources/data/testCars.json');
9
+ const JSONDirectory = path.join(envDirectory, './test/resources');
10
+ const suitesDirectory = path.join(envDirectory, './test/tests/suites');
11
+ const jsonExtension = '.json';
12
+ const testExtension = '.test';
13
+ const testSuitePattern = 'Suite.js';
14
+
15
+ const getFiles = (directory, extension) => {
16
+ const allFiles = fs.readdirSync(directory);
17
+ const selectedFiles = allFiles.filter((file) => file.endsWith(extension));
18
+ allFiles.forEach((file) => {
19
+ const fullPath = path.join(directory, file);
20
+ if (fs.statSync(fullPath).isDirectory()) {
21
+ const nestedFiles = getFiles(fullPath, extension);
22
+ selectedFiles.push(...nestedFiles.map((nestedFile) => path.join(file, nestedFile)));
23
+ }
24
+ });
25
+
26
+ return selectedFiles;
27
+ };
28
+
29
+ const generateClassInit = (selectedFiles, directory) => `class JSONLoader {\n${selectedFiles.map((file) => {
30
+ const variableName = path.parse(file).name;
31
+ return `\tstatic get ${variableName}() {\n\t\tconst ${variableName} = require('${path.join(directory, file)}');\n\t\treturn JSON.parse(JSON.stringify(${variableName}));\n\t}\n\n`;
32
+ }).join('')}`;
33
+
34
+ const generateTestSuitesNames = (selectedFiles) => {
35
+ const suiteNames = selectedFiles
36
+ .map((file) => file.replace(testSuitePattern, ''))
37
+ .map((name) => `'${name}'`)
38
+ .join(', ');
39
+ return `\tstatic get testSuitesNames() {\n\t\treturn [${suiteNames}];\n\t}\n\n`;
40
+ };
41
+
42
+ const generateJSONLoader = (filePath, directory) => {
43
+ const jsonFiles = getFiles(directory, jsonExtension);
44
+ const testSuites = getFiles(suitesDirectory, testSuitePattern);
45
+ const classInit = generateClassInit(jsonFiles, directory);
46
+ const suitesNames = generateTestSuitesNames(testSuites);
47
+ const classExport = '}\n\nmodule.exports = JSONLoader;';
48
+ fs.writeFileSync(filePath, classInit + suitesNames + classExport);
49
+ };
50
+
51
+ const setConfigData = (directory, extension) => {
52
+ const files = getFiles(directory, extension);
53
+ const configFile = files.filter((file) => file.includes('config')).pop();
54
+ if (configFile) {
55
+ const filePath = `${directory}/${configFile}`;
56
+ const data = JSON.parse(fs.readFileSync(filePath, 'utf8'));
57
+ data.parallel = process.argv.includes('--parallel');
58
+ data.setPolicyWaitingTWB = process.argv.includes('--setPolicyWaitingTWB');
59
+ try {
60
+ data.verification = Boolean(JSON.parse(process.env.VERIFICATION ?? data.verification));
61
+ } catch (error) { // eslint-disable-next-line no-console
62
+ console.log(' [err] incorrect value of "VERIFICATION" .env variable!');
63
+ }
64
+
65
+ try {
66
+ const value = JSON.parse(process.env.SET_POLICY_WAITING_TWB ?? data.setPolicyWaitingTWB);
67
+ data.setPolicyWaitingTWB = Boolean(value);
68
+ } catch (error) { // eslint-disable-next-line no-console
69
+ console.log(' [err] incorrect value of "SET_POLICY_WAITING_TWB" .env variable!');
70
+ }
71
+
72
+ try {
73
+ data.getPolicyTWB = Boolean(JSON.parse(process.env.GET_POLICY_TWB ?? data.getPolicyTWB));
74
+ } catch (error) { // eslint-disable-next-line no-console
75
+ console.log(' [err] incorrect value of "GET_POLICY_TWB" .env variable!');
76
+ }
77
+
78
+ if (process.env.GATEWAY_URL) {
79
+ const value = process.env.GATEWAY_URL.match(/\b(?:localhost|dev|staging)\b/g);
80
+ if (value) {
81
+ data.environment = value.pop();
82
+ } else { // eslint-disable-next-line no-console
83
+ console.log(' [err] incorrect value of "GATEWAY_URL" .env variable!');
84
+ }
85
+ } else { // eslint-disable-next-line no-console
86
+ console.log(' [err] "GATEWAY_URL" .env variable not exists!');
87
+ }
88
+
89
+ fs.writeFileSync(filePath, JSON.stringify(data, null, 2), 'utf8');
90
+ }
91
+ };
92
+
93
+ const checkEnvExists = (directory, extension) => {
94
+ const files = getFiles(directory, extension);
95
+ if (!files.length) throw new Error('[err] .env.test file not exists in root directory!');
96
+ };
97
+
98
+ const generateTestDataFile = (filePath) => {
99
+ const emptyObj = {};
100
+ if (!fs.existsSync(filePath)) fs.writeFileSync(filePath, JSON.stringify(emptyObj, null, 2), 'utf8');
101
+ };
102
+
103
+ checkEnvExists(envDirectory, testExtension);
104
+ setConfigData(JSONDirectory, jsonExtension);
105
+ generateTestDataFile(testCarsFileLocation);
106
+ generateTestDataFile(testClientsFileLocation);
107
+ generateJSONLoader(loaderFileLocation, JSONDirectory);
@@ -0,0 +1,62 @@
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+ const YAML = require('js-yaml');
4
+ const JSONLoader = require('./JSONLoader');
5
+
6
+ const testSuites = JSONLoader.testSuitesNames;
7
+ const jobs = testSuites.map((suite) => ({
8
+ [`e2e tests ${suite}`]: {
9
+ image: 'lines14/cypress-java-dind:latest',
10
+ stage: 'test',
11
+ variables: {
12
+ DOCKER_HOST: 'tcp://docker:2375',
13
+ DOCKER_TLS_CERTDIR: '',
14
+ DOCKER_DRIVER: 'overlay2',
15
+ DOCKER_DAEMON_TIMEOUT: 600,
16
+ },
17
+ only: [
18
+ 'dev',
19
+ ],
20
+ services: [
21
+ {
22
+ name: 'docker:dind',
23
+ command: ['--tls=false', '--host=tcp://0.0.0.0:2375'],
24
+ },
25
+ ],
26
+ needs: [],
27
+ tags: [
28
+ 'k8s',
29
+ ],
30
+ before_script: [
31
+ // eslint-disable-next-line no-template-curly-in-string
32
+ 'echo "${ADP_NUXT_TEST}" | tr -d \'\\r\' > ./.env.test',
33
+ 'docker login --username $USER --password $PASS registry.gitlab.com',
34
+ 'service docker start',
35
+ 'npm ci --prefix ./cypress',
36
+ 'npm run lint --prefix ./cypress',
37
+ ],
38
+ script: [
39
+ 'npm run start:ci --prefix ./cypress',
40
+ `file=${suite} npm run test --prefix ./cypress`,
41
+ ],
42
+ artifacts: {
43
+ when: 'always',
44
+ expire_in: '1 month',
45
+ paths: [
46
+ 'cypress/artifacts',
47
+ 'cypress/screenshots',
48
+ 'cypress/videos',
49
+ 'cypress/resources/data/configData.json',
50
+ 'cypress/resources/data/testClients.json',
51
+ 'cypress/resources/data/testCars.json',
52
+ ],
53
+ },
54
+ },
55
+ }));
56
+
57
+ const gitlabCIConfig = Object.assign({}, ...jobs);
58
+
59
+ fs.writeFileSync(
60
+ path.join(__dirname, '..', '..', '..', '..', '.split-config.yml'),
61
+ YAML.dump(gitlabCIConfig),
62
+ );
package/src/index.js ADDED
@@ -0,0 +1,13 @@
1
+ // Auto-generated file
2
+
3
+ exports.baseAPI = require('./API/baseAPI');
4
+ exports.baseDB = require('./DB/baseDB');
5
+ exports.JSONLoader = require('./data/JSONLoader');
6
+ exports.dataUtils = require('./data/dataUtils');
7
+ exports.filesParser = require('./data/filesParser');
8
+ exports.gitlabCIGenerator = require('./data/gitlabCIGenerator');
9
+ exports.index = require('./index');
10
+ exports.logger = require('./log/logger');
11
+ exports.randomizer = require('./random/randomizer');
12
+ exports.strUtils = require('./str/strUtils');
13
+ exports.timeUtils = require('./time/timeUtils');
@@ -0,0 +1,57 @@
1
+ const path = require('path');
2
+ const moment = require('moment');
3
+ const { createWriteStream } = require('fs');
4
+ const JSONLoader = require('../data/JSONLoader');
5
+
6
+ const filePath = path.join(path.resolve(), 'artifacts', 'log.txt');
7
+ const timeList = [];
8
+ const logList = [];
9
+
10
+ class Logger {
11
+ static #title;
12
+
13
+ static log(step, title) {
14
+ logList.push(` ${step}`);
15
+ const timeStamp = moment().format().slice(0, 19).replace('T', ' ');
16
+ timeList.push(`${timeStamp}`);
17
+ if (title) this.#title = title;
18
+ if (!JSONLoader.configData.parallel) {
19
+ const stream = createWriteStream(filePath, { flags: 'a', autoClose: true });
20
+ if (!title) stream.write(`${timeStamp} ${step}\n`);
21
+ this.hideLogBodies(step);
22
+ }
23
+
24
+ return timeStamp;
25
+ }
26
+
27
+ static hideLogBodies(step) {
28
+ if (JSONLoader.configData.hiddenLogBodies && step.includes('[req]')) {
29
+ const words = step.split(' ');
30
+ const firstPart = words.slice(0, 3).join(' ');
31
+ const secondPart = words.slice(words.length - 2).join(' ');
32
+ console.log(` ${firstPart} ${secondPart}`); // eslint-disable-line no-console
33
+ } else {
34
+ console.log(` ${step}`); // eslint-disable-line no-console
35
+ }
36
+ }
37
+
38
+ static logParallel() {
39
+ logList.forEach((step) => this.hideLogBodies(step.trim()));
40
+ }
41
+
42
+ static logToFileParallel() {
43
+ const zip = (a, b) => a.map((k, i) => [k, b[i]]);
44
+ const summaryList = zip(timeList, logList);
45
+ summaryList.shift();
46
+ const fileName = filePath.split('/')
47
+ .map((part, index, array) => (index === array.length - 1 ? `${this.#title}.${part}` : part))
48
+ .join('/');
49
+ const stream = createWriteStream(fileName, { flags: 'a', autoClose: true });
50
+ summaryList.forEach((logString) => logString.forEach((logSubString, index) => {
51
+ /* eslint no-unused-expressions: ["error", { "allowTernary": true }] */
52
+ index % 2 !== 0 ? stream.write(`${logSubString}\n`) : stream.write(`${logSubString}`);
53
+ }));
54
+ }
55
+ }
56
+
57
+ module.exports = Logger;
@@ -0,0 +1,148 @@
1
+ const moment = require('moment');
2
+ const JSONLoader = require('../data/JSONLoader');
3
+
4
+ class Randomizer {
5
+ static getRandomDatesIntervalFromTomorrow(count, unitOfTime) {
6
+ const nextDayObject = moment().add(1, 'days').startOf('day');
7
+ const unixOne = nextDayObject.unix();
8
+ const unixTwo = moment(moment().add(1, 'days').startOf('day')).add(count, unitOfTime).unix();
9
+
10
+ const startDateUnix = moment.unix(this.getRandomFloat(unixOne, unixTwo)).unix();
11
+ let finishDateUnix;
12
+ do {
13
+ finishDateUnix = moment.unix(this.getRandomFloat(startDateUnix, unixTwo)).unix();
14
+ } while ((finishDateUnix - startDateUnix) < 86400 * 2);
15
+
16
+ const startDateObject = moment.unix(startDateUnix).startOf('day');
17
+ const finishDateObject = moment.unix(finishDateUnix).startOf('day');
18
+ const startDate = startDateObject.format(JSONLoader.testData.datesFormatDMY);
19
+ const finishDate = finishDateObject.format(JSONLoader.testData.datesFormatDMY);
20
+
21
+ const daysDifferenceIncluded = finishDateObject.diff(startDateObject, 'days') + 1;
22
+
23
+ const getAbsoluteMonth = (date) => {
24
+ const months = Number(moment(date, JSONLoader.testData.datesFormatDMY).format('MM'));
25
+ const years = Number(moment(date, JSONLoader.testData.datesFormatDMY).format('YYYY'));
26
+ return months + (years * 12);
27
+ };
28
+
29
+ const currentMonth = getAbsoluteMonth(moment.unix(unixOne)
30
+ .format(JSONLoader.testData.datesFormatDMY));
31
+ const startMonth = getAbsoluteMonth(startDate);
32
+ const finishMonth = getAbsoluteMonth(finishDate);
33
+ let startMonthDifference = startMonth - currentMonth;
34
+ let finishMonthDifference = finishMonth - currentMonth;
35
+
36
+ if (nextDayObject.date() === 1) startMonthDifference += 1;
37
+ if (nextDayObject.date() === 1) finishMonthDifference += 1;
38
+
39
+ return {
40
+ startDate,
41
+ finishDate,
42
+ startMonthDifference,
43
+ finishMonthDifference,
44
+ daysDifferenceIncluded,
45
+ };
46
+ }
47
+
48
+ static getRandomString(
49
+ hasLowerCase = false,
50
+ hasUpperCase = false,
51
+ hasNumber = false,
52
+ hasCyrillic = false,
53
+ chosenLetter = false,
54
+ minLength = 1,
55
+ maxLength = 10,
56
+ ) {
57
+ const upperCaseLetters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
58
+ const lowerCaseLetters = 'abcdefghijklmnopqrstuvwxyz';
59
+ const numbers = '0123456789';
60
+ const cyrillicLetters = 'абвгдеёжзийклмнопрстуфхцчшщъыьэюя';
61
+
62
+ const length = this.getRandomInteger(maxLength, minLength);
63
+
64
+ let randomString = '';
65
+ if (chosenLetter) randomString += chosenLetter;
66
+
67
+ let requiredCharacters = '';
68
+ if (hasLowerCase) {
69
+ requiredCharacters
70
+ += lowerCaseLetters.charAt(Math.floor(Math.random() * lowerCaseLetters.length));
71
+ }
72
+
73
+ if (hasUpperCase) {
74
+ requiredCharacters
75
+ += upperCaseLetters.charAt(Math.floor(Math.random() * upperCaseLetters.length));
76
+ }
77
+
78
+ if (hasNumber) {
79
+ requiredCharacters
80
+ += numbers.charAt(Math.floor(Math.random() * numbers.length));
81
+ }
82
+
83
+ if (hasCyrillic) {
84
+ requiredCharacters
85
+ += cyrillicLetters.charAt(Math.floor(Math.random() * cyrillicLetters.length));
86
+ }
87
+
88
+ randomString += requiredCharacters;
89
+
90
+ const characters = (hasLowerCase ? lowerCaseLetters : '')
91
+ + (hasUpperCase ? upperCaseLetters : '')
92
+ + (hasNumber ? numbers : '')
93
+ + (hasCyrillic ? cyrillicLetters : '');
94
+ const charactersLength = characters.length;
95
+ const randomLength = length - randomString.length;
96
+
97
+ for (let i = 0; i < randomLength; i += 1) {
98
+ randomString += characters.charAt(Math.floor(Math.random() * charactersLength));
99
+ }
100
+
101
+ return this.stringShuffler(randomString);
102
+ }
103
+
104
+ static stringShuffler(inputString) {
105
+ const array = inputString.split('');
106
+ let currentIndex = array.length;
107
+ let temporaryValue;
108
+ let randomIndex;
109
+ while (currentIndex !== 0) {
110
+ randomIndex = Math.floor(Math.random() * currentIndex);
111
+ currentIndex -= 1;
112
+ temporaryValue = array[currentIndex];
113
+ array[currentIndex] = array[randomIndex];
114
+ array[randomIndex] = temporaryValue;
115
+ }
116
+
117
+ return array.join('');
118
+ }
119
+
120
+ static getRandomInteger(max = 9, min = 0) {
121
+ return Math.floor(Math.random() * (max - min + 1)) + min;
122
+ }
123
+
124
+ static getRandomFloat(min, max) {
125
+ return Math.random() * (max - min) + min;
126
+ }
127
+
128
+ static getRandomElementByText(baseElements, exceptionsList = []) {
129
+ const exceptions = exceptionsList ?? [];
130
+ const baseElementsList = baseElements.slice(0, baseElements.length);
131
+ let element;
132
+ if (exceptions.length > 0) {
133
+ while (true) { // eslint-disable-line no-constant-condition
134
+ element = baseElementsList[Math.floor(Math.random() * baseElementsList.length)];
135
+ if (!exceptions.includes(element) && (element !== '')) break;
136
+ }
137
+ } else {
138
+ while (true) { // eslint-disable-line no-constant-condition
139
+ element = baseElementsList[Math.floor(Math.random() * baseElementsList.length)];
140
+ if (element !== '') break;
141
+ }
142
+ }
143
+
144
+ return element;
145
+ }
146
+ }
147
+
148
+ module.exports = Randomizer;
@@ -0,0 +1,14 @@
1
+ class StrUtils {
2
+ static toTitleCase(str) {
3
+ return str.replace(
4
+ /\w\S*/g,
5
+ (txt) => txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase(),
6
+ );
7
+ }
8
+
9
+ static removeAllNonNumbersFromString(str) {
10
+ return str.replace(/\D/g, '');
11
+ }
12
+ }
13
+
14
+ module.exports = StrUtils;
@@ -0,0 +1,53 @@
1
+ const moment = require('moment');
2
+ const JSONLoader = require('../data/JSONLoader');
3
+
4
+ class TimeUtils {
5
+ static getDatesInterval(count, unitOfTime, options = {}) {
6
+ const { dateBegin } = options;
7
+ const startNextDay = options.startNextDay ?? true;
8
+ const isNotIncluded = options.isNotIncluded ?? true;
9
+ const reverseInterval = options.reverseInterval ?? false;
10
+
11
+ let startDate;
12
+ if (reverseInterval) {
13
+ startDate = startNextDay ? moment().subtract(1, 'days') : moment();
14
+ } else {
15
+ startDate = startNextDay ? moment().add(1, 'days') : moment();
16
+ }
17
+
18
+ let finishDate;
19
+ if (reverseInterval) {
20
+ finishDate = dateBegin
21
+ ? moment(dateBegin, JSONLoader.testData.datesFormatDMY).subtract(count, unitOfTime)
22
+ : moment(startDate).subtract(count, unitOfTime);
23
+ if (isNotIncluded) {
24
+ finishDate = moment(finishDate).add(1, 'days');
25
+ }
26
+ } else {
27
+ finishDate = dateBegin
28
+ ? moment(dateBegin, JSONLoader.testData.datesFormatDMY).add(count, unitOfTime)
29
+ : moment(startDate).add(count, unitOfTime);
30
+ if (isNotIncluded) {
31
+ finishDate = moment(finishDate).subtract(1, 'days');
32
+ }
33
+ }
34
+
35
+ startDate = moment(startDate).format(JSONLoader.testData.datesFormatDMY);
36
+ finishDate = moment(finishDate).format(JSONLoader.testData.datesFormatDMY);
37
+ return reverseInterval
38
+ ? { startDate: finishDate, finishDate: dateBegin ?? startDate }
39
+ : { startDate: dateBegin ?? startDate, finishDate };
40
+ }
41
+
42
+ static reformatDateFromYMDToDMY(date) {
43
+ return moment(date, JSONLoader.testData.datesFormatYMD)
44
+ .format(JSONLoader.testData.datesFormatDMY);
45
+ }
46
+
47
+ static reformatDateFromDMYToYMD(date) {
48
+ return moment(date, JSONLoader.testData.datesFormatDMY)
49
+ .format(JSONLoader.testData.datesFormatYMD);
50
+ }
51
+ }
52
+
53
+ module.exports = TimeUtils;