1、fixture之 yield 实现 teardown
a、带有 yield 的函数在 Python 中被称之为 generator(生成器) ,可以暂时简单的理解为函数的return , 后面可以加返回值 yield login_status, code 。
项目层级如下:
conftest.py 代码如下:
import pytest @pytest.fixture(scope=‘class‘) def open_browser(): print(‘\n打开浏览器‘) result = ‘打开浏览器成功‘ # yield 相当于return ,可返回值; 此处返回result的值 ; yield result print(‘\n关闭浏览器‘)
test_ff.py 代码如下:
class TestWeb(): # 调用open_browser接受返回值 def test_open_web(self, open_browser): result = open_browser print(result) print(‘\n打开网站‘) def test_close_web(self): print(‘\n关闭网站‘)
执行结果如下:
(venv) D:\SkyWorkSpace\WorkSpace\Pytest\Temp\day11\ff>pytest -sv ======================================================================== test session starts ======================================================================== platform win32 -- Python 3.8.6, pytest-6.2.4, py-1.10.0, pluggy-0.13.1 -- D:\SkyWorkSpace\WorkSpace\Pytest\Temp\day11\venv\Scripts\python.exe cachedir: .pytest_cache rootdir: D:\SkyWorkSpace\WorkSpace\Pytest\Temp\day11\ff collected 2 items test_ff.py::TestWeb::test_open_web 打开浏览器 打开浏览器成功 打开网站 PASSED test_ff.py::TestWeb::test_close_web 关闭网站 PASSED 关闭浏览器 ========================================================================= 2 passed in 0.02s ========================================================================= (venv) D:\SkyWorkSpace\WorkSpace\Pytest\Temp\day11\ff>