使用 Hypothesis 模块在 Python 中进行单元测试的示例代码。编写了简单的getTimeDelta
函数来获取两个日期之间的时间差。
想写getTimeDelta
函数的单元测试。使用假设模块来获得多个datetime
值。
问题是: 1. 如何传递不同的数据类型值,即time1
str 和time2
isdatetime
而无需编写多个函数?
仅检查返回值的数据类型,而不是实际结果是否正确。怎么做?
如何检查项目的数据类型,结果元组?
assertIsInstance
代码:
import unittest
from hypothesis import given
from hypothesis import strategies as st
import datetime
from dateutil.parser import parse as time_parse
def getTimeDelta(time1, time2):
try:
if isinstance(time1, str):
time1 = time_parse(time1)
if isinstance(time2, str):
time2 = time_parse(time2)
return (time1 - time2, {"message": ""})
except Exception as err:
return (False, {"message": "Exception {}".format(err)})
class TestTimeDeltaCalc(unittest.TestCase):
def __init__(self, *args, **kwargs):
super(TestTimeDeltaCalc, self).__init__(*args, **kwargs)
self.utils = Utils()
@given(st.datetimes(), st.datetimes())
def test_time_delta(self, time1, time2):
time_delta = getTimeDelta(time1, time2)
if time_delta[0] is False:
self.assertIsInstance(time_delta[0], bool)
else:
self.assertIsInstance(time_delta[0], datetime.timedelta)
self.assertIsInstance(time_delta[1], dict)
@given(st.text(), st.text())
def test_time_delta(self, time1, time2):
time_delta = getTimeDelta(time1, time2)
if time_delta[0] is False:
self.assertIsInstance(time_delta[0], bool)
else:
self.assertIsInstance(time_delta[0], datetime.timedelta)
self.assertIsInstance(time_delta[1], dict)
if __name__ == '__main__':
unittest.main()
编辑 01:
我们可以通过hypothesis.strategies.one_of(*args)
,链接修复 #Question1