Skip to content

Running Tests

Arthu Santiago edited this page Nov 30, 2026 · 1 revision

Running Tests

KeyAnyWhere has a PHPUnit suite that runs against a real PostgreSQL database: there is no SQLite fallback, because the migrations use PostgreSQL-specific SQL. This page runs the suite, a single file and a single test, and then lists the conventions to follow when writing new tests.

Before you start

The test database from the Quick Start (keyanywhere_test, the DB_TEST_* variables in config/.env) must exist. The suite creates the tables itself.

1. Run the whole suite

composer test

2. Run one file or one test

One file:

vendor/bin/phpunit tests/TestCase/Controller/UsersControllerTest.php

One test, by name:

vendor/bin/phpunit --filter testLoginComCredenciaisECodigo2faValidosAutentica

3. Run everything CI runs on a pull request

composer check runs the tests, the code style check (phpcs) and the static analysis (PHPStan level 8). Run it before considering any work done.

composer check

The code style must end with 0 errors and 0 warnings. To fix what can be fixed automatically:

composer cs-fix

Conventions for new tests

These rules come from problems that already happened. Following them keeps the suite reliable.

  • Fixtures with an explicit integer id must extend tests/Fixture/AppFixture.php, which resyncs the PostgreSQL sequence after the insert. Otherwise the next save() collides on a duplicate key.
  • Encrypted fields in fixtures must be encrypted with Criptografia::criptografar() (see EntradasFixture). Plain text there fails to decrypt.
  • Controller tests use CsrfTestTrait;. The CSRF cookie name depends on the environment: always use Application::nomeCookieCsrf(), never a literal. To send a request without the token, set $this->_csrfToken = false;.
  • Logged-in requests: AuthenticatedTestTrait::loginAsUser() and loginAsNonRootUser() fake a session, including the sessions row that SessionsKawMiddleware expects.
  • Guarded fields: User doesn't mass-assign root, tfa_ativo or tfa_secret. Set them by property assignment ($user->root = true;) after newEntity().
  • Audited tables: a test that saves an entry, category or user lists 'app.Auditorias' in $fixtures, so the audit table is emptied between tests. A test that logs a security event lists 'app.EventosSeguranca'.
  • Real 2FA through the login: flip Configure::write('debug', false) for the request and simulate HTTPS, as UsersControllerTest::postLoginEmModoProducao() does. Send a real current code (Google2FA::getCurrentOtp()).
  • Session contents after a request: read $_SESSION directly, not $this->_requestSession->read().
  • Parallel runs (mutation tests): each process gets a TEST_TOKEN and its own database, <DB_TEST_NAME>_<token>. Anything new that tests share across processes (a file, a folder) needs the same per-token treatment.

Next step

Code Quality

Clone this wiki locally