【问题标题】:How to load environment variables from file using python-dotenv before loading pytest scritps?如何在加载 pytest 脚本之前使用 python-dotenv 从文件中加载环境变量?
【发布时间】:2021-11-18 13:06:18
【问题描述】:

我在 docker 容器内使用https://github.com/pytest-docker-compose/pytest-docker-compose 进行了测试,但容器启动/关闭确实需要很长时间。然后,我想让 docker-compose 只在 CI 机器上或在需要时运行测试。

为此,我使用这种方式在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")
        ...

如果我在调用pytest -vs . 之前导出RUN_TESTS_LOCALLY=1,但如果我尝试在conftest.py 中使用https://github.com/theskumar/python-dotenv,则此文件有效:

from dotenv import load_dotenv

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

环境变量仅在python测试加载simple_test_runner.py后加载。然后,当定义 RUN_TESTS_LOCALLY=1 时,我的测试总是在 docker 内部而不是外部运行。

如何让pytest 在我的开关if RUN_TESTS_LOCALLY: 在我的测试中被评估之前调用load_dotenv()

或者您知道if RUN_TESTS_LOCALLY: 的替代方法,它允许我使用load_dotenv() 并在是否在docker-compose 中运行我的测试之间切换?

相关:

  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?

【问题讨论】:

    标签: python docker docker-compose pytest integration-testing


    【解决方案1】:

    我最初发布的代码正在运行:

    @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)
    

    问题是,当我进行测试时,我将环境变量设置为RUN_TESTS_LOCALLY=(空字符串)。这导致dotenv 无法覆盖我的环境变量。一旦我用bash unset RUN_TESTS_LOCALLY 取消设置变量,dotenv 终于可以正确加载环境文件了。

    【讨论】:

      猜你喜欢
      • 2017-07-09
      • 2021-10-14
      • 2019-01-01
      • 2015-09-02
      • 2015-09-16
      • 1970-01-01
      • 2021-11-08
      • 2016-09-05
      • 1970-01-01
      相关资源
      最近更新 更多