使用 unittest 为 Flask 应用程序编写单元测试

Jag*_*uar 0 unit-testing flask python-3.x python-unittest

我是单元测试的新手,我正在尝试为我编写的代码编写一个测试,这是一个注释系统,可将注释和一些额外信息保存到数据库中。这是代码:

@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"
Run Code Online (Sandbox Code Playgroud)

我想编写一个测试来检查POST它的一部分,但我不知道如何在POST方法中传递内容并确保一切正常。

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

小智 5

我看了你的档案。我想知道您的代码是否存在问题,即无论您使用什么方法请求它,它总是返回“调用的 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"
Run Code Online (Sandbox Code Playgroud)

首先创建一个名为 的文件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()
Run Code Online (Sandbox Code Playgroud)

打开您的终端并cd进入您的目录,然后运行python3 app.py​​. 如果您使用的是 Windows,则python app.py改为运行。

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