如何模拟basic_get函数?

时间:2019-04-01 20:40:36

标签: python mocking pytest pika

我想模拟pika basic_get函数,该函数未直接导入到我的任何模块中。结果输出指向MagicMock对象,但是当我直接在测试函数中调用basic_get时,模拟就可以了。我可以采取什么步骤来解决这个问题?

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)   

1 个答案:

答案 0 :(得分:1)

您已经在嘲笑get_con,因此无需嘲笑原始类。只需配置您已经创建的模拟即可。

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)