Python模拟全局变量列表的函数pytest

时间:2019-12-20 23:31:02

标签: python python-3.x pytest

在测试消息总线将调用其全局变量之一中指定的函数时

messagebus.py

from . import handlers

class MessageBus:
    ...
    def handle_event(self, event: events.Event):
        handlers_ = EVENT_HANDLERS.get(type(event))
        ...

EVENT_HANDLERS = {
    events.BatchConfirmed: [handlers.send_remittance_to_connect, handlers.send_payment_information_to_vendor],
}

tests_handlers.py

from . import messagebus

def test_payment_batch_confirm_calls_expected_handlers(mocker):  # using pytest
    # GIVEN mocked event handlers to isolate tests
    send_remittance_to_connect_mock = \
        mocker.patch('src.disbursement.messagebus.handlers.send_remittance_to_connect')
    send_payment_information_to_vendor_mock = \
        mocker.patch('src.disbursement.handlers.send_payment_information_to_vendor')
    create_import_je_mock = mocker.patch('src.disbursement.handlers.create_import_je')

    # GIVEN a payment batch with a confirmation
    bus = messagebus.MessageBus()

    # WHEN invoking the cli to add the confirmation number
    bus.handle(commands.ConfirmPaymentBatch(
        reference=batch.reference, confirmation='PR-234848-493333333',
        payment_date=pd.Timestamp(year=2019, month=11, day=23)
    ))

    # THEN the expected handlers are called
    assert send_remittance_to_connect_mock.called  # this fails even though it is in the dictionary's list
    assert send_payment_information_to_vendor_mock.called
    assert create_import_je_mock.called

上述测试失败,并显示此错误。

AssertionError: assert False
where False = <MagicMock name='send_remittance_to_connect' id='140228606012384'>.called

我希望它在最后一个断言时失败,因为修补的处理程序函数在EVENT_HANDLERS字典中。调试器。 patch正在工作(底部紫色框)。在查看全局变量的功能时。但是,messagebusEVENT_HANDLER字典中未填充它。我认为问题是在模拟函数之前,测试文件中的import语句正在加载EVENT_HANDLERS全局字典值。因此,在实例化消息总线时不会替换它们。另外,这是唯一正在运行的测试,因此不会从其他测试中溢出。

enter image description here

我一直在研究EVENT_HANDLERS字典的猴子补丁,但我正在测试的是那些被称为猴子补丁的处理程序是否会破坏测试的目的。我该如何模拟这些功能,或者有什么其他方法可以测试呢?

0 个答案:

没有答案