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 pytest
def test_case():
expected = "Hello"
actual = "hello"
assert expected == actual
if __name__ == '__main__':
pytest.main()
B.unittest
import unittest
class 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_that
def 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')
本文介绍了Python中assert的基本用法,包括简单的断言及自定义错误描述,并探讨了Python测试框架如pytest、unittest和nose中内置的断言能力。此外,还提及了一个名为assertpy的扩展库。
6364

被折叠的 条评论
为什么被折叠?



