Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在pytest类方法中设置全局变量_Python_Python 3.x_Unit Testing_Testing_Pytest - Fatal编程技术网

Python 在pytest类方法中设置全局变量

Python 在pytest类方法中设置全局变量,python,python-3.x,unit-testing,testing,pytest,Python,Python 3.x,Unit Testing,Testing,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_fu

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

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)
我想使用pytest测试
my_func
,但测试期间未定义my_阈值。对测试来说有点陌生,所以对夹具进行了一些研究。有这样的东西,但在运行测试时仍然找不到全局

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很难探索如何在应用程序中不更改代码的情况下做到这一点。

重复我在评论中所说的,在模块中,“全局”变量只是“全局”变量。因此,当您尝试在测试模块中设置
MY_阈值时,这在
MY_文件
模块中永远不会可见

您需要执行以下操作:

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
是一个常数):


请记住,“全局”变量仅在模块上下文中是全局的……因此,如果您的应用程序正在查找
MY_THRESHOLD
,则需要在应用程序模块中设置该变量。也就是说,如果您的测试已导入myapp
,则需要设置myapp.MY_阈值。你能给我们看一下你完整的测试文件(包括
import
行)吗?@larsks为了举例,我对测试文件进行了大量简化,但我编辑了测试代码以从应用程序代码导入。这基本上就是我在现实生活中所拥有的。
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