python assert简述

来源:互联网 发布:看图王软件下载 编辑:程序博客网 时间:2024/05/22 08:24

assert断言

1.基本用法

>>> assert 1 + 1 == 2>>> assert isinstance('Hello', str)>>> assert isinstance('Hello', int)

执行结果:

Traceback (most recent call last):  File "<input>", line 1, in <module>AssertionError

只是简单说明了assert报错

2.升级+1用法:

对断言的错误简单的自定义描述

>>> s = "nothin is impossible.">>> key = "nothing">>> assert key in s, "Key: '{}' is not in Target: '{}'".format(key, s)

执行结果

Traceback (most recent call last):  File "<input>", line 1, in <module>AssertionError: Key: 'nothing' is not in Target: 'nothin is impossible.'

3.python 测试框架自带断言能力

A.pytest

import pytestdef test_case():    expected = "Hello"    actual = "hello"    assert expected == actualif __name__ == '__main__':    pytest.main()

B.unittest

import unittestclass TestStringMethods(unittest.TestCase):    def test_upper(self):        self.assertEqual('foo'.upper(), 'FoO')if __name__ == '__main__':    unittest.main()

C.ptest

from ptest.decorator import *from ptest.assertion import *@TestClass()class TestCases:    @Test()    def test1(self):        actual = 'foo'        expected = 'bar'        assert_that(expected).is_equal_to(actual)

拓展:

assertpy库下载位置

from assertpy import assert_thatdef test_something():    assert_that(1 + 2).is_equal_to(3)    assert_that('foobar')\        .is_length(6)\        .starts_with('foo')\        .ends_with('bar')    assert_that(['a', 'b', 'c'])\        .contains('a')\        .does_not_contain('x')
原创粉丝点击