搞一下pytest(未完成)

自动化测试这一两年尝试过python+selenium界面自动化和python+resquest接口自动化,前者自动化框架用unittest后者用robotframework,因为rf有很好的接口可视化界面可以直观的管理案例,执行后输出的测试报告也不错,所以后面的项目大多采用rf方案。
近期很多公众号和博主推pytest,说它更直观,上手更快。
一、pytest测试case编写规则
  • 测试类以Test开头;
  • 测试文件以test_开头或_test结尾;
  • 测试函数以test_开头
  • pytest在运行时会运行所有test _ *。py或* _test.py的文件
以 “quiet” reporting 模式执行测试,执行命令:
pytest -q test_sysexit.py
以类来管理,pytest遵照  Conventions for Python test discovery规则发现所有测试的函数(test_开头),所以必须将class的开头加上前缀Test,否则执行的时候会被跳过。
pytest可以通过内置的f ixtures / function参数来请求资源,因此可以
# content of test_tmpdir.py
def test_needsfiles(tmpdir):
    print(tmpdir)
    assert 0
$ pytest -q test_tmpdir.py
来请求唯一临时目录进行测试执行操作
二、assert断言
1.断言一般是:assert left op right
例如 assert 1 == 2
支持调用函数,属性,比较以及二进制和一元运算符
2.pytest.raises(ExpectedException, func, *args, **kwargs)
引发异常的断言通过raises方法+上下文管理器
def test_recursion_depth():
    with pytest.raises(RuntimeError) as excinfo:
        def f():
            f()

        f()
    assert "maximum recursion" in str(excinfo.value)
可以访问excinfo的 .type,.value和.traceback查看具体的报错信息。
3.pytest_assertrepr_compare(config,op,left,right )
定义断言报错信息,传入参数为断言的操作符(==,!=,<,>之类的)、断言左边的值,断言右边的值。
例子:
from test_foocompare import Foo

def pytest_assertrepr_compare(op, left, right):
    if isinstance(left, Foo) and isinstance(right, Foo) and op == "==":
        return [
            "Comparing Foo instances:",
            "   vals: {} != {}".format(left.val, right.val),
        ]
现在,鉴于此测试模块:
# content of test_foocompare.py
class Foo:
    def __init__(self, val):
        self.val = val

    def __eq__(self, other):
        return self.val == other.val

def test_compare():
    f1 = Foo(1)
    f2 = Foo(2)
    assert f1 == f2
 
三、调用和退出代码
调用命令:
python -m pytest [...]
六种退出代码:
Exit code 0:
All tests were collected and passed successfully
所有测试均已收集并成功通过
Exit code 1:
Tests were collected and run but some of the tests failed
测试已收集并运行,但有些测试失败
Exit code 2:
Test execution was interrupted by the user
测试执行被用户中断
Exit code 3:
Internal error happened while executing tests
执行测试时发生内部错误
Exit code 4:
pytest command line usage error
pytest命令行用法错误
Exit code 5:
No tests were collected
没有收集测试
一次失败后跳出:
pytest -x
n次失败之后跳出(eg.两次):
pytest --maxfail=2
测试方式:
1.按模块
pytest test_model.py
2.按目录
pytest /test
3.按关键字(不区分大小写)
pytest -k "keyword"
4.按节点ID
pytest test_mod.py::TestClass::test_method
5.按标记
例如:pytest -m -example
将运行@pytest.mark.example装饰器的所有测试案例
6.从包运行
pytest --pyargs pkg.testing
这将导入pkg.testing并使用其文件系统位置来查找并运行测试。(没接触过,暂时不太理解着点)
 
规定报告内容的参数:
  • r - short test summary info,get  failures, skips, xfails, etc.
  • a - all except passes
  • f - failed
  • E - error
  • s - skipped
  • x - xfailed
  • X - xpassed
  • p - passed
  • P - passed with output
  • a - all except pP
  • A - all
  • N - none, this can be used to display nothing (since fE is the default)
 

猜你喜欢

转载自www.cnblogs.com/fine-6/p/12625454.html