Testing properties that are date-related

Peter Otten __peter__ at web.de
Fri Oct 7 08:38:03 EDT 2011


Tim Chase wrote:

> Are there best practices for testing dates that are properties
> which take the current date into consideration?  I have something
> like
> 
>    class Foo:
>      def _get_year_range(self):
>        return (self._min_year, self._max_year)
>      def _set_year_range(self, year):
>        if isinstance(year, tuple):
>          _min, _max = map(window_date, year)
>          if _min > _max: _min, _max = _max, _min
>        else: # a raw int
>          _min = _max = window_date(year)
>        self._min_year, self._max_year = _min, _max
>      year_range = property(
>        fget=_get_year_range,
>        fget=_get_year_range,
>        )
> 
> 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:
> 
>    class TestFoo:
>      def test_year_range(self):
>        around = date(2011,1,1)
>        f = Foo()
>        f.year_range = (97, 84)
>        self.assertEqual(f.year_range, (1984, 1997))
> 
> Any suggestions/tips/hints?  Thanks,

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))

See also http://www.voidspace.org.uk/python/mock/




More information about the Python-list mailing list