为了账号安全,请及时绑定邮箱和手机立即绑定

调用参数中带有 datetime.now() 的断言_调用_once_with() 吗?

调用参数中带有 datetime.now() 的断言_调用_once_with() 吗?

吃鸡游戏 2023-09-26 14:44:17
我有以下测试代码来测试Decorator。@mock.patch('a.b.c.KafkaProducer')def test_1(self, mocked):    decorator = Decorator(....)    @decorator()    def test():        return 42    test()    start_time = ???    v = {'type': 'batch', 'start_time': start_time.isoformat()}    mocked.return_value.send.assert_called_once_with(value=v)但是,测试总是失败,因为使用属性分配给Decorator的字典参数模拟调用。这是一种比较除 之外的所有内容的方法吗?或者有其他方法来测试通话吗?start_timedatetime.now()start_time
查看完整描述

1 回答

?
一只萌萌小番薯

TA贡献1795条经验 获得超7个赞

两种实用方法:

使用https://pypi.org/project/freezegun/冻结时间

    import datetime

from freezegun import freeze_time

from unittest.mock import patch

import my_library



NOT_NOW = datetime.datetime.now()



@freeze_time("2020-01-01")

@patch("my_library.helper")

def test_foo(_helper):

    my_library.under_test(NOT_NOW)

    # kinda auto-magic

    _helper.assert_called_once_with(datetime.datetime.now())

    # or more explicitly

    _helper.assert_called_once_with(datetime.datetime(2020, 1, 1))


或者,手动评估参数


@patch("my_library.helper", return_value=42)

def test_bar(_helper):

    my_library.under_test(NOT_NOW)

    assert _helper.call_count == 1

    assert _helper.call_args[0][0]

    assert _helper.call_args[0][0] != NOT_NOW


查看完整回答
反对 回复 2023-09-26
  • 1 回答
  • 0 关注
  • 82 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信