除了在 py.test 类中为每个变量创建一个固定装置之外,还有其他选择吗?

jul*_*jul 3 fixtures pytest

我想在所有 py.test 类方法中使用一些通用数据,并且仅在该类中使用,例如

n_files = 1000
n_classes = 10
n_file_per_class = int(n_files / n_classes)
Run Code Online (Sandbox Code Playgroud)

我发现我可以使用固定装置,例如:

class TestDatasplit:

    @pytest.fixture()
    def n_files(self):
        return 1000

    @pytest.fixture()
    def n_classes(self):
        return 10

    @pytest.fixture()
    def n_files_per_class(self, n_files, n_classes):
        return int(n_files / n_classes)

    def test_datasplit_1(self, n_files):
        assert n_files == 1000

    def test_datasplit(self, n_files_per_class):
        assert n_files_per_class == 100
Run Code Online (Sandbox Code Playgroud)

但在这里我需要为所有变量创建一个固定装置,但这看起来相当冗长(我有超过 3 个变量)...

在 py.test 类中创建一堆共享变量的最佳方法是什么?

das*_*s-g 9

您的测试似乎不会改变这些值,因此您可以使用模块级或类级常量。Pytest 装置为每个测试提供一个值的单独副本,这样当一个或多个测试改变值时,测试就不会开始相互依赖(或无意中使彼此失败)。