-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvisual-regression.js
More file actions
188 lines (147 loc) · 5.99 KB
/
Copy pathvisual-regression.js
File metadata and controls
188 lines (147 loc) · 5.99 KB
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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
require('dotenv').config();
const backstop = require('backstopjs');
const axios = require('axios');
const https = require('https');
const httpsAgent = new https.Agent({
// This is required to allow self-signed certificates for local development. In production, you should use a valid certificate.
rejectUnauthorized: false
});
const referenceDomain = `${process.env.REFERENCE_DOMAIN}`;
const testDomain = `${process.env.TEST_DOMAIN}`;
const backstopViewport = process.env.BACKSTOP_VIEWPORT || 'large';
const backstopAsyncCaptureLimit = Number.parseInt(process.env.BACKSTOP_ASYNC_CAPTURE_LIMIT || '5', 10);
const backstopAsyncCompareLimit = Number.parseInt(process.env.BACKSTOP_ASYNC_COMPARE_LIMIT || '50', 10);
const statusCheckDelayMs = Number.parseInt(process.env.STATUS_CHECK_DELAY_MS || '500', 10);
const statusCheckMaxRetries = Number.parseInt(process.env.STATUS_CHECK_MAX_RETRIES || '3', 10);
const statusCheckRetryBaseDelayMs = Number.parseInt(process.env.STATUS_CHECK_RETRY_BASE_DELAY_MS || '1000', 10);
let { scenarios } = require('./paths');
const { config } = require('./config');
const { allViewports } = require('./viewports');
const setActiveViewports = () => {
let viewports = [];
switch (backstopViewport) {
case 'all':
for (const viewportKey of Object.keys(allViewports)) {
viewports.push(allViewports[viewportKey]);
}
break;
default:
viewports.push(allViewports[backstopViewport]);
}
return viewports;
};
console.log(`Using BACKSTOP_VIEWPORT=${backstopViewport} for visual regression tests.`);
const activeViewports = setActiveViewports();
if (!activeViewports || activeViewports.length === 0) {
console.error(`No valid viewports found for BACKSTOP_VIEWPORT=${backstopViewport}. Please check your .env configuration.`);
process.exit(1);
}
config.viewports = activeViewports;
config.asyncCaptureLimit = backstopAsyncCaptureLimit;
config.asyncCompareLimit = backstopAsyncCompareLimit;
const referenceConfig = structuredClone(config);
const testConfig = structuredClone(config);
const authUser = process.env.BASIC_AUTH_USER;
const authPass = process.env.BASIC_AUTH_PASSWORD;
const authCreds = authUser && authPass ? `${authUser}:${authPass}@` : '';
scenarios.forEach(scenario => {
const referenceUrl = `https://${authCreds}${referenceDomain}/${scenario.url}`;
const testUrl = `https://${authCreds}${testDomain}/${scenario.url}`;
const referenceScenario = {
label: scenario.label,
url: referenceUrl,
};
const testScenario = {
label: scenario.label,
url: testUrl,
};
if (scenario.properties) {
for (const key of Object.keys(scenario.properties)) {
referenceScenario[key] = scenario.properties[key];
testScenario[key] = scenario.properties[key];
}
}
referenceConfig.scenarios.push(referenceScenario);
testConfig.scenarios.push(testScenario);
});
const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms));
const getRetryDelayMs = (retryAfterHeader, attempt) => {
if (retryAfterHeader) {
const retryAfterSeconds = Number.parseInt(retryAfterHeader, 10);
if (!Number.isNaN(retryAfterSeconds)) {
return retryAfterSeconds * 1000;
}
}
return statusCheckRetryBaseDelayMs * (attempt + 1);
};
const headWithRetry = async (url) => {
let attempt = 0;
while (attempt <= statusCheckMaxRetries) {
try {
return await axios.head(url, { httpsAgent, maxRedirects: 5 });
} catch (err) {
const status = err.response?.status;
if (status !== 429 || attempt === statusCheckMaxRetries) {
throw err;
}
const retryAfter = err.response?.headers?.['retry-after'];
const waitMs = getRetryDelayMs(retryAfter, attempt);
console.warn(`Rate limited (429). Retrying in ${waitMs}ms for ${url}`);
await sleep(waitMs);
attempt += 1;
}
}
return null;
};
const checkStatusCodes = async () => {
const allUrls = [
...referenceConfig.scenarios.map(s => ({ label: s.label, domain: referenceDomain, url: s.url })),
...testConfig.scenarios.map(s => ({ label: s.label, domain: testDomain, url: s.url })),
];
let hasErrors = false;
for (const { label, domain, url } of allUrls) {
try {
const response = await headWithRetry(url);
if (response.status >= 400) {
console.error(`HTTP ${response.status} error for "${label}" on ${domain}: ${url}`);
hasErrors = true;
} else {
console.log(`HTTP ${response.status} — "${label}" on ${domain}`);
}
} catch (err) {
const status = err.response?.status;
if (status) {
console.error(`HTTP ${status} error for "${label}" on ${domain}: ${url}`);
} else {
console.error(`Request failed for "${label}" on ${domain}: ${url} — ${err.message}`);
}
hasErrors = true;
}
await sleep(statusCheckDelayMs);
}
return hasErrors;
};
console.log(`Checking status codes for all URLs on ${referenceDomain} and ${testDomain}...`);
checkStatusCodes().then((hasErrors) => {
if (hasErrors) {
console.error('One or more URLs returned an error status code. Aborting visual regression tests.');
process.exit(1);
}
console.log('All URLs returned successful status codes. Proceeding with visual regression tests.');
console.log(`Running backstop with ${backstopViewport} viewport against ${referenceDomain} to get the reference screenshots.`);
backstop('reference', { config: referenceConfig })
.then(() => {
console.log(`Running backstop against ${testDomain} using ${backstopViewport} viewport to validate that nothing has changed.`);
backstop('test', { config: testConfig }).then(() => {
console.log(`Backstop test passed using ${backstopViewport} viewport`);
}).catch((e) => {
console.error(`Error in backstop test when comparing ${referenceDomain} with ${testDomain} using ${backstopViewport} viewport`);
console.log(e);
process.exit(1);
});
}).catch((e) => {
console.error('Error generating reference screenshots');
console.log(e);
process.exit(1);
});
});