Posted on:
Last modified:
Python 常用的测试工具有三种:
其中 unittest 完全是从 JUnit 移植过来的,用起来稍微有些别扭。nose 和 pytest 相比,网上 大多推荐 pytest。详细的比较可以见参考文档。
和传统 unittest 中复杂的 assertEqual 等语句不同的是,pytest 中只需要简单地写 assert
语句就可以了。
pytest some_mod.py 运行某个文件中的中的测试pytest tests/ 运行某个目录中的测试pytest -x 在第一个错误的地方结束pytest --pdb,当出现异常的时候,打开 pdb
测试函数使用 test_开头,pytest 默认会查找当前目录中的 test_ 开头或者 _test 结尾的文件
中的测试并运行。使用 assert 来验证语句。
import pytest
def f():
raise SystemExit(1)
def test_mytest():
with pytest.raises(SystemExit):
f()如果在一个文件中定义了多个测试函数,那么 pytest 将按照函数定义的顺序执行。
setup 和 teardown 用来在测试开始前加载资源,并在测试结束后卸载资源。
setup_module 和 teardown_module 中setup_class 和 teardown_class 中定义加载和卸载方法。太复杂了,还没仔细研究。
如果真的是一个无限循环,那么是没法测试的,不过:
其中的第一个是比较好做的,对代码的侵入性也最小。具体可以这样做:
class Foo(object):
RUNNING = 1 # sentinel value
def start(self):
while self.RUNNING:
do_something_useful()然后在测试中:
foo = Foo()
type(foo).RUNNING = PropertyMock(side_effect=[1, 0])安装 pytest-asyncio 插件,然后在 pyproject.toml 中增加:
[tool.pytest.ini_options]
pythonpath = [ "." ]
asyncio_mode = "auto"找不到当前路径下的包也解决了。
unittest 这个库没有按照 PEP8 来,看着就不爽
import unittest
def fun(x):
return x + 1
class MyTest(unittest.TestCase):
def setUp(self):
# bootstrapping
def tearDown(self):
#clean up
def test(self):
self.assertEqual(fun(3), 4)Unittest 中的 assert 方法:
| 方法 | 含义 |
|---|---|
| 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) |
python -m unittest fun_testNote: only method starts with test is run by unittest module
"""
>>> print 'hello'
hello
"""
doctest.testmod()doctest.testmod(verbose=True) or python module.py -v
Notes on testing classes
需要转义 \n
需要使用<BLANKLINE>来代表空行
© 2016-2022 Yifei Kong. Powered by ynotes
All contents are under the CC-BY-NC-SA license, if not otherwise specified.
Opinions expressed here are solely my own and do not express the views or opinions of my employer.
友情链接: MySQL 教程站