/
testUtils.ts
107 lines (96 loc) · 2.75 KB
/
testUtils.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
// Copyright 2020 Cognite AS
import BaseCogniteClient from './baseCogniteClient';
import { BASE_URL } from './constants';
import { sleepPromise } from './utils';
export const apiKey = 'TEST_KEY';
export const project = 'TEST_PROJECT';
export const projectId = 123;
export const user = 'user@example.com';
export const loggedInResponse = {
data: { loggedIn: true, user, project, projectId },
};
export const notLoggedInResponse = {
data: { loggedIn: false, user: '', project: '' },
};
export const mockBaseUrl = 'https://example.com';
export const authTokens = {
accessToken: 'abc',
idToken: 'def',
};
export function setupClient(baseUrl: string = BASE_URL) {
return new BaseCogniteClient({
appId: 'JS SDK integration tests',
project: process.env.COGNITE_PROJECT as string,
apiKeyMode: true,
getToken: () => Promise.resolve(process.env.COGNITE_CREDENTIALS as string),
baseUrl,
});
}
export function setupLoggedInClient() {
jest.setTimeout(60 * 1000);
const client = setupClient();
return client;
}
export function setupMockableClient() {
const client = setupClient(mockBaseUrl);
return client;
}
export async function retryInSeconds<ResponseType>(
func: () => Promise<ResponseType>,
secondsBetweenRetries = 3,
statusCodeToRetry = 404,
finishAfterSeconds: number = 300
): Promise<ResponseType> {
const timeStart = Date.now();
while (Date.now() - timeStart < finishAfterSeconds * 1000) {
try {
return await func();
} catch (error) {
if (Number(error.status) !== statusCodeToRetry) {
throw error;
}
await sleepPromise(secondsBetweenRetries * 1000);
}
}
throw new Error('Time limit has been exceeded');
}
export async function runTestWithRetryWhenFailing(
testFunction: () => Promise<void>
) {
jest.setTimeout(3 * 60 * 1000);
const maxNumberOfRetries = 15;
const delayFactor = 2;
let delayInMs = 500;
let numberOfRetries = 0;
let error;
do {
try {
await testFunction();
return;
} catch (err) {
error = err;
await sleepPromise(delayInMs);
delayInMs *= delayFactor;
numberOfRetries++;
}
} while (numberOfRetries < maxNumberOfRetries);
throw error;
}
export const simpleCompare = (a: number, b: number) => a - b;
export function getSortedPropInArray<T extends { [key: string]: any }>(
arr: T[],
propName: string
) {
return arr.map((elem) => elem[propName]).sort(simpleCompare);
}
export function string2arrayBuffer(str: string) {
const buf = new ArrayBuffer(str.length * 2); // 2 bytes for each char
const bufView = new Uint16Array(buf);
for (let i = 0, strLen = str.length; i < strLen; i++) {
bufView[i] = str.charCodeAt(i);
}
return buf;
}
export function randomInt() {
return Math.floor(Math.random() * 10000000000);
}