这并没有太大的区别,这主要是因为人们的喜好.我主要使用conftest.py
个来引入您的测试所需的、但不直接使用的修复程序.因此,您可能有一个对数据库执行有用操作的装置,但需要一个数据库连接才能做到这一点.因此,您使db_connection
灯具在conftest.py
个中可用,然后您的测试只需执行以下操作:
conftest.py
个
from tests.database_fixtures import db_connection
__all__ = ['db_connection']
tests/database_fixtures.py
个
import pytest
@pytest.fixture
def db_connection():
...
@pytest.fixture
def new_user(db_connection):
...
test/test_user.py
个
from tests.database_fixtures import new_user
def test_user(new_user):
assert new_user.id > 0 # or whatever the test needs to do
If you didn't make db_connection
available in conftest.py
个 or directly import it then pytest would fail to find the db_connection
fixture when trying to use the new_user
fixture. If you directly import db_connection
into your test file, then linters will complain that it is an unused import. Worse, some may remove it, and cause your tests to fail. So making the db_connection
available in conftest.py
个, to me, is the simplest solution.
Overriding Fixtures
The one significant difference is that it is easier to override fixtures using conftest.py
个. Say you have a directory layout of:
./
├─ conftest.py
└─ tests/
├─ test_foo.py
└─ bar/
├─ conftest.py
└─ test_foobar.py
In conftest.py
个 you could have:
import pytest
@pytest.fixture
def some_value():
return 'foo'
然后在tests/bar/conftest.py
年内,你可能会有:
import pytest
@pytest.fixture
def some_value(some_value):
return some_value + 'bar'
拥有多个配置测试允许您重写一个装置,同时仍然保持对原始装置的访问.因此,接下来的测试都会奏效.
tests/test_foo.py
个
def test_foo(some_value):
assert some_value == 'foo'
tests/bar/test_foobar.py
个
def test_foobar(some_value):
assert some_value == 'foobar'
You can still do this without conftest.py
个, but it's a bit more complicated. You'd need to do something like:
import pytest
# in this scenario we would have something like:
# mv contest.py tests/custom_fixtures.py
from tests.custom_fixtures import some_value as original_some_value
@pytest.fixture
def some_value(original_some_value):
return original_some_value + 'bar'
def test_foobar(some_value):
assert some_value == 'foobar'