初始Pytest

使用Python做自动化需要考虑怎么做断言,怎么管理你的自动化案例。
最最常见的是使用Python的unittest模块,建立Testcase实例就可以涵盖测试前准备环境的搭建(setUp),执行测试代码 (run),以及测试后环境的还原(tearDown),unittest模块包含了assert方法,使用类似assertEqual(a, b)可以对测试结果检查进行判断。
许多公司目前还是使用RobotFramework进行自动化建设,RF衍生的一些Library底层的和直接用python+unittest原理一样,可视化的节目让代码更具有可读性,可以使用中文命名封装,让后续维护减少很多成本,更可喜的是RF有非常漂亮的report,不需要另外找输出报告的模块处理这件事。
相比前面两种方法,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可以通过内置的fixtures / 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)
 
posted @ 2020-04-03 11:34  小菲同学  阅读(168)  评论(0编辑  收藏  举报