python - 如何使用mock.patch覆盖Django View 进行测试?

标签 python django python-3.x mocking

是否可以使用模拟覆盖类中的函数行为?

这适用于 python 3.6.8、django 2.2.2

views.py:


YEAR_PATTERN = r"\(\d{4}\)\s*$"
LOCKED_FROM_EXTERNAL_API = False


class FetchFromExternalApi(APIView):

    @staticmethod
    def fetch_from_url(source):
        return urlopen('http://files.grouplens.org/datasets/movielens/%s.zip' % source, timeout=1)

    def post(self, request):
        global LOCKED_FROM_EXTERNAL_API, YEAR_PATTERN
        if LOCKED_FROM_EXTERNAL_API is False:
            LOCKED_FROM_EXTERNAL_API = True
            try:
                source = request.data['source']
            except KeyError:
                LOCKED_FROM_EXTERNAL_API = False
                return Response('no source data in body',
                                status=status.HTTP_400_BAD_REQUEST)
            if source in settings.AVAILABLE_SOURCES:
                try:
                    response = self.fetch_from_url(request.data['source'])
                except URLError:
                    LOCKED_FROM_EXTERNAL_API = False
                    return Response("External server respond time out",
                                    status=status.HTTP_504_GATEWAY_TIMEOUT)

我想编写测试来覆盖 fetch_from_url 方法的行为,并完全模拟它。

最佳答案

是的,您可以修补类属性和方法。

就您的情况而言,您还需要返回一个虚假的 http 响应对象,其中包含来自修补对象的预期数据。

示例:

class FakeResponse:
    """A class for creating fake http responses for the patched method"""
    def __init__(self, body, status):
        self.body = body
        self.status = status



class MyTest(TestCase):
    def test_something(self):
        with mock.patch('file_name.FetchFromExternalApi.fetch_from_url') as mock_fetch:
            # now the `mock_fetch` will act as a proxy object for the 
            # actual fetch_from_url method

            # set the return value on `mock_fetch` object as expected 
            # from the `fetch_from_url` method

            fake_response = FakeResponse(body="Some expected data body", status=200)

            mock_fetch.return_value = fake_response

            # now you can perform tests against the returned data
            self.assertTrue(whatever)

关于python - 如何使用mock.patch覆盖Django View 进行测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56674268/

相关文章:

python - 具有不同模板和参数的 Django 注册基于类的 View

python - 使用 set()/setp() 设置 matplotlib 中的未知属性

python - 修改 matplotlib 的比例

python - 使用命令行时出现 App Engine 问题

python - ProgrammingError at/admin/login/

python-3.x - 添加未在ElasticSearch索引中显示的新文档

Python 3 在学校项目中需要帮助

python - 如果条件为真,则使用不同标记的线图 python 3

Python scikit 学习管道(无特征转换)

python - PySpark:when子句中的多个条件