我曾尝试在Python中为REST客户端编写一些单元测试。我在模拟服务器的响应方面遇到了麻烦。
具体来说,我希望GET查询返回预先准备好的JSON字符串而不连接到服务器。我在Python中学到的方法是使用unittest.mock
或pytest-mock
。我的项目结构是这样的:
workspace/__init__.py
workspace/module/__init__.py
workspace/module/connector.py
workspace/tests/__init__.py
workspace/tests/test_connector.py
我将测试代码放在test_connector.py
中。我试图以这种方式使用unittest.mock.patch
:
@patch()
test_get_container_list(mocker):
(....)
以及pytest-mock
:
mocker.patch('module.connector.Connector.get_container_list.requests.sessions.get')
mocker.return_value.ok = True
mocker.return_value.json.return_value = container_list
但是我被这个错误所困扰:
ImportError: No module named 'module.connector.Connector'; 'module.connector' is not a package
我也尝试修改我的路径,但我得到的只是:
ImportError: No module named 'Connector'
ImportError: No module named 'connector.Connector'; 'connector' is not a package
我使用此命令启动了测试:
pytest tests /
来自module
目录。我的导入如下:
import configparser
import pytest
from module.connector import Connector
环境:Ubuntu 16.04,Python 3.5.2,pytest-3.2.5,py-1.5.2,pluggy-0.4.0;插件:mock-1.6.3,cov-2.5.1
所有剩余的测试都可以毫无问题地工作,只有这个测试没有。
我的问题:如何让模拟测试正常运行? (在我使用pytest-mock
或unittest.mock
)时会出现导入错误。
答案 0 :(得分:1)
我走了另一条路线而不是使用pytest-mock
我使用了request-mock
。这里的方法是通常使用requests
执行HTTP请求并模拟特定URL的响应。
import requests
import requests_mock
def test_requests():
with requests_mock.Mocker() as mock:
session = requests.Session()
url = 'https://google.com/'
mock.register_uri('GET', url, text='{"answer": "My return text"}') # mocking the http response within this context
resp = session.get('https://google.com/')
assert resp.json()['answer'] == 'My return text'
希望这能为您提供一种替代方法的灵感。
答案 1 :(得分:0)
我认为这个问题可能是Pytest和导入的问题,基本上每个人(包括我自己)似乎都有,从这里我遇到的类似问题的数量来判断。
This answer对我特别有帮助。