-
Notifications
You must be signed in to change notification settings - Fork 12
/
utils.js
55 lines (46 loc) · 1.7 KB
/
utils.js
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
import { check, fail } from "k6";
export function checkStatus({ response, expectedStatus, expectedContent, failOnError, printOnError, dynamicIds }) {
if (isEmpty(expectedStatus) && isEmpty(expectedContent)) {
console.warn('No expected status or content specified in call to checkStatus for URL ' + response.url);
return;
}
let contentCheckResult;
let statusCheckResult;
let url = response.url;
if (dynamicIds) {
dynamicIds.forEach((dynamicId) => {
if (response.url.includes(dynamicId)) {
url = url.replace(dynamicId, '[id]');
}
});
}
if (expectedContent) {
contentCheckResult = check(response, {
[`"${expectedContent}" in ${url} response`]: (r) => r.body.includes(expectedContent),
});
}
if (expectedStatus) {
const obj = {};
obj[`${response.request.method} ${url} status ${expectedStatus}`] = (r) => r.status === expectedStatus;
statusCheckResult = check(response, obj);
}
if (!statusCheckResult || !contentCheckResult && expectedContent) {
if (printOnError && response.body) {
console.log("Unexpected response: " + response.body);
}
if (failOnError) {
if (!statusCheckResult && (!contentCheckResult && expectedContent)) {
fail(`${response.request.method} ${url} status ${expectedStatus} and "${expectedContent}" not found in response`);
} else {
if (!statusCheckResult) {
fail(`Received unexpected status code ${response.status} for URL: ${url}, expected ${expectedStatus}`);
} else if (!contentCheckResult) {
fail(`"${expectedContent}" not found in response for URL: ${url}`);
}
}
}
}
}
function isEmpty(str) {
return (!str || str.length === 0);
}