【问题标题】:Is it possible to change packagewide global variables during pytest testing?是否可以在 pytest 测试期间更改包范围的全局变量?
【发布时间】:2021-01-28 12:32:12
【问题描述】:

在我的项目中,我使用一个名为“conf.py”的文件来存储几个配置变量,例如保存文件的基本路径。

# conf.py:
'''
global variables and settings
'''

# Number of nodes in the graph
NODECOUNT = 1206

# save location
BASEPATH = 'data/'

包的其他部分通过从“conf.py”导入变量来加载它们。 使用 pytest 进行测试时,我需要这些变量的其他值才能被导入的包使用。这有可能吗?

编辑: 我当前的 pytest 文件如下所示:

import pytest
import my_packages

# set up a small graph to test on
s = structure(data, name) # structure uses conf.NODECOUNT
save(conf.BASEPATH + name, s)

# Tests
class TestOneClass:
    def test_some_function():
        res = some_function(name) # loads data from 'conf.BASEPATH/name'
        assert res == expected_res
# more tests after

【问题讨论】:

    标签: python pytest


    【解决方案1】:

    您可以使用 pytest monkeypatch fixture 来执行此操作。假设您有上述conf.py,那么文件test_conf.py 将如下所示。这只是一个测试配置值的例子,你可能想用它做一些不同的事情。

    import conf
    
    def test_conf(monkeypatch):
        monkeypatch.setattr(conf, 'NODECOUNT', 5)
        assert conf.NODECOUNT == 5
    

    如果您需要更改子模块中的配置,则需要对这些子模块导入的conf 进行monkeypatch。不过方法是一样的。假设以下文件夹/文件结构:

    tmp
    ├── conf.py
    ├── __init__.py
    ├── sub
    │   ├── calc.py
    │   ├── __init__.py
    └── test_calc.py
    

    然后calc.py 看起来像这样:

    from tmp import conf
    
    def add(a, b):
        return a + b
    

    test_calc.py 看起来像这样:

    from tmp.sub import calc
    
    def test_add(monkeypatch):
        monkeypatch.setattr(calc.conf, 'NODECOUNT', 5)
        assert calc.add(1, 2) == 3
        assert calc.conf.NODECOUNT == 5
    

    【讨论】:

    • 感谢您的回答。为了更清楚,我编辑了我的问题。我尝试使用您的解决方案在我的导入后更改值(在特定测试之外),但我得到了 TypeError: must be absolute import path string, not 'NODECOUNT'
    • some_function 在哪里?在my_packages?而你的conf 被加载到my_packages 中?然后你可以使用下面的方法在 my_packages 内部进行猴子补丁 conf
    • 它们的位置与您假设的一样。但是,我需要在设置模型数据时重新定义变量。那是在任何测试之前,因为所有测试都使用相同的数据。
    • 那么在这种情况下,您可以定期导入配置并覆盖值,即import conf,然后是conf.BASEPATH = 'my test basepath'。或者是什么阻止了你?
    • 这样的话,构造函数仍然使用正常的conf.py和收集前的测试错误
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-28
    相关资源
    最近更新 更多