I've tried to write some unit tests for a REST Client in Python. I have trouble with mocking the response from the server.
Specifically, I want a GET query return a pre-prepared JSON string without connecting to the server. As I learned the way to do that in Python is to use unittest.mock
or pytest-mock
. My project structure is as such:
workspace/__init__.py
workspace/module/__init__.py
workspace/module/connector.py
workspace/tests/__init__.py
workspace/tests/test_connector.py
I put the test code in test_connector.py
. I've tried to use unittest.mock.patch
in this way:
@patch()
test_get_container_list(mocker):
(....)
as well as 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
I've been stumped however by this error:
ImportError: No module named 'module.connector.Connector'; 'module.connector' is not a package
I've also tried to modify what I'm putting in path, but all I got was:
ImportError: No module named 'Connector'
ImportError: No module named 'connector.Connector'; 'connector' is not a package
I launched tests with this command:
pytest tests/
from the module
directory. My imports look like this:
import configparser
import pytest
from module.connector import Connector
Environment: Ubuntu 16.04, Python 3.5.2, pytest-3.2.5, py-1.5.2, pluggy-0.4.0; plugins: mock-1.6.3, cov-2.5.1
All remaining tests work without problems, just this one with mocking does not.
My question: how do I make mocked tests work correctly? (import errors appear wheather I use pytest-mock
or unittest.mock
).