python-3.x - 使用 unittest 为烧瓶应用程序编写单元测试
问题描述
我是单元测试的新手,我正在尝试为我写的 coed 编写一个测试,这是一个将评论和一些额外信息保存到数据库的评论系统。这是代码:
@app.route("/", methods=["GET", "POST"])
def home():
if request.method == "POST":
ip_address = request.remote_addr
entry_content = request.form.get("content")
formatted_date = datetime.datetime.today().strftime("%Y-%m-%d/%H:%M")
app.db.entries.insert({"content": entry_content, "date": formatted_date, "IP": ip_address})
return "GET method called"
我想写一个测试来检查它的 post 部分,但我不知道如何在 post 方法中传递内容并确保一切正常。
你能帮我解决这个问题吗?
解决方案
我看了你的文件。我想知道您的代码是否存在问题,即无论您使用什么方法请求它,它总是会返回“调用的 GET 方法”。也许您可能希望将代码更改为如下所示:
@app.route("/", methods=["GET", "POST"])
def home():
if request.method == "POST":
ip_address = request.remote_addr
entry_content = request.form.get("content")
formatted_date = datetime.datetime.today().strftime("%Y-%m-%d/%H:%M")
app.db.entries.insert({"content": entry_content, "date": formatted_date, "IP": ip_address})
return "POST method called"
return "GET method called"
首先创建一个名为的文件test_app.py
并确保您的目录中没有__init__.py
。
test_app.py
应包含下列代码:
import unittest
from app import app
class AppTestCase(unittest.TestCase):
def setUp(self):
self.ctx = app.app_context()
self.ctx.push()
self.client = app.test_client()
def tearDown(self):
self.ctx.pop()
def test_home(self):
response = self.client.post("/", data={"content": "hello world"})
assert response.status_code == 200
assert "POST method called" == response.get_data(as_text=True)
if __name__ == "__main__":
unittest.main()
打开您的终端并cd
进入您的目录,然后运行python3 app.py
. 如果您使用的是 Windows,请python app.py
改为运行。
希望这能帮助您解决问题。
推荐阅读
- qt - 为什么 cmake 不模仿我的 Q_OBJECT 标头?
- regex - 熊猫和正则表达式
- c# - HttpException:超出最大请求长度,即使配置具有应允许的值
- java - 未找到请求“GET /authenticate/github? 在游戏框架 2.6 的安全社交中
- google-app-engine - 仅当在 app.yaml 中指定高于 1 的 CPU 时,Google App 引擎 Deoployment 才会收到 ERROR
- android - 一个接一个地创建新的sqlite数据库
- python - 根据数字对字符串列表进行排序
- c - 将变量传递给一个函数到另一个函数
- javascript - Javascript-将多个条件组合为1
- python-3.x - Python 3.7:Pygsheets 让所有记录停止工作