8

This is a simplified version of my problem.

I have a python application with the structure as below:

my_project
    my_app
        __init__.py
        settings.py
    tests
        __init__.py
        conftest.py
        my_test.py
     venv
# settings.py

from dotenv import load_dotenv
load_dotenv() 
MY_VALUE = os.environ["MY_KEY"]

I dont want to add a .env file in here for some reasons. I also dont want to use get method on os.environ

I want to run this test

# my_test.py

from my_app import settings # I need this for some reasons

def test_something():
    assert True

def test_env():
    assert os.environ["MY_KEY"] == 'MY_VALUE'

However, I get a KeyError because once I import settings.py, the line MY_VALUE = os.environ["MY_KEY"] is run and because MY_KEY is not in env, I get KeyError.

What I thought is that I could have conftest as below

import os
from unittest import mock

import pytest


@pytest.fixture(autouse=True)
def set_env(config):
    with mock.patch.dict(os.environ, {'MY_KEY': 'MY_VALUE'}):
        yield

But it is still the same problem.

How can I enforce this conftest before everything else.

also note that if I comment out from my_app import settings both my tests will pass

NOTE: the reason I do not want to use os.environ.get("MY_KEY") is that I want to enforce env variable to exist before the application or the test is initialized. The reason for this is that in reality, when my application is running in a docker container, the env variables are there before everything else and I want to increase dev-prod parity. https://12factor.net/dev-prod-parity

Amin Ba
  • 1,603
  • 1
  • 13
  • 38

0 Answers0