【问题标题】:Writing unit test for a flask application using unittest使用 unittest 为烧瓶应用程序编写单元测试
【发布时间】:2021-12-19 11:57:55
【问题描述】:

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

@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.x unit-testing flask python-unittest


    【解决方案1】:

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

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

    【讨论】:

    • 我试过了,但出现以下错误:[2021-11-08 10:56:07,700] 应用程序中的错误:异常 / [POST] Traceback(最近一次调用最后一次):响应 = self.full_dispatch_request() rv = self.handle_user_exception(e) rv = self.dispatch_request()
    • 顺便说一句,我正在为我的数据库使用 mongodb 云
    • 您能给出完整的错误输出吗?我无法从您提供的错误消息中找出异常类型:(
    • 很抱歉链接已过期:(请重新生成一个吗?
    猜你喜欢
    • 1970-01-01
    • 2016-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-19
    相关资源
    最近更新 更多