testit-adapter-mocha 1.1.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.
package/README.md ADDED
@@ -0,0 +1,219 @@
1
+ # Test IT TMS adapters for Mocha
2
+ ![Test IT](https://raw.githubusercontent.com/testit-tms/adapters-js/master/images/banner.png)
3
+
4
+ ## Getting Started
5
+
6
+ ### Installation
7
+ ```
8
+ npm install testit-adapter-mocha
9
+ ```
10
+
11
+ ### Adapter connection
12
+
13
+ ```js
14
+ // .mocharc.js
15
+
16
+ module.exports = {
17
+ reporter: "testit-adapter-mocha",
18
+ // ... other mocha options
19
+ }
20
+ ```
21
+
22
+ ## Configuration
23
+
24
+ | Description | Property | Environment variable |
25
+ |------------------------------------------------------------------------------------------------------------------------------------------------------------|----------------------------|-----------------------------------|
26
+ | Location of the TMS instance | url | TMS_URL |
27
+ | API secret key <br/>[How to getting API secret key?](https://github.com/testit-tms/.github/tree/main/configuration#privatetoken) | privateToken | TMS_PRIVATE_TOKEN |
28
+ | ID of project in TMS instance <br/>[How to getting project ID?](https://github.com/testit-tms/.github/tree/main/configuration#projectid) | projectId | TMS_PROJECT_ID |
29
+ | ID of configuration in TMS instance <br/>[How to getting configuration ID?](https://github.com/testit-tms/.github/tree/main/configuration#configurationid) | configurationId | TMS_CONFIGURATION_ID |
30
+ | ID of the created test run in TMS instance.<br/>It's necessary for **adapterMode** 0 or 1 | testRunId | TMS_TEST_RUN_ID |
31
+ | Parameter for specifying the name of test run in TMS instance (**It's optional**). <br/>If it is not provided, it is created automatically | testRunName | TMS_TEST_RUN_NAME |
32
+ | Adapter mode * | adapterMode | TMS_ADAPTER_MODE |
33
+ | Mode of automatic creation test cases ** (**It's optional**). | automaticCreationTestCases | TMS_AUTOMATIC_CREATION_TEST_CASES |
34
+
35
+ *The adapter supports following modes:
36
+ * 0 - in this mode, the adapter filters tests by external id and sends the results to the test run. **Default value**.
37
+ * 1 - in this mode, the adapter sends all results to the test run without filtering
38
+ * 2 - in this mode, the adapter creates a new test run and sends results to the new test run
39
+
40
+ **The adapter supports following modes:
41
+ * true - in this mode, the adapter will create a test case linked to the created autotest (not to the updated autotest)
42
+ * false - in this mode, the adapter will not create a test case. **Default value**.
43
+
44
+ ### File
45
+
46
+ 1. Adapter configuration file: `tms.config.json`
47
+
48
+ ```json
49
+ {
50
+ "url": "URL",
51
+ "privateToken": "USER_PRIVATE_TOKEN",
52
+ "projectId": "PROJECT_ID",
53
+ "configurationId": "CONFIGURATION_ID",
54
+ "testRunId": "TEST_RUN_ID",
55
+ "adapterMode": 0,
56
+ "automaticCreationTestCases": false
57
+ }
58
+ ```
59
+
60
+ 2. You can set adapter config in mocha config file: `.mocharc.js`.
61
+
62
+ ```js
63
+ module.exports = {
64
+ reporter: "testit-adapter-mocha",
65
+ tmsOptions: {
66
+ url: 'URL',
67
+ privateToken: 'USER_PRIVATE_TOKEN',
68
+ projectId: 'PROJECT_ID',
69
+ configurationId: 'CONFIGURATION_ID',
70
+ testRunId: 'TEST_RUN_ID',
71
+ adapterMode: ADAPTER_MODE,
72
+ automaticCreationTestCases: AUTOMATIC_CREATION_TEST_CASES
73
+ },
74
+ // ... other mocha options
75
+ };
76
+ ```
77
+
78
+ 3. You can set adapter config to environment variables: `.env`.
79
+
80
+ ```dotenv
81
+ TMS_PRIVATE_TOKEN=YourPrivateToken
82
+ TMS_URL=URL
83
+ TMS_PROJECT_ID=YourProjectId;
84
+ TMS_CONFIGURATION_ID=YourConfigurationId;
85
+ TMS_TEST_RUN_ID=TestRunId;
86
+ TMS_TEST_RUN_NAME=TestRunName; # optional
87
+ TMS_ADAPTER_MODE=0; # or 1, or 2
88
+ TMS_CONFIG_FILE=pathToAnotherConfigFile; #optional
89
+ TMS_AUTOMATIC_CREATION_TEST_CASES=false; # or true, optional
90
+ ```
91
+
92
+ ## Usage
93
+
94
+ Methods and properties can be used to specify information about autotest.
95
+
96
+ ### Properties
97
+
98
+ Description of metadata properties:
99
+ - `this.workItemsIds` - linking an autotest to a test case
100
+ - `this.displayName` - name of the autotest in the Test IT system
101
+ - `this.externalId` - External ID of the autotest within the project in the Test IT system
102
+ - `this.title` - title in the autotest card
103
+ - `this.description` - description in the autotest card
104
+ - `this.labels` - labels in the autotest card
105
+ - `this.links` - links in the autotest card
106
+ - `this.nameSpace` - directory in the TMS system (default - directory's name of test)
107
+ - `this.className` - subdirectory in the TMS system (default - file's name of test)
108
+
109
+ ### Methods
110
+
111
+ Description of methods:
112
+ - `this.addLinks` - links in the autotest result
113
+ - `this.addAttachments` - uploading files in the autotest result or step result
114
+ - `this.addMessage` - information about autotest in the autotest result
115
+ - `this.addSteps` - information about step in the autotest result
116
+
117
+ ## Examples
118
+
119
+ ### Simple test
120
+
121
+ ```ts
122
+ // annotations.spec.ts
123
+
124
+ import assert from "assert";
125
+ import {Context, Link} from "testit-adapter-mocha";
126
+
127
+ const links: Link[] = [
128
+ { url: "https://test01.example", title: "Example01", description: "Example01 description", type: "Issue" },
129
+ { url: "https://test02.example", title: "Example02", description: "Example02 description", type: "BlockedBy" },
130
+ { url: "https://test03.example", title: "Example03", description: "Example03 description", type: "Requirement" },
131
+ { url: "https://test04.example", title: "Example04", description: "Example04 description", type: "Defect" },
132
+ { url: "https://test05.example", title: "Example05", description: "Example05 description", type: "Repository" },
133
+ ];
134
+
135
+ const paths = [
136
+ join(__dirname, "../attachments/file.txt"),
137
+ join(__dirname, "../attachments/image.jpg")
138
+ ];
139
+
140
+ it('All annotations and methods', function (this: Context) {
141
+ this.externalId = 'external_id';
142
+ this.displayName = 'display_name';
143
+ this.title = 'title';
144
+ this.description = 'description';
145
+ this.labels = ['label1', 'label2'];
146
+ this.links = links;
147
+
148
+ this.addMessage('This is a message');
149
+ this.addLinks(links);
150
+
151
+ this.addAttachments(paths);
152
+ this.addAttachments('This is a custom attachment', 'custom.txt');
153
+ this.addAttachments('Text-like attachmnet');
154
+
155
+ this.addSteps("Step_name", (step) => {
156
+ // ... step logic
157
+ step.description = "Step Description";
158
+ step.parameters = {
159
+ login: "login",
160
+ password: "password",
161
+ };
162
+ this.addAttachments("Attachment_from_step", "step.txt");
163
+ })
164
+
165
+ assert.equal(true, true);
166
+ });
167
+ ```
168
+
169
+ ### Parameterized test
170
+
171
+ ```ts
172
+ // parameters.spec.ts
173
+
174
+ import assert from "assert";
175
+ import {Context} from "testit-adapter-mocha";
176
+
177
+ const tests = [2, 3, "string", false];
178
+
179
+ tests.forEach((value) => {
180
+ it(`3 is ${value}`, function (this: Context) {
181
+ this.parameters = {
182
+ value: value.toString(),
183
+ };
184
+
185
+ assert.strictEqual(3, value);
186
+ });
187
+ });
188
+
189
+ const tests2 = [
190
+ { args: [1, 2], expected: 3 },
191
+ { args: [1, 2, 3], expected: 7 },
192
+ { args: [1, 2, 3, 4], expected: "10" },
193
+ ];
194
+
195
+ tests2.forEach(({ args, expected }) => {
196
+ it(`correctly sum ${args} to ${expected}`, function (this: Context) {
197
+ this.parameters = {
198
+ args: args.toString(),
199
+ expected: expected.toString(),
200
+ };
201
+
202
+ assert.strictEqual(sum(args), expected);
203
+ });
204
+ });
205
+ ```
206
+
207
+ # Contributing
208
+
209
+ You can help to develop the project. Any contributions are **greatly appreciated**.
210
+
211
+ * If you have suggestions for adding or removing projects, feel free to [open an issue](https://github.com/testit-tms/adapters-js/issues/new) to discuss it, or directly create a pull request after you edit the *README.md* file with necessary changes.
212
+ * Please make sure you check your spelling and grammar.
213
+ * Create individual PR for each suggestion.
214
+ * Please also read through the [Code Of Conduct](https://github.com/testit-tms/adapters-js/blob/master/CODE_OF_CONDUCT.md) before posting your first idea as well.
215
+
216
+ # License
217
+
218
+ Distributed under the Apache-2.0 License. See [LICENSE](https://github.com/testit-tms/adapters-js/blob/master/LICENSE.md) for more information.
219
+
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,182 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ const mocha_1 = require("mocha");
13
+ const testit_js_commons_1 = require("testit-js-commons");
14
+ const step_1 = require("./step");
15
+ const utils_1 = require("./utils");
16
+ const Reporter = mocha_1.reporters.List;
17
+ const Events = mocha_1.Runner.constants;
18
+ const emptyTest = () => ({
19
+ autoTestExternalId: "",
20
+ outcome: "Passed",
21
+ stepResults: [],
22
+ setupResults: [],
23
+ teardownResults: [],
24
+ attachments: [],
25
+ });
26
+ const emptyStep = () => ({
27
+ title: "",
28
+ steps: [],
29
+ attachments: [],
30
+ });
31
+ module.exports = class extends Reporter {
32
+ constructor(runner, options) {
33
+ super(runner, options);
34
+ this.attachmentsQueue = [];
35
+ this.autotestsQueue = [];
36
+ this.autotestsForTestRun = [];
37
+ this.currentTest = emptyTest();
38
+ this.currentStep = emptyStep();
39
+ this.onStartRun = () => __awaiter(this, void 0, void 0, function* () {
40
+ this.strategy.setup();
41
+ });
42
+ this.onEndRun = () => __awaiter(this, void 0, void 0, function* () {
43
+ yield Promise.all(this.attachmentsQueue).catch((err) => {
44
+ console.log("Error loading attachments. \n", err.body);
45
+ });
46
+ yield Promise.all(this.autotestsQueue);
47
+ yield this.strategy.loadTestRun(this.autotestsForTestRun).catch((err) => {
48
+ console.log("Error load test run. \n", err.body);
49
+ });
50
+ yield this.strategy.teardown();
51
+ });
52
+ this.addAttachments = (pathsOrContent, fileName) => {
53
+ const target = this.currentType === "test" ? this.currentTest : this.currentStep;
54
+ const promise = typeof pathsOrContent === "string"
55
+ ? this.additions.addAttachments(pathsOrContent, fileName)
56
+ : this.additions.addAttachments(pathsOrContent);
57
+ promise.then((attachments) => {
58
+ var _a;
59
+ (_a = target.attachments) === null || _a === void 0 ? void 0 : _a.push(...attachments);
60
+ });
61
+ this.attachmentsQueue.push(promise);
62
+ return promise;
63
+ };
64
+ this.addLinks = (links) => {
65
+ Array.isArray(links) ? this.additions.addLinks(links) : this.additions.addLinks(links);
66
+ };
67
+ this.addMessage = (message) => {
68
+ this.additions.addMessage(message);
69
+ };
70
+ this.addSteps = (title, stepConstructor) => {
71
+ var _a;
72
+ const start = new Date();
73
+ const prevType = this.currentType;
74
+ this.currentType = "step";
75
+ const step = new step_1.TestStep(title);
76
+ try {
77
+ stepConstructor === null || stepConstructor === void 0 ? void 0 : stepConstructor(step);
78
+ }
79
+ catch (err) {
80
+ this.currentStep.outcome = "Failed";
81
+ console.log("Step failed. \n", err);
82
+ }
83
+ this.currentStep.title = step.title;
84
+ this.currentStep.description = step.description;
85
+ this.currentStep.parameters = step.parameters;
86
+ this.currentStep.outcome = "Passed";
87
+ this.currentStep.startedOn = start;
88
+ this.currentStep.completedOn = new Date();
89
+ this.currentStep.duration = Date.now() - start.getTime();
90
+ (_a = this.currentTest.stepResults) === null || _a === void 0 ? void 0 : _a.push(this.currentStep);
91
+ this.currentType = prevType;
92
+ this.currentStep = emptyStep();
93
+ };
94
+ const config = new testit_js_commons_1.ConfigComposer().compose(options === null || options === void 0 ? void 0 : options.tmsOptions);
95
+ const client = new testit_js_commons_1.Client(config);
96
+ this.strategy = testit_js_commons_1.StrategyFactory.create(client, config);
97
+ this.additions = new testit_js_commons_1.Additions(client);
98
+ this.runner.on(Events.EVENT_RUN_BEGIN, () => this.onStartRun());
99
+ this.runner.on(Events.EVENT_RUN_END, () => this.onEndRun());
100
+ this.runner.once(Events.EVENT_TEST_BEGIN, (test) => this.addMethods(test.ctx));
101
+ this.runner.once(Events.EVENT_HOOK_BEGIN, (hook) => this.addMethods(hook.ctx));
102
+ this.runner.on(Events.EVENT_TEST_BEGIN, () => this.onStartTest());
103
+ this.runner.on(Events.EVENT_TEST_END, (test) => this.onEndTest(test));
104
+ }
105
+ clearContext(ctx) {
106
+ ctx.externalId = undefined;
107
+ ctx.displayName = undefined;
108
+ ctx.title = undefined;
109
+ ctx.description = undefined;
110
+ ctx.links = [];
111
+ ctx.labels = [];
112
+ ctx.classname = undefined;
113
+ ctx.workItemsIds = [];
114
+ ctx.parameters = {};
115
+ ctx.properties = {};
116
+ }
117
+ addMethods(context) {
118
+ if (!context)
119
+ return;
120
+ context.addAttachments = this.addAttachments;
121
+ context.addLinks = this.addLinks;
122
+ context.addMessage = this.addMessage;
123
+ context.addSteps = this.addSteps;
124
+ }
125
+ onStartTest() {
126
+ this.currentType = "test";
127
+ this.currentTest.startedOn = new Date();
128
+ }
129
+ onEndTest(test) {
130
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u;
131
+ const hooks = (0, utils_1.extractHooks)(test.parent);
132
+ const setup = [...hooks.beforeAll, ...hooks.beforeEach];
133
+ const teardown = [...hooks.afterEach, ...hooks.afterAll];
134
+ const autotestPost = {
135
+ externalId: (_b = (_a = test.ctx) === null || _a === void 0 ? void 0 : _a.externalId) !== null && _b !== void 0 ? _b : testit_js_commons_1.Utils.getHash(test.title),
136
+ name: (_d = (_c = test.ctx) === null || _c === void 0 ? void 0 : _c.displayName) !== null && _d !== void 0 ? _d : test.title,
137
+ description: (_e = test.ctx) === null || _e === void 0 ? void 0 : _e.description,
138
+ title: (_f = test.ctx) === null || _f === void 0 ? void 0 : _f.title,
139
+ links: (_g = test.ctx) === null || _g === void 0 ? void 0 : _g.links,
140
+ labels: (_j = (_h = test.ctx) === null || _h === void 0 ? void 0 : _h.labels) === null || _j === void 0 ? void 0 : _j.map((label) => ({ name: label })),
141
+ namespace: (_l = (_k = test.ctx) === null || _k === void 0 ? void 0 : _k.namespace) !== null && _l !== void 0 ? _l : this._getNameSpace(test.file),
142
+ classname: (_o = (_m = test.ctx) === null || _m === void 0 ? void 0 : _m.classname) !== null && _o !== void 0 ? _o : this._getClassName(test.file),
143
+ steps: this.currentTest.stepResults,
144
+ setup,
145
+ teardown,
146
+ workItemIds: (_p = test.ctx) === null || _p === void 0 ? void 0 : _p.workItemsIds,
147
+ };
148
+ const promise = this.strategy.loadAutotest(autotestPost, test.isPassed());
149
+ this.autotestsQueue.push(promise);
150
+ this.autotestsForTestRun.push({
151
+ autoTestExternalId: autotestPost.externalId,
152
+ outcome: test.isFailed() ? "Failed" : "Passed",
153
+ startedOn: this.currentTest.startedOn,
154
+ completedOn: new Date(),
155
+ duration: (_q = test.duration) !== null && _q !== void 0 ? _q : Date.now() - this.currentTest.startedOn.getTime(),
156
+ stepResults: this.currentTest.stepResults,
157
+ setupResults: setup,
158
+ teardownResults: teardown,
159
+ attachments: this.currentTest.attachments,
160
+ links: this.additions.links,
161
+ message: ((_r = test.err) === null || _r === void 0 ? void 0 : _r.message)
162
+ ? this.additions.messages.concat(test.err.message).join("\n")
163
+ : this.additions.messages.join("\n"),
164
+ traces: (_s = test.err) === null || _s === void 0 ? void 0 : _s.stack,
165
+ parameters: (_t = test.ctx) === null || _t === void 0 ? void 0 : _t.parameters,
166
+ properties: (_u = test.ctx) === null || _u === void 0 ? void 0 : _u.properties,
167
+ });
168
+ this.resetTest(test);
169
+ }
170
+ resetTest(test) {
171
+ this.currentTest = emptyTest();
172
+ this.additions.clear();
173
+ if (test.ctx)
174
+ this.clearContext(test.ctx);
175
+ }
176
+ _getNameSpace(path) {
177
+ return path && testit_js_commons_1.Utils.getDir(path.replace(__dirname, ""));
178
+ }
179
+ _getClassName(path) {
180
+ return path && testit_js_commons_1.Utils.getFileName(path);
181
+ }
182
+ };
package/lib/step.d.ts ADDED
@@ -0,0 +1,15 @@
1
+ export interface ITestStep {
2
+ title: string;
3
+ description?: string;
4
+ parameters?: {
5
+ [key: string]: string;
6
+ };
7
+ }
8
+ export declare class TestStep implements ITestStep {
9
+ title: string;
10
+ description?: string;
11
+ parameters?: {
12
+ [p: string]: string;
13
+ };
14
+ constructor(title: string);
15
+ }
package/lib/step.js ADDED
@@ -0,0 +1,9 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.TestStep = void 0;
4
+ class TestStep {
5
+ constructor(title) {
6
+ this.title = title;
7
+ }
8
+ }
9
+ exports.TestStep = TestStep;
package/lib/types.d.ts ADDED
@@ -0,0 +1,28 @@
1
+ /// <reference types="mocha" />
2
+ import { AdapterConfig, Metadata, DynamicMethods } from "testit-js-commons";
3
+ import { ITestStep } from "./step";
4
+ declare module "mocha" {
5
+ interface Context extends Metadata, Methods {
6
+ }
7
+ }
8
+ export interface ReporterOptions extends Mocha.MochaOptions {
9
+ tmsOptions: AdapterConfig;
10
+ }
11
+ export interface Methods extends DynamicMethods {
12
+ addSteps: (title: string, stepConstructor?: (step: ITestStep) => void) => void;
13
+ }
14
+ export type Context = Mocha.Context & Metadata & Methods;
15
+ export interface Test extends Mocha.Test {
16
+ ctx?: Context;
17
+ }
18
+ export interface Hook extends Mocha.Hook {
19
+ ctx?: Context;
20
+ }
21
+ export type LinkType = "Related" | "BlockedBy" | "Defect" | "Issue" | "Requirement" | "Repository";
22
+ export interface Link {
23
+ title: string;
24
+ url: string;
25
+ description?: string;
26
+ type?: LinkType;
27
+ hasInfo?: boolean;
28
+ }
package/lib/types.js ADDED
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
package/lib/utils.d.ts ADDED
@@ -0,0 +1,10 @@
1
+ import { Step } from "testit-js-commons";
2
+ import { Suite } from "mocha";
3
+ import { Hook } from "./types";
4
+ export declare function hookToStep(hook: Hook): Step;
5
+ export declare function extractHooks(suite?: Suite): {
6
+ afterAll: Step[];
7
+ beforeAll: Step[];
8
+ afterEach: Step[];
9
+ beforeEach: Step[];
10
+ };
package/lib/utils.js ADDED
@@ -0,0 +1,25 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.extractHooks = exports.hookToStep = void 0;
4
+ function hookToStep(hook) {
5
+ var _a;
6
+ return {
7
+ title: hook.title,
8
+ duration: (_a = hook.duration) !== null && _a !== void 0 ? _a : 0,
9
+ };
10
+ }
11
+ exports.hookToStep = hookToStep;
12
+ function extractHooks(suite) {
13
+ if (!suite)
14
+ return { afterAll: [], beforeAll: [], afterEach: [], beforeEach: [] };
15
+ const hooks = extractHooks(suite.parent);
16
+ // @ts-ignore
17
+ const { _afterAll = [], _beforeAll = [], _afterEach = [], _beforeEach = [] } = suite;
18
+ return {
19
+ beforeAll: [...hooks.beforeAll, ..._beforeAll.map(hookToStep)],
20
+ afterAll: [...hooks.afterAll, ..._afterAll.map(hookToStep)],
21
+ afterEach: [...hooks.afterEach, ..._afterEach.map(hookToStep)],
22
+ beforeEach: [...hooks.beforeEach, ..._beforeEach.map(hookToStep)],
23
+ };
24
+ }
25
+ exports.extractHooks = extractHooks;
package/package.json ADDED
@@ -0,0 +1,32 @@
1
+ {
2
+ "name": "testit-adapter-mocha",
3
+ "version": "1.1.5",
4
+ "description": "Mocha adapter for Test IT",
5
+ "main": "lib/reporter.js",
6
+ "types": "lib/types.d.ts",
7
+ "scripts": {
8
+ "build": "tsc",
9
+ "watch": "tsc -w"
10
+ },
11
+ "author": {
12
+ "name": "Integration team",
13
+ "email": "integrations@testit.software"
14
+ },
15
+ "license": "Apache-2.0",
16
+ "devDependencies": {
17
+ "@types/mocha": "^10.0.1",
18
+ "@types/node": "^20.2.4",
19
+ "@types/request": "^2.48.8",
20
+ "@typescript-eslint/eslint-plugin": "^5.59.7",
21
+ "@typescript-eslint/parser": "^5.59.7",
22
+ "eslint": "^8.41.0",
23
+ "prettier": "^2.8.8"
24
+ },
25
+ "dependencies": {
26
+ "mocha": "^10.2.0",
27
+ "testit-js-commons": "^1.1.5"
28
+ },
29
+ "files": [
30
+ "lib"
31
+ ]
32
+ }