当测试消息总线将调用在其全局变量中指定的函数时
消息总线.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],
}
测试\u 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
正在工作(底部紫色框)。当查看全局变量的函数时。然而,它并没有在messagebus
类EVENT_HANDLER
字典中填写。我认为问题是测试文件中的import语句在模拟函数之前加载了EVENT_HANDLERS
全局字典值。因此,在实例化messagebus时不会替换它们。而且,这是唯一正在运行的测试,因此不会从其他测试中溢出任何内容
我正在研究monkey patching the EVENT_HANDLERS
字典,但是测试正在研究这些被称为monkey patching的处理程序,从我所知道的,是否会破坏测试的目的。如何模拟这些函数,或者用什么方法来测试
目前没有回答
相关问题 更多 >
编程相关推荐