简体   繁体   English

如何测试 function 是否引发 Flask 正确中止?

[英]How to test if function raises Flask abort properly?

I am trying to create unittests for my flask application which should assert exceptions properly.我正在尝试为我的 flask 应用程序创建单元测试,它应该正确地断言异常。

I am attaching simplified code sample on what i want to test.我在我想要测试的内容上附加了简化的代码示例。 The below test should finish as success.下面的测试应该成功完成。

def my_function():
    abort(400,"error")

import unittest

from werkzeug import exceptions

class Tests(unittest.TestCase):

    def test_event_link(self):
        self.assertRaises(exceptions.BadRequest,my_function)

unittest.main(argv=[''], verbosity=2, exit=False)

I would simply patch the Flask abort function and ensure it is called with the correct value, this is preferable as it only tests your code not the behaviour of Flasks abort function which could change with future versions of Flask and break your tests. I would simply patch the Flask abort function and ensure it is called with the correct value, this is preferable as it only tests your code not the behaviour of Flasks abort function which could change with future versions of Flask and break your tests.

See below example based on your code which also includes examples of testing the exception if this is what you would prefer to do.请根据您的代码查看下面的示例,其中还包括测试异常的示例(如果您愿意这样做)。

# code.py

from flask import abort


def my_function():
    abort(400, "error")
# test.py

import unittest
from unittest.mock import patch
from werkzeug import exceptions

import code  # Your code file code.py


class Tests(unittest.TestCase):

    @patch('code.abort')
    def test_one(self, mock_abort):
        code.my_function()
        mock_abort.assert_called_once_with(400, 'error')

    def test_two(self):
        with self.assertRaises(exceptions.BadRequest):
            code.my_function()

    def test_three(self):
        with self.assertRaisesRegexp(exceptions.BadRequest, '400 Bad Request: error'):
            code.my_function()


unittest.main(argv=[''], verbosity=2, exit=False)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM