Skip to Content
Python实用技能学习指南
book

Python实用技能学习指南

by Posts & Telecom Press, Robert Smallshire, Austin Bingham
February 2024
Intermediate to advanced
316 pages
3h 47m
Chinese
Packt Publishing
Content preview from Python实用技能学习指南

第10章 使用Python库进行单元测试

当构建更复杂的程序的时候,代码中很容易出现各种各样的缺陷。缺陷可能出现在最初编写的代码中;当我们对代码进行修改时,可能也会引入缺陷。为了可以有效处理缺陷并保持高质量的代码,一组可以运行的测试是非常有用的,这些测试可以告诉你代码是否按照预期正常工作。

为了进行这样的测试,Python标准库包含了unittest模块。

不管它的名字暗示什么,这个模块不仅仅有助于单元测试。事实上,它是一个灵活的可用于各种自动化测试的框架,从验收测试到集成测试再到单元测试都可用它。与其他语言的测试框架一样,它的主要功能是帮助你进行自动化可重复的测试。通过这样的测试,你可以随时很容易并且很轻松地验证代码是否正常工作。

unittest模块围绕着几个关键概念构建,其核心概念就是测试用例(test case)。测试用例(包含在unittest.TestCase类中)是将一组相关的测试方法组合在一起,它是unittest框架中测试组织的基本单元。稍后我们会看到,单独的测试方法在unittest.TestCase子类中以方法的形式实现。

下一个重要的概念是固件(fixture)。固件是在每个测试方法之前和/或之后运行的代码片段。固件有两个主要目的:

  • 装配(set-up)固件确保在测试运行之前测试环境处于预期状态;
  • 拆卸(tear-down)固件在测试运行后清理环境,通常是释放资源。

例如,装配固件可能会在运行测试之前在数据库中创建一个特定的条目。同样,拆卸固件可能会删除测试创建的数据库条目。固件不是测试所必需的,但它们非常普遍,而且它们对于测试的可重复性是非常重要的。

最后的关键概念是断言(assertion)。断言是测试方法内部的特定检查,最终确定测试是通过还是失败。除了这些功能外,断言可以: ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.

Read now

Unlock full access

More than 5,000 organizations count on O’Reilly

AirBnbBlueOriginElectronic ArtsHomeDepotNasdaqRakutenTata Consultancy Services

QuotationMarkO’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
Julian F.
Head of Cybersecurity
QuotationMarkI wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
Addison B.
Field Engineer
QuotationMarkI’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
Amir M.
Data Platform Tech Lead
QuotationMarkI'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.
Mark W.
Embedded Software Engineer

You might also like

人工智能技术与大数据

人工智能技术与大数据

Posts & Telecom Press, Anand Deshpande, Manish Kumar
Kafka权威指南(第2版)

Kafka权威指南(第2版)

Gwen Shapira, Todd Palino, Rajini Sivaram, Krit Petty

Publisher Resources

ISBN: 9781835889626