Skip to Content
Module developmentPublishing

Module tests

Where a module's tests live, how PHPUnit picks them up into the unit, integration and admin-screen suites, how to run them against the test database, and how to check the module with PHPStan and Mago.

By the end, your module has unit and integration tests that the engine's PHPUnit finds by itself, a test database with the module enabled, and commands that check the code with PHPStan and Mago.

All of this works in the engine source with dev dependencies: the tests/ folder, phpunit.xml.dist, phpstan-modules.neon.dist and mago.toml are not in the release archive, and a release is installed with composer install --no-dev. A module installed on a regular site cannot run its tests there.

Minimal example

An integration test checks the purchase from Money and payments: repeating a request with the same key does not charge a second time.

app/Modules/Example/Tests/Integration/BoostShopTest.php
<?php

declare(strict_types = 1);

namespace Flute\Modules\Example\Tests\Integration;

use Flute\Core\Database\Entities\User;
use Flute\Core\ModulesManager\ModuleManager;
use Flute\Modules\Example\Services\BoostShop;
use Flute\Tests\Support\IntegrationTestCase;
use PHPUnit\Framework\Attributes\PreserveGlobalState;
use PHPUnit\Framework\Attributes\RunTestsInSeparateProcesses;

#[RunTestsInSeparateProcesses]
#[PreserveGlobalState(false)]
final class BoostShopTest extends IntegrationTestCase
{
    protected static function ownedTables(): array
    {
        return ['example_boosts', 'balance_purchases', 'balance_histories'];
    }

    public function test_a_repeated_request_charges_once(): void
    {
        $app = $this->bootApp();
        $modules = $app->get(ModuleManager::class);
        if (!$modules->issetModule('Example') || $modules->getModule('Example')->status !== ModuleManager::ACTIVE) {
            self::fail('Example is not active in the test database: run app/Modules/Example/Tests/prepare-test-db.sh.');
        }

        $buyer = new User();
        $buyer->name = 'PHPUnit Buyer';
        $buyer->email = 'phpunit_buyer_' . bin2hex(random_bytes(4)) . '@example.test';
        $buyer->verified = true;
        $buyer->save();
        user()->topup(100.0, $buyer, 'phpunit');

        $shop = $app->get(BoostShop::class);
        $first = $shop->buy($buyer, 2, 'req-1');
        $again = $shop->buy($buyer, 2, 'req-1');

        self::assertTrue($again->replayed);
        self::assertSame($first->purchaseId, $again->purchaseId);
        self::assertSame(1, $this->ownRows('example_boosts')->count());
    }
}

A unit test checks pure logic without the application or the database. It is a plain PHPUnit\Framework\TestCase in Tests/Unit with the Flute\Modules\Example\Tests\Unit namespace; this is how the Whitelist module tests its admission rules.

How it works

phpunit.xml.dist at the engine root collects module tests into the shared suites by folder. The file name ends in Test.php, and the namespace follows the path: Flute\Modules\Example\Tests\Integration.

SuiteModule foldersWhat goes there
unitapp/Modules/*/Tests/Unitpure logic, no database
integrationapp/Modules/*/Tests/Integration, app/Modules/*/Gateways/*/Teststhe whole application and a real MariaDB
admin-screenapp/Modules/*/Tests/Adminadmin screens

tests/Bootstrap.php sets a test APP_KEY and separate folders for the cache, configs (storage/app/config-test, emptied in every process) and the ORM schema. The variables in phpunit.xml.dist switch the site to APP_ENV=test, FLUTE_TESTING=1 and the flute_test database, so a test never touches the flute development database.

IntegrationTestCase::bootApp(string $uri = '/', string $method = 'GET') loads the whole application into the current process: the container, helpers, the ORM and the providers of enabled modules. That is why every integration test repeats the #[RunTestsInSeparateProcesses] and #[PreserveGlobalState(false)] attributes.

The test database is a copy of the development one and already holds other rows. Before a test, the base class remembers the highest id in users, roles and the tables ownedTables() returns, and after the test it deletes only the rows above that mark. Read your own rows through ownRows($table).

If the database is unreachable, the test is skipped with a hint, and in CI (the CI variable) it fails. The engine's CI has no app/Modules folder, so you run your module's tests yourself.

Test database

Tests need the engine's Docker stack: the flute-db database container from compose.yaml and the 127.0.0.1:3307 port from docker/compose.override.yaml.example. Copy that file to compose.override.yaml at the source root; it mounts your working copy into the container. Installing the stack is described in Installing with Docker.

Copy the development database

sh tests/setup-test-db.sh

The script recreates flute_test as a copy of flute. Run it again after new migrations.

Enable the module in the copy

Add this script to the module, modelled on the one in the Reviews module. It applies every module's migrations through tests/prepare-module-dbs.sh and sets the module's status to active in the flute_modules table. It refuses a database whose name does not start with flute_test. Run it from the source root.

app/Modules/Example/Tests/prepare-test-db.sh
#!/usr/bin/env sh
set -e
db="${1:?name the test database, e.g. flute_test_89}"
case "$db" in flute_test*) ;; *) echo "$db: not a test database" >&2; exit 1 ;; esac
sh tests/prepare-module-dbs.sh "$db"
docker exec flute-db sh -lc "mariadb -uroot -p\"\$MYSQL_ROOT_PASSWORD\" $db -e \"INSERT INTO flute_modules (\\\`key\\\`, name, description, status, installed_version, created_at) SELECT 'Example', 'Example', '', 'active', '1.0.0', NOW() FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM flute_modules WHERE \\\`key\\\` = 'Example'); UPDATE flute_modules SET status = 'active' WHERE \\\`key\\\` = 'Example';\""
echo "$db: Example ready"
sh app/Modules/Example/Tests/prepare-test-db.sh flute_test

Run the module's tests

vendor/bin/phpunit app/Modules/Example/Tests/Unit
DB_HOST=127.0.0.1 DB_PORT=3307 vendor/bin/phpunit app/Modules/Example/Tests/Integration

From the host, integration tests also need DB_USERNAME and DB_PASSWORD of the stack's database user. A single test: --filter test_a_repeated_request_charges_once.

Payment gateway test

A gateway driver is checked by a shared contract. The class extends Flute\Tests\Support\Payments\GatewayContractTestCase, repeats the same two attributes and fills in four methods. The contract runs the real payment path itself: a forged signature, a repeated notification, an amount below the invoice, the answer to the gateway, and no secrets in the journal.

MethodWhat to return
driverClass(): stringthe driver class
settings(): arrayworking settings with made-up secrets
paidNotification(string $transactionId, string $amount, string $method): FluteRequesta signed "paid" notification built with $this->sandbox->notification(...)
forgedNotification(string $transactionId, string $amount): FluteRequestthe same notification with a wrong signature
currency(): string, startAnswers(): arrayoptional: the invoice currency and the gateway API answers to start()

Put the test into the module's Tests/; in the PaymentGateways module it is Gateways/<Name>/Tests, for example the Enot gateway test.

Code checks

CommandWhat it does
vendor/bin/phpstan analyse -c phpstan-modules.neon.dist app/Modules/ExamplePHPStan at level 5 for PHP 8.2. Tests folders and views are skipped, there is no baseline
vendor/bin/mago lint app/Modules/Examplethe engine's linter rules
vendor/bin/mago lint --fix --format-after-fix app/Modules/Examplefix what the linter can and format
vendor/bin/mago format app/Modules/Exampleformatting only, --dry-run to check

composer fix, composer lint and the code checks of composer test (Mago and PHPStan) never look into app/Modules: mago.toml takes only app/Core, app/Helpers and tests, and phpstan.neon.dist excludes modules. PHPUnit in composer test does find module tests, but check the module's code with the commands from the table.

Common mistakes

What you seeCause
MySQL is unreachable at db:3306 … and the test is skippedthe test ran from the host without DB_HOST=127.0.0.1 DB_PORT=3307, or the stack is down
Example is not active in the test database…prepare-test-db.sh was not run for this database
LogicException: example_boosts is not in ownedTables().ownRows() or rowMark() on a table missing from ownedTables()
the second test of a file sees the state of the first, or fails on a repeated loadthe class lacks #[RunTestsInSeparateProcesses] and #[PreserveGlobalState(false)]
No tests executed!the file does not end in Test.php, or lies outside Tests/Unit, Tests/Integration, Tests/Admin
development data is gonemigrations ran without DB_DATABASE=flute_test. The scripts from the steps above check the database name themselves

See also

On this page