1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459
|
Mocking dates and times
=======================
.. currentmodule:: testfixtures
Testing code that involves dates and times or which has behaviour
dependent on the date or time it is executed at has historically been
tricky. Mocking lets you test this type of code and
testfixtures provides three specialised mock objects to help with
this.
Dates
~~~~~
The testfixtures package provides the :func:`~testfixtures.mock_date` function
that returns a subclass of :class:`datetime.date` with a
:meth:`~datetime.date.today` method that will return a
consistent sequence of dates each time it is called.
This enables you to write tests for code such as the following, from
the ``testfixtures.tests.sample1`` package:
.. literalinclude:: ../testfixtures/tests/sample1.py
:lines: 8-9,21-22
:class:`~testfixtures.Replace` can be used to apply the mock as
shown in the following example:
>>> from testfixtures import Replace, mock_date
>>> from testfixtures.tests.sample1 import str_today_1
>>> with Replace('testfixtures.tests.sample1.date', mock_date()):
... str_today_1()
... str_today_1()
'2001-01-01'
'2001-01-02'
If you need a specific date to be returned, you can specify it:
>>> with Replace('testfixtures.tests.sample1.date', mock_date(1978, 6, 13)):
... str_today_1()
'1978-06-13'
If you need to test with a whole sequence of specific dates, this
can be done as follows:
>>> with Replace('testfixtures.tests.sample1.date', mock_date(None)) as d:
... d.add(1978, 6, 13)
... d.add(2009, 11, 12)
... str_today_1()
... str_today_1()
'1978-06-13'
'2009-11-12'
Another way to test with a specific sequence of dates is to use the
``delta_type`` and ``delta`` parameters to
:func:`~testfixtures.mock_date`. These parameters control the type and
size, respectively, of the difference between each date returned.
For example, where 2 days elapse between each returned value:
>>> with Replace('testfixtures.tests.sample1.date',
... mock_date(1978, 6, 13, delta=2, delta_type='days')) as d:
... str_today_1()
... str_today_1()
... str_today_1()
'1978-06-13'
'1978-06-15'
'1978-06-17'
The ``delta_type`` can be any keyword parameter accepted by the
:class:`~datetime.timedelta` constructor. Specifying a ``delta`` of
zero can be an effective way of ensuring that all calls to the
:meth:`~testfixtures.datetime.MockDate.today` method return the same value:
>>> with Replace('testfixtures.tests.sample1.date',
... mock_date(1978, 6, 13, delta=0)) as d:
... str_today_1()
... str_today_1()
... str_today_1()
'1978-06-13'
'1978-06-13'
'1978-06-13'
When using :func:`~testfixtures.mock_date`, you can, at any time, set
the next date to be returned using the
:meth:`~testfixtures.datetime.MockDate.set` method. The date returned after
this will be the set date plus the ``delta`` in effect:
>>> with Replace('testfixtures.tests.sample1.date', mock_date(delta=2)) as d:
... str_today_1()
... d.set(1978,8,1)
... str_today_1()
... str_today_1()
'2001-01-01'
'1978-08-01'
'1978-08-03'
Datetimes
~~~~~~~~~
The testfixtures package provides the :func:`~testfixtures.mock_datetime`
function that returns a subclass of :class:`datetime.datetime` with
a :meth:`~datetime.datetime.now` method that will return a
consistent sequence of :obj:`~datetime.datetime` objects each time
it is called.
This enables you to write tests for code such as the following, from
the ``testfixtures.tests.sample1`` package:
.. literalinclude:: ../testfixtures/tests/sample1.py
:lines: 8-10,11-12
:class:`~testfixtures.Replace` can be used to apply the mock as shown in the following example:
>>> from testfixtures import Replace, mock_datetime
>>> from testfixtures.tests.sample1 import str_now_1
>>> with Replace('testfixtures.tests.sample1.datetime', mock_datetime()):
... str_now_1()
... str_now_1()
'2001-01-01 00:00:00'
'2001-01-01 00:00:10'
If you need a specific datetime to be returned, you can specify it:
>>> with Replace('testfixtures.tests.sample1.datetime',
... mock_datetime(1978, 6, 13, 1, 2, 3)):
... str_now_1()
'1978-06-13 01:02:03'
If you need to test with a whole sequence of specific datetimes,
this can be done as follows:
>>> with Replace('testfixtures.tests.sample1.datetime',
... mock_datetime(None)) as d:
... d.add(1978, 6, 13, 16, 0, 1)
... d.add(2009, 11, 12, 11, 41, 20)
... str_now_1()
... str_now_1()
'1978-06-13 16:00:01'
'2009-11-12 11:41:20'
Another way to test with a specific sequence of datetimes is to use the
``delta_type`` and ``delta`` parameters to
:func:`~testfixtures.mock_datetime`. These parameters control the type and
size, respectively, of the difference between each datetime returned.
For example, where 2 hours elapse between each returned value:
>>> with Replace(
... 'testfixtures.tests.sample1.datetime',
... mock_datetime(1978, 6, 13, 16, 0, 1, delta=2, delta_type='hours')
... ) as d:
... str_now_1()
... str_now_1()
... str_now_1()
'1978-06-13 16:00:01'
'1978-06-13 18:00:01'
'1978-06-13 20:00:01'
The ``delta_type`` can be any keyword parameter accepted by the
:class:`~datetime.timedelta` constructor. Specifying a ``delta`` of
zero can be an effective way of ensuring that all calls to the
:meth:`~testfixtures.datetime.MockDateTime.now` method return the same value:
>>> with Replace('testfixtures.tests.sample1.datetime',
... mock_datetime(1978, 6, 13, 16, 0, 1, delta=0)) as d:
... str_now_1()
... str_now_1()
... str_now_1()
'1978-06-13 16:00:01'
'1978-06-13 16:00:01'
'1978-06-13 16:00:01'
When using :func:`~testfixtures.mock_datetime`, you can, at any time, set
the next datetime to be returned using the
:meth:`~testfixtures.datetime.MockDateTime.set` method. The value returned after
this will be the set value plus the ``delta`` in effect:
>>> with Replace('testfixtures.tests.sample1.datetime',
... mock_datetime(delta=2)) as d:
... str_now_1()
... d.set(1978, 8, 1)
... str_now_1()
... str_now_1()
'2001-01-01 00:00:00'
'1978-08-01 00:00:00'
'1978-08-01 00:00:02'
.. _timezones:
Timezones
---------
For the examples in this section, we need to have a timezone to work with:
.. code-block:: python
from datetime import tzinfo, timedelta
class ATZInfo(tzinfo):
def tzname(self, dt):
return 'A TimeZone'
def utcoffset(self, dt):
# In general, this timezone is 5 hours behind UTC
offset = timedelta(hours=-5)
return offset+self.dst(dt)
def dst(self, dt):
# However, between March and September, it is only
# 4 hours behind UTC
if 3 < dt.month < 9:
return timedelta(hours=1)
return timedelta()
By default, the internal queue of datetimes in a :func:`~testfixtures.mock_datetime`
simulates local time in the UTC timezone:
>>> datetime = mock_datetime(delta=0)
This means we get the following when the simulated date is 1st Jan 2001:
>>> datetime.set(2001, 1, 1, 10, 0)
>>> datetime.now()
datetime.datetime(2001, 1, 1, 10, 0)
>>> datetime.utcnow()
datetime.datetime(2001, 1, 1, 10, 0)
>>> datetime.now(ATZInfo())
datetime.datetime(2001, 1, 1, 5, 0, tzinfo=<ATZInfo ...>)
We get the following when the simulated date is 1st Apr 2001:
>>> datetime.set(2001, 4, 1, 10, 0)
>>> datetime.now()
datetime.datetime(2001, 4, 1, 10, 0)
>>> datetime.utcnow()
datetime.datetime(2001, 4, 1, 10, 0)
>>> datetime.now(ATZInfo())
datetime.datetime(2001, 4, 1, 6, 0, tzinfo=<ATZInfo ...>)
If you wish to simulate a different local time, you should pass its :class:`datetime.tzinfo`
to the :func:`~testfixtures.mock_datetime` constructor:
>>> datetime = mock_datetime(delta=0, tzinfo=ATZInfo())
This means we get the following when the simulated date is 1st Jan 2001:
>>> datetime.set(2001, 1, 1, 10, 0)
>>> datetime.now()
datetime.datetime(2001, 1, 1, 10, 0)
>>> datetime.utcnow()
datetime.datetime(2001, 1, 1, 15, 0)
>>> datetime.now(ATZInfo())
datetime.datetime(2001, 1, 1, 10, 0, tzinfo=<ATZInfo ...>)
We get the following when the simulated date is 1st Apr 2001:
>>> datetime.set(2001, 4, 1, 10, 0)
>>> datetime.now()
datetime.datetime(2001, 4, 1, 10, 0)
>>> datetime.utcnow()
datetime.datetime(2001, 4, 1, 14, 0)
>>> datetime.now(ATZInfo())
datetime.datetime(2001, 4, 1, 10, 0, tzinfo=<ATZInfo ...>)
.. warning::
For your own sanity, you should avoid using the ``tzinfo`` parameter or
passing :class:`~datetime.datetime` instances with non-``None`` :attr:`~datetime.datetime.tzinfo`
attributes when calling :meth:`~testfixtures.datetime.MockDateTime.add` or
:meth:`~testfixtures.datetime.MockDateTime.set`.
Times
~~~~~
The testfixtures package provides the :func:`~testfixtures.mock_time`
function that, when called, returns a replacement for the
:func:`time.time` function.
This enables you to write tests for code such as the following, from
the ``testfixtures.tests.sample1`` package:
.. literalinclude:: ../testfixtures/tests/sample1.py
:lines: 30-34
:class:`~testfixtures.Replace` can be used to apply the mock as shown in the following example:
>>> from testfixtures import Replace, mock_time
>>> from testfixtures.tests.sample1 import str_time
>>> with Replace('testfixtures.tests.sample1.time', mock_time()):
... str_time()
... str_time()
'978307200.0'
'978307201.0'
If you need an integer representing a specific time to be returned,
you can specify it:
>>> with Replace('testfixtures.tests.sample1.time',
... mock_time(1978, 6, 13, 1, 2, 3)):
... str_time()
'266547723.0'
If you need to test with a whole sequence of specific timestamps,
this can be done as follows:
>>> with Replace('testfixtures.tests.sample1.time', mock_time(None)) as t:
... t.add(1978, 6, 13, 16, 0, 1)
... t.add(2009, 11, 12, 11, 41, 20)
... str_time()
... str_time()
'266601601.0'
'1258026080.0'
Another way to test with a specific sequence of timestamps is to use the
``delta_type`` and ``delta`` parameters to
:func:`~testfixtures.mock_time`. These parameters control the type and
size, respectively, of the difference between each timestamp returned.
For example, where 2 hours elapse between each returned value:
>>> with Replace(
... 'testfixtures.tests.sample1.time',
... mock_time(1978, 6, 13, 16, 0, 1, delta=2, delta_type='hours')
... ) as d:
... str_time()
... str_time()
... str_time()
'266601601.0'
'266608801.0'
'266616001.0'
The ``delta_type`` can be any keyword parameter accepted by the
:class:`~datetime.timedelta` constructor. Specifying a ``delta`` of
zero can be an effective way of ensuring that all calls to the
:func:`~time.time` function return the same value:
>>> with Replace('testfixtures.tests.sample1.time',
... mock_time(1978, 6, 13, 16, 0, 1, delta=0)) as d:
... str_time()
... str_time()
... str_time()
'266601601.0'
'266601601.0'
'266601601.0'
When using :func:`~testfixtures.mock_time`, you can, at any time, set
the next timestamp to be returned using the
:meth:`~testfixtures.datetime.MockTime.set` method. The value returned after
this will be the set value plus the ``delta`` in effect:
>>> with Replace('testfixtures.tests.sample1.time', mock_time(delta=2)) as d:
... str_time()
... d.set(1978, 8, 1)
... str_time()
... str_time()
'978307200.0'
'270777600.0'
'270777602.0'
Gotchas with dates and times
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Using these specialised mock objects can have some intricacies as
described below:
Local references to functions
-----------------------------
There are situations where people may have obtained a local
reference to the :meth:`~datetime.date.today` or
:meth:`~datetime.datetime.now` methods, such
as the following code from the ``testfixtures.tests.sample1`` package:
.. literalinclude:: ../testfixtures/tests/sample1.py
:lines: 8-10,14-18,24-28
In these cases, you need to be careful with the replacement:
>>> from testfixtures import Replacer, mock_datetime
>>> from testfixtures.tests.sample1 import str_now_2, str_today_2
>>> with Replacer() as replace:
... today = replace('testfixtures.tests.sample1.today', mock_date().today)
... now = replace('testfixtures.tests.sample1.now', mock_datetime().now)
... str_today_2()
... str_now_2()
'2001-01-01'
'2001-01-01 00:00:00'
.. _strict-dates-and-times:
Use with code that checks class types
-------------------------------------
When using the above specialist mocks, you may find code that checks
the type of parameters passed may get confused. This is because, by
default, :class:`mock_datetime` and :class:`mock_date` return
instances of the real :class:`~datetime.datetime` and
:class:`~datetime.date` classes:
>>> from testfixtures import mock_datetime
>>> from datetime import datetime
>>> datetime_ = mock_datetime()
>>> issubclass(datetime_, datetime)
True
>>> type(datetime_.now())
<...'datetime.datetime'>
The above behaviour, however, is generally what you want as other code
in your application and, more importantly, in other code such as
database adapters, may handle instances of the real
:class:`~datetime.datetime` and :class:`~datetime.date` classes, but
not instances of the :class:`mock_datetime` and :class:`mock_date`
mocks.
That said, this behaviour can cause problems if you check the type of
an instance against one of the mock classes. Most people might expect
the following to return ``True``:
>>> isinstance(datetime_(2011, 1, 1), datetime_)
False
>>> isinstance(datetime_.now(), datetime_)
False
If this causes a problem for you, then both
:class:`~datetime.datetime` and :class:`~datetime.date` take a
`strict` keyword parameter that can be used as follows:
>>> datetime_ = mock_datetime(strict=True)
>>> type(datetime_.now())
<class 'testfixtures.datetime.MockDateTime'>
>>> isinstance(datetime_.now(), datetime_)
True
You will need to take care that you have replaced occurrences of the
class where type checking is done with the correct
:class:`mock_datetime` or :class:`mock_date`.
Also, be aware that the :meth:`~testfixtures.datetime.MockDateTime.date` method of
:class:`mock_datetime` instances will still return a normal
:class:`~datetime.date` instance. If type checking related to this is causing
problems, the type the :meth:`~testfixtures.datetime.MockDateTime.date` method returns can
be controlled as shown in the following example:
.. code-block:: python
from testfixtures import mock_date, mock_datetime
date_type = mock_date(strict=True)
datetime_type = mock_datetime(strict=True, date_type=date_type)
With things set up like this, the :meth:`~testfixtures.datetime.MockDateTime.date` method
will return an instance of the :class:`~testfixtures.datetime.MockDate` mock:
>>> somewhen = datetime_type.now()
>>> somewhen.date()
MockDate(2001, 1, 1)
>>> type(_) is date_type
True
|