Lie Ryan wrote:
Yuan HOng wrote:
In my project I have several date related methods which I want tested for
correctness. The functions use date.today() in several places. Since this
could change every time I run the test, I hope to find someway to fake a
date.today.
For illustration lets say I have a function:
from datetime import date
def today_is_2009():
return date.today().year == 2009
To test this I would like to write test function like:
def test_today_is_2009():
set_today(date(2008, 12, 31))
assert today_is_2009() == False
set_today(date(2009,1,1))
assert today_is_2009() == True
Try something like this:
import module_to_test as sut # "sut" -> system under test
from datetime import date
class FakeDate(object):
def __init__(self, value):
self._result = value
def today(self):
return self._result
def test_today_is_2009_too_old():
temp, sut.date = sut.date, FakeDate(date(2008, 12, 31))
try:
assert not sut.today_is_2009()
finally:
sut.date = temp
def test_today_is_2009_too_young():
temp, sut.date = sut.date, FakeDate(date(2010, 1, 1))
try:
assert not sut.today_is_2009()
finally:
sut.date = temp
def test_today_is_2009_just_right():
temp, sut.date = sut.date, FakeDate(date(2009, 1, 1))
try:
assert not sut.today_is_2009()
finally:
sut.date = temp
Note: each test should test 1 thing.
--Scott David Daniels
scott.dani...@acm.org
--
http://mail.python.org/mailman/listinfo/python-list