conftest.py的作用范围
一个工程下可以建多个conftest.py的文件,一般在工程根目录下设置的conftest文件起到全局作用。在不同子目录下也可以放conftest.py的文件,作用范围只能在改层级以及以下目录生效。
项目实例:
目录结构:
1.conftest在不同的层级间的作用域不一样
# conftest层级展示/conftest.py
import pytest
@pytest.fixture(scope='session', autouse=True)
def login():
print('----准备登录----')
# conftest层级展示/sougou_login/conftest
import pytest
@pytest.fixture(scope='session', autouse=True)
def bai_du():
print('-----登录百度页面-----')
# conftest层级展示/sougou_login/login_website
import pytest
class TestCase:
def test_login(self):
print('hhh,成功登录百度')
if __name__ == '__main__':
pytest.main(['-s', 'login_website.py'])
输出结果:
============================= test session starts =============================
platform win32 -- Python 3.7.0, pytest-4.0.2, py-1.7.0, pluggy-0.8.0
rootdir: C:\Program Files\PycharmProjects\conftest层级演示\sougou_login, inifile:collected 1 item
login_website.py ----准备登录----
-----登录百度页面-----
.hhh,成功登录百度
[100%]
========================== 1 passed in 0.03 seconds ===========================
Process finished with exit code 0
2.conftest是不能跨模块调用的(这里没有使用模块调用)
# conftest层级演示/log/contfest.py
import pytest
@pytest.fixture(scope='function', autouse=True)
def log_web():
print('打印页面日志成功')
# conftest层级演示/log/log_website.py
import pytest
def test_web():
print('hhh,成功一次打印日志')
def test_web1():
print('hhh,成功两次打印日志')
if __name__ == '__main__':
pytest.main(['-s', 'log_website.py'])
输出结果:
============================= test session starts =============================
platform win32 -- Python 3.7.0, pytest-4.0.2, py-1.7.0, pluggy-0.8.0
rootdir: C:\Program Files\PycharmProjects\conftest层级演示\log, inifile:
collected 2 items
log_website.py ----准备登录----
打印页面日志成功
hhh,成功一次打印日志
.打印页面日志成功
hhh,成功两次打印日志
.
========================== 2 passed in 0.02 seconds ===========================