Skip to Content
Flask Web开发:基于Python的Web应用开发实战(第2版)
book

Flask Web开发:基于Python的Web应用开发实战(第2版)

by Miguel Grinberg
August 2018
Intermediate to advanced
230 pages
6h 42m
Chinese
O'Reilly Media, Inc. Beijing
Content preview from Flask Web开发:基于Python的Web应用开发实战(第2版)
172
15
试。但遗憾的是,并非应用的所有组成部分都像数据库模型那样易于测试。在接下来的两
节中,我们将介绍更高级的测试策略,可用于测试视图函数、表单和模板。
15.2
 
Flask
测试客户端
应用的某些代码严重依赖运行中的应用所创建的环境。例如,你不能直接调用视图函数中
的代码进行测试,因为这个函数可能需要访问
Flask
上下文变量,如 request session
视图函数可能还等待接收 POST 请求中的表单数据,而且某些视图函数要求用户先登录。简
而言之,视图函数只能在请求上下文和运行中的应用里运行。
Flask
内建了一个
测试客户端
用于解决(至少部分解决)这一问题。测试客户端能复现应
用运行在
Web
服务器中的环境,让测试充当客户端来发送请求。
在测试客户端中运行的视图函数和正常情况下的没有太大区别,服务器收到请求,将其分
派给合适的视图函数,视图函数生成响应,将其返回给测试客户端。执行视图函数后,生
成的响应会传入测试,检查是否正确。
15.2.1
 测试
Web
应用
示例
15-2
是一个使用测试客户端编写的单元测试框架。
示例
15-2
 
tests/test_client.py
:使用
Flask
测试客户端编写的测试框架
import unittest
from app import create_app, db
from app.models import User, Role
class FlaskClientTestCase(unittest.TestCase):
def setUp(self): ...
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

Python机器学习基础教程

Python机器学习基础教程

Andreas C. Müller, Sarah Guido
Python编程入门与实战

Python编程入门与实战

Posts & Telecom Press, Fabrizio Romano
程序设计导论:Python语言实践

程序设计导论:Python语言实践

罗伯特 塞奇威克, 凯文 韦恩, 罗伯特 唐德罗

Publisher Resources

ISBN: 9787115489456