Ir al contenido principal

Uso programático del Playground CLI

El Playground CLI también puede controlarse de forma programática desde tu código JavaScript/TypeScript usando la función runCLI. Esto te da acceso directo a todas las funcionalidades del CLI en tu código, lo cual es útil para automatizar pruebas de extremo a extremo. Las opciones que pasas a runCLI se corresponden directamente con las opciones del CLI.

Ejecutar una instancia de WordPress con una versión específica

Con la función runCLI puedes especificar opciones como las versiones de PHP y WordPress. En el ejemplo siguiente solicitamos PHP 8.3, la última versión de WordPress y el inicio de sesión automático. Todos los argumentos soportados están definidos en el tipo RunCLIArgs.

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

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

Ejecuta el código anterior con tu runtime de TypeScript preferido, por ejemplo tsx:

npx tsx my-script.ts

Definir un blueprint

Puedes proporcionar un blueprint de dos formas: como un objeto literal pasado directamente a la propiedad blueprint, o como una cadena con la ruta a un archivo .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 tener seguridad de tipos completa al definir tu objeto blueprint, puedes importar y usar el tipo BlueprintDeclaration del paquete @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
}
}
]
};

Montar un plugin de forma programática

Puedes montar directorios locales de forma programática con runCLI. Las opciones mount y mount-before-install están disponibles. La propiedad hostPath espera una ruta a un directorio en tu máquina local. Esta ruta debe ser relativa al lugar desde el que se ejecuta tu script.

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',
},
],
});

Combinar montajes con blueprints

Puedes combinar el montaje de partes del proyecto con blueprints, por ejemplo:

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"
}
]
}
});

Pruebas automatizadas

Pruebas de integración con Vitest

La API programática es excelente para pruebas automatizadas. Aquí tienes un ejemplo completo con 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);
});
});

Probar con distintas versiones 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);
});

Configuración avanzada

Omitir la configuración de WordPress y SQLite

Cuando solo necesitas probar código PHP sin WordPress, puedes omitir la configuración para pruebas más rápidas:

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

Manejo de errores

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);
}