tox Tests Failing on Missing Env Vars - Fix passenv/setenv in CI
tox deliberately runs commands in a scrubbed environment, passing through only a small allowlist of variables. A test that reads DATABASE_URL or a secret then sees it unset in CI even though the job exported it.
What this error means
Tests pass locally but fail under tox in CI with KeyError, None, or "environment variable not set" for a value the CI job did export. The variable simply never reached the tox environment.
tests/test_db.py:5: in <module>
DATABASE_URL = os.environ["DATABASE_URL"]
E KeyError: 'DATABASE_URL'Common causes
tox scrubs the environment by default
tox passes only an allowlist of variables into each env. Anything not in passenv is invisible to the commands, regardless of what the CI job exported.
Variable needed but never declared
A test depends on an env var (DB URL, API token, locale) that was added to CI but never to passenv/setenv.
How to fix it
Pass the variable through
List the variables your tests need in passenv (supports globs).
[testenv]
passenv =
DATABASE_URL
AWS_*
CISet defaults with setenv
For values that should have a fixed default in the env, use setenv.
[testenv]
setenv =
PYTHONUTF8 = 1
APP_ENV = testHow to prevent it
- Declare every required variable in
passenv; use globs for families. - Use
setenvfor deterministic test defaults. - Document which env vars the test suite expects.