Unit Testing
Smarter takes code quality and testing seriously. As of v0.35 there are more than 8,000 tests in the full test suite and a coverage ratio of approximately 97%. Pull requests must pass all tests before they can be merged. Moreover, code coverage is monitored on pull requests to ensure that new code is adequately tested. While 100% coverage is not patently unrealistic for this project, we strive to maintain high coverage across the codebase. In parts of the codebase that we consider ‘core’, we aim for at least 90% coverage.
Try to the guidelines below to help ensure that your tests provide maximum value with minimum effort on your part. We’ve invested heavily in unit test infrastructure by way of bases classes, mixins, and fixtures to make writing tests as easy as possible.
Note
Please be aware that the principal author generously awards himself a self-assessment of “C-” for test writing skills. So, please be kind when reviewing the legacy testing infrastructure.
Local Testing
To run the test suite locally, from the project root:
make docker-test # the whole suite
make docker-test LABELS=smarter.apps.account.tests.test_activation # one module, in one shard
It builds the smarter image from your working tree, then runs the tests in shards, each in a
Docker stack of its own (see Running the Suite in Shards). A serial manage.py test in the
dev container uses one CPU core, and tests the dev container’s copy of the code, so it isn’t how
Smarter’s tests are run.
Running the Suite in Shards
CI splits the suite into eight shards, each on a runner of its own: every runner sets
SMARTER_TEST_SHARD=<n>/8, and smarter.lib.unittest.runner keeps that shard’s share of
the TestCases. To run one shard locally, pass the same variable:
docker exec -e SMARTER_TEST_SHARD=3/8 smarter-api bash -c "python manage.py test smarter"
Several shards can’t share one Docker stack. The tests write real rows without a rollback, sweep
every test account in their teardown, clear the shared Redis cache, and send requests and Celery
tasks to the one dev server and its workers, so two shards in one stack break each other’s
tests. make docker-test gives each shard a stack of its own, as CI gives each a runner:
make docker-test # as many shards as Docker has room for
make docker-test SHARDS=4 # exactly four
make docker-test LABELS=smarter.apps.secret # part of the suite, in one shard
It dumps the local database once, starts one Compose project per shard from
docker-compose.shard.yml (MariaDB in memory, Redis, the api and the two workers, without
Celery Beat), loads the dump into each, runs every shard at once, and prints each shard’s result
and every failing test. The logs are in .test-shards/. The stacks are removed afterwards
(scripts/run_test_shards.py --keep leaves them running). It builds the smarter image
first, and needs smarter-mariadb running.
Without SHARDS, it asks docker info for the CPUs and memory that Docker’s containers can
use (on Docker Desktop, the VM’s, from its Resources settings) and runs as many shards as they
have room for: a shard needs about 3.75 GB of memory and one CPU, after a reserve for the dev
stack. Memory is usually the limit, and a shard that runs out of it is killed and ends without a
result. To run more shards, give Docker Desktop more memory and CPUs.
Infrastructure Tests
Some tests use real infrastructure: they deploy LLMClients to the Kubernetes cluster, and create
DNS records and TLS certificates in AWS. They are slow, e.g. a deploy waits up to 40 minutes for a
certificate that a local cluster never issues, and they need live credentials. They are tagged
infrastructure, and skipped unless they are asked for:
python manage.py test # everything else
python manage.py test --tag infrastructure # only the infrastructure tests
SMARTER_TEST_INFRASTRUCTURE=true python manage.py test # everything
Tag a test, or a whole TestCase, that uses real infrastructure, with
smarter.lib.unittest.runner’s INFRASTRUCTURE tag:
from django.test import tag
from smarter.lib.unittest.runner import INFRASTRUCTURE
@tag(INFRASTRUCTURE)
class TestDeploy(TestAccountMixin):
...
Prefer a fake, though: the LLMHost and Vectorstore tests replace the cluster with an in-memory backend, so that they test the same code in seconds.
Vendor Tests
LLM vendors’ models disagree about request parameters that look harmless. Some of OpenAI’s models
accept only their default temperature, some reject reasoning_effort altogether, some accept
function tools only with reasoning_effort set to none, some don’t support none, and the
search models reject tools and any temperature. A rule that Smarter gets wrong breaks every prompt
to that model, so these rules are tested at two levels:
smarter.lib.openai.model_capabilitiesrecords what each model inVALID_CHAT_COMPLETION_MODELSaccepts. The platform uses it to reject an LLMClient manifest whose settings its model can never honor, and to change each request to what its model accepts.smarter/apps/provider/tests/vendor_profiles.pysimulates the vendor from it, with the vendor’s own error messages, andtest_vendor_quirks.pysends every kind of request that Smarter sends, to every model, at every kind of reasoning effort, through the chat provider’s own code, against the simulator. It runs with the rest of the suite, and fails when a model isn’t in the table.test_vendor_quirks_live.pychecks the table against the real api, and that every model answers Smarter’s requests. It sends a few hundred small, billed requests, so it is taggedvendor, and skipped unless it is asked for:
python manage.py test --tag vendor # only the vendor tests
SMARTER_TEST_VENDOR=true python manage.py test # everything, with the vendor tests
Run the vendor tests when a model is added to VALID_CHAT_COMPLETION_MODELS, before a release,
and whenever a prompt fails with a 400 from the vendor. When they fail, update the model in
smarter.lib.openai.model_capabilities, then run test_vendor_quirks.py, which shows what
Smarter must change.
Coverage Report
To generate a code coverage report, use the following command from the project root:
docker exec smarter-api bash -c "coverage run manage.py test && coverage report -m && coverage html"
# or
make coverage
Conventions
unittest
Smarter uses the built-in unittest framework for unit tests. All tests should be placed
in a tests subpackage within the app being tested. Test modules should be named with the test_*.py
pattern. Test case classes should be named with the *TestCase suffix. Individual test methods should be named
with the test_* prefix.
Try to keep tests nearby the code they are testing to make it easier to find and maintain them and to minimize the the number of individual test files any any given directory.
data files
Test data files should be placed in a data subdirectory nearby the tests package of the app being tested.
SmarterTestBase
All unit tests should inherit from SmarterTestBase,
or from a subclass thereof. This base class provides a number of useful features, including functions
for reading test data files in various formats in a read-only manner, generating unique identifiers and hash suffixes.
from smarter.lib.unittest.base_classes import SmarterTestBase
TestAccountMixin
This mixin inherits from SmarterTestBase
and provides additional supporting functionality for tests that involve user accounts, such as creating test users
and logging them in and setting up various roles and permissions. This class does a reasonably good job of
cleaning up after itself, deleting any test users it creates, regardless of whether tests pass or fail.
from smarter.apps.account.tests.mixins import TestAccountMixin
Code Quality
The project uses automated code-quality checks to keep the code clean, consistent, readable, and safe. Before code is committed, pre-commit checks automatically format Python and JavaScript code, organize imports, remove unused imports, improve Python syntax, and keep documentation comments consistent. It also checks for common mistakes such as spelling errors, trailing whitespace, invalid JSON/YAML/XML/TOML, merge conflicts, broken links, accidental credentials or private keys, debug statements, and other repository problems. Python code is checked for style and potential security issues, while JavaScript code is checked with ESLint and formatting tools. Commit messages are also checked to keep them consistent. Many of these checks can automatically fix simple problems, and pre-commit.ci runs the checks in the background and can create automatic fixes, helping ensure that every contribution meets the project’s basic standards before it becomes part of the codebase.