Skip to content

PHPUnit feature tests broken against a clean test DB: session pattern, missing seed data, unowned test fixture bugs #4626

Closed

Description

@objecttothis

Summary

While fixing GHSA-3xf6-8fmq-44wg (per-record Sales endpoint authorization), we found the existing PHPUnit feature-test suite only ever "passed" because it was accidentally running against a real, pre-populated development database (ospos, forced via phpunit.xml.dist's <env ... force="true"> overrides) rather than a clean, self-contained test database. Once phpunit.xml.dist is corrected to stop overriding .env's database.tests.database (so tests target a real, empty ospos_tests DB, satisfying TestDatabaseBootstrapSeeder's safety check), most of the existing controller tests fail.

Two real, separate bugs were found and fixed as part of that work:

  1. Employee::save_employee() (app/Models/Employee.php) had ENVIRONMENT != 'testing' && parent::save_value(...) — a stray guard from an unrelated 2018 commit (804942cff, "Add warning if migration is needed") that silently made employee creation a no-op under ENVIRONMENT=testing. Removed.
  2. Secure_Controller::__construct() used raw header() + exit() to deny access, which kills the entire PHPUnit process (not just the simulated request) under CodeIgniter\Test\FeatureTestTrait. Replaced with a ResponsableInterface-implementing exception (app/Exceptions/AccessDeniedRedirectException.php) that CI4's CodeIgniter::run() catches and converts to a real redirect response, safe under both real HTTP and FeatureTestTrait.

With both of those fixed, tests/Controllers/SalesControllerTest.php (new, added for the GHSA fix) is fully green. However, several pre-existing test files remain broken for reasons out of scope for that fix. Each item below includes the fix needed.

1. Session injection pattern is wrong across the suite

EmployeesControllerTest.php, HomeTest.php, and others use:

$session = Services::session();
$session->destroy();
$session->set('person_id', $personId);

This does not work under FeatureTestTrait — call() resets $_SESSION from the trait's own $this->session property (see vendor/codeigniter4/framework/system/Test/FeatureTestTrait.php: withSession() at line ~111, and populateGlobals() at line ~413, which does $_SESSION = $this->session), discarding anything set via Services::session() directly.

Fix: replace the Services::session() block with:

protected function loginAs(int $personId): void
{
    $this->withSession([
        'person_id'  => $personId,
        'menu_group' => 'home',
    ]);
}

SalesControllerTest.php already uses this pattern (tests/Controllers/SalesControllerTest.php::loginAs()) — copy it into EmployeesControllerTest.php's loginAs()/resetSession(), HomeTest.php's loginAs()/resetSession(), and any other test using the old pattern.

2. person_id = 1 is assumed to pre-exist as an admin user

Employee::isAdmin() (app/Models/Employee.php) hardcodes person_id === 1 as always-admin:

public function isAdmin(int $person_id): bool
{
    if ($person_id === 1) {
        return true;
    }
    foreach (ADMIN_MODULES as $module) { ... }
}

HomeTest::resetSession(), ConfigTest, etc. assume this row already exists rather than creating it — only worked by accident against the old shared dev DB. No seeder creates this row for a fresh ospos_tests database.

Fix (pick one):

  • Add a shared test helper that inserts a real person_id=1 admin row (via Employee::save_employee() with NEW_ENTRY on an empty table, person_id will be 1 from auto-increment) and have every test class needing an "admin" call it in setUp(); or
  • Change tests to create an admin via ADMIN_MODULES grants (matching isAdmin()'s fallback loop) instead of relying on person_id === 1, so the ID-based special case doesn't matter.

3. EmployeesControllerTest.php has its own bugs

  • testNonAdminCannotGrantPermissionsTheyDontHave calls an undefined $this->createTestEmployee($targetEmployeeId) — needs a real helper added (see createNonAdminEmployee() in the same file for the pattern to copy, but note it also needs a uniqid()-suffixed username/email per the fix in item 4 below).
  • testNonAdminCannotViewAdminAccount asserts the redirect URL contains no_access, but the app actually redirects to /login first (session issue, see item 1) — once item 1 is fixed, re-check whether this assertion needs to change to expect no_access specifically, since a properly authenticated non-admin should get no_access, not /login.

4. Duplicate-key test fixtures silently roll back inserts

Tests that hardcode a fixed username/email (e.g. 'cashier', 'admin_test') across repeated runs against a persistent DB ($refresh = false) hit a unique-constraint violation on the second run. Because Employee::save_employee() wraps its insert in its own transStart()/transComplete(), and CI4's BaseConnection::query() swallows the failing query (transDepth !== 0 suppresses the exception), the whole insert (people + employees + grants) silently rolls back — but MySQL's AUTO_INCREMENT still advances, so the returned "new" person_id looks valid while the row doesn't actually exist. This surfaces later as a confusing, unrelated foreign-key error (e.g. inserting a sales row referencing the phantom employee_id).

Fix: give every test-created username/email a uniqid() suffix, e.g.:

$unique = uniqid();
$employeeData['username'] = "cashier.$unique";
$personData['email'] = "cashier.$unique@test.com";

See SalesControllerTest.php::createCashierEmployee() / createReportsSalesEmployee() for the already-fixed pattern. Apply the same treatment anywhere a test file hardcodes a username/email/invoice_number/etc. that could collide across runs.

5. Employee::has_module_grant() / has_subpermissions() behavior is surprising and may itself be a bug

A user with only the base sales grant (no submodule grant) fails has_module_grant('sales', ...):

public function has_module_grant(string $permission_id, int $person_id): bool
{
    $builder = $this->db->table('grants');
    $builder->like('permission_id', $permission_id, 'after');
    $builder->where('person_id', $person_id);
    $result_count = $builder->get()->getNumRows();

    if ($result_count != 1) {
        return ($result_count != 0);
    }

    return $this->has_subpermissions($permission_id); // <-- requires a submodule-specific grant
}

public function has_subpermissions(string $permission_id): bool
{
    $builder = $this->db->table('permissions');
    $builder->like('permission_id', $permission_id . '_', 'after');
    return ($builder->get()->getNumRows() == 0); // false if ANY submodule permission is defined
}

Because the sales module has a sales_stock sub-permission row defined in permissions (inserted by a migration, unused anywhere else in app/Controllers/Sales.php or app/Libraries/Sale_lib.php), has_subpermissions('sales') returns false for EVERY user who holds only the bare sales grant — even real, currently-seeded users (e.g. person_id=2 in the test DB has only customers+sales grants and would also fail this check).

Fix (needs a decision, not just a patch):

  • If a bare sales grant is supposed to be sufficient for basic register access (as the GHSA advisory's own framing assumes — "a cashier... holds to operate the register"), has_subpermissions()'s logic is backwards: it should probably check whether the user holds any grant matching permission_id . '_%', not whether the module merely has submodules defined. As currently written, defining ANY submodule for a module silently breaks that module's base grant for everyone who doesn't also hold the submodule grant.
  • If it's intended (bare sales should never be enough on its own), then sales_stock needs to actually be granted to real users by whatever onboarding/seed flow creates cashier accounts (currently nothing does this — grep found no migration inserting sales_stock grants, and no UI checkbox references it in app/Views).
  • Test workaround already applied in SalesControllerTest.php: grant sales_stock alongside sales in createCashierEmployee()/createReportsSalesEmployee(). This should NOT be treated as the real fix — it just unblocks the GHSA regression tests.

6. Other broken test files (not yet root-caused)

ItemsCsvImportTest.php, ConfigTest.php, CustomersCsvImportTest.php, Tests\Models\EmployeeTest all have failures/errors of similar shape (redirect-instead-of-200, missing fixture data) once run against a clean DB. Likely the same root causes as items 1–4 above, but not individually verified — check each file for the Services::session() pattern (item 1) and hardcoded unique-constrained fixture values (item 4) first.

Activity

  1. arsyadal commented on Aug 17, 2026

    @arsyadal

    Picking this up — will work through items 1–4 and 6 (session pattern, admin seed row, EmployeesControllerTest bugs, uniqid-suffixed fixtures, remaining broken test files), plus item 5 using the first fix option (bare sales grant should be sufficient — will make has_subpermissions() check the acting user's own grants against permission_id_% instead of whether the module has any submodule permission defined at all).

    Will open a PR referencing this issue once the suite is green against a clean ospos_tests DB.

  2. objecttothis commented on Aug 19, 2026

    @objecttothis
    MemberAuthor

    @arsyadal Thanks for your help with this. ItemsCsvImportTest is now working properly. Use that as a template unless there is a better way you want to propose. Part of the problem is that relying on the CodeIgniter Built-in database seeding, setup and teardown is that it uses regress to walk through all the down() methods in the migrations. The problem is that not all of those down methods are implemented, so it fails. You'll want to sync your branch with the master since I've made some changes recently. Also, look at PRs #4640,
    #4627 and #4617 as those have several fixes for tests and added tests.

    An ideal solution here is one that is resilient and prevents tests from breaking each other. I would think this would mean wiping and reseeding the database between tests, but that may cause tests to take too long. It might just be that we have to write tests using unique values so they don't break each other on subsequent runs.

  3. objecttothis commented on Aug 25, 2026

    @objecttothis
    MemberAuthor

    7. Test file organization deviates from one-file-per-class

    While adding regression coverage for GHSA-3vpv-jqr3-7256 (item-kit barcode XSS), I found the suite doesn't consistently follow "one test file per class under test":

    • tests/Controllers/ItemsCsvImportTest.php and tests/Controllers/CustomersCsvImportTest.php are feature-scoped (CSV import only), not full controller test classes — no ItemsControllerTest.php/CustomersControllerTest.php exists to hold the rest of those controllers' coverage.
    • I initially made the same mistake with a new Item_kitsBarcodeTest.php before catching it — renamed to Item_kitsControllerTest.php to match the EmployeesControllerTest.php/ReportsControllerTest.php/SalesControllerTest.php convention (3 of the 5 real controller test files already use the *ControllerTest suffix).

    Fix: consolidate ItemsCsvImportTest.php into ItemsControllerTest.php (new) and CustomersCsvImportTest.php into CustomersControllerTest.php (new), or rename both to the *ControllerTest suffix and merge in remaining controller coverage as it's written. Standardize on: one test class per production class (controller/model/library/helper), named <ClassName>Test.php, holding all coverage for that class regardless of which feature/endpoint it exercises. Avoid further per-feature splintering (e.g. no Item_kitsBarcodeTest.php, SalesReportsTest.php, etc. alongside a class's main test file).

  4. jekkos commented on Aug 31, 2026

    @jekkos
    Member

    Progress update (2026-08-31)

    Picked up the suite again against a fresh clean ospos_test DB (Podman MariaDB 10.5 + PHP 8.3, CI4 4.7.4). Current full-suite result: 274 tests, 593 assertions — 21 errors + 45 failures (66 bad).

    New root cause found: cross-class test contamination (not documented in this ticket)

    This is the single biggest driver of the remaining failures and is different from items 1–6 above:

    • Nearly every controller/model class sets protected $migrateOnce = true and CI4's default protected $refresh = true.
    • In DatabaseTestTrait::setUpMigrate(), because $migrateOnce=true, only the first class that runs triggers regressDatabase() + migrateDatabase(). self::$doneMigration / self::$doneSeed are static (process-wide), so once set, every subsequent class skips migrate/seed entirely.
    • Net effect: earlier classes leave rows behind (people/employees/grants/items/stock) that the next class then sees. Classes that pass in isolation fail when run in the full suite. Verified:
      • SalesControllerTest: 12/12 pass isolated, 12 fail in-suite.
      • Running --filter "Controllers.ConfigTest::|Controllers.SalesControllerTest::" in one process reproduces the failures.
      • SaleTest / ReceivingTest error with Table 'ospos_test.ospos_migrations' doesn't exist mid-suite — the migration table is being regressed out from under a later class.

    So the suite is not actually running each class against a clean schema despite $refresh=true; it's running against an accumulating shared schema with only one regression applied.

    Direction now in progress (option A)

    Fix the migration/static-flag contamination so each class gets a consistent schema, which should unblock a large cluster (SalesControllerTest 12, SaleTest 6, ReceivingTest 1, and several others) before tackling the per-class bugs (session pattern, createTestEmployee() missing helper, customer email vs people.email column, saveLocale cross-field validation).

    Next: confirm exact DatabaseTestTrait static semantics, then choose between (a) resetting the shared doneMigration/doneSeed flags per class, (b) forcing per-class regression, or (c) a shared bootstrap that migrates once and gives every class an isolated schema via transaction rollback. Will post the chosen fix + before/after counts here.

  5. jekkos commented on Aug 31, 2026

    @jekkos
    Member

    (Addendum: the analysis and test fixes in this thread were produced by an AI assistant (opencode, model qwen3.8:27b) working under human direction and review.)

  6. objecttothis commented on Aug 31, 2026

    @objecttothis
    MemberAuthor

    @jekkos there is another bug that is preventing some tests from running. Three different classes create a sales_payments_temp table but the tables do not have the same schema and when tests call these functions in the same test, it creates a race condition and some tests failing. I solved this in #4677 by renaming two of the temp tables so we didn't run into the collision. If a different solution is better, that works too.

  7. objecttothis commented on Sep 1, 2026

    @objecttothis
    MemberAuthor

    While working a separate bugfix (giftcard/payment validation), we discussed whether EmployeeFixtureTrait::createEmployee() should be extended into a shared, grant-aware factory that SalesControllerTest, ItemsControllerTest, etc. all call, instead of each file hand-rolling its own createCashierEmployee()-style helper.

    Given items 4 and 5 above, we think this consolidation is worth doing but should come after this issue's fixes land, not before:

    • Item 4 needs every fixture to uniqid()-suffix its username/email. Right now SalesControllerTest.php's inline helpers already do this and are called out above as the reference pattern — a shared trait method would need to bake that in too.
    • Item 5's has_subpermissions() bug means current tests work around it by manually granting sales_stock alongside sales. Until that's resolved for real, a shared factory would have to either hardcode the same workaround or expose a grants param — but the "right" default grants are still an open question tied to item 5's resolution.

    Once the suite is stable against a clean DB and item 5 is decided, we'd propose: extend EmployeeFixtureTrait::createEmployee() to accept optional grants and field overrides, routed through Employee::save_employee() (matching what SalesControllerTest's helpers already do), then have SalesControllerTest.php and ItemsControllerTest.php drop their inline duplicates in favor of it. Happy to pick this up as a follow-up once the items above are settled — didn't want to bundle a fixture refactor into the fixes already in flight here.

  8. jekkos commented on Sep 3, 2026

    @jekkos
    Member

    Progress update — suite-order contamination + target test classes (as of 2026-09-03)

    Full-suite baseline → final (verified by diff of failing-test lists; zero regressions)

    Errors Failures Total failing
    Baseline (clean tree) 115 38 153
    After fixes 2 35 37

    116 tests un-broken, no new failures introduced.

    Target classes — all green

    • EmployeesControllerTest — 13/13
    • CustomersCsvImportTest — 6/6
    • HomeTest — 17/17, now stable in the full suite (it was one of the contamination victims)

    Root cause of the bulk of the failures: stale listTables() result cache

    TestDatabaseBootstrapSeeder dropped/recreated ospos_test on a separate server connection, and the initial-schema migration's down() read the table list via the shared connection's cached listTables(). CodeIgniter caches table names per-connection, so after the first bootstrap-reset class ran, every subsequent class that hit that shared connection saw a stale table list → "ospos_migrations doesn't exist", "column … doesn't exist", and the HomeTest-style suite-order contamination.

    Fix (files: app/Database/Seeds/TestDatabaseBootstrapSeeder.php, app/Database/Migrations/20170501000000_initial_schema.php):

    • Seeder calls Database::connect('tests')->resetDataCache() after drop/create so listTables()/tableExists() re-query the server.
    • Migration down() queries information_schema.TABLES directly (not the cached listTables()), preserves the migrations tracking table (so regress()/removeHistory() doesn't blow up), and clears the dataCache['table_names'] entry.

    This is the change that took errors 115 → 2 and cleared the HomeTest contamination.

    One regression I introduced and then fixed

    Making preceding tests actually run to completion exposed a global bcscale() leak: app/Events/Load_config.php:44 sets bcscale() from app config, so a prior class running to completion left bcscale(4) active for Sale_libPaymentTest::testAddPaymentAccumulatesAmountForExistingId (bcadd returned 15.0000 vs expected 15). Pinned/restored bcscale around that class in tests/Libraries/Sale_libPaymentTest.php.

    Also fixed along the way (test-hygiene, not app code)

    • CustomersCsvImportTest: isolated via the same bootstrap-reset (unique emails still required); testEmptyEmailIsAccepted given a distinctive name so its lookup can't collide with other "John Doe" rows; expected-message assertions relaxed to match the actual language strings.
    • app/Language/en/Customers.php: csv_import_partially_failed message now carries the {0}/{1} placeholders (was missing, so sprintf-style interpolation never ran).

    Remaining 37 failures — all pre-existing, outside this issue's scope

    • 2 errors = real app bug: app/Models/Sale.php:74 references a nonexistent column payments.sale_cash_refund (the table's actual column is cash_refund, as correctly used at Sale.php:1102 and Summary_report.php:70). Unblocking this should clear most of the Sale/Receiving failures.
    • ConfigTest (21), LoginTest (3), OSPOSRulesTest (4) — fail even in isolation on the clean tree (mailpath/theme validation, captcha).

    Next step: fix the Sale.php:74 column reference and re-measure.

  9. jekkos commented on Sep 3, 2026

    @jekkos
    Member

    Progress update (2) — Sale.php temp-table bug fixed; 0 errors, 118 tests fixed, 0 regressions

    Continuing down the remaining pre-existing failures. Just fixed the 2 hard errors (the last ones) in SalesControllerTest.

    The bug

    Two model methods both build the shared temp table sales_payments_temp using CREATE TEMPORARY TABLE IF NOT EXISTS, but with different schemas:

    • Sale::create_temp_table() (app/Models/Sale.php:1096) — complete: includes sale_cash_refund + reference_code
    • Sale::create_temp_table_sales_payments_data() (app/Models/Sale.php:1416) — incomplete: lacked both

    Sale::get_info() selects payments.sale_cash_refund / payments.reference_code. Because both use IF NOT EXISTS on the same connection, whichever path runs first "wins" and freezes the schema.

    Order dependence: in SalesControllerTest, testEmployeeWithReportsSalesCanGetSearch (→ search(), the incomplete builder) runs before ...CanGetRow/...CanGetEdit (→ get_info()). The incomplete table was already present, so get_info()'s query threw:

    DatabaseException: Unknown column 'payments.sale_cash_refund' in 'field list'
    

    Run a single test in isolation it passed (the complete builder won there), which is why it looked flaky.

    Fix

    Aligned the incomplete builder (Sale.php:1416) to emit the same sale_cash_refund + reference_code columns as the complete one, so the temp table is schema-compatible regardless of call order. Additive, minimal, no behavior change to the reports path (it doesn't read the two extra columns).

    Results

    Run Errors Failures
    Baseline 115 38
    After Plan A + B + bcscale 2 35
    After this fix 0 35

    SalesControllerTest + Sale_libPaymentTest + ReceivingTest: 27/27 pass. Full-suite diff vs. the previous run: 2 fixed, 0 regressions.

    Cumulative: 118 tests fixed, 0 regressions.

    Remaining (35, all pre-existing — fail in a clean-isolation baseline, not regressions)

    • Tests\Config\Validation\OSPOSRulesTest (4)
    • Tests\Controllers\ConfigTest (~21)
    • Tests\Controllers\LoginTest (3)
    • tests\Models\{Employee,Sale,Receiving}Test (handful)

    Next up: the ConfigTest cluster.

  10. objecttothis commented on Sep 3, 2026

    @objecttothis
    MemberAuthor

    @jekkos there are some fixed unit tests in some of the 3.4.2 marked open pull requests. If it saves time, you can cherry pick those files and not need to redo work.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions