欢迎您访问365答案网,请分享给你的朋友!
生活常识 学习资料

pytest--内置fixture

时间:2023-05-14

要使用python内置的fixture,首先得明确fixture返回的数据类型
fixture参考官网 https://docs.pytest.org/en/7.0.x/reference/reference.html#tmpdir-factory

tempdir 和 tempdir_factory

负责在运行前创建临时文件目录,并在测试结束后删除
如果测试代码要对文件进行读写操作,可以使用tmpdir或tmpdir_factory来创建目录
tmpdir的作用范围是函数级别,tmpdir_factory的作用范围是会话级别
查看官方文件,可以看到tmpdir返回的是一个py._path.local.LocalPath的对象

py._path.local.LocalPath的API文档 https://py.readthedocs.io/en/latest/path.html
使用dirname可以打印出tmpdir的路径

def test_tempdir(tmpdir): print("dirname:{}".format(tmpdir.dirname)) sub_dir=tmpdir.mkdir("test01") print("sub dirname:{}".format(sub_dir)) another_file=sub_dir.join("somethng.txt") another_file.write("use tmpdir") read_txt=another_file.read() assert read_txt=="use tmpdir"

运行结果:

rootdir: E:JenkinsLearnMy-pytesttest, configfile: pytest.iniplugins: cov-3.0.0collecting ..、collected 1 itemtest_my_add.py::test_tempdir nodeid:api case/test_my_add.py::test_tempdirdirname:C:UsersAdministratorAppDataLocalTemppytest-of-xxxxpytest-4sub dirname:C:UsersAdministratorAppDataLocalTemppytest-of-xxxxpytest-4test_tempdir0test01PASSED

tmpdir_factory则是一个TempdirFactory对象

def test_tmpdir_factory(tmpdir_factory): base_tmp=tmpdir_factory.getbasetemp() print("base_tmp:{}".format(base_tmp))

运行结果:

plugins: cov-3.0.0collecting ..、collected 1 itemtest_my_add.py::test_tmpdir_factory nodeid:api case/test_my_add.py::test_tmpdir_factorybase_tmp:C:UsersAdministratorAppDataLocalTemppytest-of-xxxpytest-5PASSED

pytestconfig

pytestconfig可以通过命令行参数,选项,配置文件,插件,运行目录等方式控制pytest
它返回一个pytest.config.Config对象 Config的API:https://docs.pytest.org/en/latest/reference/reference.html#config

Config有一个方法getoption,可以获取命令行的参数的值

def test_pytestconfig(pytestconfig): verbose_value=pytestconfig.getoption("verbose") print("value:{}".format(verbose_value))

运行结果:

test_my_add.py::test_pytestconfig nodeid:api case/test_my_add.py::test_pytestconfigvalue:1PASSED

request

request是个特殊的fixture,主要是提供测试方法正在使用的fixture的信息,比如fixture的名字,scope等
https://docs.pytest.org/en/7.0.x/reference/reference.html#request
param属性,request.param可以请求fixture的参数

@pytest.fixture()def my_fixture_two(my_fixture_three,request): print("fixture name:{}".format(request.fixturename)) return "a"def test_request(my_fixture_two): a=my_fixture_two

运行结果:

test_my_add.py::test_request nodeid:api case/test_my_add.py::test_requestfixture name:my_fixture_twoPASSED

Copyright © 2016-2020 www.365daan.com All Rights Reserved. 365答案网 版权所有 备案号:

部分内容来自互联网,版权归原作者所有,如有冒犯请联系我们,我们将在三个工作时内妥善处理。