Testing properties that are date-related

Ethan Furman ethan at stoneleaf.us
Fri Oct 7 10:45:49 EDT 2011


Tim Chase wrote:
> On 10/07/11 07:38, Peter Otten wrote:
>>> Are there best practices for testing dates that are properties
>>> which take the current date into consideration
>>>
>>> The problem is that the behavior of the window_date function
>>> depends on the current date (the function makes a guess about
>>> adding the century if the year was<100).  It *does* take an
>>> "around" parameter that defaults to the current date.  So for
>>> pure testing of the window_date() function, I can hard-code some
>>> date where I know what the expected values should be.
>>>
>>> However if I want to write a test-harness for my property, I have
>>> no way (AFAIK) to pass in this fixed date to _set_year_range() so
>>> that the success/failure of my tests doesn't depend on the day I
>>> run them
>>
>> Temporarily replace the window_date() function with something that you 
>> can
>> control completely. Assuming Foo and window_date are defined in foo.py:
>>
>> # untested
>> import foo
>>
>> class TestFoo:
>>      def setUp(self):
>>          foo.window_date = functools.partial(foo.window_date,
>> around=date(2011, 1, 1))
>>      def tearDown(self):
>>          foo.window_date = foo.window_date.func
>>      def test_year_range(self):
>>          f = Foo()
>>          f.year_range = (97, 84)
>>          self.assertEqual(f.year_range, (1984, 1997))
> 
> I had to twiddle my class code a bit to make sure it referenced 
> module.window_date() everywhere instead of just a raw window_date() 
> (originally pulled in via "from module import window_date") so that it 
> picked up the new function, but otherwise it worked like a charm.

Another option is injection:

import foo

def window_date(...):
     ...

foo.window_date = window_date


~Ethan~



More information about the Python-list mailing list