0

I have tests which on inside docker container with https://github.com/pytest-docker-compose/pytest-docker-compose, but it does take too long for the container to start up/shutdown. Then, I would like to let docker-compose run tests only CI machine or when need.

For this, I used this way of defining tests on simple_test_runner.py:

import os

THIS_FOLDER = os.path.dirname(os.path.realpath(__file__))
RUN_TESTS_LOCALLY = os.environ.get('RUN_TESTS_LOCALLY')

if RUN_TESTS_LOCALLY:
    def test_simple(run_process, load_env):
        output, returncode = run_process("python3 " + THIS_FOLDER + "/simple_test.py")
        assert returncode == 0

else:
    def test_simple(function_scoped_container_getter):
        container = function_scoped_container_getter.get("container_name")
        exec = container.create_exec("python3 /simple_test.py")
        ...

This works file if I export RUN_TESTS_LOCALLY=1 before calling pytest -vs ., but if I try to use https://github.com/theskumar/python-dotenv in my conftest.py:

from dotenv import load_dotenv

@pytest.fixture(scope='session', autouse=True)
def load_env():
    print("Loading .env file")
    load_dotenv()

The environment variables are only loaded after python test loaded the simple_test_runner.py. Then, my tests are always running inside docker instead of outside it when RUN_TESTS_LOCALLY=1 is defined.

How can I make pytest to call load_dotenv() before my switch if RUN_TESTS_LOCALLY: is evaluated inside my tests?

Or do you know an alternative to if RUN_TESTS_LOCALLY: which allows me to use load_dotenv() and switch between running my tests inside docker-compose or not?

Related:

  1. https://github.com/quiqua/pytest-dotenv
  2. How to load variables from .env file for pytests
  3. pytest -- how do I use global / session-wide fixtures?

1 Answer 1

0

The code I originally posted is working:

@pytest.fixture(scope='session', autouse=True)
def load_env(request):
    file = THIS_FOLDER + '/.env'
    if request.config.getoption("verbose") > 0:
        print("Loading", file, file=sys.stderr)
    load_dotenv(dotenv_path=file)

The problem was that when I had tested, I had set my environment variable to RUN_TESTS_LOCALLY= (the empty string). This was causing dotenv to not override my environment variable. Once I unset the variable with bash unset RUN_TESTS_LOCALLY, dotenv was finally loading the environment file correctly.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.