freezegun


Namefreezegun JSON
Version 1.2.1 PyPI version JSON
download
home_pagehttps://github.com/spulec/freezegun
SummaryLet your Python tests travel through time
upload_time2022-03-18 09:06:39
maintainer
docs_urlNone
authorSteve Pulec
requires_python>=3.6
licenseApache 2.0
keywords
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage
            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, from the start of setUpClass to the end of tearDownClass

    @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 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 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": "",
    "docs_url": null,
    "requires_python": ">=3.6",
    "maintainer_email": "",
    "keywords": "",
    "author": "Steve Pulec",
    "author_email": "spulec@gmail.com",
    "download_url": "https://files.pythonhosted.org/packages/89/a9/ebf3d233893752ca282d91c88103facf6d7d05ce22978829e4e0cbc4113d/freezegun-1.2.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, from the start of setUpClass to the end of tearDownClass\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 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 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\n\n",
    "bugtrack_url": null,
    "license": "Apache 2.0",
    "summary": "Let your Python tests travel through time",
    "version": "1.2.1",
    "split_keywords": [],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "md5": "c93debd7b0d707cd24f3556a4bb3294e",
                "sha256": "15103a67dfa868ad809a8f508146e396be2995172d25f927e48ce51c0bf5cb09"
            },
            "downloads": -1,
            "filename": "freezegun-1.2.1-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "c93debd7b0d707cd24f3556a4bb3294e",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.6",
            "size": 16843,
            "upload_time": "2022-03-18T09:06:37",
            "upload_time_iso_8601": "2022-03-18T09:06:37.473918Z",
            "url": "https://files.pythonhosted.org/packages/d2/cf/cb14c48cad1366bd08d5f5482b3d7ea0696b6d38a2764752d331fa8bbd22/freezegun-1.2.1-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "md5": "43257363edf06d2d1426bf44e8c3ec30",
                "sha256": "b4c64efb275e6bc68dc6e771b17ffe0ff0f90b81a2a5189043550b6519926ba4"
            },
            "downloads": -1,
            "filename": "freezegun-1.2.1.tar.gz",
            "has_sig": false,
            "md5_digest": "43257363edf06d2d1426bf44e8c3ec30",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.6",
            "size": 29740,
            "upload_time": "2022-03-18T09:06:39",
            "upload_time_iso_8601": "2022-03-18T09:06:39.435224Z",
            "url": "https://files.pythonhosted.org/packages/89/a9/ebf3d233893752ca282d91c88103facf6d7d05ce22978829e4e0cbc4113d/freezegun-1.2.1.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2022-03-18 09:06:39",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "github_user": "spulec",
    "github_project": "freezegun",
    "travis_ci": false,
    "coveralls": true,
    "github_actions": true,
    "requirements": [],
    "tox": true,
    "lcname": "freezegun"
}
        
Elapsed time: 0.34857s