使用 setup_class 初始化“冲突";带参数化选项 [英] 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()
现在,我的问题是我在设置类中初始化值(var_name、the_method).
Now, my problem is that I initialize the values (var_name, the_method) in the setup class.
因此,当我在参数化中使用不同的值时,这些值将被忽略.
So, when I use different values in the parametrize, these values are ignored.
因此,现在的测试是通过将 the_method
值作为 Whatever
而不是 Average
(我想在不同的参数设置).
So, the test right now is done by taking as the_method
value as Whatever
and not as Average
(which I want to have in the different parametrize setup).
有没有办法在不丢失 setup_class
的情况下处理这个问题?
Is there a way to deal with this without loosing the setup_class
?
因为,如果我省略 setup_class,它就可以工作.
Because, if I ommit the setup_class, ok it works.
推荐答案
好吧,您可以将 setup_class
方法的责任限制为使用任何非抛出异常数据创建变量的实例
Well, you can just limit the responsibility of setup_class
method to a creation of Variables' instance with any non-throwing-exception data
@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 实例.
But personally, I don't think passing None
s to the constructor is a very clean solution. I suggest making the parameters optional or creating Variables` instance every test.
这篇关于使用 setup_class 初始化“冲突";带参数化选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!