Pular para o conteúdo principal

Uso programático do Playground CLI

O Playground CLI também pode ser controlado de forma programática no seu código JavaScript/TypeScript usando a função runCLI. Isso dá acesso direto a todas as funcionalidades do CLI no seu código, o que é útil para automatizar testes de ponta a ponta. As opções que você passa para runCLI correspondem diretamente às opções do CLI.

Executando uma instância WordPress com uma versão específica

Usando a função runCLI, você pode especificar opções como as versões do PHP e do WordPress. No exemplo abaixo, solicitamos PHP 8.3, a versão mais recente do WordPress e login automático. Todos os argumentos suportados estão definidos no tipo RunCLIArgs.

import { runCLI } from "@wp-playground/cli";

const cliServer = await runCLI({
command: 'server',
php: '8.3',
wp: 'latest',
login: true,
});

Execute o código acima usando seu runtime TypeScript preferido, por exemplo tsx:

npx tsx my-script.ts

Definindo um blueprint

Você pode fornecer um blueprint de duas formas: como um objeto literal passado diretamente à propriedade blueprint, ou como uma string com o caminho para um arquivo .json externo.

import { runCLI, RunCLIServer } from "@wp-playground/cli";

const cliServer: RunCLIServer = await runCLI({
command: 'server',
wp: 'latest',
blueprint: {
steps: [
{
"step": "setSiteOptions",
"options": {
"blogname": "Blueprint Title",
"blogdescription": "A great blog description"
}
}
],
},
});

Para segurança total de tipos ao definir seu objeto de blueprint, você pode importar e usar o tipo BlueprintDeclaration do pacote @wp-playground/blueprints:

import type { BlueprintDeclaration } from '@wp-playground/blueprints';

const myBlueprint: BlueprintDeclaration = {
landingPage: "/wp-admin/",
steps: [
{
"step": "installTheme",
"themeData": {
"resource": "wordpress.org/themes",
"slug": "twentytwentyone"
},
"options": {
"activate": true
}
}
]
};

Montando um plugin de forma programática

Você pode montar diretórios locais de forma programática usando runCLI. As opções mount e mount-before-install estão disponíveis. A propriedade hostPath espera um caminho para um diretório na sua máquina local. Esse caminho deve ser relativo ao local de onde seu script está sendo executado.

import { runCLI } from "@wp-playground/cli";

cliServer = await runCLI({
command: 'server',
login: true,
'mount-before-install': [
{
hostPath: './[my-plugin-local-path]',
vfsPath: '/wordpress/wp-content/plugins/my-plugin',
},
],
});

Combinando montagens com blueprints

Você pode combinar a montagem de partes do projeto com blueprints, por exemplo:

import { runCLI, RunCLIServer } from "@wp-playground/cli";

const cliServer: RunCLIServer;

cliServer = await runCLI({
command: 'server',
php: '8.3',
wp: 'latest',
login: true,
mount: [
{
"hostPath": "./plugin/",
"vfsPath": "/wordpress/wp-content/plugins/playwright-test"
}
],
blueprint: {
steps: [
{
"step": "activatePlugin",
"pluginPath": "/wordpress/wp-content/plugins/playwright-test/plugin-playwright.php"
}
]
}
});

Testes automatizados

Testes de integração com Vitest

A API programática é excelente para testes automatizados. Aqui está um exemplo completo usando Vitest:

import { describe, test, expect, afterEach } from 'vitest';
import { runCLI, RunCLIServer } from "@wp-playground/cli";

describe('My Plugin Tests', () => {
const cliServer: RunCLIServer;

afterEach(async () => {
if (cliServer) {
await cliServer[Symbol.asyncDispose]();
}
});

test('plugin activates successfully', async () => {
cliServer = await runCLI({
command: 'server',
mount: [
{
hostPath: './my-plugin',
vfsPath: '/wordpress/wp-content/plugins/my-plugin'
}
],
blueprint: {
steps: [
{
step: 'activatePlugin',
pluginPath: '/wordpress/wp-content/plugins/my-plugin/plugin.php'
}
]
}
});

const homeUrl = new URL('/', cliServer.serverUrl);
const response = await fetch(homeUrl);

expect(response.status).toBe(200);
const html = await response.text();
expect(html).toContain('My Plugin');
});

test('plugin settings page loads', async () => {
cliServer = await runCLI({
command: 'server',
login: true, // Auto-login as admin
mount: [
{
hostPath: './my-plugin',
vfsPath: '/wordpress/wp-content/plugins/my-plugin'
}
],
blueprint: {
steps: [
{
step: 'activatePlugin',
pluginPath: '/wordpress/wp-content/plugins/my-plugin/plugin.php'
}
]
}
});

const settingsUrl = new URL(
'/wp-admin/options-general.php?page=my-plugin',
cliServer.serverUrl
);
const response = await fetch(settingsUrl);

expect(response.status).toBe(200);
});
});

Testando com diferentes versões de WordPress/PHP

test('plugin works with WordPress 6.4 and PHP 8.3', async () => {
cliServer = await runCLI({
command: 'server',
php: '8.3',
wp: '6.4',
mount: [
{
hostPath: './my-plugin',
vfsPath: '/wordpress/wp-content/plugins/my-plugin'
}
],
blueprint: {
steps: [
{
step: 'activatePlugin',
pluginPath: '/wordpress/wp-content/plugins/my-plugin/plugin.php'
}
]
}
});

const homeUrl = new URL('/', cliServer.serverUrl);
const response = await fetch(homeUrl);

expect(response.status).toBe(200);
});

Configuração avançada

Pular a configuração do WordPress e do SQLite

Quando você só precisa testar código PHP sem WordPress, pode pular a configuração para testes mais rápidos:

import { runCLI } from "@wp-playground/cli";

const cliServer = await runCLI({
command: 'server',
php: '8.3',
wordpressInstallMode: 'do-not-attempt-installing',
skipSqliteSetup: true,
});

// Test PHP version
await cliServer.playground.writeFile(
'/wordpress/version.php',
'<?php echo phpversion(); ?>'
);

const versionUrl = new URL('/version.php', cliServer.serverUrl);
const response = await fetch(versionUrl);
const version = await response.text();
console.log('PHP Version:', version); // Outputs: 8.3.x

Tratamento de erros

import { runCLI } from "@wp-playground/cli";

try {
const cliServer = await runCLI({
command: 'server',
debug: true // Enable PHP error logging
});

// Your test code here

} catch (error) {
console.error('Server failed to start:', error);
}