使用 setup_class 初始化 "conflicts" 和参数化选项

using setup_class for initialization "conflicts" with parametrize options

我有这个文件:

import numpy as np


class Variables(object):

    def __init__(self, var_name, the_method):

        self.var_name = var_name
        self.the_method = the_method

    def evaluate_v(self):
        var_name, the_method = self.var_name, self.the_method

        if the_method == 'Average':
            return np.average(var_name)

和这个测试文件:

import unittest
import pytest
import numpy as np

from .variables import Variables


class TestVariables():

    @classmethod
    def setup_class(cls):
        var_name = np.array([1, 2, 3])
        the_method = 'Whatever'
        cls.variables = Variables(var_name, the_method)

    @pytest.mark.parametrize(
        "var_name, the_method, expected_output", [
            (np.array([1, 2, 3]), 'Average', 2),
        ])
    def test_evaluate_v_method_returns_correct_results(
        self, var_name, the_method,expected_output):

        var_name, the_method = self.variables.var_name, self.variables.the_method

        obs = self.variables.evaluate_v()  
        assert obs == expected_output

if __name__ == "__main__":
    unittest.main()

现在,我的问题是我在设置 class.

中初始化值 (var_name、the_method)

因此,当我在参数化中使用不同的值时,这些值将被忽略。

所以,现在的测试是通过将 the_method 值作为 Whatever 而不是 Average 来完成的(我想在不同的参数化设置中)。

有没有办法在不丢失 setup_class 的情况下处理这个问题?

因为,如果我省略 setup_class,就可以了。

好吧,您可以将 setup_class 方法的职责限制为使用任何 non-throwing-exception 数据

创建变量实例
@classmethod
    def setup_class(cls):            
        cls.variables = Variables(None, None)

并创建测试

    @pytest.mark.parametrize(
        "var_name, the_method, expected_output", [
            (np.array([1, 2, 3]), 'Average', 2),
            (np.array([1, 2, 3]), 'Whatever', 'whatever you want')
        ])
    def test_evaluate_v_method_returns_correct_results(
        self, var_name, the_method, expected_output):

        self.variables.var_name = var_name
        self.variables.the_method = the_method

        assert self.variables.evaluate_v() == expected_output

但就我个人而言,我认为将 None 传递给构造函数并不是一个非常干净的解决方案。我建议在每次测试时将参数设为可选或创建 Variables` 实例。