I would like to mock pika basic_get function which is not directly imported in any of my modules. Result output points to MagicMock object, but when I call basic_get directly in the testing function, mocking works. What steps could I take to solve this issue?
cli.py
@click.command
def main():
connection, channel = get_con()
message = channel.basic_get('some_queue', no_ack=True)
print(message)
con.py
def get_con.py
parameters = pika.URLParameters('amqp://')
connection = pika.BlockingConnection(parameters)
channel = connection.channel()
return connection, channel
test.py
@patch('pika.channel.Channel.basic_get')
def test_something(basic_get_mock):
with patch('con.get_con', return_value=(MagicMock(), MagicMock())) as get_con_mock:
basic_get_mock.return_value = 45
runner = CliRunner()
result = runner.invoke(main)
print(result.output)
You are already mocking get_con
, so there's no need to mock the original class; just configure the mock you are already creating.
def test_something():
mock_conn = MagicMock()
mock_channel = MagicMock()
with patch('con.get_con', return_value=(mock_conn, mock_channel)):
mock_channel.basic_get.return_value = 45
runner = CliRunner()
result = runner.invoke(main)
print(result.output)