栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

pytest--内置fixture

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

pytest--内置fixture

要使用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.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
PASSED
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_pytestconfig
value:1
PASSED
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_request
fixture name:my_fixture_two
PASSED
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/741212.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号