首页 > 解决方案 > 使用 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 方法中传递内容并确保一切正常。

你能帮我解决这个问题吗?

标签: python-3.xunit-testingflaskpython-unittest

解决方案


我看了你的文件。我想知道您的代码是否存在问题,即无论您使用什么方法请求它,它总是会返回“调用的 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改为运行。

希望这能帮助您解决问题。


推荐阅读