Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to use python-dotenv with pytest, or best way to have a pytest test/dev-environment with seperate configs

I want to use the python dotenv-lib at my python project. My dev-environment should use .env-file and the test-suite (pytest) should use .env.test automatically.

Until now I didn't find a satisfying solution.

I'm not very familiar with python. Maybe somebody can point me in the right direction.

Should I load the .env.test file in a pytest hook?

like image 932
wuarmin Avatar asked Jan 11 '18 16:01

wuarmin


2 Answers

For anyone coming in 2019 or later:

You can use pytest-dotenv 😉.

like image 152
Lual Avatar answered Oct 23 '22 14:10

Lual


After some investigation I came to the conclusion of not using python-dotenv. I ended up using the cool library simple-settings and pytest hooks. It solves my requirements quite well! simple-settings can load settings from several file-types. Which setting-file is loaded can be decided through an environment variable.

Following post can be very helpful, if somebody wants to learn something about pytest and its conftest file: In py.test, what is the use of conftest.py files?

Here's my conftest.py file with two hooks implemented:

import os

def pytest_configure(config):
  os.environ['SIMPLE_SETTINGS'] = 'config.test'
  return config

def pytest_unconfigure(config):
  os.environ['SIMPLE_SETTINGS'] = 'config.development'
  return config

If I run some test with pytest the corresponding environment variable is set. So my test-suite uses automatically the right settings.

like image 45
wuarmin Avatar answered Oct 23 '22 15:10

wuarmin