将 python-dotenv 与 pytest 一起使用的最佳方式,或使用单独配置的 pytest test/dev-environment 的最佳方式

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

我想在我的 python 项目中使用 python dotenv-lib。我的开发环境应该使用 .env-file 并且测试套件(pytest)应该自动使用 .env.test 。

直到现在我还没有找到满意的解决方案。

我对python不是很熟悉。也许有人可以指出正确的方向。

我应该在 pytest 挂钩中加载 .env.test 文件吗?

经过一些调查,我得出了不使用 python-dotenv 的结论。我最终使用了很棒的库 simple-settings and pytest hooks。很好的解决了我的需求! simple-settings 可以从多种文件类型加载设置。加载哪个设置文件可以通过环境变量来决定。

如果有人想了解有关 pytest 及其 conftest 文件的内容,请关注 post:

这是我的 conftest.py 文件,实现了两个挂钩:

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

如果我运行使用pytest进行一些测试,则设置相应的环境变量。所以我的测试套件会自动使用正确的设置。

对于 2019 年或之后来的任何人:

您可以使用 pytest-dotenv .