---
author: deng
date: "20250122"
category: Note
tags:
  - Python
  - UnitTest
  - Pytest
  - Note
---

![cover](resources/test_your_code.png)

- Abstract
	- [Pytest](https://docs.pytest.org/en/stable/) is a popular testing framework for Python known for its simplicity. It breaks away from the class-based structure, offering a more flexible and intuitive approach. (Yep. More Pythonic than [unittest](https://docs.python.org/3/library/unittest.html)!)
- Resources
	- 心法
		- [為什麼你應該寫單元測試——《Python 工匠》筆記 ](https://blog.kyomind.tw/python-craftsman-02/) - Code and Me
	- 入門
		- [Python 測試入門 - 開始使用 PyTest](https://blog.tzing.tw/posts/python-testing-pytest-08de903a) - 拾遺
		- [# Python 測試入門 - PyTest Fixture](https://blog.tzing.tw/posts/python-testing-pytest-fixture-91b547f2) - 拾遺
		- [7 個實用的 pytest plugins](https://myapollo.com.tw/blog/7-useful-pytest-plugins/) - MyApollo
		- [Pytest 101 - 給 Python 開發者的測試入門 (3) - 圖解 Mock & 測試框架語法整理](https://minglunwu.com/notes/2023/pytest_101_3.html/) - Byte and Ink
		- [How To Test Python Exception Handling Using Pytest Assert (A Simple Guide)](https://pytest-with-eric.com/introduction/pytest-assert-exception/) - Pytest with Eric
	- 更上一層樓
		- [13 Proven Ways To Improve Test Runtime With Pytest](https://pytest-with-eric.com/pytest-advanced/pytest-improve-runtime/) - Pytest with Eric
			- 對於進階者相當推薦Eric的[部落格](https://pytest-with-eric.com/)，有相當多的情境可以參考
- Note
	- 雖個人不追求100%測試覆蓋率，但我在寫測試時都會裝上[Pytest-cov](https://pytest-cov.readthedocs.io/en/latest/readme.html)插件以掌握專案當下覆蓋率的情況
		- 透過``--cov``引數調用，例如``pytest --cov=./src ./tests``
	- 專案越肥大通常測試會花上更多時間，搭配[Pytest-xdist](https://pytest-xdist.readthedocs.io/en/stable/distribution.html)插件可簡單地將測試平行化以節省寶貴時間
		- 透過``-n``引數調用，例如``pytest -n auto``
		- 若測試物件之間有依賴性，可使用xdist_group_mark將物件分群，同群的物件將會在同一行程內執行
		- 平行化通常伴隨更多資源的消耗，使用時需小心～
	- 善用[Fixture](https://docs.pytest.org/en/stable/explanation/fixtures.html#sharing-test-data)將某些資料共享或暫存給其他測試使用，進一步節省測試時間
	- Pytest也支援[pyproject.toml](https://docs.pytest.org/en/stable/reference/customize.html#pyproject-toml)進行配置哦