wiz*_*owl 9 python mocking nose
我正在为通过 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
Run Code Online (Sandbox Code Playgroud)
我有两个问题。
(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()
Run Code Online (Sandbox Code Playgroud)
一些文件.py
from flask import request
def method_called_from_route():
data = request.values
assert(data == "MyData")
Run Code Online (Sandbox Code Playgroud)
这将模拟整个请求对象。如果您只想模拟 request.values 而保持所有其他值不变,则这是行不通的。
Mau*_*ldi -4
你试图做的事情只会适得其反。RFC 2616之后的请求是:
从客户端到服务器的请求消息在该消息的第一行中包括要应用于资源的方法、资源的标识符以及所使用的协议版本。
模拟 Flask 请求你需要重建它的结构,当然,你不会想做的!
最好的方法应该是使用Flask-Testing之类的东西或使用像这样的一些食谱,然后测试你的方法。
| 归档时间: |
|
| 查看次数: |
10832 次 |
| 最近记录: |