- pytest 中应用 assert 进行断言,和 unittest 是有区别的,后边具体列举;
- pytest 中的 assert 后能够为表达式,为 True 示意用例通过。
- 咱们写一个 class,代码中就能够看到所有的断言:
- 罕用断言:
办法 |
查看 |
assertEqual(a, b) |
a ==b |
assertNotEqual(a, b) |
a !=b |
assertTrue(x) |
bool(x) is True |
assertFalse(x) |
Bool(x) is False |
assertIs(a, b) |
a is b |
assertIsNot(a, b) |
a is not b |
assertIsNone(x) |
x is None |
assertIsNotNone(x) |
x is not None |
assertIn(a, b) |
a in b |
assertNotIn(a, b) |
a not in b |
assertIsInstance(a, b) |
isinstance(a,b) |
assertNotIsInstance(a, b) |
not isinstance(a,b) |
# -*- coding:utf-8 -*-
# 作者:NoamaNelson
# 日期:2021/11/26
# 文件名称:test_unint.py
# 作用:unittest 断言
# 分割:VX(NoamaNelson)
# 博客:https://blog.csdn.net/NoamaNelson
import unittest
class TestU(unittest.TestCase):
def setUp(self) -> None:
self.a = 3
self.b = 4
self.c = 3
self.d = 0
def tearDown(self) -> None:
pass
def test_o(self):
self.assertTrue(self.c, msg="后果为 False")
def test_t(self):
self.assertEqual(self.a, self.c, msg="a 和 c 不相等")
if __name__ == "__main__":
unittest.main()
断言 |
阐明 |
assert a |
判断 a 为真 |
assert not a |
判断 a 不为真 |
assert a in b |
判断 b 蕴含 a |
assert a == b |
判断 a 等于 b |
assert a != b |
判断 a 不等于 b |
# -*- coding:utf-8 -*-
# 作者:NoamaNelson
# 日期:2021/11/26
# 文件名称:test_assert.py
# 作用:assert 断言
# 分割:VX(NoamaNelson)
# 博客:https://blog.csdn.net/NoamaNelson
import pytest
class TestU():
def test_f(self):
a = 3
b = 4
s = a + b
return s
def test_func(self):
assert self.test_f() == 7, "计算结果不是 7"
if __name__ == "__main__":
pytest.main()
(venv) F:\pytest_study\test_case\test_d>pytest test_assert.py
============================================ test session starts =============================================
platform win32 -- Python 3.7.0, pytest-6.2.4, py-1.10.0, pluggy-0.13.1
rootdir: F:\pytest_study\test_case\test_d
plugins: allure-pytest-2.8.12, cov-2.8.1, forked-1.1.3, html-2.0.1, metadata-1.8.0, ordering-0.6, xdist-1.31.0
collected 2 items
test_assert.py .. [100%]
============================================= 2 passed in 0.31s ==============================================
- 能够应用 pytest.raises 作为上下文管理器,当抛出异样时能够获取到对应的异样实例;
- 目标是断言抛出的异样是不是预期想要的;
- 比方如下,断言
1 / 0
的异样是不是 ZeroDivisionError
,其中ZeroDivisionError
是异样类型,用 type
从异样信息中获取;division by zero
是异样的值,应用 value
从异样信息中获取。
def test_a(self):
with pytest.raises(ZeroDivisionError) as e:
1 / 0
assert e.type == ZeroDivisionError
assert "division by zero" in str(e.value)