Skip to content
Latchkey

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.

tox output
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).

tox.ini
[testenv]
passenv =
    DATABASE_URL
    AWS_*
    CI

Set defaults with setenv

For values that should have a fixed default in the env, use setenv.

tox.ini
[testenv]
setenv =
    PYTHONUTF8 = 1
    APP_ENV = test

How to prevent it

  • Declare every required variable in passenv; use globs for families.
  • Use setenv for deterministic test defaults.
  • Document which env vars the test suite expects.

Related guides

Tired of flaky CI? Latchkey auto-heals failed jobs and retries them for you. Start free →