美文网首页
pytest-常用断言

pytest-常用断言

作者: Chaweys | 来源:发表于2021-05-31 23:09 被阅读0次

    pytest-断言assert
    与unittest不同,pytest使用的是python自带的assert关键字来进行断言
    assert关键字后面可以接一个表达式,只要表达式的最终结果为True,那么断言通过,用例执行成功,否则用例执行失败.
    
    
    举例:
    可以再断言之后逗号分隔,输出有效提示信息
    
    #coding=utf-8
    
    def func():
        return 3
    
    class TestAssert:
        def test_start(self):
            a = func()
            assert a % 2 ==0, "判断 a 是否为偶数,当前 a 的值为:{0}".format(a)
    
    CMD运行结果:
    E:\ProjectStudy\Pytest框架>pytest -s test_assert.py
    ================================================= test session starts =================================================
    platform win32 -- Python 3.8.0, pytest-6.2.2, py-1.10.0, pluggy-0.13.1
    rootdir: E:\ProjectStudy\Pytest框架
    plugins: forked-1.3.0, parallel-0.0.10, xdist-2.2.1
    collected 1 item
    
    test_assert.py F
    
    ====================================================== FAILURES =======================================================
    ________________________________________________ TestAssert.test_start ________________________________________________
    
    self = <Pytest框架.test_assert.TestAssert object at 0x00000274F4A3ED00>
    
        def test_start(self):
            a = func()
    >       assert a % 2 ==0, "判断 a 是否为偶数,当前 a 的值为:{0}".format(a)
    E       AssertionError: 判断 a 是否为偶数,当前 a 的值为:3
    E       assert (3 % 2) == 0
    
    test_assert.py:9: AssertionError
    =============================================== short test summary info ===============================================
    FAILED test_assert.py::TestAssert::test_start - AssertionError: 判断 a 是否为偶数,当前 a 的值为:3
    
    
    
    常用断言:
    assert xx      判断 xx 为真
    assert not xx  判断 xx 不为真
    assert a in b  判断 b 包含 a
    assert a == b  判断 a 等于 b
    assert a != b  判断 a 不等于 b
    
    
    对可能会可能不会出现异常的测试用例断言,使用断言装饰器@pytest.mark.xfail(raises=ZeroDivisionError)
    class TestAssert:
        def test_start(self):
            a = func()
            assert a % 2 ==0, "判断 a 是否为偶数,当前 a 的值为:{0}".format(a)
    
        @pytest.mark.xfail(raises=ZeroDivisionError)
        def test_two(self):
            1/0
    

    相关文章

      网友评论

          本文标题:pytest-常用断言

          本文链接:https://www.haomeiwen.com/subject/pplzjltx.html