我认为最简单的方法是用我的软件环境作为“测试”重新加载配置模块
我的代码有一个config.py
,它用作配置处理代码,我在其中定义了我要运行的每个环境的所有配置设置
config.py
class Config(object):
DEBUG = False
TESTING = False
DATABASE_URI = 'sqlite:///:memory:'
class ProductionConfig(Config):
DATABASE_URI = 'mysql://user@localhost/foo'
class DevelopmentConfig(Config):
DEBUG = True
class TestingConfig(Config):
TESTING = True
config_lookup = dict(
testing=TestingConfig(),
development=DevelopmentConfig(),
production=ProductionConfig(),
)
config = config_lookup[os.getenv('ENVIRONMENT', 'development')]
一种方法是使用重载:
在我的conftest.py
上,我希望确保所有测试都按照TestingConfig运行。
因此,我会这样做:
conftest.py
@pytest.fixture(autouse=True)
def cfg():
# Reload the global 'config' instance.
os.environ["ENVIRONMENT"] = "testing"
importlib.reload(sys.modules["config"])
不幸的是,这种方法似乎并不像importlib.reload()
所预期的那样适用于所有情况
importlib.reload()
Reload a previously imported module. The argument must be a module object, so it must have been successfully imported before. Read more:importlib Docs
此解决方案可能在第一个实例中有效,但在使用不同类型的导入时会变得棘手。(对象vs子模块)
导入一个对象
from app.config import config
print('Environment is:',type(config).__name__)
# Environment is:Development <- Wrong
一个模块被导入
import app.config as _
print('Environment is:',type(_.config).__name__)
# Environment is:Testing <-- correct
另一种方法是确保在执行pytests时始终设置环境变量:
ENVIRONMENT=testing python -m pytest tests
这不是一个理想的方法,因为您可能会忘记附加环境
相关问题:
difference-between-from-x-import-y-and-import-x-yPython Bug
另一种似乎很有效的方法是确保在运行
conftest.py
之前设置环境。正在使用python-env看起来很好用。从上到下,这是一个没有维护的旧存储库,但也是一小段代码
相关问题 更多 >
编程相关推荐