本文介绍了 Max Lai 使用 pytest 进行单元测试的经验,强调了编写测试的重要性以确保代码的正确性和可维护性。文章详细讲解了pytest的安装步骤、基本用法以及单元测试的最佳实践,包括如何创建测试文件、验证结果,并探讨了mock和fixture的使用场景。最终,文章还提到了一些pytest插件和代码覆盖率工具,以帮助提升测试质量和效果。
pytest test 命名規則
•Test file name:
recognizes test_*.py or *_test.py as the test files.
• Test function name:
requires the test method names to start with “test”.
何謂單元測試
Wikipedia 的定義
• Unittests are typically automated tests written and run by
software developers
• to ensure that a section of an application (known as the “unit”)
• meets its design and behaves as intended.
• In procedural programming, a unit could be an entire module,
but it is more commonly an individual function or procedure.
source: https://en.wikipedia.org/wiki/Unit_testing
1st SUT 出口驗證
•進入點(entry point): sum(a,b)
• 出口點(exit point): return value
SUT
sum(a, b)
return value
• SUT: Sytem Under Test, 被測試系統
• 有些人會稱為 CUT (Class Under Test or Code Under Test)
$ pytest -v--setup-show test_fixtures.py
test_fixtures.py::test_some_data
SETUP F some_data
test_fixtures.py::test_some_data (fixtures used: some_data)PASSED
TEARDOWN F some_data
test_fixtures.py::test_inc_data
SETUP F some_data
test_fixtures.py::test_inc_data (fixtures used: some_data)PASSED
TEARDOWN F some_data
================================ 3 passed in 0.07s =============================
Fixture 的 SETUP & TEARDOWN
47.
fixture — yield
•The code before the yield runs before each test;
• The code after the yield runs after the test.
$ pytest -v -s test_yield.py
test_yield.py::test Pre condition
Body of test
PASSEDPost condition
#1
#2
#3
系統時間無法簡單地使用 mock object
EAttributeError: <module 'datetime' from
'/Users/maxlai/miniconda3/envs/pytestlab/lib/python3.8/datetime.py’>
does not have the attribute 'now'