Testing and operations
Testing
This page sets up PHPUnit in an application, tests routes in-process with Taphra\Testing\HttpTestCase, gives the tests their own database, logs users in, and replaces AI providers with a fake transport. Pest works on the same base class.
The examples on this page were run as written with PHPUnit 11 and Pest 3 on PHP 8.4, in an application made from the skeleton.
Contents
#- Setting up PHPUnit
- HTTP tests
- HTML pages, redirects and HTMX
- Raw bodies: webhooks and XML
- A database for tests
- Logged-in users
- Faking AI providers
- Pest
- What in-process tests do not cover
Setting up PHPUnit
#PHPUnit is a development dependency of your app, not of the framework:
composer require --dev phpunit/phpunit:^11Boot the app once for the whole run. The bootstrap hands error handling back to PHPUnit (the app registers its own handlers) and points the default connection at a test database:
<?php
// test/bootstrap.php
chdir(__DIR__ . '/../app/Static');
require 'indexcommon.php';
// Hand errors and exceptions back to PHPUnit (the app registers its own handlers).
restore_error_handler();
restore_exception_handler();
// Tests use their own SQLite database.
foreach (['type' => 'sqlite', 'name' => APP_TMP_PATH . '/test.sqlite', 'host' => '', 'port' => '', 'user' => '', 'password' => ''] as $key => $value) {
\Taphra\Config::set("databases.app_master.$key", $value);
}<?xml version="1.0" encoding="UTF-8"?>
<!-- phpunit.xml -->
<phpunit bootstrap="test/bootstrap.php" colors="true">
<testsuites>
<testsuite name="app">
<directory>test</directory>
</testsuite>
</testsuites>
<php>
<env name="APP_ENV" value="dev"/>
</php>
</phpunit>Run the tests in development mode, as above: an unknown APP_ENV such as test means production, which caches the parsed configuration and hides error details.
php taphra make:test Post # test/unit/PostTest.php
php taphra make:test Post --integration # test/integration/PostTest.php
vendor/bin/phpunitmake:test writes an empty PHPUnit\Framework\TestCase; change the parent class to HttpTestCase for HTTP tests.
HTTP tests
#HttpTestCase sends a request through the same PSR-15 pipeline and router the application uses, without a server: routes from app/Config/routes.yml, route group middleware, the controller, and its response. The routes and controller tested here are the ones from REST APIs (GET /api/posts, GET /api/posts/{id} and POST /api/posts).
<?php
// test/Http/PostApiTest.php
use Taphra\DatabaseConnection;
use Taphra\SchemaBuilder;
use Taphra\Testing\HttpTestCase;
class PostApiTest extends HttpTestCase
{
protected function setUp(): void
{
parent::setUp();
$schema = new SchemaBuilder(DatabaseConnection::load('app_master'));
$schema->dropIfExists('posts');
$schema->create('posts', function ($t) {
$t->id();
$t->string('title');
$t->text('body')->nullable();
$t->string('status', 20)->default('draft');
});
}
public function testCreatesAPost(): void
{
$this->postJson('/api/posts', ['title' => 'Hello', 'status' => 'published'])
->assertCreated()
->assertHeader('Location', '/api/posts/1')
->assertJsonPath('title', 'Hello');
$this->get('/api/posts')
->assertOk()
->assertJsonPath('0.title', 'Hello');
}
public function testRejectsInvalidInput(): void
{
$this->postJson('/api/posts', ['title' => 'x'])
->assertUnprocessable()
->assertJsonHasKey('errors');
}
public function testMissingPostIs404(): void
{
$this->get('/api/posts/99')->assertNotFound();
}
public function testWrongMethodIs405(): void
{
$this->delete('/api/posts')->assertStatus(405)->assertHeader('Allow');
}
}Requests: get($path, $headers = []), post($path, $body = [], $headers = []), put(), patch(), delete() (form fields), and postJson(), putJson(), patchJson() (a JSON body with Content-Type: application/json). A query string in $path fills $_GET. The request headers are also in $_SERVER while the request runs, as a web server puts them (HX-Request as HTTP_HX_REQUEST, Content-Type as CONTENT_TYPE). Each request starts with status 200, and $_GET, $_POST and the request method are restored after it. A $_SERVER entry a header filled goes back to what it was before the request (removed if it did not exist) when it still holds the header's value; if your app changed or removed it during the request, your app's change stays, so a test can check it.
Each returns a Taphra\Testing\TestResponse. Its assertions return the response, so they chain:
| Assertion | Passes when |
|---|---|
assertStatus(int) |
the status is exactly this |
assertOk(), assertCreated(), assertNoContent() |
200, 201, 204 |
assertUnauthorized(), assertForbidden(), assertNotFound(), assertUnprocessable() |
401, 403, 404, 422 |
assertSuccessful(), assertServerError() |
any 2xx, any 5xx |
assertRedirect(?string $location = null) |
a 3xx, with this Location when given |
assertSee(string), assertDontSee(string) |
the body contains (does not contain) the text |
assertBodyEquals(string), assertBodyEmpty() |
the body is exactly this, or empty |
assertHeader(string $name, ?string $value = null), assertHeaderMissing(string) |
the header is present (with this value), or absent |
assertJsonPath(string $path, mixed $expected) |
the value at a dot path (user.email, items.0.id) equals $expected |
assertJsonFragment(array) |
the decoded body has these top-level keys with these values |
assertJsonEquals(array) |
the decoded body is exactly this array |
assertJsonHasKey(string) |
the decoded body has this top-level key |
getStatus(), getBody(), getHeader($name), json() and getPsr7Response() read the response directly.
To put middleware in front of the application for one test, call $this->withMiddleware(new SomeMiddleware()) before the request; to change it for a whole class, override buildPipeline(), which must end with Taphra\Http\ActionDispatcherMiddleware.
HTML pages, redirects and HTMX
#An HTML controller tests the same way, as long as its actions return. redirect() ends the PHP process, which would end the test run; an action that returns $this->seeOther($url) answers with a 303 and a Location header that the test can check, and $this->header() sets headers the test sees:
// app/Controllers/NoteController.php (actions)
public function store(): string
{
// ... validate and save $_POST ...
return $this->seeOther('/notes');
}
public function index(): string
{
if ($this->isHtmx()) {
$this->htmxTriggerEvent('notes-loaded');
return 'the list'; // the partial an HTMX swap expects
}
return 'the whole page';
}<?php
// test/Http/NoteTest.php
use Taphra\Testing\HttpTestCase;
class NoteTest extends HttpTestCase
{
public function testSavingRedirectsToTheList(): void
{
$this->post('/notes', ['body' => 'Buy milk', '_csrf_token' => \Taphra\Security::generateCsrfToken()])
->assertStatus(303)
->assertRedirect('/notes');
}
public function testHtmxGetsThePartial(): void
{
$this->get('/notes', ['HX-Request' => 'true'])
->assertOk()
->assertBodyEquals('the list')
->assertHeader('HX-Trigger', 'notes-loaded');
}
}The routes are POST /notes: note/store and GET /notes: note/index. A controller that extends the skeleton's AppController checks the CSRF token, so the form sends one; the X-CSRF-Token header works too, since request headers reach $_SERVER.
Raw bodies: webhooks and XML
#postRaw($path, $body, $contentType, $headers = []) sends a body exactly as given, with its Content-Type: a signed webhook payload, XML, a JSON list, malformed JSON. sendRaw($method, $path, $body, $contentType, $headers = []) does the same for any method. The body travels through the pipeline as on a server: middleware such as JsonBodyMiddleware parses it when the pipeline has it, a JSON object or list also fills $_POST, and a form-urlencoded body fills $_POST as PHP does. The action and every middleware of the test's pipeline, route middleware included, read the bytes with Request::rawBody() (Requests), since php://input is empty in tests.
<?php
// test/Http/WebhookTest.php
use Taphra\Testing\HttpTestCase;
class WebhookTest extends HttpTestCase
{
public function testASignedEventIsAccepted(): void
{
$payload = '{"event":"invoice.paid","id":"evt_1"}';
$this->postRaw('/webhooks/billing', $payload, 'application/json', [
'X-Signature' => hash_hmac('sha256', $payload, 'test-secret'),
])->assertOk();
}
public function testATamperedBodyIsRefused(): void
{
$payload = '{"event":"invoice.paid","id":"evt_1"}';
$this->postRaw('/webhooks/billing', $payload . ' ', 'application/json', [
'X-Signature' => hash_hmac('sha256', $payload, 'test-secret'),
])->assertUnauthorized();
}
public function testMalformedJsonIsABadRequest(): void
{
$payload = '{"event": ';
$this->postRaw('/webhooks/billing', $payload, 'application/json', [
'X-Signature' => hash_hmac('sha256', $payload, 'test-secret'),
])->assertStatus(400);
}
}The webhook action is the one in Requests, routed as POST /webhooks/billing, with WEBHOOK_SECRET=test-secret set for the tests (<env name="WEBHOOK_SECRET" value="test-secret"/> in phpunit.xml).
A database for tests
#The bootstrap above sends the app_master connection to app/tmp/test.sqlite. Create the tables each test needs in setUp(), as PostApiTest does, or run your migrations' up() methods there, and fill them with factories:
(new \App\Factories\PostFactory())->count(3)->create();SQLite is fast enough to rebuild the schema per test. To test against MySQL or PostgreSQL, point the connection at a dedicated test database in the bootstrap instead.
The DataStores and DatabaseConnection::load() keep one connection per name for the whole test run. An in-memory SQLite database (name: ':memory:') therefore keeps its tables from one test to the next; call \Taphra\DataStore::flushConnections() in setUp() for an empty one per test, or after replacing the database file.
Logged-in users
#Tests run in one PHP process, so Auth::login() before a request logs the user in for that request. Log out in tearDown() so the next test starts as a guest.
<?php
// test/Http/MeTest.php
use Taphra\Auth;
use Taphra\Testing\HttpTestCase;
class MeTest extends HttpTestCase
{
protected function tearDown(): void
{
Auth::logout();
parent::tearDown();
}
public function testGuestsGet401(): void
{
$this->get('/api/me')->assertUnauthorized();
}
public function testLoggedInUser(): void
{
Auth::login(['id' => 7, 'name' => 'Ann']);
$this->get('/api/me')->assertOk()->assertJsonEquals(['id' => 7, 'name' => 'Ann']);
}
}/api/me is the AuthMiddleware route group from Authentication.
Faking AI providers
#Providers send their HTTP requests through a transport. Taphra\Ai\Http\FakeTransport answers with queued responses instead of calling the network, and records what would have been sent. Give it to the provider in the AI configuration for the test, and put the app's configuration back afterwards with AiConfig::snapshot() and restore():
<?php
// test/Http/SummaryTest.php
use Taphra\Ai\AI;
use Taphra\Ai\AiConfig;
use Taphra\Ai\Http\FakeTransport;
use Taphra\Testing\HttpTestCase;
class SummaryTest extends HttpTestCase
{
private array $savedAiConfig;
private FakeTransport $http;
protected function setUp(): void
{
parent::setUp();
$this->savedAiConfig = AiConfig::snapshot();
$this->http = new FakeTransport();
AI::configure([
'default_provider' => 'anthropic',
'providers' => [
'anthropic' => ['api_key' => 'test', 'model' => 'claude-opus-5-5', 'transport' => $this->http],
],
]);
}
protected function tearDown(): void
{
AiConfig::restore($this->savedAiConfig);
AI::reset();
parent::tearDown();
}
public function testSummarises(): void
{
$this->http->queueJson([
'content' => [['type' => 'text', 'text' => 'A short summary.']],
'stop_reason' => 'end_turn',
'usage' => ['input_tokens' => 12, 'output_tokens' => 4],
]);
$this->postJson('/api/summaries', ['text' => 'A long article ...'])
->assertOk()
->assertJsonPath('summary', 'A short summary.');
$sent = $this->http->lastRequest()->json();
$this->assertSame('Summarise: A long article ...', $sent['messages'][0]['content']);
}
}The controller under test calls AI::complete() as it would in production:
// app/Controllers/SummaryController.php
namespace App\Controllers;
use Taphra\Ai\AI;
use Taphra\RestController;
class SummaryController extends RestController
{
public function create(): string
{
$reply = AI::complete([['role' => 'user', 'content' => 'Summarise: ' . ($_POST['text'] ?? '')]]);
return $this->json(['summary' => $reply['content']]);
}
}FakeTransport also has queueRaw(), queueStream() (chunks for streaming responses) and queueConnectionError(), and requests() lists every request sent. The response shapes for each provider are in AI.
Pest
#Pest 3 runs on PHPUnit 11 and can use HttpTestCase as the base of its test files:
composer require --dev pestphp/pest:^3<?php
// test/Pest.php
uses(Taphra\Testing\HttpTestCase::class)->in('Pest');<?php
// test/Pest/HealthTest.php
it('answers the health check', function () {
$this->get('/health')
->assertOk()
->assertJsonPath('status', 'ok');
});vendor/bin/pest --test-directory=test # runs the PHPUnit classes tooPest looks in tests/ by default; the option points it at test/, where make:test writes. Once Pest is installed, run the suite with vendor/bin/pest.
What in-process tests do not cover
#- Actions that end the request.
redirect(),htmxRedirect(),htmxRefresh(),sse(), and a failed$this->validate()in a controller end the PHP process, which would end the test run. Return$this->seeOther($url)instead ofredirect(), as above; test the others separately, or with requests to a running server. - Headers set with PHP's
header(). The command line sends no headers, so a header an action sets with PHP's ownheader()is not in the response the test gets. Set it with$this->header()(in any controller), which also puts it in that response. - What the web front controller adds. The default security headers and the session cookie are sent by
app/Static/index.php, not by the pipeline the tests use.