You need to enable JavaScript to run this app. Python 3.9 如何编写Cloud Datastore数据检索逻辑的单元测试
优惠活动
大模型
产品
解决方案
定价
更多

Python 3.9 如何编写Cloud Datastore数据检索逻辑的单元测试

完整单元测试实现

测试覆盖逻辑

需要覆盖代码所有核心分支:

  • property1为value1/value2时,取property2作为timestamp1
  • property1为value3时,取property3作为timestamp1
  • timestamp2大于timestamp1时,返回timestamp2格式化结果
  • timestamp1大于timestamp2时,返回timestamp1格式化结果

完整test_main.py代码

import pytest
from datetime import datetime, timezone
from unittest.mock import Mock, patch
import main

# 参数化覆盖所有测试场景
@pytest.mark.parametrize(
    "entity1_props, entity2_ts, expected_output",
    [
        # 场景1:property1=value1,timestamp1>timestamp2,返回property2格式化结果
        (
            {"property1": "value1", "property2": datetime(2023,10,1, tzinfo=timezone.utc), "property3": datetime(2023,9,1, tzinfo=timezone.utc)},
            datetime(2023,9,15, tzinfo=timezone.utc),
            "2023-10-01T00:00:00Z"
        ),
        # 场景2:property1=value2,timestamp2>timestamp1,返回entity2的timestamp格式化结果
        (
            {"property1": "value2", "property2": datetime(2023,9,1, tzinfo=timezone.utc), "property3": datetime(2023,8,1, tzinfo=timezone.utc)},
            datetime(2023,9,15, tzinfo=timezone.utc),
            "2023-09-15T00:00:00Z"
        ),
        # 场景3:property1=value3,timestamp1>timestamp2,返回property3格式化结果
        (
            {"property1": "value3", "property2": datetime(2023,8,1, tzinfo=timezone.utc), "property3": datetime(2023,10,1, tzinfo=timezone.utc)},
            datetime(2023,9,15, tzinfo=timezone.utc),
            "2023-10-01T00:00:00Z"
        ),
    ]
)
@patch("main.datastore_client")
def test_get_timestamp(mock_datastore, entity1_props, entity2_ts, expected_output):
    # 模拟两次查询返回的query对象
    mock_query1 = Mock()
    mock_query1.fetch.return_value = [entity1_props]
    mock_query2 = Mock()
    mock_query2.fetch.return_value = [{"property1": entity2_ts}]
    
    # 两次调用datastore_client.query分别返回对应模拟query对象
    mock_datastore.query.side_effect = [mock_query1, mock_query2]
    
    # 执行测试函数
    result = main.get_timestamp()
    
    # 断言返回结果符合预期
    assert result == expected_output
    
    # 可选:验证Datastore调用参数符合预期,避免逻辑写错
    mock_datastore.key.assert_any_call("kind1", "entity1_key_id")
    mock_datastore.key.assert_any_call("job_results", "entity2_key_id")
    mock_query1.key_filter.assert_called_once()
    mock_query2.key_filter.assert_called_once()

运行说明

直接执行pytest test_main.py -v即可运行所有测试用例,分支覆盖完成后会输出通过结果。

内容的提问来源于stack exchange,提问作者Michael W.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.08 03:24:03