TypeError: missing 1 required positional argument while using pytest fixture

TypeError: missing 1 required positional argument while using pytest fixture

我已经在文件中编写了测试 类,并且我正在尝试使用 pytest fixtures,这样我就不必在每个测试函数中创建相同的输入数据。下面是最小的工作示例。

import unittest
import pytest

@pytest.fixture
def base_value():
    return 5

class Test(unittest.TestCase):

    def test_add_two(self, base_value):
        result = base_value + 2
        self.assertEqual(result, 7, "Result doesn't match")

但是,当我使用 pytest-3 对此进行测试时,出现以下错误:

TypeError: test_add_two() missing 1 required positional argument: 'base_value'

这让我感到困惑,因为 base_value 显然是 test_add_two 的参数之一。非常感谢任何帮助。

这是因为您混合了 pytestunittest。尝试

@pytest.fixture
def base_value():
    return 5


class Test:
    def test_add_two(self, base_value):
        result = base_value + 2
        assert result == 7, "Result doesn't match"

如果失败,错误将是

def test_add_two(self, base_value):
        result = base_value + 2
>       assert result == 8, "Result doesn't match"
E       AssertionError: Result doesn't match
E       assert 7 == 8

但是pytest不兼容unittest吗?

仅在有限的基础上。来自 Pytest unittest.TestCase Support

pytest features in unittest.TestCase subclasses The following pytest features work in unittest.TestCase subclasses:

  • Marks: skip, skipif, xfail;
  • Auto-use fixtures;

The following pytest features do not work, and probably never will due to different design philosophies:

  • Fixtures (except for autouse fixtures, see below);
  • Parametrization;
  • Custom hooks;

Third party plugins may or may not work well, depending on the plugin and the test suite.