| 1 |
/** |
| 2 |
* Global setup for Playwright tests. |
| 3 |
* |
| 4 |
* Authenticates as WordPress admin and saves the storage state |
| 5 |
* so all tests run as an authenticated admin user. |
| 6 |
*/ |
| 7 |
const { chromium } = require( '@playwright/test' ); |
| 8 |
const fs = require( 'fs' ); |
| 9 |
const path = require( 'path' ); |
| 10 |
|
| 11 |
async function globalSetup( config ) { |
| 12 |
const { storageState, baseURL } = config.projects[ 0 ].use; |
| 13 |
const storageStatePath = |
| 14 |
typeof storageState === 'string' ? storageState : undefined; |
| 15 |
|
| 16 |
if ( ! storageStatePath ) { |
| 17 |
return; |
| 18 |
} |
| 19 |
|
| 20 |
// Ensure artifacts directory exists. |
| 21 |
const storageDir = path.dirname( storageStatePath ); |
| 22 |
if ( ! fs.existsSync( storageDir ) ) { |
| 23 |
fs.mkdirSync( storageDir, { recursive: true } ); |
| 24 |
} |
| 25 |
|
| 26 |
const wpUser = process.env.WP_USERNAME || 'admin'; |
| 27 |
const wpPassword = process.env.WP_PASSWORD || 'admin'; |
| 28 |
|
| 29 |
const browser = await chromium.launch(); |
| 30 |
const context = await browser.newContext( { |
| 31 |
baseURL, |
| 32 |
ignoreHTTPSErrors: true, |
| 33 |
} ); |
| 34 |
const page = await context.newPage(); |
| 35 |
|
| 36 |
// Log in to WordPress admin (retry up to 3 times for slow CI environments). |
| 37 |
const maxAttempts = 3; |
| 38 |
for ( let attempt = 1; attempt <= maxAttempts; attempt++ ) { |
| 39 |
try { |
| 40 |
await page.goto( '/wp-login.php', { timeout: 30_000 } ); |
| 41 |
await page.fill( '#user_login', wpUser ); |
| 42 |
await page.fill( '#user_pass', wpPassword ); |
| 43 |
await page.click( '#wp-submit' ); |
| 44 |
await page.waitForURL( '**/wp-admin/**', { |
| 45 |
timeout: 30_000, |
| 46 |
} ); |
| 47 |
break; |
| 48 |
} catch ( e ) { |
| 49 |
if ( attempt === maxAttempts ) { |
| 50 |
throw e; |
| 51 |
} |
| 52 |
// eslint-disable-next-line no-console |
| 53 |
console.log( |
| 54 |
`Login attempt ${ attempt } failed, retrying...` |
| 55 |
); |
| 56 |
await page.waitForTimeout( 3000 ); |
| 57 |
} |
| 58 |
} |
| 59 |
|
| 60 |
// Save auth state. |
| 61 |
await context.storageState( { path: storageStatePath } ); |
| 62 |
|
| 63 |
await browser.close(); |
| 64 |
} |
| 65 |
|
| 66 |
module.exports = globalSetup; |
| 67 |
|