要使用python内置的fixture,首先得明确fixture返回的数据类型
fixture参考官网 https://docs.pytest.org/en/7.0.x/reference/reference.html#tmpdir-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.ini plugins: cov-3.0.0 collecting ... collected 1 item test_my_add.py::test_tempdir nodeid:api case/test_my_add.py::test_tempdir dirname:C:UsersAdministratorAppDataLocalTemppytest-of-xxxxpytest-4 sub dirname:C:UsersAdministratorAppDataLocalTemppytest-of-xxxxpytest-4test_tempdir0test01 PASSED
tmpdir_factory则是一个TempdirFactory对象
def test_tmpdir_factory(tmpdir_factory):
base_tmp=tmpdir_factory.getbasetemp()
print("base_tmp:{}".format(base_tmp))
运行结果:
plugins: cov-3.0.0 collecting ... collected 1 item test_my_add.py::test_tmpdir_factory nodeid:api case/test_my_add.py::test_tmpdir_factory base_tmp:C:UsersAdministratorAppDataLocalTemppytest-of-xxxpytest-5 PASSEDpytestconfig
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_pytestconfig value:1 PASSEDrequest
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_request fixture name:my_fixture_two PASSED



