testit-api-client 1.0.0 → 1.0.1

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.
@@ -0,0 +1,6 @@
1
+ module.exports = {
2
+ presets: [
3
+ ['@babel/preset-env', { targets: { node: 'current' } }],
4
+ '@babel/preset-typescript',
5
+ ],
6
+ };
package/jest.config.ts ADDED
@@ -0,0 +1,194 @@
1
+ /*
2
+ * For a detailed explanation regarding each configuration property and type check, visit:
3
+ * https://jestjs.io/docs/configuration
4
+ */
5
+
6
+ export default {
7
+ // All imported modules in your tests should be mocked automatically
8
+ // automock: false,
9
+
10
+ // Stop running tests after `n` failures
11
+ // bail: 0,
12
+
13
+ // The directory where Jest should store its cached dependency information
14
+ // cacheDirectory: "C:\\Users\\Andrey\\AppData\\Local\\Temp\\jest",
15
+
16
+ // Automatically clear mock calls and instances between every test
17
+ clearMocks: true,
18
+
19
+ // Indicates whether the coverage information should be collected while executing the test
20
+ // collectCoverage: false,
21
+
22
+ // An array of glob patterns indicating a set of files for which coverage information should be collected
23
+ // collectCoverageFrom: undefined,
24
+
25
+ // The directory where Jest should output its coverage files
26
+ // coverageDirectory: undefined,
27
+
28
+ // An array of regexp pattern strings used to skip coverage collection
29
+ // coveragePathIgnorePatterns: [
30
+ // "\\\\node_modules\\\\"
31
+ // ],
32
+
33
+ // Indicates which provider should be used to instrument code for coverage
34
+ coverageProvider: 'v8',
35
+
36
+ // A list of reporter names that Jest uses when writing coverage reports
37
+ // coverageReporters: [
38
+ // "json",
39
+ // "text",
40
+ // "lcov",
41
+ // "clover"
42
+ // ],
43
+
44
+ // An object that configures minimum threshold enforcement for coverage results
45
+ // coverageThreshold: undefined,
46
+
47
+ // A path to a custom dependency extractor
48
+ // dependencyExtractor: undefined,
49
+
50
+ // Make calling deprecated APIs throw helpful error messages
51
+ // errorOnDeprecated: false,
52
+
53
+ // Force coverage collection from ignored files using an array of glob patterns
54
+ // forceCoverageMatch: [],
55
+
56
+ // A path to a module which exports an async function that is triggered once before all test suites
57
+ // globalSetup: undefined,
58
+
59
+ // A path to a module which exports an async function that is triggered once after all test suites
60
+ // globalTeardown: undefined,
61
+
62
+ // A set of global variables that need to be available in all test environments
63
+ // globals: {},
64
+
65
+ // The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers.
66
+ // maxWorkers: "50%",
67
+
68
+ // An array of directory names to be searched recursively up from the requiring module's location
69
+ // moduleDirectories: [
70
+ // "node_modules"
71
+ // ],
72
+
73
+ // An array of file extensions your modules use
74
+ // moduleFileExtensions: [
75
+ // "js",
76
+ // "jsx",
77
+ // "ts",
78
+ // "tsx",
79
+ // "json",
80
+ // "node"
81
+ // ],
82
+
83
+ // A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module
84
+ // moduleNameMapper: {},
85
+
86
+ // An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader
87
+ // modulePathIgnorePatterns: [],
88
+
89
+ // Activates notifications for test results
90
+ // notify: false,
91
+
92
+ // An enum that specifies notification mode. Requires { notify: true }
93
+ // notifyMode: "failure-change",
94
+
95
+ // A preset that is used as a base for Jest's configuration
96
+ // preset: undefined,
97
+
98
+ // Run tests from one or more projects
99
+ // projects: undefined,
100
+
101
+ // Use this configuration option to add custom reporters to Jest
102
+ // reporters: undefined,
103
+
104
+ // Automatically reset mock state between every test
105
+ // resetMocks: false,
106
+
107
+ // Reset the module registry before running each individual test
108
+ // resetModules: false,
109
+
110
+ // A path to a custom resolver
111
+ // resolver: undefined,
112
+
113
+ // Automatically restore mock state between every test
114
+ // restoreMocks: false,
115
+
116
+ // The root directory that Jest should scan for tests and modules within
117
+ // rootDir: undefined,
118
+
119
+ // A list of paths to directories that Jest should use to search for files in
120
+ // roots: [
121
+ // "<rootDir>"
122
+ // ],
123
+
124
+ // Allows you to use a custom runner instead of Jest's default test runner
125
+ // runner: "jest-runner",
126
+
127
+ // The paths to modules that run some code to configure or set up the testing environment before each test
128
+ // setupFiles: [],
129
+
130
+ // A list of paths to modules that run some code to configure or set up the testing framework before each test
131
+ // setupFilesAfterEnv: [],
132
+
133
+ // The number of seconds after which a test is considered as slow and reported as such in the results.
134
+ // slowTestThreshold: 5,
135
+
136
+ // A list of paths to snapshot serializer modules Jest should use for snapshot testing
137
+ // snapshotSerializers: [],
138
+
139
+ // The test environment that will be used for testing
140
+ // testEnvironment: "jest-environment-node",
141
+
142
+ // Options that will be passed to the testEnvironment
143
+ // testEnvironmentOptions: {},
144
+
145
+ // Adds a location field to test results
146
+ // testLocationInResults: false,
147
+
148
+ // The glob patterns Jest uses to detect test files
149
+ // testMatch: [
150
+ // "**/__tests__/**/*.[jt]s?(x)",
151
+ // "**/?(*.)+(spec|test).[tj]s?(x)"
152
+ // ],
153
+
154
+ // An array of regexp pattern strings that are matched against all test paths, matched tests are skipped
155
+ // testPathIgnorePatterns: [
156
+ // "\\\\node_modules\\\\"
157
+ // ],
158
+
159
+ // The regexp pattern or array of patterns that Jest uses to detect test files
160
+ // testRegex: [],
161
+
162
+ // This option allows the use of a custom results processor
163
+ // testResultsProcessor: undefined,
164
+
165
+ // This option allows use of a custom test runner
166
+ // testRunner: "jest-circus/runner",
167
+
168
+ // This option sets the URL for the jsdom environment. It is reflected in properties such as location.href
169
+ // testURL: "http://localhost",
170
+
171
+ // Setting this value to "fake" allows the use of fake timers for functions such as "setTimeout"
172
+ // timers: "real",
173
+
174
+ // A map from regular expressions to paths to transformers
175
+ // transform: undefined,
176
+
177
+ // An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation
178
+ // transformIgnorePatterns: [
179
+ // "\\\\node_modules\\\\",
180
+ // "\\.pnp\\.[^\\\\]+$"
181
+ // ],
182
+
183
+ // An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them
184
+ // unmockedModulePathPatterns: undefined,
185
+
186
+ // Indicates whether each individual test should be reported during the run
187
+ // verbose: undefined,
188
+
189
+ // An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode
190
+ // watchPathIgnorePatterns: [],
191
+
192
+ // Whether to use watchman for file crawling
193
+ // watchman: true,
194
+ };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "testit-api-client",
3
- "version": "1.0.0",
4
- "description": "Client provides methods for communication with TestIt API.",
3
+ "version": "1.0.1",
4
+ "description": "Client provides methods for communication with Test IT API.",
5
5
  "main": "dist/index.js",
6
6
  "scripts": {
7
7
  "test": "jest",
@@ -33,9 +33,6 @@
33
33
  "querystring": "^0.2.1",
34
34
  "zod": "^3.11.6"
35
35
  },
36
- "files": [
37
- "dist"
38
- ],
39
36
  "bugs": {
40
37
  "url": "https://github.com/testit-tms/api-client-js/issues"
41
38
  },
package/readme.md CHANGED
@@ -3,11 +3,17 @@
3
3
  Client provides methods for communication with TestIt API.
4
4
 
5
5
  # Installation
6
+
6
7
  ```
7
8
  npm i <TBD>
8
9
  ```
10
+ or
11
+ ```
12
+ yarn add <TBD>
13
+ ```
9
14
 
10
15
  # Usage
16
+
11
17
  ```ts
12
18
  const client = new Client({
13
19
  url: 'http://test.com',
package/src/client.ts ADDED
@@ -0,0 +1,183 @@
1
+ import axios, { AxiosInstance, AxiosResponse } from 'axios';
2
+ import minimist from 'minimist';
3
+ import {
4
+ Attachment,
5
+ Autotest,
6
+ AutotestPost,
7
+ AutotestPut,
8
+ AutotestQuery,
9
+ AutotestResultsForTestRun,
10
+ ClientConfig,
11
+ ClientConfigWithFile,
12
+ IClient,
13
+ TestRunGet,
14
+ TestRunPost,
15
+ WorkItemId,
16
+ } from './types';
17
+ import { existsSync, readFileSync } from 'fs';
18
+ import FormData from 'form-data';
19
+ import { basename } from 'path';
20
+ import { validateConfig } from './validation';
21
+
22
+ export class Client implements IClient {
23
+ private readonly axios: AxiosInstance;
24
+ private config: ClientConfig;
25
+
26
+ constructor(config: Partial<ClientConfigWithFile>) {
27
+ const { configFile, ...restConfig } = config;
28
+ let finalConfig = restConfig;
29
+ if (configFile) {
30
+ finalConfig = Client.mergeConfig(
31
+ finalConfig,
32
+ this.readConfigFile(configFile)
33
+ );
34
+ }
35
+ finalConfig = Client.mergeConfig(finalConfig, this.readEnvConfig());
36
+ finalConfig = Client.mergeConfig(finalConfig, this.readCliConfig());
37
+ this.config = validateConfig(finalConfig);
38
+ const baseURL = new URL('/api/v2', this.config.url).toString();
39
+ this.axios = axios.create({
40
+ baseURL,
41
+ headers: {
42
+ Authorization: `PrivateToken ${this.config.privateToken}`,
43
+ },
44
+ });
45
+ }
46
+
47
+ async checkConnection() {
48
+ try {
49
+ await axios.get(new URL('version.json', this.config.url).toString());
50
+ } catch (err) {
51
+ throw new Error('Cannot connect to TestIt');
52
+ }
53
+ }
54
+
55
+ // TODO: add query object
56
+ async getAutotest(query: AutotestQuery): Promise<Autotest[]> {
57
+ const params = new URLSearchParams();
58
+ Object.keys(query).forEach((key) => {
59
+ const value = query[key as keyof AutotestQuery];
60
+ if (value === undefined) {
61
+ return;
62
+ }
63
+ if (Array.isArray(value)) {
64
+ value.forEach((v) => params.append(key, v));
65
+ } else {
66
+ params.append(key, value.toString());
67
+ }
68
+ });
69
+ return this.axios
70
+ .get(`/autoTests?${params.toString()}`)
71
+ .then((res) => res.data);
72
+ }
73
+
74
+ async createAutotest(autotest: AutotestPost): Promise<Autotest> {
75
+ return this.axios.post('/autoTests', autotest).then((res) => res.data);
76
+ }
77
+
78
+ async updateAutotest(autotest: AutotestPut): Promise<void> {
79
+ return this.axios.put('/autoTests', autotest);
80
+ }
81
+
82
+ async linkToWorkItem(
83
+ autotestId: string,
84
+ workItem: WorkItemId
85
+ ): Promise<void> {
86
+ return this.axios.post(`/autoTests/${autotestId}/workItems`, workItem);
87
+ }
88
+
89
+ async createTestRun(testRun: TestRunPost): Promise<TestRunGet> {
90
+ return this.axios
91
+ .post('/testRuns', testRun)
92
+ .then((res) => res.data as TestRunGet);
93
+ }
94
+
95
+ async startTestRun(testRunId: string): Promise<void> {
96
+ return this.axios.post(`/testRuns/${testRunId}/start`);
97
+ }
98
+
99
+ async loadTestRunResults(
100
+ testRunId: string,
101
+ results: AutotestResultsForTestRun[]
102
+ ): Promise<string[]> {
103
+ return await this.axios
104
+ .post<AutotestResultsForTestRun[], AxiosResponse<string[]>>(
105
+ `/testRuns/${testRunId}/testResults`,
106
+ results
107
+ )
108
+ .then((res) => res.data);
109
+ }
110
+
111
+ async completeTestRun(testRunId: string): Promise<void> {
112
+ return this.axios.post(`/testRuns/${testRunId}/complete`);
113
+ }
114
+
115
+ getConfig(): ClientConfig {
116
+ return this.config;
117
+ }
118
+
119
+ async loadAttachment(filePath: string): Promise<Attachment> {
120
+ const form = new FormData();
121
+ form.append('file', readFileSync(filePath), basename(filePath));
122
+ return this.axios
123
+ .post<FormData, AxiosResponse<Attachment>>('/Attachments', form, {
124
+ headers: form.getHeaders(),
125
+ })
126
+ .then((res) => res.data);
127
+ }
128
+
129
+ private readCliConfig(): Partial<ClientConfig> {
130
+ const args = minimist(process.argv.slice(2));
131
+ let config = {};
132
+ if (args['testitConfig']) {
133
+ config = this.readConfigFile(args['testitConfig']);
134
+ }
135
+ return Client.mergeConfig(config, {
136
+ url: args['testitUrl'],
137
+ privateToken: args['testitPrivateToken'],
138
+ projectId: args['testitProjectId'],
139
+ configurationId: args['testitConfigurationId'],
140
+ testRunId: args['testitTestRunId'],
141
+ });
142
+ }
143
+
144
+ private readEnvConfig(): Partial<ClientConfig> {
145
+ let config = {};
146
+ if (process.env['TESTIT_CONFIG_FILE']) {
147
+ config = this.readConfigFile(process.env['TESTIT_CONFIG_FILE']);
148
+ }
149
+ return Client.mergeConfig(config, {
150
+ url: process.env['TESTIT_URL'],
151
+ privateToken: process.env['TESTIT_PRIVATE_TOKEN'],
152
+ projectId: process.env['TESTIT_PROJECT_ID'],
153
+ configurationId: process.env['TESTIT_CONFIGURATION_ID'],
154
+ testRunId: process.env['TESTIT_TEST_RUN_ID'],
155
+ });
156
+ }
157
+
158
+ private readConfigFile(path: string): Partial<ClientConfig> {
159
+ if (!existsSync(path)) {
160
+ throw new Error('Config file not found');
161
+ }
162
+ const config = JSON.parse(
163
+ readFileSync(path, { encoding: 'utf8' })
164
+ ) as Partial<ClientConfig>;
165
+ if (config.privateToken) {
166
+ console.warn('Private token is in config file, it is not secure');
167
+ }
168
+ return config;
169
+ }
170
+
171
+ static mergeConfig(
172
+ oldConfig: Partial<ClientConfig>,
173
+ newConfig: Partial<ClientConfig>
174
+ ): Partial<ClientConfig> {
175
+ return {
176
+ url: newConfig.url ?? oldConfig.url,
177
+ privateToken: newConfig.privateToken ?? oldConfig.privateToken,
178
+ projectId: newConfig.projectId ?? oldConfig.projectId,
179
+ configurationId: newConfig.configurationId ?? oldConfig.configurationId,
180
+ testRunId: newConfig.testRunId ?? oldConfig.testRunId,
181
+ };
182
+ }
183
+ }
package/src/index.ts ADDED
@@ -0,0 +1,2 @@
1
+ export * from './client';
2
+ export * from './types';
@@ -0,0 +1,15 @@
1
+ export interface AttachmentPut {
2
+ id: string;
3
+ }
4
+
5
+ export interface Attachment {
6
+ fileId: string;
7
+ type: string;
8
+ size: number;
9
+ name: string;
10
+ createDate?: string;
11
+ modifiedDate?: string;
12
+ createdById?: string;
13
+ modifiedById?: string;
14
+ id?: string;
15
+ }
@@ -0,0 +1,102 @@
1
+ import { LabelPost, LabelShort } from './label';
2
+ import { Link, LinkPost, LinkPut } from './link';
3
+ import { AutotestStep } from './autotestStep';
4
+
5
+ export interface AutotestPost {
6
+ globalId?: number;
7
+ isDeleted?: boolean;
8
+ id?: string;
9
+ createdDate?: string;
10
+ modifiedDate?: string;
11
+ createdById?: string;
12
+ modifiedById?: string;
13
+ mustBeApproved?: boolean;
14
+ externalId: string;
15
+ links?: LinkPost[];
16
+ projectId: string;
17
+ name: string;
18
+ namespace?: string;
19
+ classname?: string;
20
+ steps?: AutotestStep[];
21
+ setup?: AutotestStep[];
22
+ teardown?: AutotestStep[];
23
+ title?: string;
24
+ description?: string;
25
+ labels?: LabelPost[];
26
+ }
27
+
28
+ export interface AutotestPut {
29
+ id?: string;
30
+ externalId: string;
31
+ links?: LinkPost[];
32
+ projectId: string;
33
+ name: string;
34
+ namespace?: string;
35
+ classname?: string;
36
+ steps?: AutotestStep[];
37
+ setup?: AutotestStep[];
38
+ teardown?: AutotestStep[];
39
+ title?: string;
40
+ description?: string;
41
+ labels?: LabelPost[];
42
+ }
43
+
44
+ export interface Autotest {
45
+ globalId?: number;
46
+ isDeleted?: boolean;
47
+ id?: string;
48
+ createdDate?: string;
49
+ modifiedDate?: string;
50
+ createdById?: string;
51
+ modifiedById?: string;
52
+ mustBeApproved?: boolean;
53
+ externalId: string;
54
+ links?: LinkPut[];
55
+ projectId: string;
56
+ name: string;
57
+ namespace?: string;
58
+ classname?: string;
59
+ steps?: AutotestStep[];
60
+ setup?: AutotestStep[];
61
+ teardown?: AutotestStep[];
62
+ title?: string;
63
+ description?: string;
64
+ labels?: LabelPost[];
65
+ }
66
+
67
+ export interface AutotestGet {
68
+ externalId?: string;
69
+ links?: Link[];
70
+ projectId?: string;
71
+ name?: string;
72
+ namespace?: string;
73
+ classname?: string;
74
+ steps?: AutotestStep[];
75
+ setup?: AutotestStep[];
76
+ teardown: AutotestStep[];
77
+ global?: number;
78
+ createdDate?: string;
79
+ modifiedDate?: string;
80
+ createdById?: string;
81
+ modifiedById?: string;
82
+ labels?: LabelShort[];
83
+ id?: string;
84
+ isDeleted?: boolean;
85
+ }
86
+
87
+ export interface AutotestQuery {
88
+ projectId?: string;
89
+ externalId?: string;
90
+ globalId?: number;
91
+ namespace?: string;
92
+ isNamespaceNull?: boolean;
93
+ classname?: string;
94
+ isClassnameNull?: boolean;
95
+ isDeleted?: boolean;
96
+ labels?: string[];
97
+ skip?: number;
98
+ take?: number;
99
+ orderBy?: string;
100
+ searchField?: string;
101
+ searchValue?: string;
102
+ }
@@ -0,0 +1,23 @@
1
+ import { AttachmentPut } from './attachment';
2
+ import { LinkPost } from './link';
3
+ import { OutcomeType } from './outcome';
4
+ import { Parameters } from './parameters';
5
+ import { AttachmentPutModelAutotestStepResults } from './stepResults';
6
+
7
+ export interface AutotestResultsForTestRun {
8
+ configurationId: string;
9
+ links?: LinkPost[];
10
+ failureReasonName?: string;
11
+ autotestExternalId: string;
12
+ outcome: OutcomeType;
13
+ message?: string;
14
+ traces?: string;
15
+ startedOn?: string;
16
+ completeOn?: string;
17
+ duration?: number;
18
+ attachments?: AttachmentPut[];
19
+ parameters?: Parameters;
20
+ stepResults?: AttachmentPutModelAutotestStepResults[];
21
+ setupResults?: AttachmentPutModelAutotestStepResults[];
22
+ teardownResults?: AttachmentPutModelAutotestStepResults[];
23
+ }
@@ -0,0 +1,5 @@
1
+ export interface AutotestStep {
2
+ title: string;
3
+ description?: string;
4
+ steps?: AutotestStep[];
5
+ }
@@ -0,0 +1 @@
1
+ export type Capabilities = Record<string, string>;
@@ -0,0 +1,29 @@
1
+ import {
2
+ Attachment,
3
+ Autotest,
4
+ AutotestPost,
5
+ AutotestPut,
6
+ AutotestQuery,
7
+ AutotestResultsForTestRun,
8
+ ClientConfig,
9
+ TestRunGet,
10
+ TestRunPost,
11
+ WorkItemId,
12
+ } from '.';
13
+
14
+ export interface IClient {
15
+ checkConnection(): Promise<void>;
16
+ getAutotest(query: AutotestQuery): Promise<Autotest[]>;
17
+ createAutotest(autotest: AutotestPost): Promise<Autotest>;
18
+ updateAutotest(autotest: AutotestPut): Promise<void>;
19
+ linkToWorkItem(autotestId: string, workItem: WorkItemId): Promise<void>;
20
+ createTestRun(testRun: TestRunPost): Promise<TestRunGet>;
21
+ startTestRun(testRunId: string): Promise<void>;
22
+ loadTestRunResults(
23
+ testRunId: string,
24
+ results: AutotestResultsForTestRun[]
25
+ ): Promise<string[]>;
26
+ completeTestRun(testRunId: string): Promise<void>;
27
+ getConfig(): ClientConfig;
28
+ loadAttachment(fileName: string): Promise<Attachment>;
29
+ }
@@ -0,0 +1,11 @@
1
+ export interface ClientConfig {
2
+ url: string;
3
+ privateToken: string;
4
+ projectId: string;
5
+ configurationId: string;
6
+ testRunId?: string;
7
+ }
8
+
9
+ export interface ClientConfigWithFile extends ClientConfig {
10
+ configFile?: string;
11
+ }
@@ -0,0 +1,17 @@
1
+ import { Capabilities } from './capabilities';
2
+
3
+ export interface Configuration {
4
+ description?: string;
5
+ isActive?: boolean;
6
+ capabilities: Capabilities;
7
+ projectId?: string;
8
+ isDefault?: boolean;
9
+ name?: string;
10
+ createdDate?: string;
11
+ modifiedDate?: string;
12
+ createdById?: string;
13
+ modifiedById?: string;
14
+ globalId?: number;
15
+ id?: number;
16
+ isDeleted?: boolean;
17
+ }
@@ -0,0 +1,18 @@
1
+ export * from './attachment';
2
+ export * from './autotest';
3
+ export * from './autotestResults';
4
+ export * from './autotestStep';
5
+ export * from './capabilities';
6
+ export * from './client';
7
+ export * from './config';
8
+ export * from './configuration';
9
+ export * from './label';
10
+ export * from './link';
11
+ export * from './outcome';
12
+ export * from './parameters';
13
+ export * from './properties';
14
+ export * from './stepResults';
15
+ export * from './tag';
16
+ export * from './testResult';
17
+ export * from './testRun';
18
+ export * from './workItem';
@@ -0,0 +1,8 @@
1
+ export interface LabelShort {
2
+ globalId?: number;
3
+ name: string;
4
+ }
5
+
6
+ export interface LabelPost {
7
+ name: string;
8
+ }
@@ -0,0 +1,33 @@
1
+ export type LinkType =
2
+ | 'Related'
3
+ | 'BlockedBy'
4
+ | 'Defect'
5
+ | 'Issue'
6
+ | 'Requirement'
7
+ | 'Repository';
8
+
9
+ export interface LinkPost {
10
+ title?: string;
11
+ url: string;
12
+ description?: string;
13
+ type?: LinkType;
14
+ hasInfo?: boolean;
15
+ }
16
+
17
+ export interface LinkPut {
18
+ id?: string;
19
+ title?: string;
20
+ url: string;
21
+ description?: string;
22
+ type?: LinkType;
23
+ hasInfo?: boolean;
24
+ }
25
+
26
+ export interface Link {
27
+ id?: string;
28
+ title?: string;
29
+ url: string;
30
+ description?: string;
31
+ type?: LinkType;
32
+ hasInfo?: boolean;
33
+ }
@@ -0,0 +1,6 @@
1
+ export type OutcomeType =
2
+ | 'Passed'
3
+ | 'Failed'
4
+ | 'Pending'
5
+ | 'Blocked'
6
+ | 'Skipped';
@@ -0,0 +1 @@
1
+ export type Parameters = Record<string, string>;
@@ -0,0 +1 @@
1
+ export type Properties = Record<string, string>;
@@ -0,0 +1,15 @@
1
+ import { AttachmentPut } from './attachment';
2
+ import { OutcomeType } from './outcome';
3
+ import { Parameters } from './parameters';
4
+
5
+ export interface AttachmentPutModelAutotestStepResults {
6
+ title?: string;
7
+ description?: string;
8
+ startedOn?: string;
9
+ completedOn?: string;
10
+ duration?: number;
11
+ outcome?: OutcomeType;
12
+ stepResults?: AttachmentPutModelAutotestStepResults[];
13
+ attachments?: AttachmentPut[];
14
+ parameters?: Parameters;
15
+ }
@@ -0,0 +1,3 @@
1
+ export interface TagShort {
2
+ name: string;
3
+ }
@@ -0,0 +1,9 @@
1
+ export interface TestPointShort {
2
+ testSuiteId?: string;
3
+ id?: string;
4
+ testerId?: string;
5
+ workItemId?: string;
6
+ configurationId?: string;
7
+ status?: string;
8
+ lastTestResultId?: string;
9
+ }
@@ -0,0 +1,32 @@
1
+ import { Attachment } from './attachment';
2
+ import { AutotestGet } from './autotest';
3
+ import { Configuration } from './configuration';
4
+ import { Link } from './link';
5
+ import { OutcomeType } from './outcome';
6
+ import { Parameters } from './parameters';
7
+ import { Properties } from './properties';
8
+ import { TestPointShort } from './testPoint';
9
+
10
+ export interface TestResultGet {
11
+ configuration?: Configuration;
12
+ autotest?: AutotestGet;
13
+ is?: string;
14
+ configurationId?: string;
15
+ workItemVersionId?: string;
16
+ autotestId?: string;
17
+ message?: string;
18
+ traces?: string;
19
+ startedOn?: string;
20
+ completedOn?: string;
21
+ runByUserId?: string;
22
+ stoppedByUserId?: string;
23
+ testPointId?: string;
24
+ testPoint?: TestPointShort;
25
+ testRunId?: string;
26
+ outcome?: OutcomeType;
27
+ comment?: string;
28
+ links?: Link[];
29
+ attachments?: Attachment[];
30
+ parameters?: Parameters;
31
+ properties?: Properties;
32
+ }
@@ -0,0 +1,27 @@
1
+ import { TestResultGet } from './testResult';
2
+
3
+ export type TestRunStateType =
4
+ | 'NotStarted'
5
+ | 'InProgress'
6
+ | 'Stopped'
7
+ | 'Completed';
8
+
9
+ export interface TestRunPost {
10
+ projectId: string;
11
+ name?: string;
12
+ }
13
+
14
+ export interface TestRunGet {
15
+ startedOn?: string;
16
+ completedOn?: string;
17
+ stateName?: TestRunStateType;
18
+ projectId?: string;
19
+ testPlanId?: string;
20
+ testResults?: TestResultGet[];
21
+ createdDate?: string;
22
+ modifiedDate?: string;
23
+ createById?: string;
24
+ modifiedById?: string;
25
+ id: string;
26
+ name: string;
27
+ }
@@ -0,0 +1,3 @@
1
+ export interface WorkItemId {
2
+ id: string;
3
+ }
@@ -0,0 +1,14 @@
1
+ import { z } from 'zod';
2
+ import { ClientConfig } from '.';
3
+
4
+ const configSchema = z.object({
5
+ configurationId: z.string().uuid(),
6
+ privateToken: z.string(),
7
+ projectId: z.string().uuid(),
8
+ url: z.string().url(),
9
+ testRunId: z.string().uuid().optional(),
10
+ });
11
+
12
+ export function validateConfig(config: Partial<ClientConfig>): ClientConfig {
13
+ return configSchema.parse(config);
14
+ }
@@ -0,0 +1,191 @@
1
+ import { Client } from '../src/client';
2
+ import { ClientConfig } from '../src/types/config';
3
+
4
+ jest.mock('fs', () => ({
5
+ existsSync: () => {
6
+ return true;
7
+ },
8
+ readFileSync: (path: string) => {
9
+ switch (path) {
10
+ case '/constructor/config':
11
+ return JSON.stringify({
12
+ url: 'http://file.com',
13
+ } as ClientConfig);
14
+ case '/cli/config':
15
+ return JSON.stringify({
16
+ configurationId: 'cliConfigConfigurationId',
17
+ } as ClientConfig);
18
+ case '/env/config':
19
+ return JSON.stringify({
20
+ projectId: 'envConfigProjectId',
21
+ } as ClientConfig);
22
+ default:
23
+ return {};
24
+ }
25
+ },
26
+ }));
27
+
28
+ describe('Client test', () => {
29
+ describe('Merge config', () => {
30
+ const baseConfig: ClientConfig = {
31
+ url: 'http://base.com',
32
+ projectId: 'baseProjectId',
33
+ configurationId: 'baseConfigurationId',
34
+ privateToken: 'basePrivateToken',
35
+ testRunId: 'baseTestRunId',
36
+ };
37
+
38
+ it('Merge url', () => {
39
+ const mergeUrl = 'http://merge.com';
40
+ const newConfig = Client.mergeConfig(baseConfig, { url: mergeUrl });
41
+
42
+ expect(newConfig).toEqual({ ...baseConfig, url: mergeUrl });
43
+ });
44
+
45
+ it('Merge project id', () => {
46
+ const mergeProjectId = 'mergeProjectId';
47
+ const newConfig = Client.mergeConfig(baseConfig, {
48
+ projectId: mergeProjectId,
49
+ });
50
+
51
+ expect(newConfig).toEqual({
52
+ ...baseConfig,
53
+ projectId: mergeProjectId,
54
+ });
55
+ });
56
+
57
+ it('Merge configuration id', () => {
58
+ const mergeConfigurationId = 'mergeConfigurationId';
59
+ const newConfig = Client.mergeConfig(baseConfig, {
60
+ configurationId: mergeConfigurationId,
61
+ });
62
+
63
+ expect(newConfig).toEqual({
64
+ ...baseConfig,
65
+ configurationId: mergeConfigurationId,
66
+ });
67
+ });
68
+
69
+ it('Merge private token', () => {
70
+ const mergePrivateToken = 'mergePrivateToken';
71
+ const newConfig = Client.mergeConfig(baseConfig, {
72
+ privateToken: mergePrivateToken,
73
+ });
74
+
75
+ expect(newConfig).toEqual({
76
+ ...baseConfig,
77
+ privateToken: mergePrivateToken,
78
+ });
79
+ });
80
+
81
+ it('Merge test run id', () => {
82
+ const mergeTestRunId = 'mergeTestRunId';
83
+ const newConfig = Client.mergeConfig(baseConfig, {
84
+ testRunId: mergeTestRunId,
85
+ });
86
+
87
+ expect(newConfig).toEqual({
88
+ ...baseConfig,
89
+ testRunId: mergeTestRunId,
90
+ });
91
+ });
92
+ });
93
+
94
+ describe('Configuration loading', () => {
95
+ let oldEnv = process.env;
96
+ let oldArgs = process.argv;
97
+
98
+ beforeEach(() => {
99
+ process.env = { ...oldEnv };
100
+ process.argv = [...oldArgs];
101
+ });
102
+
103
+ afterAll(() => {
104
+ process.env = oldEnv;
105
+ process.argv = oldArgs;
106
+ });
107
+
108
+ const config: ClientConfig = {
109
+ url: 'http://test.com',
110
+ configurationId: 'configurationId',
111
+ privateToken: 'privateToken',
112
+ projectId: 'projectId',
113
+ testRunId: 'testRunId',
114
+ };
115
+ it('Constructor config', () => {
116
+ const client = new Client(config);
117
+
118
+ expect(client.getConfig()).toEqual(config);
119
+ });
120
+
121
+ it('Constructor config with file', () => {
122
+ const client = new Client({
123
+ ...config,
124
+ configFile: '/constructor/config',
125
+ });
126
+
127
+ expect(client.getConfig()).toEqual({ ...config, url: 'http://file.com' });
128
+ });
129
+
130
+ it('Env config', () => {
131
+ const envConfig: ClientConfig = {
132
+ url: 'http://env.com',
133
+ configurationId: 'envConfigurationId',
134
+ privateToken: 'envPrivateToken',
135
+ projectId: 'envProjectId',
136
+ testRunId: 'envTestRunId',
137
+ };
138
+ process.env['TESTIT_URL'] = envConfig.url;
139
+ process.env['TESTIT_PRIVATE_TOKEN'] = envConfig.privateToken;
140
+ process.env['TESTIT_PROJECT_ID'] = envConfig.projectId;
141
+ process.env['TESTIT_CONFIGURATION_ID'] = envConfig.configurationId;
142
+ process.env['TESTIT_TEST_RUN_ID'] = envConfig.testRunId;
143
+ const client = new Client(config);
144
+
145
+ expect(client.getConfig()).toEqual(envConfig);
146
+ });
147
+
148
+ it('Env config with file', () => {
149
+ process.env['TESTIT_CONFIG_FILE'] = '/env/config';
150
+ const client = new Client(config);
151
+
152
+ expect(client.getConfig()).toEqual({
153
+ ...config,
154
+ projectId: 'envConfigProjectId',
155
+ });
156
+ });
157
+
158
+ it('Cli args config', () => {
159
+ const cliConfig: ClientConfig = {
160
+ url: 'http://cli.com',
161
+ configurationId: 'cliConfigurationId',
162
+ privateToken: 'cliPrivateToken',
163
+ projectId: 'cliProjectId',
164
+ testRunId: 'cliTestRunId',
165
+ };
166
+ process.argv.push(
167
+ `--testitUrl=${cliConfig.url}`,
168
+ `--testitPrivateToken`,
169
+ cliConfig.privateToken!,
170
+ `--testitProjectId=${cliConfig.projectId}`,
171
+ `--testitConfigurationId`,
172
+ cliConfig.configurationId!,
173
+ `--testitTestRunId=${cliConfig.testRunId}`
174
+ );
175
+ const client = new Client(config);
176
+
177
+ expect(client.getConfig()).toEqual(cliConfig);
178
+ });
179
+
180
+ it('Cli args config with config file', () => {
181
+ process.argv.push(`--testitConfig`, '/cli/config');
182
+
183
+ const client = new Client(config);
184
+
185
+ expect(client.getConfig()).toEqual({
186
+ ...config,
187
+ configurationId: 'cliConfigConfigurationId',
188
+ });
189
+ });
190
+ });
191
+ });
@@ -0,0 +1,68 @@
1
+ import { v4 } from 'uuid';
2
+ import { ClientConfig } from '../src/types';
3
+ import { validateConfig } from '../src/validation';
4
+
5
+ describe('Config validation test', () => {
6
+ it('should return valid config', () => {
7
+ const config: Partial<ClientConfig> = {
8
+ projectId: v4(),
9
+ configurationId: v4(),
10
+ privateToken: 'random token',
11
+ url: 'http://localhost:5000',
12
+ };
13
+ const result = validateConfig(config);
14
+ expect(result).toEqual(config);
15
+ });
16
+
17
+ it('should return valid config with test run id', () => {
18
+ const config: Partial<ClientConfig> = {
19
+ projectId: v4(),
20
+ configurationId: v4(),
21
+ privateToken: 'random token',
22
+ url: 'http://localhost:5000',
23
+ testRunId: v4(),
24
+ };
25
+ const result = validateConfig(config);
26
+ expect(result).toEqual(config);
27
+ });
28
+
29
+ it('should thrown without project id', () => {
30
+ const config: Partial<ClientConfig> = {
31
+ configurationId: v4(),
32
+ privateToken: 'random token',
33
+ url: 'http://localhost:5000',
34
+ testRunId: v4(),
35
+ };
36
+ expect(() => validateConfig(config)).toThrow();
37
+ });
38
+
39
+ it('should thrown without configuration id', () => {
40
+ const config: Partial<ClientConfig> = {
41
+ projectId: v4(),
42
+ privateToken: 'random token',
43
+ url: 'http://localhost:5000',
44
+ testRunId: v4(),
45
+ };
46
+ expect(() => validateConfig(config)).toThrow();
47
+ });
48
+
49
+ it('should thrown without token', () => {
50
+ const config: Partial<ClientConfig> = {
51
+ projectId: v4(),
52
+ configurationId: v4(),
53
+ url: 'http://localhost:5000',
54
+ testRunId: v4(),
55
+ };
56
+ expect(() => validateConfig(config)).toThrow();
57
+ });
58
+
59
+ it('should thrown without url', () => {
60
+ const config: Partial<ClientConfig> = {
61
+ projectId: v4(),
62
+ configurationId: v4(),
63
+ privateToken: 'random token',
64
+ testRunId: v4(),
65
+ };
66
+ expect(() => validateConfig(config)).toThrow();
67
+ });
68
+ });
package/tsconfig.json ADDED
@@ -0,0 +1,102 @@
1
+ {
2
+ "compilerOptions": {
3
+ /* Visit https://aka.ms/tsconfig.json to read more about this file */
4
+
5
+ /* Projects */
6
+ // "incremental": true, /* Enable incremental compilation */
7
+ // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
8
+ // "tsBuildInfoFile": "./", /* Specify the folder for .tsbuildinfo incremental compilation files. */
9
+ // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects */
10
+ // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
11
+ // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
12
+
13
+ /* Language and Environment */
14
+ "target": "es2017" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */,
15
+ // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
16
+ // "jsx": "preserve", /* Specify what JSX code is generated. */
17
+ // "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */
18
+ // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
19
+ // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h' */
20
+ // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
21
+ // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using `jsx: react-jsx*`.` */
22
+ // "reactNamespace": "", /* Specify the object invoked for `createElement`. This only applies when targeting `react` JSX emit. */
23
+ // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
24
+ // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
25
+
26
+ /* Modules */
27
+ "module": "CommonJS" /* Specify what module code is generated. */,
28
+ // "rootDir": "./", /* Specify the root folder within your source files. */
29
+ "moduleResolution": "node" /* Specify how TypeScript looks up a file from a given module specifier. */,
30
+ // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
31
+ // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
32
+ // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
33
+ // "typeRoots": [], /* Specify multiple folders that act like `./node_modules/@types`. */
34
+ // "types": [], /* Specify type package names to be included without being referenced in a source file. */
35
+ // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
36
+ // "resolveJsonModule": true, /* Enable importing .json files */
37
+ // "noResolve": true, /* Disallow `import`s, `require`s or `<reference>`s from expanding the number of files TypeScript should add to a project. */
38
+
39
+ /* JavaScript Support */
40
+ // "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the `checkJS` option to get errors from these files. */
41
+ // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
42
+ // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from `node_modules`. Only applicable with `allowJs`. */
43
+
44
+ /* Emit */
45
+ "declaration": true /* Generate .d.ts files from TypeScript and JavaScript files in your project. */,
46
+ // "declarationMap": true, /* Create sourcemaps for d.ts files. */
47
+ // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
48
+ // "sourceMap": true, /* Create source map files for emitted JavaScript files. */
49
+ // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If `declaration` is true, also designates a file that bundles all .d.ts output. */
50
+ "outDir": "./dist" /* Specify an output folder for all emitted files. */,
51
+ // "removeComments": true, /* Disable emitting comments. */
52
+ // "noEmit": true, /* Disable emitting files from a compilation. */
53
+ // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
54
+ // "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types */
55
+ // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
56
+ // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
57
+ // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
58
+ // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
59
+ // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
60
+ // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
61
+ // "newLine": "crlf", /* Set the newline character for emitting files. */
62
+ // "stripInternal": true, /* Disable emitting declarations that have `@internal` in their JSDoc comments. */
63
+ // "noEmitHelpers": true, /* Disable generating custom helper functions like `__extends` in compiled output. */
64
+ // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
65
+ // "preserveConstEnums": true, /* Disable erasing `const enum` declarations in generated code. */
66
+ // "declarationDir": "./", /* Specify the output directory for generated declaration files. */
67
+
68
+ /* Interop Constraints */
69
+ // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
70
+ // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
71
+ "esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility. */,
72
+ // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
73
+ "forceConsistentCasingInFileNames": true /* Ensure that casing is correct in imports. */,
74
+
75
+ /* Type Checking */
76
+ "strict": true /* Enable all strict type-checking options. */,
77
+ // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied `any` type.. */
78
+ // "strictNullChecks": true, /* When type checking, take into account `null` and `undefined`. */
79
+ // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
80
+ // "strictBindCallApply": true, /* Check that the arguments for `bind`, `call`, and `apply` methods match the original function. */
81
+ // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
82
+ // "noImplicitThis": true, /* Enable error reporting when `this` is given the type `any`. */
83
+ // "useUnknownInCatchVariables": true, /* Type catch clause variables as 'unknown' instead of 'any'. */
84
+ // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
85
+ // "noUnusedLocals": true, /* Enable error reporting when a local variables aren't read. */
86
+ // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read */
87
+ // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
88
+ // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
89
+ // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
90
+ // "noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */
91
+ // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
92
+ // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type */
93
+ // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
94
+ // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
95
+
96
+ /* Completeness */
97
+ // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
98
+ "skipLibCheck": true /* Skip type checking all .d.ts files. */
99
+ },
100
+ "include": ["src"],
101
+ "exclude": ["*.test.*"]
102
+ }