pytest內建fixture之pytestconfig
阿新 • • 發佈:2021-07-26
前言
pytestconfig是pytest的一個內建fixture,可以獲取上下文,它的作用跟request.config是一樣的,可以獲取配置物件。
pytestconfig的原始碼
@fixture(scope="session") def pytestconfig(request: FixtureRequest) -> Config: """Session-scoped fixture that returns the :class:`_pytest.config.Config` object. Example:: def test_foo(pytestconfig): if pytestconfig.getoption("verbose") > 0: ...""" return request.config
從原始碼中可以看到,實際上返回的就是request.config,所以說pytestconfig的作用與request.config的作用是一樣的。
原始碼中還提供了使用示例:
def test_foo(pytestconfig): if pytestconfig.getoption("verbose") > 0:
pytestconfig中有2個比較常用的方法:
- getoption:獲取命令列中的引數;
- getini:獲取pytest.ini配置檔案中的引數;
getoption獲取命令列引數:
# file_name: configtest.py def pytest_addoption(parser): parser.addoption( "--cmdopt", action="store", default="type1", help="my option: type1 or type2" ) @pytest.fixture() def cmdopt(pytestconfig): return pytestconfig.getoption("--cmdopt")
測試用例:
# file_name: test_option.pyimport pytest def test_cmd_1(cmdopt): # 通過conftest中定義的fixture來獲取引數值 print("test_cmd_1當前獲取的引數為:{}".format(cmdopt)) def test_cmd_2(pytestconfig): # 直接通過pytestconfig獲取引數值 cmdopt = pytestconfig.getoption("cmdopt") print("test_cmd_2當前獲取的引數為:{}".format(cmdopt)) if __name__ == '__main__': pytest.main(['-s', 'test_option.py'])
命令列中執行指令:pytest test_option.py -s --cmdopt=type2,執行結果為:
從結果中可以看到,兩種方式都可以獲取到命令列引數cmdopt的值。
pytestconfig動態新增pytest.ini配置引數(addini)
我們之前在conftest.py檔案中通過在鉤子函式pytest_addoption中使用addoption方法來新增命令列引數,現在我們在鉤子函式pytest_addoption中使用addini來新增配置引數:
def addini(self, name, help, type=None, default=None): """ register an ini-file option. :name: name of the ini-variable :type: type of the variable, can be ``pathlist``, ``args``, ``linelist`` or ``bool``. :default: default value if no ini-file option exists but is queried. The value of ini-variables can be retrieved via a call to :py:func:`config.getini(name) <_pytest.config.Config.getini>`. """ assert type in (None, "pathlist", "args", "linelist", "bool") self._inidict[name] = (help, type, default) self._ininames.append(name)
上面是addini的原始碼,從原始碼中可以看到addini方法有4個引數:name,help,type,default
- name:是引數的名稱;
- help:是幫助說明,方便查閱;
- type:是引數型別,預設None,可以設定:None, "pathlist", "args", "linelist", "bool";
- default:引數預設值;
舉例:
# file_name: configtest.py def pytest_addoption(parser): # 新增命令列引數 parser.addoption( "--cmdopt", action="store", default="type1", help="my option: type1 or type2" ) # 新增配置引數 parser.addini( "base_url", type=None, default="http://www.lwjnicole.com", help="新增base_url配置引數" ) @pytest.fixture() def base_url(pytestconfig): return pytestconfig.getini("base_url")
測試用例:
# file_name: test_option.py import pytest def test_base_url(base_url): print("當前獲取到的base_url = {}".format(base_url)) if __name__ == '__main__': pytest.main(['-s', 'test_option.py'])
命令列輸入指令:pytest test_option.py -s ,執行結果:
從結果中可以看到我們獲取到了通過addini()新增的配置引數base_url。
pytestconfig獲取配置檔案中的配置引數(getini)
現在有配置檔案pytest.ini的內容如下:
# file_name: pytest.ini [pytest] markers = slow: run slow mark case fast: run fast mark case xfail_strict = True addopts = -v --reruns=2 --html=report.html --self-contained-html log_cli = False norecursedirs = venv report util log python_files = test*.py python_classes = Test* python_functions = test_*
測試用例:
# file_name: test_option.py import pytest def test_get_ini(pytestconfig): log_cli = pytestconfig.getini("log_cli") print("\n獲取到的log_cli = {}".format(log_cli)) xfail_strict = pytestconfig.getini("xfail_strict") print("\n獲取到的xfail_strict = {}".format(xfail_strict)) addopts = pytestconfig.getini("addopts") print("\n獲取到的addopts = {}".format(addopts)) if __name__ == '__main__': pytest.main(['-s', 'test_option.py'])
執行結果:
從執行結果中可以看到我們可以通過pytestconfig.getini()方法來獲取配置檔案中的配置引數。
去期待陌生,去擁抱驚喜。