Wil*_*ill 8 python unit-testing fixtures pytest python-unittest
我正在尝试使用我的单元测试py.test的装置,结合使用unittest.我已经把一些灯具在一个conftest.py文件在项目的顶层(如描述在这里),装饰他们@pytest.fixture,并把他们的名字作为参数传递给需要它们的测试功能.
如图所示py.test --fixtures test_stuff.py,灯具正确注册,但是当我跑步时py.test,我得到了NameError: global name 'my_fixture' is not defined.这似乎只发生在我使用子类时unittest.TestCase- 但是py.test文档似乎表明它可以很好地发挥作用unittest.
为什么我使用时测试不能看到灯具unittest.TestCase?
@pytest.fixture
def my_fixture():
return 'This is some fixture data'
Run Code Online (Sandbox Code Playgroud)
import unittest
import pytest
class TestWithFixtures(unittest.TestCase):
def test_with_a_fixture(self, my_fixture):
print(my_fixture)
Run Code Online (Sandbox Code Playgroud)
@pytest.fixture()
def my_fixture():
return 'This is some fixture data'
Run Code Online (Sandbox Code Playgroud)
import pytest
class TestWithFixtures:
def test_with_a_fixture(self, my_fixture):
print(my_fixture)
Run Code Online (Sandbox Code Playgroud)
出于好奇,我更多地问这个问题; 现在我只是unittest完全放弃了.
小智 11
您可以将 pytest 固定装置unittest.TestCase与 pytest 选项一起使用autouse。但是,如果您使用test_ 夹具来使用单位方法,则会出现以下错误:
Fixtures are not meant to be called directly,...
### conftest.py
@pytest.fixture
def my_fixture():
return 'This is some fixture data'
Run Code Online (Sandbox Code Playgroud)
一种解决方案是使用一种prepare_fixture方法将固定装置设置为类的属性TestWithFixtures,以便固定装置可用于所有单元测试方法。
### test_stuff.py
import unittest
import pytest
class TestWithFixtures(unittest.TestCase):
@pytest.fixture(autouse=True)
def prepare_fixture(self, my_fixture):
self.myfixture = my_fixture
def test_with_a_fixture(self):
print(self.myfixture)
Run Code Online (Sandbox Code Playgroud)
虽然pytest支持通过非单元测试方法的测试函数参数接收fixture,但unittest.TestCase方法不能直接接收fixture函数参数作为实现可能会导致运行通用unittest.TestCase测试套件的能力.
从底部的注释部分:https: //pytest.org/latest/unittest.html
可以使用unittest.TestCasees的固定装置.有关更多信息,请参阅该页面.
小智 5
将夹具定义为可访问变量(如input以下示例所示)。要定义它,请使用request.cls.VARIABLE_NAME_YOU_DEFINE = RETURN_VALUE
use@pytest.mark.usefixtures("YOUR_FIXTURE")在unittest类外部使用fixture,在unittest类内部,通过 访问fixture self.VARIABLE_NAME_YOU_DEFINE。
例如
import unittest
import pytest
@pytest.fixture(scope="class")
def test_input(request):
request.cls.input = {"key": "value"}
@pytest.mark.usefixtures("test_input")
class MyTestCase(unittest.TestCase):
def test_something(self):
self.assertEqual(self.input["key"], "value")
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3708 次 |
| 最近记录: |