Testing Strategy
This document explains the structure of the Txlog Server test suite, and the reasons for it. To run the tests, see How to Run Tests.
A Real Database
Most of the server logic is SQL. For example, SQL finds the active asset, the installed build and the vulnerabilities that a transaction fixed. A mock database accepts a query that PostgreSQL refuses. For this reason, the tests use a real PostgreSQL.
Two decisions make this practical:
- The suite makes its own schema. Each package with database tests calls
testdb.EnsureSchemafromTestMain. This function applies the same migrations that the server applies when it starts. The database can be empty, and each run also tests the migrations. - Without a database, the tests skip. A contributor without PostgreSQL can run the other tests.
make test starts a database and sets TXLOG_TEST_REQUIRE_DB. With this variable, the tests fail if they cannot connect to the database. As a result, a bad setup does not look like a good result.
What Each Package Tests
| Package | Subject |
|---|---|
auth | The link between OIDC accounts and users, and the LDAP names. |
controllers | The dashboard pages, with the real templates. |
controllers/api/v1 | The REST API: what each endpoint stores, returns and refuses. |
database | The advisory locks, and the second run of a failed migration. |
models | The asset life cycle (UpsertAsset) and the topology templates. |
scheduler | The data retention, the default schedules and the dashboard statistics. |
tests | Scenarios with more than one step, such as an asset that the server replaces and then activates again. |
util | The template functions. These tests do not use a database. |
vulnerabilities | The severity of an advisory, and the counts of fixed and introduced vulnerabilities. |
The tests of the HTTP handlers use a Gin router and httptest. Each test sends a request, and then examines the response and the stored rows. These tests do not call the functions behind the handler, so you can change those functions.
One Database for All Packages
All packages use the same txlog_test database, and Go runs the packages in parallel. As a result, each test uses machine IDs and hostnames with its own prefix (for example, scheduler-test-). When the test ends, it deletes only its own data:
func TestSomething(t *testing.T) {
db := testdb.Open(t) // skips the test when PostgreSQL is unreachable
defer db.Close()
defer cleanupTestData(t, db)
// ... test code
}A test must not expect an empty table. It must not count rows that it did not create.
What Makes a Good Test
A test must fail only when the behavior is incorrect. Send a request or call an exported function, and then examine the result. Do not write a test that repeats the implementation, because it always passes.
