<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>unittest &#8211; 李辉 / Grey Li</title>
	<atom:link href="https://greyli.com/tag/unittest/feed/" rel="self" type="application/rss+xml" />
	<link>https://greyli.com</link>
	<description>一个编程和写作爱好者的在线记事本</description>
	<lastBuildDate>Thu, 06 Nov 2025 11:36:11 +0000</lastBuildDate>
	<language>zh-CN</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>https://wordpress.org/?v=4.9.26</generator>

<image>
	<url>https://greyli.com/wp-content/uploads/2025/03/avatar-500-compressed-144x144.jpg</url>
	<title>unittest &#8211; 李辉 / Grey Li</title>
	<link>https://greyli.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>《Flask 入门教程》第 9 章：测试</title>
		<link>https://greyli.com/flask-tutorial-chapter-9-test/</link>
		<comments>https://greyli.com/flask-tutorial-chapter-9-test/#respond</comments>
		<pubDate>Wed, 23 Jan 2019 04:04:20 +0000</pubDate>
		<dc:creator><![CDATA[李辉]]></dc:creator>
				<category><![CDATA[计算机与编程]]></category>
		<category><![CDATA[coverage.py]]></category>
		<category><![CDATA[Flask]]></category>
		<category><![CDATA[Flask 入门教程]]></category>
		<category><![CDATA[unittest]]></category>
		<category><![CDATA[单元测试]]></category>

		<guid isPermaLink="false">http://greyli.com/?p=2215</guid>
		<description><![CDATA[在此之前，每次为程序添加了新功能，我们都要手动在浏览器里访问程序进行测试。除了测试新添加的功能，你还要确保旧的 [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>
	在此之前，每次为程序添加了新功能，我们都要手动在浏览器里访问程序进行测试。除了测试新添加的功能，你还要确保旧的功能依然正常工作。在功能复杂的大型程序里，如果每次修改代码或添加新功能后手动测试所有功能，那会产生很大的工作量。另一方面，手动测试并不可靠，重复进行测试操作也很枯燥。
</p>
<p>
	基于这些原因，为程序编写自动化测试就变得非常重要。
</p>
<p>
	<strong>注意</strong>&nbsp;为了便于介绍，本书统一在这里介绍关于测试的内容。在实际的项目开发中，你应该在开发每一个功能后立刻编写相应的测试，确保测试通过后再开发下一个功能。
</p>
<h2>
	单元测试<br />
</h2>
<p>
	单元测试指对程序中的函数等独立单元编写的测试，它是自动化测试最主要的形式。这一章我们将会使用 Python 标准库中的测试框架 unittest 来编写单元测试，首先通过一个简单的例子来了解一些基本概念。假设我们编写了下面这个函数：
</p>
<pre>
def sayhello(to=None):
    if to:
        return &#39;Hello, %s!&#39; % to
    return &#39;Hello!&#39;</pre>
<p>
	下面是我们为这个函数编写的单元测试：
</p>
<pre>
import unittest

from module_foo import sayhello


class SayHelloTestCase(unittest.TestCase):  # 测试用例

    def setUp(self):  # 测试固件
        pass

    def tearDown(self):  # 测试固件
        pass

    def test_sayhello(self):  # 第 1 个测试
        rv = sayhello()
        self.assertEqual(rv, &#39;Hello!&#39;)
       
    def test_sayhello_to_somebody(self)  # 第 2 个测试
        rv = sayhello(to=&#39;Grey&#39;)
		self.assertEqual(rv, &#39;Hello, Grey!&#39;)


if __name__ == &#39;__main__&#39;:
    unittest.main()</pre>
<p>
	测试用例继承&nbsp;<code>unittest.TestCase</code>&nbsp;类，在这个类中创建的以&nbsp;<code>test_</code>&nbsp;开头的方法将会被视为测试方法。
</p>
<p>
	内容为空的两个方法很特殊，它们是测试固件，用来执行一些特殊操作。比如&nbsp;<code>setUp()</code>&nbsp;方法会在每个测试方法执行前被调用，而&nbsp;<code>tearDown()</code>&nbsp;方法则会在每一个测试方法执行后被调用（注意这两个方法名称的大小写）。
</p>
<p>
	如果把执行测试方法比作战斗，那么准备弹药、规划战术的工作就要在&nbsp;<code>setUp()</code>&nbsp;方法里完成，而打扫战场则要在&nbsp;<code>tearDown()</code>方法里完成。
</p>
<p>
	每一个测试方法（名称以&nbsp;<code>test_</code>&nbsp;开头的方法）对应一个要测试的函数 / 功能 / 使用场景。在上面我们创建了两个测试方法，<code>test_sayhello()</code>&nbsp;方法测试&nbsp;<code>sayhello()</code>&nbsp;函数，<code>test_sayhello_to_somebody()</code>&nbsp;方法测试传入参数时的&nbsp;<code>sayhello()</code>&nbsp;函数。
</p>
<p>
	在测试方法里，我们使用断言方法来判断程序功能是否正常。以第一个测试方法为例，我们先把&nbsp;<code>sayhello()</code>&nbsp;函数调用的返回值保存为&nbsp;<code>rv</code>&nbsp;变量（return value），然后使用&nbsp;<code>self.assertEqual(rv, &#39;Hello!&#39;)</code>&nbsp;来判断返回值内容是否符合预期。如果断言方法出错，就表示该测试方法未通过。
</p>
<p>
	下面是一些常用的断言方法：
</p>
<ul>
<li>
		assertEqual(a, b)
	</li>
<li>
		assertNotEqual(a, b)
	</li>
<li>
		assertTrue(x)
	</li>
<li>
		assertFalse(x)
	</li>
<li>
		assertIs(a, b)
	</li>
<li>
		assertIsNot(a, b)
	</li>
<li>
		assertIsNone(x)
	</li>
<li>
		assertIsNotNone(x)
	</li>
<li>
		assertIn(a, b)
	</li>
<li>
		assertNotIn(a, b)
	</li>
</ul>
<p>
	这些方法的作用从方法名称上基本可以得知。
</p>
<p>
	假设我们把上面的测试代码保存到 test_sayhello.py 文件中，通过执行&nbsp;<code>python test_sayhello.py</code>&nbsp;命令即可执行所有测试，并输出测试的结果、通过情况、总耗时等信息。
</p>
<h2>
	测试 Flask 程序<br />
</h2>
<p>
	回到我们的程序，我们在项目根目录创建一个 test_watchlist.py 脚本来存储测试代码，我们先编写测试固件和两个简单的基础测试：
</p>
<p>
	<em>test_watchlist.py：测试固件</em>
</p>
<pre>
import unittest

from app import app, db, Movie, User


class WatchlistTestCase(unittest.TestCase):

    def setUp(self):
        # 更新配置
        app.config.update(
            TESTING=True,
            SQLALCHEMY_DATABASE_URI=&#39;sqlite:///:memory:&#39;
        )
        # 创建数据库和表
        db.create_all()
        # 创建测试数据，一个用户，一个电影条目
        user = User(name=&#39;Test&#39;, username=&#39;test&#39;)
        user.set_password(&#39;123&#39;)
        movie = Movie(title=&#39;Test Movie Title&#39;, year=&#39;2019&#39;)
        # 使用 add_all() 方法一次添加多个模型类实例，传入列表
        db.session.add_all([user, movie])
        db.session.commit()

        self.client = app.test_client()  # 创建测试客户端
        self.runner = app.test_cli_runner()  # 创建测试命令运行器

    def tearDown(self):
        db.session.remove()  # 清除数据库会话
        db.drop_all()  # 删除数据库表
    
    # 测试程序实例是否存在
    def test_app_exist(self):
        self.assertIsNotNone(app)

    # 测试程序是否处于测试模式
    def test_app_is_testing(self):
        self.assertTrue(app.config['TESTING'])</pre>
<p>
	某些配置，在开发和测试时通常需要使用不同的值。在&nbsp;<code>setUp()</code>&nbsp;方法中，我们更新了两个配置变量的值，首先将&nbsp;<code>TESTING</code>&nbsp;设为&nbsp;<code>True</code>&nbsp;来开启测试模式，这样在出错时不会输出多余信息；然后将&nbsp;<code>SQLALCHEMY_DATABASE_URI</code>&nbsp;设为&nbsp;<code>&#39;sqlite:///:memory:&#39;</code>，这会使用 SQLite 内存型数据库，不会干扰开发时使用的数据库文件。你也可以使用不同文件名的 SQLite 数据库文件，但内存型数据库速度更快。
</p>
<p>
	接着，我们调用&nbsp;<code>db.create_all()</code>&nbsp;创建数据库和表，然后添加测试数据到数据库中。在&nbsp;<code>setUp()</code>&nbsp;方法最后创建的两个类属性分别为测试客户端和测试命令运行器，前者用来模拟客户端请求，后者用来触发自定义命令，下一节会详细介绍。
</p>
<p>
	在&nbsp;<code>tearDown()</code>&nbsp;方法中，我们调用&nbsp;<code>db.session.remove()</code>&nbsp;清除数据库会话并调用&nbsp;<code>db.drop_all()</code>&nbsp;删除数据库表。测试时的程序状态和真实的程序运行状态不同，所以需要调用&nbsp;<code>db.session.remove()</code>&nbsp;来确保数据库会话被清除。
</p>
<h3>
	测试客户端<br />
</h3>
<p>
	<code>app.test_client()</code>&nbsp;返回一个测试客户端对象，可以用来模拟客户端（浏览器），我们创建类属性&nbsp;<code>self.client</code>&nbsp;来保存它。对它调用&nbsp;<code>get()</code>&nbsp;方法就相当于浏览器向服务器发送 GET 请求，调用&nbsp;<code>post()</code>&nbsp;则相当于浏览器向服务器发送 POST 请求，以此类推。下面是两个发送 GET 请求的测试方法，分别测试 404 页面和主页：
</p>
<p>
	<em>test_watchlist.py：测试固件</em>
</p>
<pre>
class WatchlistTestCase(unittest.TestCase):
    # ...
    # 测试 404 页面
    def test_404_page(self):
        response = self.client.get(&#39;/nothing&#39;)  # 传入目标 URL
        data = response.get_data(as_text=True)
        self.assertIn(&#39;Page Not Found - 404&#39;, data)
        self.assertIn(&#39;Go Back&#39;, data)
        self.assertEqual(response.status_code, 404)  # 判断响应状态码
    
    # 测试主页
    def test_index_page(self):
        response = self.client.get(&#39;/&#39;)
        data = response.get_data(as_text=True)
        self.assertIn(&#39;Test\&#39;s Watchlist&#39;, data)
        self.assertIn(&#39;Test Movie Title&#39;, data)
        self.assertEqual(response.status_code, 200)</pre>
<p>
	调用这类方法返回包含响应数据的响应对象，对这个响应对象调用&nbsp;<code>get_data()</code>&nbsp;方法并把&nbsp;<code>as_text</code>&nbsp;参数设为&nbsp;<code>True</code>&nbsp;可以获取 Unicode 格式的响应主体。我们通过判断响应主体中是否包含预期的内容来测试程序是否正常工作，比如 404 页面响应是否包含 Go Back，主页响应是否包含标题 Test&#39;s Watchlist。
</p>
<p>
	接下来，我们要测试数据库操作相关的功能，比如创建、更新和删除电影条目。这些操作对应的请求都需要登录账户后才能发送，我们先编写一个用于登录账户的辅助方法：
</p>
<p>
	<em>test_watchlist.py：测试辅助方法</em>
</p>
<pre>
class WatchlistTestCase(unittest.TestCase):
    # ...
    # 辅助方法，用于登入用户
    def login(self):
        self.client.post(&#39;/login&#39;, data=dict(
            username=&#39;test&#39;,
            password=&#39;123&#39;
        ), follow_redirects=True)</pre>
<p>
	在&nbsp;<code>login()</code>&nbsp;方法中，我们使用&nbsp;<code>post()</code>&nbsp;方法发送提交登录表单的 POST 请求。和&nbsp;<code>get()</code>&nbsp;方法类似，我们需要先传入目标 URL，然后使用&nbsp;<code>data</code>&nbsp;关键字以字典的形式传入请求数据（字典中的键为表单&nbsp;<code>&lt;input&gt;</code>&nbsp;元素的&nbsp;<code>name</code>&nbsp;属性值），作为登录表单的输入数据；而将&nbsp;<code>follow_redirects</code>&nbsp;参数设为&nbsp;<code>True</code>&nbsp;可以跟随重定向，最终返回的会是重定向后的响应。
</p>
<p>
	下面是测试创建、更新和删除条目的测试方法：
</p>
<p>
	<em>test_watchlist.py：测试创建、更新和删除条目</em>
</p>
<pre>
class WatchlistTestCase(unittest.TestCase):
    # ...
    # 测试创建条目
    def test_create_item(self):
        self.login()
        
        # 测试创建条目操作
        response = self.client.post(&#39;/&#39;, data=dict(
            title=&#39;New Movie&#39;,
            year=&#39;2019&#39;
        ), follow_redirects=True)
        data = response.get_data(as_text=True)
        self.assertIn(&#39;Item created.&#39;, data)
        self.assertIn(&#39;New Movie&#39;, data)
        
        # 测试创建条目操作，但电影标题为空
        response = self.client.post(&#39;/&#39;, data=dict(
            title=&#39;&#39;,
            year=&#39;2019&#39;
        ), follow_redirects=True)
        data = response.get_data(as_text=True)
        self.assertNotIn(&#39;Item created.&#39;, data)
        self.assertIn(&#39;Invalid input.&#39;, data)
        
        # 测试创建条目操作，但电影年份为空
        response = self.client.post(&#39;/&#39;, data=dict(
            title=&#39;New Movie&#39;,
            year=&#39;&#39;
        ), follow_redirects=True)
        data = response.get_data(as_text=True)
        self.assertNotIn(&#39;Item created.&#39;, data)
        self.assertIn(&#39;Invalid input.&#39;, data)

    # 测试更新条目
    def test_update_item(self):
        self.login()
        
        # 测试更新页面
        response = self.client.get(&#39;/movie/edit/1&#39;)
        data = response.get_data(as_text=True)
        self.assertIn(&#39;Edit item&#39;, data)
        self.assertIn(&#39;Test Movie Title&#39;, data)
        self.assertIn(&#39;2019&#39;, data)
        
        # 测试更新条目操作
        response = self.client.post(&#39;/movie/edit/1&#39;, data=dict(
            title=&#39;New Movie Edited&#39;,
            year=&#39;2019&#39;
        ), follow_redirects=True)
        data = response.get_data(as_text=True)
        self.assertIn(&#39;Item updated.&#39;, data)
        self.assertIn(&#39;New Movie Edited&#39;, data)
        
        # 测试更新条目操作，但电影标题为空
        response = self.client.post(&#39;/movie/edit/1&#39;, data=dict(
            title=&#39;&#39;,
            year=&#39;2019&#39;
        ), follow_redirects=True)
        data = response.get_data(as_text=True)
        self.assertNotIn(&#39;Item updated.&#39;, data)
        self.assertIn(&#39;Invalid input.&#39;, data)
        
        # 测试更新条目操作，但电影年份为空
        response = self.client.post(&#39;/movie/edit/1&#39;, data=dict(
            title=&#39;New Movie Edited Again&#39;,
            year=&#39;&#39;
        ), follow_redirects=True)
        data = response.get_data(as_text=True)
        self.assertNotIn(&#39;Item updated.&#39;, data)
        self.assertNotIn(&#39;New Movie Edited Again&#39;, data)
        self.assertIn(&#39;Invalid input.&#39;, data)

    # 测试删除条目
    def test_delete_item(self):
        self.login()
        
        response = self.client.post(&#39;/movie/delete/1&#39;, follow_redirects=True)
        data = response.get_data(as_text=True)
        self.assertIn(&#39;Item deleted.&#39;, data)
        self.assertNotIn(&#39;Test Movie Title&#39;, data)</pre>
<p>
	在这几个测试方法中，大部分的断言都是在判断响应主体是否包含正确的提示消息和电影条目信息。
</p>
<p>
	登录、登出和认证保护等功能的测试如下所示：
</p>
<p>
	<em>test_watchlist.py：测试认证相关功能</em>
</p>
<pre>
class WatchlistTestCase(unittest.TestCase):
    # ...
    # 测试登录保护
    def test_login_protect(self):
        response = self.client.get(&#39;/&#39;)
        data = response.get_data(as_text=True)
        self.assertNotIn(&#39;Logout&#39;, data)
        self.assertNotIn(&#39;Settings&#39;, data)
        self.assertNotIn(&#39;&lt;form method=&quot;post&quot;&gt;&#39;, data)
        self.assertNotIn(&#39;Delete&#39;, data)
        self.assertNotIn(&#39;Edit&#39;, data)

    # 测试登录
    def test_login(self):
        response = self.client.post(&#39;/login&#39;, data=dict(
            username=&#39;test&#39;,
            password=&#39;123&#39;
        ), follow_redirects=True)
        data = response.get_data(as_text=True)
        self.assertIn(&#39;Login success.&#39;, data)
        self.assertIn(&#39;Logout&#39;, data)
        self.assertIn(&#39;Settings&#39;, data)
        self.assertIn(&#39;Delete&#39;, data)
        self.assertIn(&#39;Edit&#39;, data)
        self.assertIn(&#39;&lt;form method=&quot;post&quot;&gt;&#39;, data)
        
        # 测试使用错误的密码登录
        response = self.client.post(&#39;/login&#39;, data=dict(
            username=&#39;test&#39;,
            password=&#39;456&#39;
        ), follow_redirects=True)
        data = response.get_data(as_text=True)
        self.assertNotIn(&#39;Login success.&#39;, data)
        self.assertIn(&#39;Invalid username or password.&#39;, data)
        
        # 测试使用错误的用户名登录
        response = self.client.post(&#39;/login&#39;, data=dict(
            username=&#39;wrong&#39;,
            password=&#39;123&#39;
        ), follow_redirects=True)
        data = response.get_data(as_text=True)
        self.assertNotIn(&#39;Login success.&#39;, data)
        self.assertIn(&#39;Invalid username or password.&#39;, data)
        
        # 测试使用空用户名登录
        response = self.client.post(&#39;/login&#39;, data=dict(
            username=&#39;&#39;,
            password=&#39;123&#39;
        ), follow_redirects=True)
        data = response.get_data(as_text=True)
        self.assertNotIn(&#39;Login success.&#39;, data)
        self.assertIn(&#39;Invalid input.&#39;, data)
        
        # 测试使用空密码登录
        response = self.client.post(&#39;/login&#39;, data=dict(
            username=&#39;test&#39;,
            password=&#39;&#39;
        ), follow_redirects=True)
        data = response.get_data(as_text=True)
        self.assertNotIn(&#39;Login success.&#39;, data)
        self.assertIn(&#39;Invalid input.&#39;, data)

    # 测试登出
    def test_logout(self):
        self.login()

        response = self.client.get(&#39;/logout&#39;, follow_redirects=True)
        data = response.get_data(as_text=True)
        self.assertIn(&#39;Goodbye.&#39;, data)
        self.assertNotIn(&#39;Logout&#39;, data)
        self.assertNotIn(&#39;Settings&#39;, data)
        self.assertNotIn(&#39;Delete&#39;, data)
        self.assertNotIn(&#39;Edit&#39;, data)
        self.assertNotIn(&#39;&lt;form method=&quot;post&quot;&gt;&#39;, data)
    
    # 测试设置
    def test_settings(self):
        self.login()
        
        # 测试设置页面
        response = self.client.get(&#39;/settings&#39;)
        data = response.get_data(as_text=True)
        self.assertIn(&#39;Settings&#39;, data)
        self.assertIn(&#39;Your Name&#39;, data)

        # 测试更新设置
        response = self.client.post(&#39;/settings&#39;, data=dict(
            name=&#39;Grey Li&#39;,
        ), follow_redirects=True)
        data = response.get_data(as_text=True)
        self.assertIn(&#39;Settings updated.&#39;, data)
        self.assertIn(&#39;Grey Li&#39;, data)

        # 测试更新设置，名称为空
        response = self.client.post(&#39;/settings&#39;, data=dict(
            name=&#39;&#39;,
        ), follow_redirects=True)
        data = response.get_data(as_text=True)
        self.assertNotIn(&#39;Settings updated.&#39;, data)
        self.assertIn(&#39;Invalid input.&#39;, data)</pre>
<h3>
	测试命令<br />
</h3>
<p>
	除了测试程序的各个视图函数，我们还需要测试自定义命令。<code>app.test_cli_runner()</code>&nbsp;方法返回一个命令运行器对象，我们创建类属性&nbsp;<code>self.runner</code>&nbsp;来保存它。通过对它调用&nbsp;<code>invoke()</code>&nbsp;方法可以执行命令，传入命令函数对象，或是使用&nbsp;<code>args</code>&nbsp;关键字直接给出命令参数列表。<code>invoke()</code>&nbsp;方法返回的命令执行结果对象，它的&nbsp;<code>output</code>&nbsp;属性返回命令的输出信息。下面是我们为各个自定义命令编写的测试方法：
</p>
<p>
	<em>test_watchlist.py：测试自定义命令行命令</em>
</p>
<pre>
# 导入命令函数
from app import app, db, Movie, User, forge, initdb


class WatchlistTestCase(unittest.TestCase):
    # ...
    # 测试虚拟数据
    def test_forge_command(self):
        result = self.runner.invoke(forge)
        self.assertIn(&#39;Done.&#39;, result.output)
        self.assertNotEqual(Movie.query.count(), 0)

    # 测试初始化数据库
    def test_initdb_command(self):
        result = self.runner.invoke(initdb)
        self.assertIn(&#39;Initialized database.&#39;, result.output)

    # 测试生成管理员账户
    def test_admin_command(self):
        db.drop_all()
        db.create_all()
        result = self.runner.invoke(args=['admin', '--username', 'grey', '--password', '123'])
        self.assertIn(&#39;Creating user...&#39;, result.output)
        self.assertIn(&#39;Done.&#39;, result.output)
        self.assertEqual(User.query.count(), 1)
        self.assertEqual(User.query.first().username, &#39;grey&#39;)
        self.assertTrue(User.query.first().validate_password(&#39;123&#39;))

    # 测试更新管理员账户
    def test_admin_command_update(self):
        # 使用 args 参数给出完整的命令参数列表
        result = self.runner.invoke(args=['admin', '--username', 'peter', '--password', '456'])
        self.assertIn(&#39;Updating user...&#39;, result.output)
        self.assertIn(&#39;Done.&#39;, result.output)
        self.assertEqual(User.query.count(), 1)
        self.assertEqual(User.query.first().username, &#39;peter&#39;)
        self.assertTrue(User.query.first().validate_password(&#39;456&#39;))</pre>
<p>
	在这几个测试中，大部分的断言是在检查执行命令后的数据库数据是否发生了正确的变化，或是判断命令行输出（<code>result.output</code>）是否包含预期的字符。
</p>
<h3>
	运行测试<br />
</h3>
<p>
	最后，我们在程序结尾添加下面的代码：
</p>
<pre>
if __name__ == &#39;__main__&#39;:
    unittest.main()</pre>
<p>
	使用下面的命令执行测试：
</p>
<pre>
$ python test_watchlist.py
...............
----------------------------------------------------------------------
Ran 15 tests in 2.942s

OK</pre>
<p>
	如果测试出错，你会看到详细的错误信息，进而可以有针对性的修复对应的程序代码，或是调整测试方法。
</p>
<h2>
	测试覆盖率<br />
</h2>
<p>
	为了让让程序更加强壮，你可以添加更多、更完善的测试。那么，如何才能知道程序里有哪些代码还没有被测试？整体的测试覆盖率情况如何？我们可以使用&nbsp;<a href="https://coverage.readthedocs.io/en/v4.5.x/" rel="nofollow">Coverage.py</a>&nbsp;来检查测试覆盖率，首先安装它（添加&nbsp;<code>--dev</code>&nbsp;参数将它作为开发依赖安装）：
</p>
<pre>
$ pipenv install coverage --dev</pre>
<p>
	使用下面的命令执行测试并检查测试覆盖率：
</p>
<pre>
$ coverage run --source=app test_watchlist.py</pre>
<p>
	因为我们只需要检查程序脚本 app.py 的测试覆盖率，所以使用&nbsp;<code>--source</code>&nbsp;选项来指定要检查的模块或包。
</p>
<p>
	最后使用下面的命令查看覆盖率报告：
</p>
<pre>
$ coverage report
Name     Stmts   Miss  Cover
----------------------------
app.py     146      5    97%</pre>
<p>
	从上面的表格可以看出，一共有 146 行代码，没测试到的代码有 5 行，测试覆盖率为 97%。
</p>
<p>
	你还可以使用 coverage html 命令获取详细的 HTML 格式的覆盖率报告，它会在当前目录生成一个 htmlcov 文件夹，打开其中的 index.html 即可查看覆盖率报告。点击文件名可以看到具体的代码覆盖情况，如下图所示：
</p>
<p>
	<a href="https://github.com/greyli/flask-tutorial/blob/master/chapters/images/9-1.png" rel="noopener noreferrer" target="_blank"><img alt="覆盖率报告" src="https://github.com/greyli/flask-tutorial/raw/master/chapters/images/9-1.png" /></a>
</p>
<p>
	同时在 .gitignore 文件后追加下面两行，忽略掉生成的覆盖率报告文件：
</p>
<pre>
<code>htmlcov/
.coverage
</code></pre>
<h2>
	本章小结<br />
</h2>
<p>
	通过测试后，我们就可以准备上线程序了。结束前，让我们提交代码：
</p>
<pre>
$ git add .
$ git commit -m &quot;Add unit test with unittest&quot;
$ git push</pre>
<p>
	<strong>提示</strong> 你可以在 GitHub 上查看本书示例程序的对应 commit：<a href="https://github.com/greyli/watchlist/commit/66dc48719c797da00a9e29355b39d77abb45f574" spellcheck="false">66dc487</a>。
</p>
<h2>
	进阶提示<br />
</h2>
<ul>
<li>
		访问 Coverage.py 文档（<a href="https://coverage.readthedocs.xn--io%29-gu5f2nt19p/" rel="nofollow">https://coverage.readthedocs.io）或执行</a>&nbsp;coverage help 命令来查看更多用法。
	</li>
<li>
		使用标准库中的 unittest 编写单元测试并不是唯一选择，你也可以使用第三方测试框架，比如非常流行的&nbsp;<a href="https://pytest.org/" rel="nofollow">pytest</a>。
	</li>
<li>
		<a href="http://helloflask.com/book/" rel="nofollow">《Flask Web 开发实战》</a>&nbsp;第 12 章详细介绍了测试 Flask 程序的相关知识，包括使用&nbsp;<a href="https://www.seleniumhq.org/" rel="nofollow">Selenium</a>&nbsp;编写用户界面测试，使用&nbsp;<a href="https://github.com/PyCQA/flake8">Flake8</a>&nbsp;检查代码质量等。
	</li>
<li>
		本书主页 &amp; 相关资源索引：<a href="http://helloflask.com/tutorial">http://helloflask.com/tutorial</a>。
	</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>https://greyli.com/flask-tutorial-chapter-9-test/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
