Testing
The headless bundle ships a test API in OpenDxp\Bundle\HeadlessBundle\Test. It sends requests to your headless
endpoints and checks every response against the API documentation. This page builds on Testing.
Setup
The documentation check validates every response with the OpenAPI validator. Install it as a development dependency:
composer require --dev league/openapi-psr7-validator
The import in tests/config/test.yaml switches on the documentation check:
imports:
- { resource: '@OpenDxpHeadlessBundle/config/test/services.yaml' }
Without the import, your tests still run, but no response is checked against the documentation.
If the test environment has no JWT key pair, add a shared secret to the same file:
parameters:
env(JWT_SECRET_KEY): 'a-secret-that-only-the-tests-know'
env(JWT_PUBLIC_KEY): ''
env(JWT_PASSPHRASE): ''
lexik_jwt_authentication:
encoder:
signature_algorithm: HS256
The test API signs in with users of your API user class. Its factory extends AbstractApiUserFactory:
<?php
declare(strict_types=1);
namespace App\Tests\Factory;
use OpenDxp\Bundle\HeadlessBundle\Test\Factory\AbstractApiUserFactory;
use OpenDxp\Model\DataObject\User;
/**
* @extends AbstractApiUserFactory<User>
*/
final class UserFactory extends AbstractApiUserFactory
{
public static function class(): string
{
return User::class;
}
}
If your API user class has another name, use that class instead of User. The factory gives every user a unique
email address as its login identifier.
Sending a request
Api::start() sends a JSON request without a user to the API host, in the default language of your installation:
use App\Tests\Factory\EventFactory;
use OpenDxp\Bundle\HeadlessBundle\Test\Api;
it('returns an event', function () {
$event = EventFactory::new()->create([
'title' => 'Open Day',
'seats' => 40,
]);
$browser = Api::start()->get(sprintf('/events/%d', $event->getId()));
$browser->assertStatus(200);
expect($browser->json()->decoded())->toBe([
'id' => $event->getId(),
'title' => 'Open Day',
'seats' => 40,
]);
});
EventFactory is a factory of your project.
Write the factory shows how you write one.
Pass the json option when your endpoint expects a request body:
$browser = Api::start()->post('/events', [
'json' => [
'title' => 'Open Day',
'seats' => 40,
],
]);
$browser->assertStatus(201);
The API returns status 422 when the validation of a request fails. You may check which field the response reports:
$browser
->assertStatus(422)
->assertJsonMatches('violations[0].propertyPath', 'seats');
Authenticated requests
Use Api::actingAs() when your endpoint requires a signed-in user. The test API creates a token for the user and
sends it as a bearer token:
use App\Tests\Factory\UserFactory;
use OpenDxp\Bundle\HeadlessBundle\Test\Api;
it('lists the bookings of the user', function () {
$user = UserFactory::createOne();
$browser = Api::actingAs($user)->get('/bookings');
$browser->assertStatus(200);
});
To check that your endpoint refuses anonymous requests, send the same request with Api::start():
Api::start()->get('/bookings')->assertStatus(401);
Choosing a site
As soon as your installation has a site, the API refuses every request without the X-OpenDxp-Api-Site header. Pass
the header in an HttpOptions object when your test creates a site:
use OpenDxp\Bundle\HeadlessBundle\Test\Api;
use OpenDxp\Test\Factory\SiteFactory;
use Zenstruck\Browser\HttpOptions;
it('returns the events of the site', function () {
$site = SiteFactory::createOne();
$options = HttpOptions::create()->withHeader('X-OpenDxp-Api-Site', (string) $site->getId());
$browser = Api::start($options)->get('/events');
$browser->assertStatus(200);
});
Api::actingAs() accepts the same options as its second argument:
Api::actingAs($user, $options)->get('/bookings');
The options apply to every request that the returned browser sends.
Choosing a locale
The test API sends the default language of your installation in the X-OpenDxp-Api-Locale header. Override the
header when you test a response in another language:
$options = HttpOptions::create()->withHeader('X-OpenDxp-Api-Locale', 'fr');
$browser = Api::start($options)->get('/events');
The locale must be a valid language of your installation, or the API returns status 400. You may chain several
withHeader() calls to send a site and a locale together.
Using your own API host
The test API sends its requests to api.headless.test, which matches the default
host pattern of the API. If your project configures its own pattern, send a
host that matches it:
$options = HttpOptions::create()->withServer(['HTTP_HOST' => 'headless.example.test']);
$browser = Api::start($options)->get('/events');
Only requests to the API host are checked against the documentation. A request to any other host passes without a check.
User factory states
The user factory has a state for each account flow:
| State | Creates a user who |
|---|---|
withLocale(string $locale) | has chosen a preferred language |
withPassword(string $password) | signs in with a known password |
requestingPasswordReset(string $token, DateTimeInterface $requestedAt) | has requested a password reset with this token |
requestingLoginIdentifierChange(string $new, string $token, DateTimeInterface $at) | has requested a new login identifier with this token |
For example, a test of the login endpoint needs a user with a known password:
$user = UserFactory::new()
->withPassword('a-password-of-ada')
->create();
$browser = Api::start()->post('/auth/login', [
'json' => [
'loginIdentifier' => $user->getLoginIdentifier(),
'password' => 'a-password-of-ada',
],
]);
A test of a password reset link needs a user with a pending request:
use Carbon\Carbon;
$user = UserFactory::new()
->requestingPasswordReset('a-token-of-ada', Carbon::now())
->create();
Api::start()->post('/account/reset-password-request/a-token-of-ada', [
'json' => ['newPassword' => 'a-new-password'],
]);
Failures
The test fails with a message that names the request, the documented path and the reason. For example, if the
documentation declares title as a string that cannot be null, an event without a title fails like this:
GET /events/{id} breaks the documentation. Body does not match schema for content-type "application/json" for
Response [get /events/{id} 200] Keyword validation failed: Value cannot be null The field is "title".
These are the failures you will see most often:
| Message | Meaning |
|---|---|
Body does not match schema ... The field is "..." | The named field is missing, has the wrong type or is null although it may not be null. |
OpenAPI spec contains no such operation [/events/{id},get,500] | The endpoint returned a status that the documentation does not list. |
OpenAPI spec contains no such operation [/events/{id}] | The documentation does not describe the route at all. |
The firewall "headless_api" keeps a session. | The firewall of the API is not stateless. |
GET /events/1 uses the session. | The endpoint started or used a session. |
Either the endpoint or its documentation is wrong. Fix the endpoint when it returns something it should not. Fix the documentation when the endpoint is right and the description is incomplete.