← Back to list

Effective python note chapter 9

第九章: Testing and Debugging

郭政旻 (Nick Kuo) · 2020-09-12 02:10 · 8 claps · 5.1 min read
#effective-python #python
Open on Medium ↗
Wiki topics: 💻 · Programming

Effective python note chapter 9

第九章: **Testing and Debugging

# Item 75: Debug 時, 使用 repr strings 印出結果

  • 用內建的 print 印出可讀的數值, 但是會隱藏 type 資訊
  • 調用 repr 印出數值的資訊, 這些 repr strings 通常會被傳入 eval function 來拿到原始的資訊
  • 了解 %s, %r 及 F-strings
  • 可以定義 repr finction 在你的 class 中, 客製化想要印出的訊息
class Test():
    def __init__(self):
        pass
    def __repr__(self):
        return "the repr"
    def __str__(self):
        return "the str"
>>> a = Test()
>>> a
the repr
>>> print(a)
the str
============================================================
class BetterClass:
    def __init__(self, x, y):
        self.x = x
        self.y = y
    def __repr__(self):
        // !r 表示顯示對象本體
        return f'BetterClass({self.x!r}, {self.y!r})'
obj = BetterClass(2, 'bar')
print(obj)
>>>
BetterClass(2, 'bar')

# Item 76: 在 TestCase 的 subclasses 中驗證相關的行為

  • 可以繼承 unittest 裡的 TestCase class 來建立自己的測試案例, test method 名稱必是 test 開頭
  • 使用 testcase 定義的 helper methods, 例如 assertEqual, 來確保預期的行為, 不要用內建的 assert statement
  • 考慮 subTest helper method 寫 data driven tests, 來減少 boilerplat

# Item 77: 將 test 的 setUp, tearDown, setUpModule 及 tearDownModule 獨立開來

  • 寫 unit tests 及 integration tests 是很重要的
  • 使用 setUP 及 tearDown methods 確保你的 test 與其他 test 是獨立的環境
  • 在 integration tests 中, 使用 setUPModule 及 tearDownModule 讓你的整個 module 在 lifetime 都擁有一樣的初始值
# integration_test.py
from unittest import TestCase, main
def setUpModule():
    print('* Module setup')
def tearDownModule():
    print('* Module clean-up')
class IntegrationTest(TestCase):
    def setUp(self):
        print('* Test setup')
    def tearDown(self):
        print('* Test clean-up')
    def test_end_to_end1(self):
        print('* Test 1')
    def test_end_to_end2(self):
        print('* Test 2')
if __name__ == '__main__':
    main()

# Item 78: 在有複雜的相依性時, 使用 mocks 來測試程式

  • 使用 unittest.mock module 來模擬真實行為, 當你要測試的環境條件較複雜時, 會是很有幫助得會是很有幫助的
  • 做 mock時, 驗證驗證行為, 程式及獨立的 function 是很重要的, 使用 Mock.assert_called_one_with 來測試 methods
  • Keyword-only arguments 及 unittest.mock.path family of functions 用於注入 mocks 到你的程式中測試

# Item 79: 封裝 dependencies 來加速 mocking 及 testing

  • 當 unittest 需要設置許多重複的模板做 mocks, 有一個解法為把這些依賴的 functions 封裝到 class 中, 可以更容易使用
  • unittest.mock 裡的 Mock class, 回傳新的 mock 當作模擬 classes
  • 在 end-to-end 的測試中, 重構你的程式讓他有更多的 helper function, 可以用在 injecting mock dependencies 測試中, 是有價值的

# Item 80: 考慮使用 pdb 做互動式的 debub

  • 可以用內建的 break-point function 來做互動式的 debugger
  • python debugger prompt 是一個 python shell 可以讓你在執行程式時檢查及修改 python 的狀態
  • Shell command pdb 可以精確的控制程式的執行
  • pdb module 當你的程式有發生 exceptions 時, 可以用於 debug, (using python -m pdb -c continue <program path>) or the interactive Python interpreter (using import pdb; pdb.pm())

# Item 81: 使用 tracemalloc 來明記憶體的使用情況

  • 可以了解 python 程式的 memory leak
  • gc module 可以查看記憶體使用量, 但是缺少較詳細資訊, 而 tracemalloc 有更完整的資訊

有問題或是有錯誤的地方, 歡迎留言與我討論, 謝謝您。

[embed]Previous article: Effective python note chapter 8 第八章: Robustness and Performancemedium.com

[embed]Next article: Effective python note chapter 10 第十章: Collaborationmedium.com


메타데이터
post_id
8e352e5db42e
slug
effective-python-note-chapter-9-8e352e5db42e
url
https://medium.com/@nickest14/effective-python-note-chapter-9-8e352e5db42e
canonical_url
https://medium.com/@nickest14/effective-python-note-chapter-9-8e352e5db42e
author_url
https://medium.com/@nickest14
status
ok
fetched_at
2026-07-15 22:34:01