Skip to content

Commit 0c0ab54

Browse files
committed
Build/Test Tools: Replace E2E site state hooks with fixtures.
Four E2E specs each had their own hooks to put settings, options and must-use plugins back after a test. Three shared fixtures in `tests/e2e/fixtures/site.js` now restore that state in teardown, also when a test fails. If a restore fails, the test fails. `siteSettings` changes settings through REST, `siteOptions` changes options through WP-CLI, and `muPlugin` writes a must-use plugin and deletes it after the test. The settings and options fixtures restore only the keys a test changes. The E2E README has a new Fixtures section. Follow-up to [56949], [58068], [58430], [64409], [64584], [65274]. Developed in: #15709 Props adrianmoldovanwp. See #66455. git-svn-id: https://develop.svn.wordpress.org/trunk@65312 602fd350-edb4-49c9-b593-d223f7449a82
1 parent 2f5f4cd commit 0c0ab54

7 files changed

Lines changed: 188 additions & 122 deletions

File tree

‎tests/e2e/README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
# E2E TestsEnd-To-End (E2E) tests for WordPress.## Running the testsThe e2e tests require a production-like environment to run. By default, they will assume an environment is available at `http://localhost:8889`, with username `admin` and password `password`.If you don't already have an environment ready, you can set one up by following [these instructions](https://github.com/WordPress/wordpress-develop/blob/master/README.md).Then you can launch the tests by running:```npm run test:e2e```which will run the test suite using a headless browser.If your environment has a different url, username or password to the default, you can provide the base URL, username and password like this:```WP_BASE_URL=http://mycustomurl WP_USERNAME=username WP_PASSWORD=password npm run test:e2e```**DO NOT run these tests in an actual production environment, as they will delete all your content.**For debugging purposes, you might want to follow the test visually. You can do so by running the tests in an interactive mode:```npm run test:e2e -- --ui```[UI Mode](https://playwright.dev/docs/test-ui-mode) let's you explore, run and debug tests with a time travel experience complete with watch mode.All test files are loaded into the testing sidebar where you can expand each file and describe block to individually run, view, watch and debug each test.You can also run a single test file separately:```npm run test:e2e tests/e2e/specs/hello.test.js```## ProjectsThe suite has three Playwright projects, defined in `playwright.config.js`:* `all`: every spec, one at a time on one worker. `npm run test:e2e` runs this project.* `parallel`: specs that can share the site with other tests. Spec files run at the same time on several workers, one for every two CPU cores. Tests inside one file still run in order. Run it with `npm run test:e2e -- --project=parallel`.* `serial`: specs that break the site for other tests. They run one at a time on one worker. Run it with `npm run test:e2e -- --project=serial`.CI runs `parallel` and `serial` in separate jobs.New specs go in `parallel` by default. Add a spec to `SERIAL_SPECS` only if it makes the site unusable for other tests, or if it changes content or settings that other tests use, for example with `requestUtils.deleteAllPosts()`.Before you open a pull request with a new spec, run its project a few times with `--shuffle`. Playwright then runs the spec files in a random order, so a spec that needs another spec to run first, or that breaks a spec that runs after it, fails:```npm run test:e2e -- --project=parallel --shuffle```Playwright prints the seed of each run, for example `shuffle seed 317753389`. To run the same order again, give the seed: `--shuffle 317753389`.## Logged-out pagesMost specs run logged in as the admin user. There are two ways to run a test logged out:* To make the `page` of a whole `describe` group logged out, add `test.use( { storageState: { cookies: [], origins: [] } } )` to the group. See `specs/dashboard.test.js`.* To use a logged-out page next to the logged-in `page` in one test, import `test` and `expect` from `../fixtures` and use the `loggedOutPage` fixture. Its browser context has no cookies, and it closes when the test ends. Unlike `page`, it resolves a URL that starts with `/` against the host only, not the full `WP_BASE_URL`, so it does not work with a site in a subdirectory. See `specs/cache-control-headers-directives.test.js`.## Documentation* Block Editor Handbook end to end testing overview: https://developer.wordpress.org/block-editor/contributors/code/testing-overview/#end-to-end-testing* Gutenberg e2e-test-utils-playwright package API docs: https://github.com/WordPress/gutenberg/tree/trunk/packages/e2e-test-utils-playwright* Playwright API docs: https://playwright.dev/docs (the version we are using is indicated in the `@wordpress/scripts` package: https://github.com/WordPress/gutenberg/blob/trunk/packages/scripts/package.json)
1+
# E2E TestsEnd-To-End (E2E) tests for WordPress.## Running the testsThe e2e tests require a production-like environment to run. By default, they will assume an environment is available at `http://localhost:8889`, with username `admin` and password `password`.If you don't already have an environment ready, you can set one up by following [these instructions](https://github.com/WordPress/wordpress-develop/blob/master/README.md).Then you can launch the tests by running:```npm run test:e2e```which will run the test suite using a headless browser.If your environment has a different url, username or password to the default, you can provide the base URL, username and password like this:```WP_BASE_URL=http://mycustomurl WP_USERNAME=username WP_PASSWORD=password npm run test:e2e```**DO NOT run these tests in an actual production environment, as they will delete all your content.**For debugging purposes, you might want to follow the test visually. You can do so by running the tests in an interactive mode:```npm run test:e2e -- --ui```[UI Mode](https://playwright.dev/docs/test-ui-mode) let's you explore, run and debug tests with a time travel experience complete with watch mode.All test files are loaded into the testing sidebar where you can expand each file and describe block to individually run, view, watch and debug each test.You can also run a single test file separately:```npm run test:e2e tests/e2e/specs/hello.test.js```## ProjectsThe suite has three Playwright projects, defined in `playwright.config.js`:* `all`: every spec, one at a time on one worker. `npm run test:e2e` runs this project.* `parallel`: specs that can share the site with other tests. Spec files run at the same time on several workers, one for every two CPU cores. Tests inside one file still run in order. Run it with `npm run test:e2e -- --project=parallel`.* `serial`: specs that break the site for other tests. They run one at a time on one worker. Run it with `npm run test:e2e -- --project=serial`.CI runs `parallel` and `serial` in separate jobs.New specs go in `parallel` by default. Add a spec to `SERIAL_SPECS` only if it makes the site unusable for other tests, or if it changes content or settings that other tests use, for example with `requestUtils.deleteAllPosts()`.Before you open a pull request with a new spec, run its project a few times with `--shuffle`. Playwright then runs the spec files in a random order, so a spec that needs another spec to run first, or that breaks a spec that runs after it, fails:```npm run test:e2e -- --project=parallel --shuffle```Playwright prints the seed of each run, for example `shuffle seed 317753389`. To run the same order again, give the seed: `--shuffle 317753389`.## Logged-out pagesMost specs run logged in as the admin user. There are two ways to run a test logged out:* To make the `page` of a whole `describe` group logged out, add `test.use( { storageState: { cookies: [], origins: [] } } )` to the group. See `specs/dashboard.test.js`.* To use a logged-out page next to the logged-in `page` in one test, import `test` and `expect` from `../fixtures` and use the `loggedOutPage` fixture. Its browser context has no cookies, and it closes when the test ends. Unlike `page`, it resolves a URL that starts with `/` against the host only, not the full `WP_BASE_URL`, so it does not work with a site in a subdirectory. See `specs/cache-control-headers-directives.test.js`.## FixturesTo change a setting, an option, or a must-use plugin, import `test` and `expect` from `../fixtures`, and use one of the fixtures in `fixtures/site.js`. Each fixture restores the state when the test ends, also if the test fails. If a restore fails, the test fails.* `siteSettings`: reads and changes the settings of `/wp/v2/settings` through REST, with `get()` and `set( patch )`. It restores only the keys passed to `set`. See `specs/privacy.test.js`.* `siteOptions`: reads and changes options through WP-CLI, with `get( names )` and `set( values )`. It reads and restores the stored `gmt_offset`, not the value calculated for a named timezone. It restores only the keys passed to `set`. See `specs/general-settings-invalid-timezone.test.js`.* `muPlugin`: writes a must-use plugin with `write( fileName, php )`, and deletes the file when the test ends. Call `write` before the test visits a page. See `specs/fatal-error-handler.test.js`.If the test changes a setting or an option through a form, first call `set` with the current value. The fixture then knows that it must restore the key.## Documentation* Block Editor Handbook end to end testing overview: https://developer.wordpress.org/block-editor/contributors/code/testing-overview/#end-to-end-testing* Gutenberg e2e-test-utils-playwright package API docs: https://github.com/WordPress/gutenberg/tree/trunk/packages/e2e-test-utils-playwright* Playwright API docs: https://playwright.dev/docs (the version we are using is indicated in the `@wordpress/scripts` package: https://github.com/WordPress/gutenberg/blob/trunk/packages/scripts/package.json)

‎tests/e2e/fixtures/index.js‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,11 @@
33
*/
44
import { test as base, expect } from '@wordpress/e2e-test-utils-playwright';
55

6+
/**
7+
* Internal dependencies
8+
*/
9+
import { muPlugin, siteOptions, siteSettings } from './site';
10+
611
export const test = base.extend( {
712
loggedOutPage: async ( { browser }, use ) => {
813
const context = await browser.newContext( {
@@ -11,6 +16,9 @@ export const test = base.extend( {
1116
await use( await context.newPage() );
1217
await context.close();
1318
},
19+
muPlugin,
20+
siteOptions,
21+
siteSettings,
1422
} );
1523

1624
export { expect };

‎tests/e2e/fixtures/site.js‎

Lines changed: 148 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,148 @@
1+
/**
2+
* External dependencies
3+
*/
4+
import { mkdir, rm, writeFile } from 'node:fs/promises';
5+
import { join } from 'node:path';
6+
7+
/**
8+
* WordPress dependencies
9+
*/
10+
import { expect } from '@wordpress/e2e-test-utils-playwright';
11+
12+
/**
13+
* Internal dependencies
14+
*/
15+
import { wpCli } from '../utils/wp-cli';
16+
17+
/**
18+
* Writes options, then reads options, through WP-CLI.
19+
*
20+
* @param {string} baseURL The URL of the site.
21+
* @param {string[]} names The names of the options to read.
22+
* @param {Object} values The option values to write. A value of `false` deletes the option.
23+
* @return {Object} The stored values of the options in `names`.
24+
*/
25+
function syncOptions( baseURL, names, values = {} ) {
26+
const input = Buffer.from( JSON.stringify( { names, values } ) ).toString(
27+
'base64'
28+
);
29+
30+
return JSON.parse(
31+
wpCli( [
32+
`--url=${ baseURL }`,
33+
'eval',
34+
`
35+
// Read and restore the stored offset, not the value calculated for a named timezone.
36+
remove_filter( 'pre_option_gmt_offset', 'wp_timezone_override_offset' );
37+
$input = json_decode( base64_decode( '${ input }' ), true );
38+
foreach ( $input['values'] as $option => $value ) {
39+
// get_option() returns false for an option that does not exist.
40+
false === $value ? delete_option( $option ) : update_option( $option, $value );
41+
}
42+
$stored = array();
43+
foreach ( $input['names'] as $option ) {
44+
$stored[ $option ] = get_option( $option );
45+
}
46+
echo wp_json_encode( (object) $stored );
47+
`,
48+
] )
49+
);
50+
}
51+
52+
/**
53+
* Waits for all restores to finish, so that one failure does not stop the others.
54+
*
55+
* @param {Promise[]} restores The restores in progress.
56+
* @throws {AggregateError} If a restore failed.
57+
*/
58+
async function settleRestores( restores ) {
59+
const errors = ( await Promise.allSettled( restores ) )
60+
.filter( ( { status } ) => status === 'rejected' )
61+
.map( ( { reason } ) => reason );
62+
63+
if ( errors.length > 0 ) {
64+
throw new AggregateError(
65+
errors,
66+
errors.map( ( { message } ) => message ).join( '\n' )
67+
);
68+
}
69+
}
70+
71+
/**
72+
* Reads and changes site settings through REST. Teardown restores the keys passed to `set`.
73+
*/
74+
export const siteSettings = async ( { requestUtils }, use ) => {
75+
const originals = {};
76+
const get = () => requestUtils.rest( { path: '/wp/v2/settings' } );
77+
const post = ( data ) =>
78+
requestUtils.rest( { method: 'POST', path: '/wp/v2/settings', data } );
79+
80+
await use( {
81+
get,
82+
set: async ( patch ) => {
83+
const current = await get();
84+
for ( const key of Object.keys( patch ) ) {
85+
if ( ! Object.hasOwn( originals, key ) ) {
86+
originals[ key ] = current[ key ];
87+
}
88+
}
89+
await post( patch );
90+
},
91+
} );
92+
93+
await settleRestores(
94+
Object.entries( originals ).map( async ( [ key, value ] ) => {
95+
const original = { [ key ]: value };
96+
expect( await post( original ) ).toMatchObject( original );
97+
} )
98+
);
99+
};
100+
101+
/**
102+
* Reads and changes site options through WP-CLI. Teardown restores the keys passed to `set`.
103+
*/
104+
export const siteOptions = async ( { baseURL }, use ) => {
105+
let originals = {};
106+
107+
await use( {
108+
get: async ( names ) => syncOptions( baseURL, names ),
109+
set: async ( values ) => {
110+
originals = {
111+
...syncOptions( baseURL, Object.keys( values ) ),
112+
...originals,
113+
};
114+
syncOptions( baseURL, [], values );
115+
},
116+
} );
117+
118+
const names = Object.keys( originals );
119+
if ( names.length > 0 ) {
120+
expect( syncOptions( baseURL, names, originals ) ).toEqual( originals );
121+
}
122+
};
123+
124+
/**
125+
* Writes must-use plugins. Teardown deletes each file that `write` wrote.
126+
*/
127+
export const muPlugin = async ( {}, use ) => {
128+
const directory = join(
129+
process.cwd(),
130+
process.env.LOCAL_DIR ?? 'src',
131+
'wp-content/mu-plugins'
132+
);
133+
const files = new Set();
134+
135+
await use( {
136+
write: async ( fileName, php ) => {
137+
const file = join( directory, fileName );
138+
files.add( file );
139+
await mkdir( directory, { recursive: true } );
140+
await writeFile( file, php );
141+
return file;
142+
},
143+
} );
144+
145+
await settleRestores(
146+
[ ...files ].map( ( file ) => rm( file, { force: true } ) )
147+
);
148+
};

‎tests/e2e/specs/fatal-error-handler.test.js‎

Lines changed: 4 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,36 +1,12 @@
11
/**
2-
* External dependencies
2+
* Internal dependencies
33
*/
4-
import { existsSync, mkdirSync, writeFileSync, unlinkSync } from 'node:fs';
5-
import { join } from 'node:path';
6-
7-
/**
8-
* WordPress dependencies
9-
*/
10-
import { test, expect } from '@wordpress/e2e-test-utils-playwright';
4+
import { test, expect } from '../fixtures';
115

126
test.describe( 'Fatal error handler', () => {
13-
const muPlugins = join(
14-
process.cwd(),
15-
process.env.LOCAL_DIR ?? 'src',
16-
'wp-content/mu-plugins'
17-
);
18-
const muPluginFile = join( muPlugins, 'fatal-error.php' );
19-
20-
test.beforeAll( async () => {
21-
const muPluginCode = `<?php new NonExistentClass();`;
22-
23-
if ( ! existsSync( muPlugins ) ) {
24-
mkdirSync( muPlugins, { recursive: true } );
25-
}
26-
writeFileSync( muPluginFile, muPluginCode );
27-
} );
28-
29-
test.afterAll( async () => {
30-
unlinkSync( muPluginFile );
31-
} );
7+
test( 'should display fatal error notice', async ( { admin, page, muPlugin } ) => {
8+
await muPlugin.write( 'fatal-error.php', `<?php new NonExistentClass();` );
329

33-
test( 'should display fatal error notice', async ( { admin, page } ) => {
3410
await admin.visitAdminPage( '/' );
3511

3612
await expect(

‎tests/e2e/specs/general-settings-invalid-timezone.test.js‎

Lines changed: 7 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -1,49 +1,19 @@
1-
import { test, expect } from '@wordpress/e2e-test-utils-playwright';
2-
import { wpCli } from '../utils/wp-cli';
3-
4-
function timezoneOptions( baseURL, values ) {
5-
const restore = values === undefined ? '' : `
6-
$values = json_decode( base64_decode( '${ Buffer.from( JSON.stringify( values ) ).toString( 'base64' ) }' ), true );
7-
foreach ( $values as $option => $value ) {
8-
update_option( $option, $value );
9-
}
10-
`;
11-
12-
return JSON.parse( wpCli( [
13-
`--url=${ baseURL }`, 'eval',
14-
`
15-
// Read and restore the stored offset, not the value calculated for a named timezone.
16-
remove_filter( 'pre_option_gmt_offset', 'wp_timezone_override_offset' );
17-
${ restore }
18-
echo wp_json_encode( array(
19-
'timezone_string' => get_option( 'timezone_string' ),
20-
'gmt_offset' => get_option( 'gmt_offset' ),
21-
) );
22-
`,
23-
] ) );
24-
}
1+
import { test, expect } from '../fixtures';
252

263
test.describe( 'Settings -> General', () => {
274
const invalidTimezones = [ '', '0', 'Barry/Gary' ];
28-
let originalOptions;
295

30-
test.beforeEach( async ( { admin, baseURL } ) => {
31-
originalOptions = undefined;
32-
originalOptions = timezoneOptions( baseURL );
6+
test.beforeEach( async ( { admin } ) => {
337
await admin.visitAdminPage( '/options-general.php' );
348
} );
359

36-
test.afterEach( async ( { baseURL } ) => {
37-
if ( originalOptions === undefined ) {
38-
return;
39-
}
10+
for ( const invalidTimezone of invalidTimezones ) {
11+
test( `Does not allow saving an invalid timezone string with "${invalidTimezone}"`, async ( { admin, page, siteOptions } ) => {
12+
const originalOptions = await siteOptions.get( [ 'timezone_string', 'gmt_offset' ] );
4013

41-
// The settings form can normalize stored UTC offsets, so restore the options directly.
42-
expect( timezoneOptions( baseURL, originalOptions ) ).toEqual( originalOptions );
43-
} );
14+
// The settings form can normalize stored UTC offsets, so register the options for the fixture to restore directly.
15+
await siteOptions.set( originalOptions );
4416

45-
for ( const invalidTimezone of invalidTimezones ) {
46-
test( `Does not allow saving an invalid timezone string with "${invalidTimezone}"`, async ( { admin, page } ) => {
4717
const validTimezone = originalOptions.timezone_string === 'Europe/Lisbon' ? 'Africa/Libreville' : 'Europe/Lisbon';
4818

4919
// Set the timezone to a different valid value.

‎tests/e2e/specs/login-localize-script.test.js‎

Lines changed: 8 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,13 @@
11
/**
2-
* External dependencies
2+
* Internal dependencies
33
*/
4-
import { existsSync, mkdirSync, writeFileSync, unlinkSync } from 'node:fs';
5-
import { join } from 'node:path';
6-
7-
/**
8-
* WordPress dependencies
9-
*/
10-
import { test, expect } from '@wordpress/e2e-test-utils-playwright';
4+
import { test, expect } from '../fixtures';
115

126
test.describe( 'Localize Script on wp-login.php', () => {
13-
const muPlugins = join(
14-
process.cwd(),
15-
process.env.LOCAL_DIR ?? 'src',
16-
'wp-content/mu-plugins'
17-
);
18-
const muPluginFile = join( muPlugins, 'login-test.php' );
19-
20-
test.beforeAll( async () => {
21-
const muPluginCode = `<?php
7+
test( 'should localize script', async ( { page, muPlugin } ) => {
8+
await muPlugin.write(
9+
'login-test.php',
10+
`<?php
2211
add_action(
2312
'login_enqueue_scripts',
2413
function() {
@@ -30,19 +19,9 @@ test.describe( 'Localize Script on wp-login.php', () => {
3019
]
3120
);
3221
}
33-
);`;
34-
35-
if ( ! existsSync( muPlugins ) ) {
36-
mkdirSync( muPlugins, { recursive: true } );
37-
}
38-
writeFileSync( muPluginFile, muPluginCode );
39-
} );
40-
41-
test.afterAll( async () => {
42-
unlinkSync( muPluginFile );
43-
} );
22+
);`
23+
);
4424

45-
test( 'should localize script', async ( { page } ) => {
4625
await page.goto( '/wp-login.php' );
4726
await expect(
4827
page.getByRole( 'button', { name: 'Log In', exact: true } )

0 commit comments

Comments
 (0)