using setup_class for initialization “conflicts” with parametrize options

纵饮孤独 提交于 2019-12-14 03:18:24

问题


I have this file:

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)

and this test file:

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()

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.

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).

Is there a way to deal with this without loosing the setup_class?

Because, if I ommit the setup_class, ok it works.


回答1:


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)

and create tests

    @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

But personally, I don't think passing Nones to the constructor is a very clean solution. I suggest making the parameters optional or creating Variables` instance every test.



来源:https://stackoverflow.com/questions/41891939/using-setup-class-for-initialization-conflicts-with-parametrize-options

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!