首页 > 解决方案 > 在 pytest 类方法中设置全局变量

问题描述

我有一个应用程序,它在启动时从远程源读取一些配置设置并将它们存储在全局范围内。此应用程序中的函数使用该全局配置中的设置。从功能上讲,它最终看起来像这样......

def define_globals():
    global MY_THRESHOLD
    MY_THRESHOLD = 123

def my_func(my_input):
    return my_input > MY_THRESHOLD

def run():
    define_globals()
    my_func(122)

我想my_func使用 pytest 进行测试,但在测试期间未定义 MY_THRESHOLD。对测试有点新,所以稍微研究了一下固定装置。有这样的东西,但在运行测试时仍然没有找到全局。

import pytest
import my_file

@pytest.fixture()
def set_gloabls():
    global MY_THRESHOLD
    MY_THRESHOLD = 123

class TestMyApplication(object):

    @pytest.mark.usefixtures("set_gloabls")
    def test_my_func(self):
        assert my_file.my_func(122) == False

我想我认为夹具将在被测试文件的范围内工作?IDK 很难弄清楚如何在不更改应用程序代码的情况下做到这一点。

标签: pythonpython-3.xunit-testingtestingpytest

解决方案


重申我在评论中所说的,“全局”变量只是模块中的“全局”。因此,当您尝试MY_THRESHOLD在测试模块中进行设置时,这将永远不会在您的my_file模块中可见。

你需要做这样的事情:

import pytest
import my_file

@pytest.fixture()
def set_globals():
    my_file.MY_THRESHOLD = 123

class TestMyApplication(object):

    @pytest.mark.usefixtures("set_globals")
    def test_my_func(self):
        assert my_file.my_func(122) == False

事实上,因为它是一个全局的,你也可以这样做(假设MY_THRESHOLD在你的测试中这是一个常数):

import pytest
import my_file

my_file.MY_THRESHOLD = 123

class TestMyApplication(object):

    def test_my_func(self):
        assert my_file.my_func(122) == False

推荐阅读