gpt4 book ai didi

python - 模拟 flask.request 在 python nosetests

转载 作者:太空宇宙 更新时间:2023-11-03 12:11:32 26 4
gpt4 key购买 nike

我正在为通过 Flask 下的路由调用的代码编写测试用例。我不想通过设置测试应用程序并调用命中路由的 URL 来测试代码,我想直接调用该函数。为了完成这项工作,我需要模拟 flask.request 并且我似乎无法管理它。谷歌/stackoverflow 搜索导致了很多答案,这些答案显示了如何设置一个测试应用程序,这又不是我想要做的。

代码看起来像这样。

somefile.py
-----------
from flask import request

def method_called_from_route():
data = request.values

# do something with data here

test_somefile.py
----------------
import unittest
import somefile

class SomefileTestCase(unittest.TestCase):

@patch('somefile.request')
def test_method_called_from_route(self, mock_request):
# want to mock the request.values here

我有两个问题。

(1) 按照我在上面概述的方式修补请求是行不通的。我收到类似于“AttributeError: 'Blueprint' object has no attribute 'somefile'”的错误

(2) 如果可以修补请求对象,我不知道如何准确地模拟它。它实际上没有 return_value,因为它不是函数。

同样,我找不到任何关于如何执行此操作的示例,所以我觉得可以接受一个新问题。

最佳答案

试试这个

test_somefile.py

import unittest
import somefile
import mock

class SomefileTestCase(unittest.TestCase):

def test_method_called_from_route(self):
m = mock.MagicMock()
m.values = "MyData"
with mock.patch("somefile.request", m):
somefile.method_called_from_route()

unittest.main()

somefile.py

from flask import request

def method_called_from_route():
data = request.values
assert(data == "MyData")

这将模拟整个请求对象。如果你只想模拟 request.values 而保持所有其他不变,这是行不通的。

关于python - 模拟 flask.request 在 python nosetests,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36729846/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com