In 2023, while pytest-dotenv
is super helpful because it just works, I feel like it's a bit overkill since most projects probably already have python-dotenv
installed. As a result, using a conftest.py
file to setup a pytest
fixture that loads your .env
file can be done in 3 fairly simple steps!
Steps
- Add a
conftest.py
file to your tests
folder
- Import
pytest
and from dotenv import load_dotenv, find_dotenv
- Define a
pytest
fixture
@pytest.fixture(scope='session', autouse=True)
def load_env():
env_file = find_dotenv('.env.tests')
load_dotenv(env_file)
This pytest
fixture works thanks to two key pieces.
First, setting the scope to session
as well as autouse=True
ensures this fixture runs before anything else.
Second, using find_dotenv(file_name)
ensures the correct file path is used in load_dotenv(file_path)
no matter what you call your .env
file. If you do happen to call your test env file .env
, then you can drop the find_dotenv()
call and just run load_dotenv()
without any arguments. python-dotenv
should have no problem finding any typical .env
files via load_dotenv()
That's it! Hopefully this helps, especially those that don't want to install another package to their project!