Skip to content

Commit 7034c7a

Browse files
committed
Merge branch 'main' into bugfix/ios-pointer-hover-mounting
2 parents f3dc74d + 4160322 commit 7034c7a

116 files changed

Lines changed: 4099 additions & 674 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎.github/workflow-scripts/__tests__/visual-compare-test.js‎

Lines changed: 54 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
*/
1010

1111
const {compareCapture, compareImages, policyFor} = require('../visual/compare');
12-
const {resolveContext} = require('../visual/compare-run');
12+
const {resolveContext, stageBaseline} = require('../visual/compare-run');
1313
const {buildManifest, sha256} = require('../visual/manifest');
1414
const {readPngDimensions} = require('../visual/png');
1515
const {validateCapture} = require('../visual/validate');
@@ -117,6 +117,26 @@ describe('visual comparison', () => {
117117
expect(() => validateCapture(directory)).toThrow('path must be');
118118
});
119119

120+
test.each([
121+
[true, null],
122+
[false, 'unstable must be true or absent'],
123+
['yes', 'unstable must be true or absent'],
124+
])('validates unstable: %p', (unstable, error) => {
125+
const manifest = writeCapture(directory, {
126+
'text/width-mode/default': makePng(4, 4),
127+
});
128+
manifest.images[0].unstable = unstable;
129+
fs.writeFileSync(
130+
path.join(directory, 'manifest.json'),
131+
JSON.stringify(manifest),
132+
);
133+
if (error == null) {
134+
expect(validateCapture(directory)).toEqual(manifest);
135+
} else {
136+
expect(() => validateCapture(directory)).toThrow(error);
137+
}
138+
});
139+
120140
test('rejects duplicates, mismatched hashes and unlisted files', () => {
121141
const manifest = writeCapture(directory, {
122142
'text/width-mode/default': makePng(4, 4),
@@ -261,6 +281,39 @@ describe('visual comparison', () => {
261281
});
262282
});
263283

284+
describe('stageBaseline', () => {
285+
test('leaves out unstable screenshots', () => {
286+
const captureDir = path.join(directory, 'capture');
287+
const outDir = path.join(directory, 'out');
288+
const manifest = writeCapture(captureDir, {
289+
'text/stable/default': makePng(4, 4),
290+
'text/unstable/default': makePng(4, 4),
291+
});
292+
manifest.images[1].unstable = true;
293+
stageBaseline({outDir, captureDir, manifest, sha: SHA_A});
294+
const prefix = `baselines/${manifest.environmentKey}/${SHA_A}`;
295+
const staged = JSON.parse(
296+
fs.readFileSync(
297+
path.join(outDir, 'baseline-manifests', prefix, 'manifest.json'),
298+
'utf8',
299+
),
300+
);
301+
expect(staged.images.map(image => image.id)).toEqual([
302+
'text/stable/default',
303+
]);
304+
expect(
305+
fs.existsSync(
306+
path.join(
307+
outDir,
308+
'baseline-images',
309+
prefix,
310+
'text/unstable/default.png',
311+
),
312+
),
313+
).toBe(false);
314+
});
315+
});
316+
264317
describe('resolveContext', () => {
265318
const ENV = {
266319
CAPTURE_HEAD_SHA: SHA_A,

‎.github/workflow-scripts/__tests__/visual-report-test.js‎

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -150,14 +150,17 @@ describe('visual reports and approval', () => {
150150
{id: 'a/b/same', status: 'unchanged'},
151151
changed('a/b/changed'),
152152
]),
153-
platform('ios', [{id: 'a/b/new', status: 'added', captured: {}}]),
153+
platform('ios', [
154+
{id: 'a/b/new', status: 'added', captured: {}},
155+
{id: 'a/b/flaky', status: 'added', captured: {unstable: true}},
156+
]),
154157
],
155158
headSha: SHA_A,
156159
gateSummary: 'Needs approval.',
157160
});
158161
expect(body.startsWith(COMMENT_MARKER)).toBe(true);
159162
expect(body).toContain(
160-
'**2 visual difference(s)** at `aaaaaaaaaaaa`. Needs approval.',
163+
'**3 visual difference(s)** at `aaaaaaaaaaaa`. Needs approval.',
161164
);
162165
expect(body).toContain(
163166
'### android `a/b/changed`: Changed, 3 px (3.000%)',
@@ -168,7 +171,10 @@ describe('visual reports and approval', () => {
168171
expect(body).toContain(
169172
'<details><summary>Expected and Captured</summary>',
170173
);
171-
expect(body).toContain('### ios `a/b/new`: New');
174+
expect(body).toContain('### ios `a/b/new`: New\n');
175+
expect(body).toContain(
176+
'### ios `a/b/flaky`: New, unstable: its two captures differed',
177+
);
172178
expect(body).toContain('<details open><summary>Captured</summary>');
173179
expect(body).not.toContain('a/b/same');
174180
});
Lines changed: 188 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,188 @@
1+
/**
2+
* Copyright (c) Meta Platforms, Inc. and affiliates.
3+
*
4+
* This source code is licensed under the MIT license found in the
5+
* LICENSE file in the root directory of this source tree.
6+
*
7+
* @noflow
8+
* @format
9+
*/
10+
11+
const {buildManifest} = require('../visual/manifest');
12+
const {
13+
flowsTaking,
14+
judgeRetakes,
15+
retakeCandidates,
16+
retakeScreenshots,
17+
screenshotIds,
18+
} = require('../visual/retake');
19+
const {ANDROID_ENVIRONMENT, SHA_A} = require('./__fixtures__/visual');
20+
const fs = require('node:fs');
21+
const os = require('node:os');
22+
const path = require('node:path');
23+
24+
const baselineManifest = {
25+
images: [
26+
{id: 'switch/basic/default', sha256: 'a'},
27+
{id: 'switch/basic/toggled', sha256: 'b'},
28+
],
29+
};
30+
31+
const BUNNY = path.join(
32+
__dirname,
33+
'../../../packages/rn-tester/js/assets/bunny.png',
34+
);
35+
36+
const images = [
37+
{id: 'switch/basic/default', sha256: 'a'},
38+
{id: 'switch/basic/toggled', sha256: 'x'},
39+
{id: 'view/basic/default', sha256: 'n'},
40+
];
41+
42+
describe('visual retake', () => {
43+
test('reads the test IDs a flow captures', () => {
44+
const flow = [
45+
'appId: ${APP_ID}',
46+
'---',
47+
'- takeScreenshot:',
48+
' path: ${VISUAL_OUTPUT_DIR}/switch/basic/default',
49+
' cropOn:',
50+
" id: 'switch-basic'",
51+
'- takeScreenshot:',
52+
" path: '${VISUAL_OUTPUT_DIR}/switch/basic/toggled'",
53+
].join('\n');
54+
expect(screenshotIds(flow)).toEqual([
55+
'switch/basic/default',
56+
'switch/basic/toggled',
57+
]);
58+
});
59+
60+
test('selects only the flows that take the given IDs', () => {
61+
const files = {
62+
'/flows/switch.yml':
63+
'- takeScreenshot: ${VISUAL_OUTPUT_DIR}/switch/basic/toggled',
64+
'/flows/text.yml':
65+
'- takeScreenshot: ${VISUAL_OUTPUT_DIR}/text/width-mode/default',
66+
'/flows/view.yml':
67+
'- takeScreenshot: ${VISUAL_OUTPUT_DIR}/view/basic/default',
68+
};
69+
expect(
70+
flowsTaking(
71+
Object.keys(files),
72+
['text/width-mode/default', 'switch/basic/toggled'],
73+
file => files[file],
74+
),
75+
).toEqual(['/flows/switch.yml', '/flows/text.yml']);
76+
});
77+
78+
test('retakes changed and new screenshots but not unchanged ones', () => {
79+
expect(retakeCandidates(images, baselineManifest)).toEqual({
80+
changed: ['switch/basic/toggled'],
81+
added: ['view/basic/default'],
82+
});
83+
});
84+
85+
test.each([
86+
['matches the baseline', 'b', ['switch/basic/toggled']],
87+
['still differs', 'y', []],
88+
['is missing', null, []],
89+
])('replaces a changed screenshot if its retake %s', (_, sha, replaced) => {
90+
expect(
91+
judgeRetakes({
92+
changed: ['switch/basic/toggled'],
93+
added: [],
94+
images,
95+
baselineManifest,
96+
retakeSha: () => sha,
97+
}).replaced,
98+
).toEqual(replaced);
99+
});
100+
101+
test.each([
102+
['is identical', 'n', []],
103+
['differs', 'y', ['view/basic/default']],
104+
['is missing', null, ['view/basic/default']],
105+
])('marks a new screenshot unstable if its retake %s', (_, sha, unstable) => {
106+
expect(
107+
judgeRetakes({
108+
changed: [],
109+
added: ['view/basic/default'],
110+
images,
111+
baselineManifest,
112+
retakeSha: () => sha,
113+
}).unstable,
114+
).toEqual(unstable);
115+
});
116+
117+
test('retakes every screenshot when the environment has no baseline', async () => {
118+
// The repo's Jest config fakes timers, and the retake waits on one.
119+
jest.useRealTimers();
120+
const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'visual-test-'));
121+
const fetchSpy = jest
122+
.spyOn(global, 'fetch')
123+
.mockResolvedValue(new Response(null, {status: 404}));
124+
try {
125+
const outputDir = path.join(directory, 'out');
126+
const png = fs.readFileSync(BUNNY);
127+
const write = (dir, id, contents) => {
128+
fs.mkdirSync(path.join(dir, path.dirname(id)), {recursive: true});
129+
fs.writeFileSync(path.join(dir, `${id}.png`), contents);
130+
};
131+
write(outputDir, 'view/basic/default', png);
132+
write(outputDir, 'view/basic/flaky', png);
133+
const flow = path.join(directory, 'view.yml');
134+
fs.writeFileSync(
135+
flow,
136+
[
137+
'- takeScreenshot: ${VISUAL_OUTPUT_DIR}/view/basic/default',
138+
'- takeScreenshot: ${VISUAL_OUTPUT_DIR}/view/basic/flaky',
139+
].join('\n'),
140+
);
141+
const runFlows = jest.fn((flows, retakeDir) => {
142+
write(retakeDir, 'view/basic/default', png);
143+
write(retakeDir, 'view/basic/flaky', Buffer.concat([png, png]));
144+
});
145+
const {unstable} = await retakeScreenshots({
146+
platform: 'android',
147+
environment: ANDROID_ENVIRONMENT,
148+
flows: [flow],
149+
outputDir,
150+
publicBaseUrl: 'https://storage.example',
151+
runFlows,
152+
candidateShas: [SHA_A],
153+
delayMs: 0,
154+
});
155+
expect(runFlows).toHaveBeenCalledWith([flow], `${outputDir}-retake`);
156+
expect(unstable).toEqual(['view/basic/flaky']);
157+
} finally {
158+
fetchSpy.mockRestore();
159+
fs.rmSync(directory, {recursive: true, force: true});
160+
}
161+
});
162+
163+
test('marks unstable screenshots in the manifest', () => {
164+
const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'visual-test-'));
165+
try {
166+
const png = fs.readFileSync(BUNNY);
167+
for (const id of ['view/basic/default', 'view/basic/flaky']) {
168+
fs.mkdirSync(path.join(directory, path.dirname(id)), {recursive: true});
169+
fs.writeFileSync(path.join(directory, `${id}.png`), png);
170+
}
171+
const manifest = buildManifest({
172+
captureDir: directory,
173+
platform: 'android',
174+
environment: ANDROID_ENVIRONMENT,
175+
git: null,
176+
unstableIds: ['view/basic/flaky'],
177+
});
178+
expect(manifest.images.map(({id, unstable}) => ({id, unstable}))).toEqual(
179+
[
180+
{id: 'view/basic/default', unstable: undefined},
181+
{id: 'view/basic/flaky', unstable: true},
182+
],
183+
);
184+
} finally {
185+
fs.rmSync(directory, {recursive: true, force: true});
186+
}
187+
});
188+
});

‎.github/workflow-scripts/visual/capture.js‎

Lines changed: 53 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,12 @@
1212
* Captures every visual flow in one Maestro invocation, so the JVM and
1313
* driver startup (around two minutes on an iOS simulator) is paid once per
1414
* job rather than once per flow. Flows that fail are rerun, and only those,
15-
* on later attempts.
15+
* on later attempts. Screenshots that then differ from the baseline, or
16+
* have none, are retaken once (see retake.js).
1617
*/
1718

19+
const {readAndroidEnvironment, readIosEnvironment} = require('./manifest');
20+
const {retakeScreenshots} = require('./retake');
1821
const childProcess = require('node:child_process');
1922
const fs = require('node:fs');
2023
const path = require('node:path');
@@ -28,7 +31,10 @@ node capture.js <platform> <app_path> <app_id> <flows_dir> <output_dir> [ios_udi
2831
2932
Installs the app, then runs every flow in <flows_dir> in one Maestro
3033
invocation, writing screenshots under <output_dir>. Failed flows are retried
31-
up to ${DEFAULT_ATTEMPTS} attempts in total (VISUAL_CAPTURE_ATTEMPTS).
34+
up to ${DEFAULT_ATTEMPTS} attempts in total (VISUAL_CAPTURE_ATTEMPTS). With
35+
VISUAL_PUBLIC_BASE_URL set, screenshots that differ from the baseline or have
36+
none are retaken once, and the IDs of new screenshots whose two captures
37+
differ are written as a JSON array to VISUAL_UNSTABLE_PATH.
3238
`;
3339

3440
/** The flows directly inside `flowsDir`, sorted. Helpers live elsewhere. */
@@ -140,7 +146,7 @@ function writeSummary(lines) {
140146
}
141147
}
142148

143-
function main(args = process.argv.slice(2)) {
149+
async function main(args = process.argv.slice(2)) {
144150
const [platform, appPath, appId, flowsDir, outputDir, udid] = args;
145151
if (
146152
!['android', 'ios'].includes(platform) ||
@@ -193,14 +199,57 @@ function main(args = process.argv.slice(2)) {
193199
summary.push('', `Failed after ${attempts} attempt(s):`);
194200
summary.push(...pending.map(flow => `- \`${flow}\``));
195201
}
202+
203+
const publicBaseUrl = process.env.VISUAL_PUBLIC_BASE_URL;
204+
if (publicBaseUrl != null && publicBaseUrl !== '') {
205+
try {
206+
const {unstable, lines} = await retakeScreenshots({
207+
platform,
208+
environment:
209+
platform === 'android'
210+
? readAndroidEnvironment()
211+
: readIosEnvironment(udid),
212+
flows: allFlows,
213+
outputDir,
214+
publicBaseUrl,
215+
runFlows: (flows, retakeDir) =>
216+
runAttempt(
217+
maestroArgs({
218+
flows,
219+
appId,
220+
outputDir: retakeDir,
221+
reportPath: path.resolve('visual-capture-report-retake.xml'),
222+
udid,
223+
attempt: attempts + 1,
224+
}),
225+
),
226+
});
227+
if (lines.length > 0) {
228+
summary.push('', ...lines);
229+
}
230+
if (process.env.VISUAL_UNSTABLE_PATH) {
231+
fs.writeFileSync(
232+
process.env.VISUAL_UNSTABLE_PATH,
233+
`${JSON.stringify(unstable)}\n`,
234+
);
235+
}
236+
} catch (error) {
237+
// The original screenshots are still valid, so compare goes ahead
238+
// with them.
239+
console.warn('Retaking screenshots failed:', error);
240+
}
241+
}
196242
writeSummary(summary);
197243
if (pending.length > 0) {
198244
process.exitCode = 1;
199245
}
200246
}
201247

202248
if (require.main === module) {
203-
main();
249+
main().catch(error => {
250+
console.error(error);
251+
process.exitCode = 1;
252+
});
204253
}
205254

206255
module.exports = {collectFlows, failedFlowsFromJUnit, maestroArgs};

0 commit comments

Comments
 (0)