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

Question:

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?

Asked By: wuarmin

||

Answers:

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.

Answered By: wuarmin

For anyone coming in 2019 or later:

You can use pytest-dotenv .

Answered By: Lual

I would use setUpClass() method to do it, which gets loaded before individual tests are run.

    class TestCases(Testcase):
    
        @classmethod
        def setUpClass(cls):
            from dotenv import load_dotenv
            load_dotenv(".dev-env")
    
        def test_myrandomtest():
            self.assert(something,something, "Oh crap")
Answered By: Austin p.b