运行pytest parametrize fixture我得到`self`没有定义

时间:2017-01-26 08:30:25

标签: python pytest

我有这堂课:

accept.py

class AcceptC(object):

    def __init__(self):
        self.minimum = 30
        self.maximum = 40

和unittest:

accept_test.py

import unittest
import pytest

from app.accept import AcceptC


class TestAcceptC(unittest.TestCase):

    def setUp(self):
        self.accept = AcceptC()


@pytest.mark.parametrize(
    "minimum, maximum, expected_min, expected_max", [
        ("13", "5", 30, 40),
        ("30", "40", 30, 40),
    ])
def test_init_returns_correct_results(minimum, maximum, expected_min, expected_max):
    expected_min = self.accept.minimum
    expected_max = self.accept.maximum
    self.assertEqual(minimum, expected_min)
    self.assertEqual(maximum, expected_max)


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

使用pytest运行时,出现错误:

  

NameError:name' self'未定义

我还看到我不能在测试函数中使用self作为参数。

最后,有没有办法避免使用:

expected_min = self.accept.minimum
expected_max = self.accept.maximum

立即使用self.accept.minimum

如果我使用self作为测试函数的参数,则返回:

  

夹具'自我'找不到

2 个答案:

答案 0 :(得分:2)

你错过了方法中的self(假设它是一个方法,如果它是一个函数而不是你需要使它成为TestAcceptC方法的第一个)参数列表:

def test_init_returns_correct_results(minimum, maximum, expected_min, expected_max):

应该是(我做了一些额外的更改;远离unittest以及更多pytest - 就像):

class TestAcceptC():  # no need to subclass unittest

    @classmethod
    def setup_class(cls):
        # Called when setting up the class
        cls.accept = AcceptC()

    @pytest.mark.parametrize(
        ["minimum", "maximum", "expected_min", "expected_max"], [
            ("13", "5", 30, 40),
            ("30", "40", 30, 40),
        ])
    def test_init_returns_correct_results(self, minimum, maximum, expected_min, expected_max):
        # difference is here -------------^^^^
        # pytest can use normal asserts here.
        assert self.accept.minimum == expected_min
        assert self.accept.maximum == expected_max

答案 1 :(得分:0)

问题仅是由于:

class TestAcceptC(unittest.TestCase):

这种对unittest.TestCase的继承将打破pytest固定装置的“自我”。

信息:https://docs.pytest.org/en/3.0.1/unittest.html