We're sunsetting PodQuest on 2025-07-28. Thank you for your support!
Export Podcast Subscriptions
cover of episode Mocking in Python with unittest.mock  -  Michael Foord

Mocking in Python with unittest.mock - Michael Foord

2025/2/7
logo of podcast Test & Code

Test & Code

AI Deep Dive AI Chapters Transcript
People
B
Brian Okken
Topics
Brian Okken: 我对 Michael Foord 的生平和贡献进行了介绍,他是一位 Python 核心开发者,对 Python 社区做出了巨大贡献,尤其是在单元测试方面。他创建了 unittest.mock 库,并对 Python 的测试工具的构建做出了重要贡献。 Michael Foord: 我目前从事 Python 培训和承包工作,之前在 Red Hat 工作过,参与 Ansible Tower 的测试自动化。我参与过英国原子能机构的项目,为核聚变反应堆设计软件。我编写了 unittest.mock 库,它源于我在 Resolver Systems 的工作经历,并受到测试驱动开发的影响。我严格遵循测试驱动开发,测试与代码比例至少为 3:1,但过度的单元测试会带来问题。单元测试应该测试行为单元,而不是实现单元;应该通过公共 API 进行测试。mock 的使用存在误解,Martin Fowler 对 mock 的定义过于严格。patch 和 mock 的结合使得测试难以测试的代码成为可能,但这可能会导致编写易于测试的代码的动力不足。patch 的强大之处在于它能够自动恢复被修改的状态。mock 对象可以伪装成任何其他对象。我更倾向于 AAA(Arrange, Act, Assert)风格的模拟,先设置,再执行,最后断言。模拟的经典用途是模拟外部依赖项,以在单元测试中返回确定性结果。unittest.mock 库最初是为了替换 Resolver Systems 代码库中大量的模拟对象而创建的,后来又增加了 API 限制功能。每次使用 patch 都是一种失败的承认,应该尽量减少 mock 和 patch 的使用。mock 应该作为最后手段,应该努力设计易于测试的系统。清晰的层次设计有助于减少对 mock 的依赖。测试策略会影响设计,应该尽量将副作用放入单独的函数中,以便更容易测试。在 Python 测试培训中,mock 只是其中一部分内容,我更推荐使用 Pytest 而不是 unittest。我通常直接使用 unittest.mock,而不是 Pytest 的 mock 插件。Pytest 的 fixture 机制虽然强大,但过度使用会造成“fixture hell”。任何框架或策略都不能阻止编写糟糕的代码。unittest 的缺点在于样板代码过多,以及缺乏 Pytest 的 fixture 机制等特性。我写了一篇关于软件开发和测试最佳实践的文章,可以在 opensource.com 上找到。

Deep Dive

Chapters
This episode is a tribute to Michael Foord, a key figure in the Python community and creator of the unittest.mock library. The interview, originally recorded in 2021, covers his career, contributions to Python testing, and his philosophy on mocking.
  • Episode is a replay of a 2021 interview with Michael Foord.
  • Michael Foord was a pivotal figure in the Python community.
  • He created the mock library (now unittest.mock).

Shownotes Transcript

This episode is a replay of a 2021 interview I did with Michael Foord.We lost Michael in January, and I'd like to revisit this interview as a tribute. 

Michael Foord was a pivotal figure in the Python community and the creator of the mock library that's now unittest.mock. But he did so much more as well. His contributions continue to resonate within the developer community. This interview is just a small peek at his influence. 

In this episode

  • Introduction to Michael Foord
  • The Mock Library Origins
  • Mocking and Testing Philosophy
  • Career Path and Consulting
  • Understanding Mocking
  • The Power of Patch
  • Testing Strategies and Design
  • Mocking External Dependencies
  • Teaching Testing and Mocking

python.org has put up an "In memoriam" page for Michael Foord), and many people have shared stories and memories.

Links: