FreezeGun: Let your Python tests travel through time
====================================================
.. image:: https://img.shields.io/pypi/v/freezegun.svg
:target: https://pypi.python.org/pypi/freezegun/
.. image:: https://github.com/spulec/freezegun/workflows/CI/badge.svg
:target: https://github.com/spulec/freezegun/actions
.. image:: https://coveralls.io/repos/spulec/freezegun/badge.svg?branch=master
:target: https://coveralls.io/r/spulec/freezegun
FreezeGun is a library that allows your Python tests to travel through time by mocking the datetime module.
Usage
-----
Once the decorator or context manager have been invoked, all calls to datetime.datetime.now(), datetime.datetime.utcnow(), datetime.date.today(), time.time(), time.localtime(), time.gmtime(), and time.strftime() will return the time that has been frozen. time.monotonic() and time.perf_counter() will also be frozen, but as usual it makes no guarantees about their absolute value, only their changes over time.
Decorator
~~~~~~~~~
.. code-block:: python
from freezegun import freeze_time
import datetime
import unittest
# Freeze time for a pytest style test:
@freeze_time("2012-01-14")
def test():
assert datetime.datetime.now() == datetime.datetime(2012, 1, 14)
# Or a unittest TestCase - freezes for every test, and set up and tear down code
@freeze_time("1955-11-12")
class MyTests(unittest.TestCase):
def test_the_class(self):
assert datetime.datetime.now() == datetime.datetime(1955, 11, 12)
# Or any other class - freezes around each callable (may not work in every case)
@freeze_time("2012-01-14")
class Tester(object):
def test_the_class(self):
assert datetime.datetime.now() == datetime.datetime(2012, 1, 14)
# Or method decorator, might also pass frozen time object as kwarg
class TestUnitTestMethodDecorator(unittest.TestCase):
@freeze_time('2013-04-09')
def test_method_decorator_works_on_unittest(self):
self.assertEqual(datetime.date(2013, 4, 9), datetime.date.today())
@freeze_time('2013-04-09', as_kwarg='frozen_time')
def test_method_decorator_works_on_unittest(self, frozen_time):
self.assertEqual(datetime.date(2013, 4, 9), datetime.date.today())
self.assertEqual(datetime.date(2013, 4, 9), frozen_time.time_to_freeze.today())
@freeze_time('2013-04-09', as_kwarg='hello')
def test_method_decorator_works_on_unittest(self, **kwargs):
self.assertEqual(datetime.date(2013, 4, 9), datetime.date.today())
self.assertEqual(datetime.date(2013, 4, 9), kwargs.get('hello').time_to_freeze.today())
Context manager
~~~~~~~~~~~~~~~
.. code-block:: python
from freezegun import freeze_time
def test():
assert datetime.datetime.now() != datetime.datetime(2012, 1, 14)
with freeze_time("2012-01-14"):
assert datetime.datetime.now() == datetime.datetime(2012, 1, 14)
assert datetime.datetime.now() != datetime.datetime(2012, 1, 14)
Raw use
~~~~~~~
.. code-block:: python
from freezegun import freeze_time
freezer = freeze_time("2012-01-14 12:00:01")
freezer.start()
assert datetime.datetime.now() == datetime.datetime(2012, 1, 14, 12, 0, 1)
freezer.stop()
Timezones
~~~~~~~~~
.. code-block:: python
from freezegun import freeze_time
@freeze_time("2012-01-14 03:21:34", tz_offset=-4)
def test():
assert datetime.datetime.utcnow() == datetime.datetime(2012, 1, 14, 3, 21, 34)
assert datetime.datetime.now() == datetime.datetime(2012, 1, 13, 23, 21, 34)
# datetime.date.today() uses local time
assert datetime.date.today() == datetime.date(2012, 1, 13)
@freeze_time("2012-01-14 03:21:34", tz_offset=-datetime.timedelta(hours=3, minutes=30))
def test_timedelta_offset():
assert datetime.datetime.now() == datetime.datetime(2012, 1, 13, 23, 51, 34)
Nice inputs
~~~~~~~~~~~
FreezeGun uses dateutil behind the scenes so you can have nice-looking datetimes.
.. code-block:: python
@freeze_time("Jan 14th, 2012")
def test_nice_datetime():
assert datetime.datetime.now() == datetime.datetime(2012, 1, 14)
Function and generator objects
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
FreezeGun is able to handle function and generator objects.
.. code-block:: python
def test_lambda():
with freeze_time(lambda: datetime.datetime(2012, 1, 14)):
assert datetime.datetime.now() == datetime.datetime(2012, 1, 14)
def test_generator():
datetimes = (datetime.datetime(year, 1, 1) for year in range(2010, 2012))
with freeze_time(datetimes):
assert datetime.datetime.now() == datetime.datetime(2010, 1, 1)
with freeze_time(datetimes):
assert datetime.datetime.now() == datetime.datetime(2011, 1, 1)
# The next call to freeze_time(datetimes) would raise a StopIteration exception.
``tick`` argument
~~~~~~~~~~~~~~~~~
FreezeGun has an additional ``tick`` argument which will restart time at the given
value, but then time will keep ticking. This is an alternative to the default
parameters which will keep time stopped.
.. code-block:: python
@freeze_time("Jan 14th, 2020", tick=True)
def test_nice_datetime():
assert datetime.datetime.now() > datetime.datetime(2020, 1, 14)
``auto_tick_seconds`` argument
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
FreezeGun has an additional ``auto_tick_seconds`` argument which will autoincrement the
value every time by the given amount from the start value. This is an alternative to the default
parameters which will keep time stopped. Note that given ``auto_tick_seconds`` the ``tick`` parameter will be ignored.
.. code-block:: python
@freeze_time("Jan 14th, 2020", auto_tick_seconds=15)
def test_nice_datetime():
first_time = datetime.datetime.now()
auto_incremented_time = datetime.datetime.now()
assert first_time + datetime.timedelta(seconds=15) == auto_incremented_time
Manual ticks
~~~~~~~~~~~~
FreezeGun allows for the time to be manually forwarded as well.
.. code-block:: python
def test_manual_tick():
initial_datetime = datetime.datetime(year=1, month=7, day=12,
hour=15, minute=6, second=3)
with freeze_time(initial_datetime) as frozen_datetime:
assert frozen_datetime() == initial_datetime
frozen_datetime.tick()
initial_datetime += datetime.timedelta(seconds=1)
assert frozen_datetime() == initial_datetime
frozen_datetime.tick(delta=datetime.timedelta(seconds=10))
initial_datetime += datetime.timedelta(seconds=10)
assert frozen_datetime() == initial_datetime
.. code-block:: python
def test_monotonic_manual_tick():
initial_datetime = datetime.datetime(year=1, month=7, day=12,
hour=15, minute=6, second=3)
with freeze_time(initial_datetime) as frozen_datetime:
monotonic_t0 = time.monotonic()
frozen_datetime.tick(1.0)
monotonic_t1 = time.monotonic()
assert monotonic_t1 == monotonic_t0 + 1.0
Moving time to specify datetime
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
FreezeGun allows moving time to specific dates.
.. code-block:: python
def test_move_to():
initial_datetime = datetime.datetime(year=1, month=7, day=12,
hour=15, minute=6, second=3)
other_datetime = datetime.datetime(year=2, month=8, day=13,
hour=14, minute=5, second=0)
with freeze_time(initial_datetime) as frozen_datetime:
assert frozen_datetime() == initial_datetime
frozen_datetime.move_to(other_datetime)
assert frozen_datetime() == other_datetime
frozen_datetime.move_to(initial_datetime)
assert frozen_datetime() == initial_datetime
@freeze_time("2012-01-14", as_arg=True)
def test(frozen_time):
assert datetime.datetime.now() == datetime.datetime(2012, 1, 14)
frozen_time.move_to("2014-02-12")
assert datetime.datetime.now() == datetime.datetime(2014, 2, 12)
Parameter for ``move_to`` can be any valid ``freeze_time`` date (string, date, datetime).
Default arguments
~~~~~~~~~~~~~~~~~
Note that FreezeGun will not modify default arguments. The following code will
print the current date. See `here <http://docs.python-guide.org/en/latest/writing/gotchas/#mutable-default-arguments>`_ for why.
.. code-block:: python
from freezegun import freeze_time
import datetime as dt
def test(default=dt.date.today()):
print(default)
with freeze_time('2000-1-1'):
test()
Installation
------------
To install FreezeGun, simply:
.. code-block:: bash
$ pip install freezegun
On Debian systems:
.. code-block:: bash
$ sudo apt-get install python-freezegun
Ignore packages
---------------
Sometimes it's desired to ignore FreezeGun behaviour for particular packages (i.e. libraries).
It's possible to ignore them for a single invocation:
.. code-block:: python
from freezegun import freeze_time
with freeze_time('2020-10-06', ignore=['threading']):
# ...
By default FreezeGun ignores following packages:
.. code-block:: python
[
'nose.plugins',
'six.moves',
'django.utils.six.moves',
'google.gax',
'threading',
'Queue',
'selenium',
'_pytest.terminal.',
'_pytest.runner.',
'gi',
]
It's possible to set your own default ignore list:
.. code-block:: python
import freezegun
freezegun.configure(default_ignore_list=['threading', 'tensorflow'])
Please note this will override default ignore list. If you want to extend existing defaults
please use:
.. code-block:: python
import freezegun
freezegun.configure(extend_ignore_list=['tensorflow'])
Raw data
{
"_id": null,
"home_page": "https://github.com/spulec/freezegun",
"name": "freezegun",
"maintainer": null,
"docs_url": null,
"requires_python": ">=3.7",
"maintainer_email": null,
"keywords": null,
"author": "Steve Pulec",
"author_email": "spulec@gmail.com",
"download_url": "https://files.pythonhosted.org/packages/2c/ef/722b8d71ddf4d48f25f6d78aa2533d505bf3eec000a7cacb8ccc8de61f2f/freezegun-1.5.1.tar.gz",
"platform": null,
"description": "FreezeGun: Let your Python tests travel through time\n====================================================\n\n.. image:: https://img.shields.io/pypi/v/freezegun.svg\n :target: https://pypi.python.org/pypi/freezegun/\n.. image:: https://github.com/spulec/freezegun/workflows/CI/badge.svg\n :target: https://github.com/spulec/freezegun/actions\n.. image:: https://coveralls.io/repos/spulec/freezegun/badge.svg?branch=master\n :target: https://coveralls.io/r/spulec/freezegun\n\nFreezeGun is a library that allows your Python tests to travel through time by mocking the datetime module.\n\nUsage\n-----\n\nOnce the decorator or context manager have been invoked, all calls to datetime.datetime.now(), datetime.datetime.utcnow(), datetime.date.today(), time.time(), time.localtime(), time.gmtime(), and time.strftime() will return the time that has been frozen. time.monotonic() and time.perf_counter() will also be frozen, but as usual it makes no guarantees about their absolute value, only their changes over time.\n\nDecorator\n~~~~~~~~~\n\n.. code-block:: python\n\n from freezegun import freeze_time\n import datetime\n import unittest\n\n # Freeze time for a pytest style test:\n\n @freeze_time(\"2012-01-14\")\n def test():\n assert datetime.datetime.now() == datetime.datetime(2012, 1, 14)\n\n # Or a unittest TestCase - freezes for every test, and set up and tear down code\n\n @freeze_time(\"1955-11-12\")\n class MyTests(unittest.TestCase):\n def test_the_class(self):\n assert datetime.datetime.now() == datetime.datetime(1955, 11, 12)\n\n # Or any other class - freezes around each callable (may not work in every case)\n\n @freeze_time(\"2012-01-14\")\n class Tester(object):\n def test_the_class(self):\n assert datetime.datetime.now() == datetime.datetime(2012, 1, 14)\n\n # Or method decorator, might also pass frozen time object as kwarg\n\n class TestUnitTestMethodDecorator(unittest.TestCase):\n @freeze_time('2013-04-09')\n def test_method_decorator_works_on_unittest(self):\n self.assertEqual(datetime.date(2013, 4, 9), datetime.date.today())\n\n @freeze_time('2013-04-09', as_kwarg='frozen_time')\n def test_method_decorator_works_on_unittest(self, frozen_time):\n self.assertEqual(datetime.date(2013, 4, 9), datetime.date.today())\n self.assertEqual(datetime.date(2013, 4, 9), frozen_time.time_to_freeze.today())\n\n @freeze_time('2013-04-09', as_kwarg='hello')\n def test_method_decorator_works_on_unittest(self, **kwargs):\n self.assertEqual(datetime.date(2013, 4, 9), datetime.date.today())\n self.assertEqual(datetime.date(2013, 4, 9), kwargs.get('hello').time_to_freeze.today())\n\nContext manager\n~~~~~~~~~~~~~~~\n\n.. code-block:: python\n\n from freezegun import freeze_time\n\n def test():\n assert datetime.datetime.now() != datetime.datetime(2012, 1, 14)\n with freeze_time(\"2012-01-14\"):\n assert datetime.datetime.now() == datetime.datetime(2012, 1, 14)\n assert datetime.datetime.now() != datetime.datetime(2012, 1, 14)\n\nRaw use\n~~~~~~~\n\n.. code-block:: python\n\n from freezegun import freeze_time\n\n freezer = freeze_time(\"2012-01-14 12:00:01\")\n freezer.start()\n assert datetime.datetime.now() == datetime.datetime(2012, 1, 14, 12, 0, 1)\n freezer.stop()\n\nTimezones\n~~~~~~~~~\n\n.. code-block:: python\n\n from freezegun import freeze_time\n\n @freeze_time(\"2012-01-14 03:21:34\", tz_offset=-4)\n def test():\n assert datetime.datetime.utcnow() == datetime.datetime(2012, 1, 14, 3, 21, 34)\n assert datetime.datetime.now() == datetime.datetime(2012, 1, 13, 23, 21, 34)\n\n # datetime.date.today() uses local time\n assert datetime.date.today() == datetime.date(2012, 1, 13)\n\n @freeze_time(\"2012-01-14 03:21:34\", tz_offset=-datetime.timedelta(hours=3, minutes=30))\n def test_timedelta_offset():\n assert datetime.datetime.now() == datetime.datetime(2012, 1, 13, 23, 51, 34)\n\nNice inputs\n~~~~~~~~~~~\n\nFreezeGun uses dateutil behind the scenes so you can have nice-looking datetimes.\n\n.. code-block:: python\n\n @freeze_time(\"Jan 14th, 2012\")\n def test_nice_datetime():\n assert datetime.datetime.now() == datetime.datetime(2012, 1, 14)\n\nFunction and generator objects\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nFreezeGun is able to handle function and generator objects.\n\n.. code-block:: python\n\n def test_lambda():\n with freeze_time(lambda: datetime.datetime(2012, 1, 14)):\n assert datetime.datetime.now() == datetime.datetime(2012, 1, 14)\n\n def test_generator():\n datetimes = (datetime.datetime(year, 1, 1) for year in range(2010, 2012))\n\n with freeze_time(datetimes):\n assert datetime.datetime.now() == datetime.datetime(2010, 1, 1)\n\n with freeze_time(datetimes):\n assert datetime.datetime.now() == datetime.datetime(2011, 1, 1)\n\n # The next call to freeze_time(datetimes) would raise a StopIteration exception.\n\n``tick`` argument\n~~~~~~~~~~~~~~~~~\n\nFreezeGun has an additional ``tick`` argument which will restart time at the given\nvalue, but then time will keep ticking. This is an alternative to the default\nparameters which will keep time stopped.\n\n.. code-block:: python\n\n @freeze_time(\"Jan 14th, 2020\", tick=True)\n def test_nice_datetime():\n assert datetime.datetime.now() > datetime.datetime(2020, 1, 14)\n\n``auto_tick_seconds`` argument\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nFreezeGun has an additional ``auto_tick_seconds`` argument which will autoincrement the\nvalue every time by the given amount from the start value. This is an alternative to the default\nparameters which will keep time stopped. Note that given ``auto_tick_seconds`` the ``tick`` parameter will be ignored.\n\n.. code-block:: python\n\n @freeze_time(\"Jan 14th, 2020\", auto_tick_seconds=15)\n def test_nice_datetime():\n first_time = datetime.datetime.now()\n auto_incremented_time = datetime.datetime.now()\n assert first_time + datetime.timedelta(seconds=15) == auto_incremented_time\n\n\nManual ticks\n~~~~~~~~~~~~\n\nFreezeGun allows for the time to be manually forwarded as well.\n\n.. code-block:: python\n\n def test_manual_tick():\n initial_datetime = datetime.datetime(year=1, month=7, day=12,\n hour=15, minute=6, second=3)\n with freeze_time(initial_datetime) as frozen_datetime:\n assert frozen_datetime() == initial_datetime\n\n frozen_datetime.tick()\n initial_datetime += datetime.timedelta(seconds=1)\n assert frozen_datetime() == initial_datetime\n\n frozen_datetime.tick(delta=datetime.timedelta(seconds=10))\n initial_datetime += datetime.timedelta(seconds=10)\n assert frozen_datetime() == initial_datetime\n\n.. code-block:: python\n\n def test_monotonic_manual_tick():\n initial_datetime = datetime.datetime(year=1, month=7, day=12,\n hour=15, minute=6, second=3)\n with freeze_time(initial_datetime) as frozen_datetime:\n monotonic_t0 = time.monotonic()\n frozen_datetime.tick(1.0)\n monotonic_t1 = time.monotonic()\n assert monotonic_t1 == monotonic_t0 + 1.0\n\n\nMoving time to specify datetime\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nFreezeGun allows moving time to specific dates.\n\n.. code-block:: python\n\n def test_move_to():\n initial_datetime = datetime.datetime(year=1, month=7, day=12,\n hour=15, minute=6, second=3)\n\n other_datetime = datetime.datetime(year=2, month=8, day=13,\n hour=14, minute=5, second=0)\n with freeze_time(initial_datetime) as frozen_datetime:\n assert frozen_datetime() == initial_datetime\n\n frozen_datetime.move_to(other_datetime)\n assert frozen_datetime() == other_datetime\n\n frozen_datetime.move_to(initial_datetime)\n assert frozen_datetime() == initial_datetime\n\n\n @freeze_time(\"2012-01-14\", as_arg=True)\n def test(frozen_time):\n assert datetime.datetime.now() == datetime.datetime(2012, 1, 14)\n frozen_time.move_to(\"2014-02-12\")\n assert datetime.datetime.now() == datetime.datetime(2014, 2, 12)\n\nParameter for ``move_to`` can be any valid ``freeze_time`` date (string, date, datetime).\n\n\nDefault arguments\n~~~~~~~~~~~~~~~~~\n\nNote that FreezeGun will not modify default arguments. The following code will\nprint the current date. See `here <http://docs.python-guide.org/en/latest/writing/gotchas/#mutable-default-arguments>`_ for why.\n\n.. code-block:: python\n\n from freezegun import freeze_time\n import datetime as dt\n\n def test(default=dt.date.today()):\n print(default)\n\n with freeze_time('2000-1-1'):\n test()\n\n\nInstallation\n------------\n\nTo install FreezeGun, simply:\n\n.. code-block:: bash\n\n $ pip install freezegun\n\nOn Debian systems:\n\n.. code-block:: bash\n\n $ sudo apt-get install python-freezegun\n\n\nIgnore packages\n---------------\n\nSometimes it's desired to ignore FreezeGun behaviour for particular packages (i.e. libraries).\nIt's possible to ignore them for a single invocation:\n\n\n.. code-block:: python\n\n from freezegun import freeze_time\n\n with freeze_time('2020-10-06', ignore=['threading']):\n # ...\n\n\nBy default FreezeGun ignores following packages:\n\n.. code-block:: python\n\n [\n 'nose.plugins',\n 'six.moves',\n 'django.utils.six.moves',\n 'google.gax',\n 'threading',\n 'Queue',\n 'selenium',\n '_pytest.terminal.',\n '_pytest.runner.',\n 'gi',\n ]\n\n\nIt's possible to set your own default ignore list:\n\n.. code-block:: python\n\n import freezegun\n\n freezegun.configure(default_ignore_list=['threading', 'tensorflow'])\n\n\nPlease note this will override default ignore list. If you want to extend existing defaults\nplease use:\n\n.. code-block:: python\n\n import freezegun\n\n freezegun.configure(extend_ignore_list=['tensorflow'])\n",
"bugtrack_url": null,
"license": "Apache 2.0",
"summary": "Let your Python tests travel through time",
"version": "1.5.1",
"project_urls": {
"Bug Tracker": "https://github.com/spulec/freezegun/issues",
"Changes": "https://github.com/spulec/freezegun/blob/master/CHANGELOG",
"Documentation": "https://github.com/spulec/freezegun/blob/master/README.rst",
"Homepage": "https://github.com/spulec/freezegun",
"Source Code": "https://github.com/spulec/freezegun"
},
"split_keywords": [],
"urls": [
{
"comment_text": "",
"digests": {
"blake2b_256": "510b0d7fee5919bccc1fdc1c2a7528b98f65c6f69b223a3fd8f809918c142c36",
"md5": "4aa240867416d1f65cb295e57d8834eb",
"sha256": "bf111d7138a8abe55ab48a71755673dbaa4ab87f4cff5634a4442dfec34c15f1"
},
"downloads": -1,
"filename": "freezegun-1.5.1-py3-none-any.whl",
"has_sig": false,
"md5_digest": "4aa240867416d1f65cb295e57d8834eb",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": ">=3.7",
"size": 17569,
"upload_time": "2024-05-11T17:32:51",
"upload_time_iso_8601": "2024-05-11T17:32:51.715506Z",
"url": "https://files.pythonhosted.org/packages/51/0b/0d7fee5919bccc1fdc1c2a7528b98f65c6f69b223a3fd8f809918c142c36/freezegun-1.5.1-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": "",
"digests": {
"blake2b_256": "2cef722b8d71ddf4d48f25f6d78aa2533d505bf3eec000a7cacb8ccc8de61f2f",
"md5": "fb7324aaa31c6fafabf16a623cc62e38",
"sha256": "b29dedfcda6d5e8e083ce71b2b542753ad48cfec44037b3fc79702e2980a89e9"
},
"downloads": -1,
"filename": "freezegun-1.5.1.tar.gz",
"has_sig": false,
"md5_digest": "fb7324aaa31c6fafabf16a623cc62e38",
"packagetype": "sdist",
"python_version": "source",
"requires_python": ">=3.7",
"size": 33697,
"upload_time": "2024-05-11T17:32:53",
"upload_time_iso_8601": "2024-05-11T17:32:53.911087Z",
"url": "https://files.pythonhosted.org/packages/2c/ef/722b8d71ddf4d48f25f6d78aa2533d505bf3eec000a7cacb8ccc8de61f2f/freezegun-1.5.1.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2024-05-11 17:32:53",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "spulec",
"github_project": "freezegun",
"travis_ci": false,
"coveralls": true,
"github_actions": true,
"requirements": [],
"tox": true,
"lcname": "freezegun"
}