Testing a useful feature: from one rule to an HTTP journey

Test note-and-event atomicity in one article_demo through the domain rule, MySQL 8.4/InnoDB transaction and HTTP client journey, using the guarded shared database fixture.

A detail, a connection and a complete path: three scales for checking one feature.
A detail, a connection and a complete path: three scales for checking one feature.

A button returned a response and a row appeared in a table. That is a useful first signal. A change that must survive refactoring needs a more precise question: which behavior must remain intact?

Continue note creation in the same article_demo. The controller chapter already introduced Note, CreateNote, MysqlNoteStore, HTTP and Console; the form chapter extended that same Note with states. The main example already persists a note and its created event atomically in MySQL 8.4/InnoDB. Here we test that guarantee at different levels, keeping the existing model, Kernel and routes.

Three promises, three observation levels

A title must not be empty after standard trim(). This rule already belongs to src/Domain/Note.php and is checked by tests/Unit/NoteTest.php without HTTP or a database. Preserve the specific EmptyNoteTitle rejection extending NoteRuleViolation. A new table does not change that rule.

Storage must save both a note and its event or leave no part of a failed operation. HTTP must return 201 and Location, and the subsequent GET must read the record. One large test can cross all three levels, but separate checks identify the broken promise more precisely.

Check the existing store’s atomicity

Use src/Infrastructure/MysqlNoteStore.php from the same application. Both tables use InnoDB on MySQL 8.4: notes has a signed BIGINT AUTO_INCREMENT ID and a LONGTEXT title in utf8mb4; note_events has a foreign key and uniqueness constraint on note_id, with a constraint allowing only created for kind. This is one local creation record per note, not a message broker or delivery guarantee. The store constructor only configures PDO and executes no DDL. Separate NotesSchema and app:notes:initialize explicitly prepare the teaching schema with IF NOT EXISTS; this is not a schema upgrade system, a repair for incompatible tables or a transfer of old SQLite data.

src/Infrastructure/MysqlNoteStore.php:

<?php

declare(strict_types=1);

namespace App\Infrastructure;

use App\Domain\Note;

final class MysqlNoteStore
{
    public function __construct(
        #[\Symfony\Component\DependencyInjection\Attribute\Autowire(service: 'app.notes_connection')]
        private \PDO $connection,
    )
    {
        if ($connection->getAttribute(\PDO::ATTR_DRIVER_NAME) !== 'mysql') {
            throw new \InvalidArgumentException('The notes store requires the MySQL PDO driver.');
        }

        $connection->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
        $connection->setAttribute(\PDO::ATTR_DEFAULT_FETCH_MODE, \PDO::FETCH_ASSOC);
        $connection->setAttribute(\PDO::ATTR_EMULATE_PREPARES, false);
    }

    public function save(Note $note): int
    {
        if ($this->connection->inTransaction()) {
            throw new \LogicException('Note creation must own its transaction.');
        }

        $this->connection->beginTransaction();

        try {
            $statement = $this->connection->prepare('INSERT INTO notes (title) VALUES (:title)');
            $statement->execute(['title' => $note->title]);
            $id = (int) $this->connection->lastInsertId();
            $this->connection->prepare('INSERT INTO note_events (note_id, kind) VALUES (?, ?)')
                ->execute([$id, 'created']);
            $this->connection->commit();

            return $id;
        } catch (\Throwable $failure) {
            if ($this->connection->inTransaction()) {
                $this->connection->rollBack();
            }

            throw $failure;
        }
    }

    /** @return array{id: int, title: string}|null */
    public function find(int $id): ?array
    {
        $statement = $this->connection->prepare('SELECT id, title FROM notes WHERE id = :id');
        $statement->bindValue(':id', $id, \PDO::PARAM_INT);
        $statement->execute();
        $row = $statement->fetch();

        return $row === false ? null : ['id' => (int) $row['id'], 'title' => (string) $row['title']];
    }
}

save() owns the transaction: insert the note, obtain its ID, insert the event and commit through one connection. It rejects calls inside a caller-owned transaction. On failure it rolls back if the transaction is still active and rethrows the original failure. DDL is outside this operation: in MySQL it can cause an implicit commit. Gaps in AUTO_INCREMENT after rollback are normal and do not mean business records were lost.

The use case and entry points remain shared

CreateNote still creates a valid Note, invokes storage and returns the ID and title. Title validation precedes the first write. Console and HTTP gain atomicity through that same use case; the controller does not need a second implementation.

src/Application/CreateNote.php:

<?php

declare(strict_types=1);

namespace App\Application;

use App\Domain\Note;
use App\Infrastructure\MysqlNoteStore;

final readonly class CreateNote
{
    public function __construct(private MysqlNoteStore $store)
    {
    }

    /** @return array{id: int, title: string} */
    public function __invoke(string $title): array
    {
        $note = new Note($title);
        $id = $this->store->save($note);

        return ['id' => $id, 'title' => $note->title];
    }
}

Preserve earlier services and imports in config/services.yaml and use the named PDO connection app.notes_connection with DEMO_NOTES_DSN, DEMO_NOTES_USER and DEMO_NOTES_PASSWORD. PHP PDO MySQL is required; queries use native prepared statements with PDO::ATTR_EMULATE_PREPARES=false. The HTTP/Console account has DML-only permissions. Initialization uses a separate app.notes_migrator_connection: supply DEMO_NOTES_MIGRATOR_USER and DEMO_NOTES_MIGRATOR_PASSWORD only to the app:notes:initialize process, not to the shared HTTP environment. The configuration supplements the file rather than replacing it; keep POST /notes, GET /notes/{id} and the GET /notes catalogue.

services:
    _defaults:
        autowire: true
        autoconfigure: true

    App\Application\CreateNote: ~
    app.notes_connection:
        class: PDO
        arguments:
            $dsn: '%env(DEMO_NOTES_DSN)%'
            $username: '%env(DEMO_NOTES_USER)%'
            $password: '%env(DEMO_NOTES_PASSWORD)%'
            $options:
                !php/const PDO::ATTR_ERRMODE: !php/const PDO::ERRMODE_EXCEPTION
                !php/const PDO::ATTR_DEFAULT_FETCH_MODE: !php/const PDO::FETCH_ASSOC
                !php/const PDO::ATTR_EMULATE_PREPARES: false
    app.notes_migrator_connection:
        class: PDO
        arguments:
            $dsn: '%env(DEMO_NOTES_DSN)%'
            $username: '%env(DEMO_NOTES_MIGRATOR_USER)%'
            $password: '%env(DEMO_NOTES_MIGRATOR_PASSWORD)%'
            $options:
                !php/const PDO::ATTR_ERRMODE: !php/const PDO::ERRMODE_EXCEPTION
                !php/const PDO::ATTR_EMULATE_PREPARES: false
    App\Infrastructure\MysqlNoteStore: ~
    App\Infrastructure\NotesSchema: ~
    App\Command\InitializeNotesCommand: ~
    App\Controller\NoteController: ~
    App\Command\CreateNoteCommand: ~

Failure must happen after the first change

tests/Integration/MysqlNoteStoreTest.php checks the store on real MySQL 8.4. The shared App\Infrastructure\MysqlLab creates its own disposable schema and separate migrator and runtime accounts only on the server selected by the guarded test fixture. Setup explicitly invokes NotesSchema through the migrator before the business transaction; store operations use the DML connection. Separate native PDO connections share the same schema: one performs the operation and another inspects committed state. The migrator installs a controlled trigger that aborts event insertion with SIGNAL SQLSTATE '45000' after the note insert. This is a real MySQL failure propagated through PDO and rollback of the owned transaction, not a mocked rollback call. A separate check verifies that the runtime account cannot execute CREATE, ALTER or DROP.

See the complete test in tests/Integration/MysqlNoteStoreTest.php in the same article_demo; run it with the shared MySQL fixture rather than as an isolated snippet.

The shared infrastructure lives in src/Infrastructure/MysqlLab.php. It verifies the selected disposable MySQL 8.4 server, provides separate native connections and removes only its own schemas and accounts. It is a test helper, not an HTTP application service.

After failure the test expects zero notes and events, removes the trigger and retries creation. A successful retry also checks that the connection remains usable, without requiring consecutive IDs with no gaps. Another test reads through a new store instance and a separate connection to the same schema. The fixture cleans only its own disposable resources, not an arbitrary reader database.

HTTP checks the client journey

Preserve tests/Controller/NoteControllerTest.php from the earlier step. testCreateReturnsLocationAndAReadablePersistedNote sends POST, checks 201 and Location, then reads the note. It should detect an incorrect status even when SQL works. testListingDoesNotCreateANote protects catalogue reads from an accidental write.

MySQL 8.4 stores committed data on the server: another connection to the same schema can read it independently of one Kernel lifetime. The HTTP example retains disableReboot() for its shared test client, while the separate integration check demonstrates reading through another store on a separate native PDO connection. This does not check TLS, a reverse proxy or button appearance; those need different observations.

Check the checks themselves

APP_ENV=test php vendor/bin/phpunit tests/Unit/NoteTest.php
for test_file in \
    tests/Application/CreateNoteTest.php \
    tests/Controller/NoteControllerTest.php \
    tests/Command/CreateNoteCommandTest.php \
    tests/Integration/MysqlNoteStoreTest.php
do
    bash fixtures/mysql_labs/run.sh php vendor/bin/phpunit "$test_file" || exit "$?"
done

Run the four main-note PHPUnit files through bash fixtures/mysql_labs/run.sh php vendor/bin/phpunit, passing the relevant test path as shown above. The guarded shared fixture uses cached disposable MySQL 8.4; MysqlLab verifies the server and creates resources owned by the test. The wrapper supplies test-server configuration, not a ready-made DSN for an arbitrary HTTP process. For ordinary HTTP/Console use, provision a separate schema and accounts first, configure DEMO_NOTES_DSN, DEMO_NOTES_USER and DEMO_NOTES_PASSWORD, and explicitly run app:notes:initialize with separate migrator credentials before creating notes. The unit test tests/Unit/NoteTest.php needs no database. Here we observe a shared note-and-event commit, neither record remaining after controlled failure, a successful retry and reading over a separate connection; these checks do not extend the guarantee to other risks.

After your own successful baseline run, temporarily change one rule at a time: permit an empty title, replace rollback with commit inside catch, or return 200 instead of 201. The unit, integration and HTTP checks respectively should detect the broken promise. Restore the code after each probe; several simultaneous faults can hide one another.

A new test should address a new risk. Repeated-POST idempotency, authorization, concurrent writes and event delivery are outside this guarantee. Missing PDO MySQL or an unreachable server is an environment issue; a dependency-container failure concerns application composition; a partial write after rollback breaks the storage agreement. Name the observed cause precisely.

See PHP PDO for transaction semantics and Symfony Testing for test levels and the Kernel client. Also useful here are the PDO MySQL documentation and the MySQL 8.4 sections on implicit commits, InnoDB AUTO_INCREMENT handling and SIGNAL.

  1. Symfony Core One business operation, one transaction: saving a note with its tags
  2. Symfony Core Where the controller ends: one use case for creating a note in Symfony
  3. Symfony Core Form validation and product rules: why they are different checks
  4. Databases The article was saved but the event was not sent: why use a transactional outbox

A project by the author · Weather Solution200

After reading, a look outside.

Temperature, rain and wind in your city. Check the forecast and plan the hours ahead.

Check the forecast
Next article