【发布时间】:2021-08-16 21:00:16
【问题描述】:
我是使用 python 进行单元测试的新手,我在尝试为我的代码编写一个代码时遇到了麻烦,我在其中获取了两个 Datastore entities 和根据条件设置时间戳。
我的main.py 看起来像这样:
from google.cloud import datastore
datastore_client = datastore.Client()
def get_timestamp():
# fetch property1 (string), property2 (timestamp), property3 (timestamp) from entity1
query = datastore_client.query(kind="kind1")
key_entity1 = datastore_client.key("kind1", "entity1_key_id")
query.key_filter(key_entity1, "=")
list_entity1 = list(query.fetch())
entity1 = dict(list_entity1[0])
property1 = entity1['property1']
# based on the value of property1 set timestamp1
if property1 == "value1" or property1 == "value2":
timestamp1 = entity1['property2']
elif property1 == "value3":
timestamp1 = entity1['property3']
# fetch property1 (timestamp) from entity2
query = datastore_client.query(kind="kind1")
key_entity2 = datastore_client.key("job_results", "entity2_key_id")
query.key_filter(key_entity2, "=")
list_entity2 = list(query.fetch())
entity2 = dict(list_entity2[0])
timestamp2 = entity2['property1']
if timestamp2 > timestamp1:
timestamp = timestamp2.isoformat().replace('+00:00', 'Z')
elif timestamp1 > timestamp2:
timestamp = timestamp1.isoformat().replace('+00:00', 'Z')
return timestamp
所以我从 Datastore 中获取两个实体及其属性,我根据条件选择时间戳属性,然后比较两个时间戳。
通过搜索,我只知道我可以使用 patch 来模拟 Datastore API,test_main.py 看起来像这样:
import pytest
from unittest.mock import Mock, patch
import main
@patch("main.datastore_client")
def test_get_timestamp():
# test code
谁能帮我告诉我代码的单元测试是什么样子的? 如果有帮助,我正在使用 Python 3.9。
感谢您的帮助,并提前致谢。
【问题讨论】:
标签: python unit-testing google-api google-cloud-datastore