zoukankan      html  css  js  c++  java
  • 内置fixture---tmpdir和tmpdir_factory

    tmpdir和tmpdir_factory

    内置的tmpdirtmpdir_factory负责在测试开始运行前创建临时文件或目录,并在测试结束后删除。单个测试使用tmpdir,多个测试使用tmpdir_factory
    tmpdir的作用范围是函数级别,tmpdir_factory的是会话级别 ,如果需要其他级别的,需要创建一个新的fixture。

    def test_tmpdir(tmpdir):
        a_file=tmpdir.join("a.txt")
        b_dir=tmpdir.mkdir("something")
        b_file=b_dir.join("b.txt") 
        a_file.write("aaa")
        b_file.write("bbb")
        assert a_file.read()=="aaa"  and b_file.read()=="bbb"
    

    pytestconfig

    内置的pytestconfig可以通过命令行参数,选项,配置文件,插件,运行目录等方式来控制pytest。它是request.config的快捷方式,被称为“pytest配置对象”

    def pytest_addoption(parser):  #pytest的hook函数pytest_addoption,可添加命令行选项
        parser.addoption("--myopt",action="store_true",help="some my option")
        parser.addoption("--foo",action="store",default="bar",help="foo:bar or baz")
    
    def test_option(pytestconfig):
        print(pytestconfig.gettoption('myopt'))
        print(pytestconfig.gettoption('foo'))
        print(pytestconfig.option.foo)
    # 一些例子
    def test_pytestconfig(pytestconfig):
        print(pytestconfig.args)
        print(pytestconfig.inifile)
        print(pytestconfig.invocation_dir)
        print(pytestconfig.rootdir)
        print(pytestconfig.getoption('showlocals'))
    

    使用cache

    cache用于测试会话传递给下一段会话
    --last-failed(仅运行上次未通过的)和--failed-first (之前未通过的首先运行)很好的展示cache的功能,看看cache是如何存储这些标识数据的。
    --cache-show可以显示cache存储的信息
    --clear-cache 运行前清空cache缓存

    def test_cache(cache):
        cache.get(key,default)
        cache.set(key,value)
    

    使用capsys

    允许使用代码读取stdout和stderr,capsys.redouterr() 也可以临时禁止抓取日志输出capsys.redouterr()
    pytest通常会抓取输出,仅当全部用例结束后,抓取到的日志才会显示出来。--s参数可以关闭这个功能,在测试运行期就把输出直接发送到stdout,但有时可能只需要部分信息,则可以用 capsys.disabled()临时让输出绕过默认的输出捕获机制
    capsys.redouterr()

    def test_disabled(capsys):
        with.capsys.disabled():
            print("aaaa")
        print("bbb")  # pytest -q 和 pytest -q -s的区别
    

    monkeypatch

    在运行期间对类或模块进行动态修改。常用于替换被测试代码的部分运行环境,或将输入依赖或输出依赖替换成更容易测试的对象或函数。测试结束后,无论结果是通过还是失败,代码都会复原(所有修改都会撤销)
    例如:修改环境变量monkey.setenv('HOME',tmpdir.mkdir('home'))

    努力努力努力
  • 相关阅读:
    二维数组的最大联通子数组
    四则运算网页终结版
    Python+Selenium进阶版(四)-封装一个自己的类-浏览器引擎类
    Python+Selenium进阶版(三)- 二次封装Selenium中几个方法
    Python+Selenium进阶版(二)- Python中类/函数/模块的简单介绍
    Python+Selenium进阶版 (一)- Python IDE工具-PyCharm的安装和使用
    Python+Selenium学习-Xpat增强梳理版
    Python+Selenium练习(三十一)- 截图并保存
    Python+Selenium练习(三十)- 获取页面元素的href属性
    Python+Selenium练习(二十九)- 获取当前页面全部图片信息
  • 原文地址:https://www.cnblogs.com/wwtest/p/14132242.html
Copyright © 2011-2022 走看看