如果您想测试该函数是否正在执行预期的操作,则 Doctest 很有用。在您的情况下,我假设您想b
从参数中减去小时数datetime
并返回差值。
将您的函数重写为subtime
def subtime(a,b):
subtract = datetime.timedelta(hours=b)
difference = a - subtract
return difference
要运行 doctest,您需要提供一些示例调用值和预期结果。想想你的功能的极端情况(可能发生奇怪事情的地方)。现在让我们形成一些测试用例
- 减去少于 24 小时
- 正好减去 24 小时
- 减去超过 24 小时
- 减去 0 小时
- 添加几个小时(-ve 参数)
现在写下在每种情况下如何调用该函数。为简单起见,使用与datetime
第一个参数相同的参数。(不要使用脚本变量,例如now
因为您无法在脚本运行时预测它们的值)
subtime(datetime.datetime(2013,11,11,11,0),10)
subtime(datetime.datetime(2013,11,11,11,0),24)
subtime(datetime.datetime(2013,11,11,11,0),30)
subtime(datetime.datetime(2013,11,11,11,0),0)
subtime(datetime.datetime(2013,11,11,11,0),-5)
现在计算(使用笔和纸)每种情况的理想结果
datetime.datetime(2013, 11, 11, 1, 0)
datetime.datetime(2013, 11, 10, 11, 0)
datetime.datetime(2013, 11, 10, 5, 0)
datetime.datetime(2013, 11, 11, 11, 0)
datetime.datetime(2013, 11, 11, 16, 0)
在文档字符串中将此添加到您的函数中""" """
def subtime(a,b):
""" (datetime,int) -> datetime
Subtract b hours from a datetime.datetime and return the new datetime object
>>> subtime(datetime.datetime(2013,11,11,11,0),10)
datetime.datetime(2013, 11, 11, 1, 0)
>>> subtime(datetime.datetime(2013,11,11,11,0),24)
datetime.datetime(2013, 11, 10, 11, 0)
>>> subtime(datetime.datetime(2013,11,11,11,0),30)
datetime.datetime(2013, 11, 10, 5, 0)
>>> subtime(datetime.datetime(2013,11,11,11,0),0)
datetime.datetime(2013, 11, 11, 11, 0)
>>> subtime(datetime.datetime(2013,11,11,11,0),-5)
datetime.datetime(2013, 11, 11, 16, 0)
"""
subtract = datetime.timedelta(hours=b)
difference = now - subtract
return difference
你的脚本现在是
import datetime
import doctest
import os
def parseOptions():
import optparse
parser = optparse.OptionParser(usage= '-h')
parser.add_option('-d', '--difference', \
type= 'int')
(options, args) = parser.parse_args()
return options
now = datetime.datetime.now()
def subtime(a,b):
""" (datetime,int) -> datetime
Subtract b hours from a datetime.datetime and return the new datetime object
>>> subtime(datetime.datetime(2013,11,11,11,0),10)
datetime.datetime(2013, 11, 11, 1, 0)
>>> subtime(datetime.datetime(2013,11,11,11,0),24)
datetime.datetime(2013, 11, 10, 11, 0)
>>> subtime(datetime.datetime(2013,11,11,11,0),30)
datetime.datetime(2013, 11, 10, 5, 0)
>>> subtime(datetime.datetime(2013,11,11,11,0),0)
datetime.datetime(2013, 11, 11, 11, 0)
>>> subtime(datetime.datetime(2013,11,11,11,0),-5)
datetime.datetime(2013, 11, 11, 16, 0)
"""
subtract = datetime.timedelta(hours=b)
difference = a - subtract
return difference
if __name__== "__main__":
doctest.testmod()
print
print 'This is the time now -', now.strftime("%I:%M:%S %p %a, %B %d %Y")
difference=subtime(now,10)
print 'This is the time minus the difference -', difference.strftime("%I:%M:%S %p %a, %B %d %Y")
print
和输出
$ python try.py
This is the time now - 02:40:57 PM Tue, May 28 2013
This is the time minus the difference - 04:40:57 AM Tue, May 28 2013
请注意,使用 doctest 如果所有测试都通过,您将不会获得任何与测试相关的输出。(一切都好)