Skip to content

Avoid using dotenv in tests. #16

@BlueCrescent

Description

@BlueCrescent

Loading dotenv globally might change the os.environ for all tests. (I am not actually sure about this. It could be that pytest uses multiple processes.)
Note, that no .env file should be considered to be available when running the tests, anyways.
So, it would be better, to patch os.environ for the test that needs it:

@patch.dict(os.environ, {'MY_VARIABLE': 'my_value', **os.environ})
def test_my_test():
    # Your test code here

If you actually need API stuff (like keys, urls) from the .env for e2e tests, you could also use a construction like this:

from dotenv import dotenv_values

@patch.dict(os.environ, {**dotenv_values(), **os.environ})
def test_my_test():
    # Your test code here

Note, such tests should be turned off, by default, e.g. via:

@pytest.mark.skipif(not os.getenv('MY_VARIABLE'), reason="MY_VARIABLE is not set")
def test_my_test():
    # Your test code here

I think, these two thing should be combinable, if you like this:

@pytest.mark.skipif(not os.getenv('MY_VARIABLE'), reason="MY_VARIABLE is not set")
@patch.dict(os.environ, {**dotenv_values(), **os.environ})
def test_my_test():
    # Your test code here

Originally posted by @BlueCrescent in #15 (comment)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions