Python RESTful API 的单元测试
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30310860/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Unit Testing for a Python RESTful API
提问by Josh Usre
What's the best way to perform Unit Testing for a RESTful API that includes email functionality (lost passwords, user activation) in Python?
在 Python 中对包含电子邮件功能(丢失密码、用户激活)的 RESTful API 执行单元测试的最佳方法是什么?
Everything is done via HTTP POST / GET and at this time, authentication isn't involved.
一切都是通过 HTTP POST / GET 完成的,此时不涉及身份验证。
Should I just use the requests
library and manually do everything I want? Is it possible to use requests
to automate the parts of my Unit Testing that involves email?
我应该只使用requests
图书馆并手动完成我想做的一切吗?是否可以用于requests
自动化我的单元测试中涉及电子邮件的部分?
采纳答案by Freek Wiekmeijer
Often the web framework that you use to implement the REST api will also offer unit testing support. For example:
通常,用于实现 REST api 的 Web 框架也会提供单元测试支持。例如:
- Flask: http://flask.pocoo.org/docs/latest/testing/
- Django: http://django-testing-docs.readthedocs.org/en/latest/views.html
- 烧瓶:http: //flask.pocoo.org/docs/latest/testing/
- Django:http: //django-testing-docs.readthedocs.org/en/latest/views.html
These test classes are shortcuts which plug the request directly into the framework's Url dispatcher. That saves you the hassle of finding a free port, spawning a "real" server and connecting the http client from your unit test.
这些测试类是将请求直接插入框架的 Url 调度程序的快捷方式。这样可以省去寻找空闲端口、生成“真实”服务器以及从单元测试连接 http 客户端的麻烦。
As for the e-mail sending: I would mock that part in the TestCase.setUp
method. Just change the reference to the e-mail sending module / class to another module/class which loops the outgoing e-mail back to the unit test for evaluation rather than e-mailing.
至于发送电子邮件:我会在TestCase.setUp
方法中模拟该部分。只需将对电子邮件发送模块/类的引用更改为另一个模块/类,该模块/类将外发电子邮件循环回单元测试进行评估,而不是发送电子邮件。