Python:模拟日期时间问题

标签 python unit-testing datetime timedelta

这是我的 Python 方法:

for time in (timedelta(hours=3), timedelta(minutes=30)):

    delay = (datetime.now() + time).strftime('%Y-%m-%dT%H:%M:%S')
    payload = json.dumps({
        "channels": [
            "accountID-{acct_id}".format(acct_id=account_id)
        ],
        "push_time": delay,
        "data": {
            "alert": "Test Push",
            "m": "12345"
        },
    })

    try:
        requests.post(
            "https://api.parse.com/1/push",
            data=payload,
            headers={
                "X-Parse-Application-Id": settings.PARSE_APPLICATION_ID,
                "X-Parse-REST-API-Key": settings.PARSE_REST_API_KEY,
                "Content-Type": "application/json"
            }
        )
    except requests.exceptions.RequestException as e:
        logging.getLogger().setLevel(logging.ERROR)

这是我的测试:

@patch("requests.post")
def test_send_push_notifications_to_parse(self, post_mock):
    post_mock.return_value = {"status": 200}
    mailing = Mock()
    mailing.name = "Foo Name"
    mailing.account_id = 12345
    mailing.mailing_id = 45

    payload = json.dumps({
        "channels": [
            "accountID-12345"
        ],
        "push_time": "2014-03-04T15:00:00",
        "data": {
            "alert": "Test Push",
            "m": "12345"
        },
    })

    send_push_notification_to_parse(mailing.account_id, mailing.mailing_id, mailing.name)

    post_mock.assert_called_with(
        "https://api.parse.com/1/push",
        data=payload,
        headers={
            "X-Parse-Application-Id": settings.PARSE_APPLICATION_ID,
            "X-Parse-REST-API-Key": settings.PARSE_REST_API_KEY,
            "Content-Type": "application/json"
        }
    )

测试失败,因为 POST 请求位于 datetime 对象发生更改的循环内。如何修补 datetime 对象以使我的测试通过?

最佳答案

只需在模块中模拟日期时间:

@patch("your.module.datetime")
@patch("requests.post")
def test_send_push_notifications_to_parse(self, post_mock, dt_mock):
    # set datetime.now() to a fixed value
    dt_mock.now.return_value = datetime.datetime(2013, 2, 1, 10, 9, 8)

您通过导入将datetime绑定(bind)到模块中,上面的@patch装饰器将用模拟替换该对象。

如果需要测试多个值,可以设置 dt_mock.now.side_effect attribute反而;列表将导致模拟在顺序调用时从该列表中一一返回值,一种方法可让您在每次根据需要调用 datetime.now() 时生成一个新值。

关于Python:模拟日期时间问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22253967/

相关文章:

python - 如何为不同的分类列创建带有编码的管道?

c++ - 忽略 C++ 单元测试

c# - 如何在派生 Controller 中模拟 HttpContext.RequestServices.GetService<> 注入(inject)的服务?

c# - 字符串无法识别 C#

python - Airflow 1.9.0 无法对任务进行排队

python - spaCy 的词性和依赖标签是什么意思?

python - 在 Python MatPlotLib 中生成频率热图,从 .csv 文件读取 X 和 Y 坐标

android - 为android测试任务生成xml报告

datetime - 在组织模式表中计算工期

java - Android 中 localTime 和 localDate 的替代类是什么?