Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions .github/workflow-scripts/__tests__/visual-report-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ const {
blobKey,
publicUrl,
reportPrefix,
storageLocation,
} = require('../visual/storage');
const {SHA_A, SHA_B} = require('./__fixtures__/visual');

Expand Down Expand Up @@ -79,10 +80,24 @@ describe('visual reports and approval', () => {
}),
],
[() => approvalKey(1, '../x')],
[() => storageLocation({})],
[() => storageLocation({bucket: 'gs://rn-visual'})],
])('rejects invalid input', build => {
expect(build).toThrow('Invalid');
});

test('reads the bucket and its public URL from the visual config', () => {
expect(storageLocation({bucket: 'rn-visual'})).toEqual({
bucket: 'rn-visual',
publicBaseUrl: 'https://storage.googleapis.com/rn-visual',
});
expect(() =>
storageLocation(
require('../../../packages/rn-tester/visual-tests/config.json'),
),
).not.toThrow();
});

test('encodes each path segment of public URLs', () => {
expect(publicUrl('https://cdn.example/bucket/', 'a b/c#d.png')).toBe(
'https://cdn.example/bucket/a%20b/c%23d.png',
Expand Down
14 changes: 11 additions & 3 deletions .github/workflow-scripts/visual/approve-run.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ const {
fetchJsonOrNull,
listPrefixes,
publicUrl,
storageLocation,
} = require('./storage');
const fs = require('node:fs');
const path = require('node:path');
Expand All @@ -43,6 +44,12 @@ function requireEnv(name) {
return value;
}

function readStorageLocation() {
return storageLocation(
JSON.parse(fs.readFileSync(requireEnv('VISUAL_CONFIG'), 'utf8')),
);
}

/** The results of the most recent comparison for a PR head, or null. */
async function latestResults({bucket, publicBaseUrl, prNumber, headSha}) {
const runs = await listPrefixes(
Expand Down Expand Up @@ -83,9 +90,10 @@ async function prepare() {

const prNumber = event.pull_request.number;
const headSha = event.pull_request.head.sha;
const {bucket, publicBaseUrl} = readStorageLocation();
const results = await latestResults({
bucket: requireEnv('VISUAL_BUCKET'),
publicBaseUrl: requireEnv('VISUAL_PUBLIC_BASE_URL'),
bucket,
publicBaseUrl,
prNumber,
headSha,
});
Expand Down Expand Up @@ -149,7 +157,7 @@ async function report() {
? null
: await fetchJsonOrNull(
publicUrl(
requireEnv('VISUAL_PUBLIC_BASE_URL'),
readStorageLocation().publicBaseUrl,
approvalKey(prNumber, fingerprint),
),
);
Expand Down
15 changes: 10 additions & 5 deletions .github/workflow-scripts/visual/capture.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@

const {readAndroidEnvironment, readIosEnvironment} = require('./manifest');
const {retakeScreenshots} = require('./retake');
const {storageLocation} = require('./storage');
const childProcess = require('node:child_process');
const fs = require('node:fs');
const path = require('node:path');
Expand All @@ -32,9 +33,10 @@ node capture.js <platform> <app_path> <app_id> <flows_dir> <output_dir> [ios_udi
Installs the app, then runs every flow in <flows_dir> in one Maestro
invocation, writing screenshots under <output_dir>. Failed flows are retried
up to ${DEFAULT_ATTEMPTS} attempts in total (VISUAL_CAPTURE_ATTEMPTS). With
VISUAL_PUBLIC_BASE_URL set, screenshots that differ from the baseline or have
none are retaken once, and the IDs of new screenshots whose two captures
differ are written as a JSON array to VISUAL_UNSTABLE_PATH.
VISUAL_CONFIG set to the visual config, screenshots that differ from the
baseline in the bucket it names, or have none, are retaken once, and the IDs
of new screenshots whose two captures differ are written as a JSON array to
VISUAL_UNSTABLE_PATH.
`;

/** The flows directly inside `flowsDir`, sorted. Helpers live elsewhere. */
Expand Down Expand Up @@ -200,9 +202,12 @@ async function main(args = process.argv.slice(2)) {
summary.push(...pending.map(flow => `- \`${flow}\``));
}

const publicBaseUrl = process.env.VISUAL_PUBLIC_BASE_URL;
if (publicBaseUrl != null && publicBaseUrl !== '') {
const configPath = process.env.VISUAL_CONFIG;
if (configPath != null && configPath !== '') {
try {
const {publicBaseUrl} = storageLocation(
JSON.parse(fs.readFileSync(configPath, 'utf8')),
);
const {unstable, lines} = await retakeScreenshots({
platform,
environment:
Expand Down
13 changes: 8 additions & 5 deletions .github/workflow-scripts/visual/compare-run.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ const {
findBaseline,
publicUrl,
reportPrefix,
storageLocation,
} = require('./storage');
const {validateCapture} = require('./validate');
const fs = require('node:fs');
Expand All @@ -61,6 +62,10 @@ function requireEnv(name) {
return value;
}

function readConfig() {
return JSON.parse(fs.readFileSync(requireEnv('VISUAL_CONFIG'), 'utf8'));
}

function writeFile(filePath, contents) {
fs.mkdirSync(path.dirname(filePath), {recursive: true});
fs.writeFileSync(filePath, contents);
Expand Down Expand Up @@ -283,10 +288,8 @@ async function prepare() {
const github = createGitHubClient();
const artifactsDir = requireEnv('VISUAL_ARTIFACTS_DIR');
const outDir = requireEnv('OUT_DIR');
const publicBaseUrl = requireEnv('VISUAL_PUBLIC_BASE_URL');
const config = JSON.parse(
fs.readFileSync(requireEnv('VISUAL_CONFIG'), 'utf8'),
);
const config = readConfig();
const {publicBaseUrl} = storageLocation(config);

const context = await resolveContext(github);
if (context == null) {
Expand Down Expand Up @@ -381,7 +384,7 @@ function platformConclusion(platform) {
async function report() {
const github = createGitHubClient();
const outDir = requireEnv('OUT_DIR');
const publicBaseUrl = requireEnv('VISUAL_PUBLIC_BASE_URL');
const {publicBaseUrl} = storageLocation(readConfig());
const state = JSON.parse(
fs.readFileSync(path.join(outDir, 'state.json'), 'utf8'),
);
Expand Down
16 changes: 16 additions & 0 deletions .github/workflow-scripts/visual/storage.js
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,21 @@ function approvalKey(prNumber, fingerprint) {
return `approvals/pull/${prNumber}/${fingerprint}.json`;
}

/**
* The Google Cloud Storage bucket named in config.json, and the public URL
* its objects are read from. Uploads go to the same bucket.
*/
function storageLocation(config) {
const bucket = config?.bucket;
if (
typeof bucket !== 'string' ||
!/^[a-z0-9][a-z0-9._-]+[a-z0-9]$/.test(bucket)
) {
throw new Error(`Invalid bucket in the visual config: ${String(bucket)}`);
}
return {bucket, publicBaseUrl: `https://storage.googleapis.com/${bucket}`};
}

function publicUrl(publicBaseUrl, key) {
return `${publicBaseUrl.replace(/\/$/, '')}/${key
.split('/')
Expand Down Expand Up @@ -176,4 +191,5 @@ module.exports = {
listPrefixes,
publicUrl,
reportPrefix,
storageLocation,
};
7 changes: 4 additions & 3 deletions .github/workflows/visual-approve-rntester.yml
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,7 @@ concurrency:

env:
OUT_DIR: /tmp/visual-approval
VISUAL_BUCKET: ${{ vars.VISUAL_BUCKET }}
VISUAL_PUBLIC_BASE_URL: ${{ vars.VISUAL_PUBLIC_BASE_URL }}
VISUAL_CONFIG: packages/rn-tester/visual-tests/config.json

jobs:
approve:
Expand Down Expand Up @@ -64,7 +63,9 @@ jobs:
uses: google-github-actions/setup-gcloud@aa5489c8933f4cc7a4f7d45035b3b1440c9c10db # v3.0.1
- name: Record approval
if: steps.staged.outputs.upload == 'true'
run: gcloud storage cp --recursive --no-clobber "$OUT_DIR/upload/*" "gs://$VISUAL_BUCKET/"
run: |
VISUAL_BUCKET=$(jq -er .bucket "$VISUAL_CONFIG")
gcloud storage cp --recursive --no-clobber "$OUT_DIR/upload/*" "gs://$VISUAL_BUCKET/"
- name: Update gate
env:
GITHUB_TOKEN: ${{ github.token }}
Expand Down
5 changes: 3 additions & 2 deletions .github/workflows/visual-capture-rntester.yml
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,9 @@ env:
VISUAL_FLOWS: packages/rn-tester/visual-tests/flows
VISUAL_OUTPUT_DIR: /tmp/visual-capture
VISUAL_HEAD_SHA: ${{ github.event.pull_request.head.sha || github.sha }}
# Read-only, to retake screenshots that differ from the baseline.
VISUAL_PUBLIC_BASE_URL: ${{ vars.VISUAL_PUBLIC_BASE_URL }}
# Names the bucket that screenshots differing from the baseline are
# retaken against. Read-only, over its public URL.
VISUAL_CONFIG: packages/rn-tester/visual-tests/config.json
# New screenshots whose two captures differ, for manifest.js. Outside the
# output directory, so it isn't uploaded.
VISUAL_UNSTABLE_PATH: /tmp/visual-unstable.json
Expand Down
3 changes: 1 addition & 2 deletions .github/workflows/visual-compare-rntester.yml
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,6 @@ concurrency:
env:
OUT_DIR: /tmp/visual-out
VISUAL_ARTIFACTS_DIR: /tmp/visual-artifacts
VISUAL_BUCKET: ${{ vars.VISUAL_BUCKET }}
VISUAL_PUBLIC_BASE_URL: ${{ vars.VISUAL_PUBLIC_BASE_URL }}
VISUAL_CONFIG: packages/rn-tester/visual-tests/config.json

jobs:
Expand Down Expand Up @@ -136,6 +134,7 @@ jobs:
- name: Upload report and baseline
if: steps.staged.outputs.upload == 'true'
run: |
VISUAL_BUCKET=$(jq -er .bucket "$VISUAL_CONFIG")
# Objects are write-once; --no-clobber makes a rerun skip what an
# earlier attempt already uploaded.
gcloud storage cp --recursive --no-clobber "$OUT_DIR/upload/*" "gs://$VISUAL_BUCKET/"
Expand Down
2 changes: 2 additions & 0 deletions packages/rn-tester/visual-tests/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ Only `main` and pull requests into it are compared. Stable branches have no base

The baseline for a PR is the one for the commit it's based on, or the nearest earlier commit on `main` that has one. Baselines are keyed by device environment too (OS image, screen size, density, font scale, locale and so on), so a change to the CI device starts a fresh baseline rather than failing every PR.

Baselines, reports and approvals are stored in the public Google Cloud Storage bucket named by `bucket` in `config.json`. Capture reads it over its public URL. Visual Compare RNTester and Visual Approve RNTester upload to it with the access granted by the repository's `VISUAL_GCP_PROJECT` and `VISUAL_WORKLOAD_IDENTITY_PROVIDER` variables, so moving the bucket means changing both.

## Adding a test

1. Pick or add an RNTester example, and give its root view a `testID`. Keep the example's content fixed: no dates, random values, network images or animations that are still running when the screenshot is taken.
Expand Down
1 change: 1 addition & 0 deletions packages/rn-tester/visual-tests/config.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
{
"bucket": "react-native-visual-testing",
"defaults": {
"threshold": 0,
"includeAA": true,
Expand Down
Loading