Repository navigation
Description
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:
Employee::save_employee()(app/Models/Employee.php) hadENVIRONMENT != '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 underENVIRONMENT=testing. Removed.Secure_Controller::__construct()used rawheader()+exit()to deny access, which kills the entire PHPUnit process (not just the simulated request) underCodeIgniter\Test\FeatureTestTrait. Replaced with aResponsableInterface-implementing exception (app/Exceptions/AccessDeniedRedirectException.php) that CI4'sCodeIgniter::run()catches and converts to a real redirect response, safe under both real HTTP andFeatureTestTrait.
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=1admin row (viaEmployee::save_employee()withNEW_ENTRYon an empty table,person_idwill be1from auto-increment) and have every test class needing an "admin" call it insetUp(); or - Change tests to create an admin via
ADMIN_MODULESgrants (matchingisAdmin()'s fallback loop) instead of relying onperson_id === 1, so the ID-based special case doesn't matter.
3. EmployeesControllerTest.php has its own bugs
testNonAdminCannotGrantPermissionsTheyDontHavecalls an undefined$this->createTestEmployee($targetEmployeeId)— needs a real helper added (seecreateNonAdminEmployee()in the same file for the pattern to copy, but note it also needs auniqid()-suffixed username/email per the fix in item 4 below).testNonAdminCannotViewAdminAccountasserts the redirect URL containsno_access, but the app actually redirects to/loginfirst (session issue, see item 1) — once item 1 is fixed, re-check whether this assertion needs to change to expectno_accessspecifically, since a properly authenticated non-admin should getno_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
salesgrant 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 matchingpermission_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
salesshould never be enough on its own), thensales_stockneeds to actually be granted to real users by whatever onboarding/seed flow creates cashier accounts (currently nothing does this — grep found no migration insertingsales_stockgrants, and no UI checkbox references it inapp/Views). - Test workaround already applied in
SalesControllerTest.php: grantsales_stockalongsidesalesincreateCashierEmployee()/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
arsyadal commentedon Aug 17, 2026
Picking this up — will work through items 1–4 and 6 (session pattern, admin seed row,
EmployeesControllerTestbugs, uniqid-suffixed fixtures, remaining broken test files), plus item 5 using the first fix option (baresalesgrant should be sufficient — will makehas_subpermissions()check the acting user's own grants againstpermission_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_testsDB.objecttothis commentedon Aug 19, 2026
@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.
objecttothis commentedon Aug 25, 2026
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.phpandtests/Controllers/CustomersCsvImportTest.phpare feature-scoped (CSV import only), not full controller test classes — noItemsControllerTest.php/CustomersControllerTest.phpexists to hold the rest of those controllers' coverage.Item_kitsBarcodeTest.phpbefore catching it — renamed toItem_kitsControllerTest.phpto match theEmployeesControllerTest.php/ReportsControllerTest.php/SalesControllerTest.phpconvention (3 of the 5 real controller test files already use the*ControllerTestsuffix).Fix: consolidate
ItemsCsvImportTest.phpintoItemsControllerTest.php(new) andCustomersCsvImportTest.phpintoCustomersControllerTest.php(new), or rename both to the*ControllerTestsuffix 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. noItem_kitsBarcodeTest.php,SalesReportsTest.php, etc. alongside a class's main test file).jekkos commentedon Aug 31, 2026
Progress update (2026-08-31)
Picked up the suite again against a fresh clean
ospos_testDB (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:
protected $migrateOnce = trueand CI4's defaultprotected $refresh = true.DatabaseTestTrait::setUpMigrate(), because$migrateOnce=true, only the first class that runs triggersregressDatabase()+migrateDatabase().self::$doneMigration/self::$doneSeedare static (process-wide), so once set, every subsequent class skips migrate/seed entirely.SalesControllerTest: 12/12 pass isolated, 12 fail in-suite.--filter "Controllers.ConfigTest::|Controllers.SalesControllerTest::"in one process reproduces the failures.SaleTest/ReceivingTesterror withTable 'ospos_test.ospos_migrations' doesn't existmid-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, customeremailvspeople.emailcolumn, saveLocale cross-field validation).Next: confirm exact
DatabaseTestTraitstatic semantics, then choose between (a) resetting the shareddoneMigration/doneSeedflags 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.jekkos commentedon Aug 31, 2026
(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.)
objecttothis commentedon Aug 31, 2026
@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.
objecttothis commentedon Sep 1, 2026
While working a separate bugfix (giftcard/payment validation), we discussed whether
EmployeeFixtureTrait::createEmployee()should be extended into a shared, grant-aware factory thatSalesControllerTest,ItemsControllerTest, etc. all call, instead of each file hand-rolling its owncreateCashierEmployee()-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:
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.has_subpermissions()bug means current tests work around it by manually grantingsales_stockalongsidesales. Until that's resolved for real, a shared factory would have to either hardcode the same workaround or expose agrantsparam — 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 optionalgrantsand field overrides, routed throughEmployee::save_employee()(matching whatSalesControllerTest's helpers already do), then haveSalesControllerTest.phpandItemsControllerTest.phpdrop 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.jekkos commentedon Sep 3, 2026
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)
116 tests un-broken, no new failures introduced.
Target classes — all green
EmployeesControllerTest— 13/13CustomersCsvImportTest— 6/6HomeTest— 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 cacheTestDatabaseBootstrapSeederdropped/recreatedospos_teston a separate server connection, and the initial-schema migration'sdown()read the table list via the shared connection's cachedlistTables(). 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):Database::connect('tests')->resetDataCache()after drop/create solistTables()/tableExists()re-query the server.down()queriesinformation_schema.TABLESdirectly (not the cachedlistTables()), preserves the migrations tracking table (soregress()/removeHistory()doesn't blow up), and clears thedataCache['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:44setsbcscale()from app config, so a prior class running to completion leftbcscale(4)active forSale_libPaymentTest::testAddPaymentAccumulatesAmountForExistingId(bcaddreturned15.0000vs expected15). Pinned/restoredbcscalearound that class intests/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);testEmptyEmailIsAcceptedgiven 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_failedmessage now carries the{0}/{1}placeholders (was missing, sosprintf-style interpolation never ran).Remaining 37 failures — all pre-existing, outside this issue's scope
app/Models/Sale.php:74references a nonexistent columnpayments.sale_cash_refund(the table's actual column iscash_refund, as correctly used atSale.php:1102andSummary_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:74column reference and re-measure.jekkos commentedon Sep 3, 2026
Progress update (2) —
Sale.phptemp-table bug fixed; 0 errors, 118 tests fixed, 0 regressionsContinuing 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_tempusingCREATE TEMPORARY TABLE IF NOT EXISTS, but with different schemas:Sale::create_temp_table()(app/Models/Sale.php:1096) — complete: includessale_cash_refund+reference_codeSale::create_temp_table_sales_payments_data()(app/Models/Sale.php:1416) — incomplete: lacked bothSale::get_info()selectspayments.sale_cash_refund/payments.reference_code. Because both useIF NOT EXISTSon 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, soget_info()'s query threw: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 samesale_cash_refund+reference_codecolumns 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
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
ConfigTestcluster.objecttothis commentedon Sep 3, 2026
@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.
fix(tests): resolve all phpunit failures — clean-DB suite green (open…