我现在正在关注此事 py.test 例如,当我不使用类时它可以工作,但是当我将测试用例引入类时,我失败了。
我设法编写的最小案例如下:
import unittest
import pytest
class FixtureTestCase(unittest.TestCase):
@pytest.mark.parametrize("test_input,expected", [
("3+5", 8),
("2+4", 6),
("6*9", 42),
])
def test_1(self, a, b):
self.assertEqual(a, b)
不幸的是,当我执行
py.test test_suite.py
我收到错误消息:
TypeError: test_1() takes exactly 3 arguments (1 given)
如何生成一系列test_1测试?
如果你是子类 unittest.TestCase
,您的测试方法不能有其他参数。如果你只是从中继承 object
,它会工作(虽然你必须使用常规 assert
陈述而不是 TestCase.assertEqual
方法。
import unittest
import pytest
class TestCase(object):
@pytest.mark.parametrize("test_input,expected", [
("3+5", 8),
("2+4", 6),
("6*9", 42),
])
def test_1(self, a, b):
assert eval(a) == b
但是,在这一点上,它有点问题为什么你使用类而不仅仅是定义函数,因为测试基本上是相同的,但需要更少的整体样板和代码。
最后,考虑到@Brendan Abel的回复和评论,我成功完成了我打算做的事情:
class TestCase(object):
@parameterized.expand([
("negative", -1.5, -2.0),
("integer", 1, 1.0),
("large fraction", 1.6, 1),
])
def test_floor(self, name, input, expected):
assert_equal(math.floor(input), expected)
@parameterized.expand([
("3+5", 8),
("2+4", 6),
("6*9", 42),
])
def test_1(self, a, b):
assert_equal(eval(a), b)
然后我就可以通过执行测试了 nosetests 命令:
nosetests -v --with-id class.py