Can unittest's setUpClass classmethod return a value to be used throughout the other tests?

Cas*_*per 1 python unit-testing class python-3.x

我正在尝试为依赖模块级数据(JSON文件)的程序编写单元测试。
因此,我当时想使用setUpClass类方法设置一个测试JSON文件,然后在运行测试后将其删除。
我遇到的问题是,模块级JSON的设置返回的值是我也打算测试的程序的其他功能所必需的。
这是我的意思的示例:

import unittest
import myProg  

class TestProg(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        # initialize() creates the JSON file
        myProg.initialize()
        f = myProg.initialize_storage()
        return f

    def test_prog_func(self):
        myProg.prog_func("test_key", "test_value", f)
Run Code Online (Sandbox Code Playgroud)

f是我其余功能需要的项目。此代码不起作用。我正在寻找一种方法,允许我return f从setUpClass中“ ”在整个测试中使用。

Mar*_*ers 5

您无法返回任何内容,不,返回值将被忽略。您可以设置类属性,这些属性可用于所有测试:

class TestProg(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        # initialize() creates the JSON file
        myProg.initialize()
        cls.f = myProg.initialize_storage()  # set a class attribute

    def test_prog_func(self):
        # self.f here will find the class attribute
        myProg.prog_func("test_key", "test_value", self.f)
Run Code Online (Sandbox Code Playgroud)

这是因为实例上的属性查找还将找到类属性(毕竟,这是方法的查找方式)。

请注意,测试运行程序将为正在运行的每个测试创建您的类的新实例;确保实例状态是干净的。类状态不会清除,因此,如果您在测试中更改类属性,则将不再具有适当的测试隔离。