Let your Python tests travel through time

Overview

FreezeGun: Let your Python tests travel through time

https://secure.travis-ci.org/spulec/freezegun.svg?branch=master https://coveralls.io/repos/spulec/freezegun/badge.svg?branch=master

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() will also be frozen, but as usual it makes no guarantees about its absolute value, only its changes over time.

Decorator

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

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

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

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.

@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.

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.

@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.

@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.

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

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 for why.

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:

$ pip install freezegun

On Debian systems:

$ 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:

from freezegun import freeze_time

with freeze_time('2020-10-06', ignore=['threading']):
    # ...

By default FreezeGun ignores following packages:

[
    '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:

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:

import freezegun

freezegun.configure(extend_ignore_list=['tensorflow'])
Comments
  • freeze_time doesn't freeze time of pytest fixtures

    freeze_time doesn't freeze time of pytest fixtures

    Following test fails which shows that freeze_time only freezes the time of the test but not of dependent fixtures.

    from datetime import date
    import pytest
    from freezegun import freeze_time
    
    @pytest.fixture
    def somedate():
        return date.today()
    
    @freeze_time("2001-01-01")
    def test_somedate(somedate):
        assert somedate == date.today()
    

    Is there a way to freeze time for depending fixtures as well?

    opened by sliverc 22
  • 0.2.3 performance issue

    0.2.3 performance issue

    Hi,

    I run into a performance issue with 0.2.3 version. 0.2.2 works just fine. Below the sample from profiler output for test function. Also the profiler shows muchbigger output for 0.2.3.

    from freezegun import freeze_time
    import datetime
    def test():
        with freeze_time('2014-10-10'):
            print datetime.datetime.now()
    

    0.2.3:

    ncalls  tottime  percall  cumtime  percall filename:lineno(function)
    1    0.010    0.010    0.395    0.395 api.py:264(stop)
    1    0.009    0.009    0.448    0.448 api.py:223(start)
    1    0.000    0.000    0.395    0.395 api.py:220(__exit__)
    1    0.000    0.000    0.448    0.448 api.py:217(__enter__)
    

    0.2.2:

    ncalls  tottime  percall  cumtime  percall filename:lineno(function)
    1    0.001    0.001    0.003    0.003 api.py:223(start)
    1    0.001    0.001    0.002    0.002 api.py:255(stop)
    1    0.000    0.000    0.002    0.002 api.py:220(__exit__)
    1    0.000    0.000    0.003    0.003 api.py:217(__enter__)
    
    opened by matino 20
  • `freeze_time` could accept a timezone argument

    `freeze_time` could accept a timezone argument

    What do you think of having freeze_time accept a timezone argument:

    @freeze_time('2015-03-09 09:00:00', timezone='US/Pacific')
    

    That would require adding pytz to the requirements, which should be fine since most Python projects have it.

    Thoughts? I might develop it.

    opened by charlax 19
  • as_arg adds frozen_time argument to front of list of arguments

    as_arg adds frozen_time argument to front of list of arguments

    Currently the following code does not work with test classes (Django, etc).

    https://github.com/spulec/freezegun/blob/master/freezegun/api.py#L669

    That line does the following

    result = func(time_factory, *args, **kwargs)
    

    That is incompatible with self being the first param to class methods and it behaves differently than most other decorators, which add their argument to the end, not the beginning. Here is an example that doesn't work

    from django.test import TestCase
    from freezegun import freeze_time
    
    
    class MyTest(TestCase):
    
      @freeze_time('2016-11-01', as_arg=True)
      def test_something_with_time(self, time_factory):
        # freeze_time overrides self instead of time_factory
        # self is now the time_factory variable
        print(self) # <TimeFactory>
        print(time_factory) # <MyTestCase>
    

    It should do this instead.

    result = func(*args, time_factory, **kwargs)
    

    This is a backwards incompatible change, but will allow the decorator to be used with class based tests. Would you be open to accepting a PR that makes this breaking change?

    opened by taylor-cedar 16
  • The new way of ignoring module since 0.3.11 has broken pytest-freezegun

    The new way of ignoring module since 0.3.11 has broken pytest-freezegun

    pytest-freezegun is adding the module _pytest module to ignorable module, since 0.3.11 module are loked up by following the stack trace on five level, it happend that coming from a pytest test you reach the _pytest module, and so any call to time.time() for example is redirected to the real function and not the freezed one.

    opened by bdauvergne 13
  • PicklingError still exists with Django 1.5

    PicklingError still exists with Django 1.5

    It is difficult to provide an exact repro for this bug, but because this issue has been seen before, I hope the owner can determine the cause and the fix.

    We have Django 1.5, and many of our test cases are failing with a stack-trace similar to the following:

    Traceback (most recent call last): File "/home/someuser/someproject/src/some_project/xyz/pqr/views.py", line 236, in test_one_type 't_type': t_types.DEP} File "/home/someuser/someproject/src/some_project/test/urlcoverage.py", line 47, in get return super(TestUrlCoverageMixin, self).get(url, _args, *_kwargs) File "/home/someuser/someproject/lib/python2.7/site-packages/django/test/client.py", line 453, in get response = super(Client, self).get(path, data=data, **extra) File "/home/someuser/someproject/lib/python2.7/site-packages/django/test/client.py", line 279, in get return self.request(**r) File "/home/someuser/someproject/lib/python2.7/site-packages/django/test/client.py", line 424, in request six.reraise(*exc_info) File "/home/someuser/someproject/lib/python2.7/site-packages/django/core/handlers/base.py", line 187, in get_response response = middleware_method(request, response) File "/home/someuser/someproject/lib/python2.7/site-packages/django/contrib/sessions/middleware.py", line 38, in process_response request.session.save() File "/home/someuser/someproject/lib/python2.7/site-packages/django/contrib/sessions/backends/db.py", line 51, in save session_data=self.encode(self._get_session(no_load=must_create)), File "/home/someuser/someproject/lib/python2.7/site-packages/django/contrib/sessions/backends/base.py", line 84, in encode serialized = self.serializer().dumps(session_dict) File "/home/someuser/someproject/lib/python2.7/site-packages/django/contrib/sessions/serializers.py", line 14, in dumps return pickle.dumps(obj, pickle.HIGHEST_PROTOCOL) PicklingError: Can't pickle <type 'datetime.datetime'>: it's not the same object as datetime.datetime

    The test-case itself derives from a class in which freezegun calls appear. That class is something like:

    class DateMockerTestCase(TestCase): def setUp(self, _args, *_kwargs): self._freezer = freeze_time("2011-05-10 12:00:00") self._freezer.start()

        # Ensure it's working.
        assert datetime.datetime.now() == datetime.datetime(
            2011, 05, 10, 12, 00, 00)
    
        super(DateMockerTestCase, self).setUp(*args, **kwargs)
    
    def tearDown(self, *args, **kwargs):
        super(DateMockerTestCase, self).tearDown(*args, **kwargs)
    
        self._freezer.stop()
    

    As you can see, that's a typical use of freezegun package.

    The issue exists in at least two commit places:

    (1) 8ed7826e1262168e3d9157b16401d607f0c7a237 (master branch) (2) freezegun version 0.1.11

    Lastly, the issue does not exist if you checkout the commit ID mentioned in (1), but switch instead to the 'ctypes' branch.

    Hope this gives people enough detail to figure out and fix the issue.

    opened by apmarathe 13
  • "illegal hardware instruction" Running tests with freeze_time

    I'm running into an interesting issue with tests that use the @freeze_time annotation in Python 2.7.13 with freezegun 0.3.8 and 0.3.9.

    During processing of this annotation, my test run is killed by the kernel with the following message: "illegal hardware instruction".

    I have no such issue in Python 3.6.

    I haven't had a chance to debug yet, but I wanted to get the query out lest anyone else has encountered this one.

    Thanks!

    opened by rmurcek 12
  • Implement cache meachanism to speed up module search

    Implement cache meachanism to speed up module search

    This should fix the performance issues reported in issue #69.

    I'd like to hear from other people that experienced the slowdowns to see if this pull request will fix their issues.

    cc @Deimos

    opened by hltbra 12
  • freeze_time breaks when cffi is installed

    freeze_time breaks when cffi is installed

    When cffi is installed freeze_time raises an exception on start

    Traceback (most recent call last):
      File "some test", line 208
        with freezegun.freeze_time(datetime.utcnow() + timedelta(seconds=Config.SESSION_TTL + 1)):
      File "/usr/local/lib/python2.7/site-packages/freezegun/api.py", line 257, in __enter__
        self.start()
      File "/usr/local/lib/python2.7/site-packages/freezegun/api.py", line 292, in start
        attribute_value = getattr(module, module_attribute)
    TypeError: getattr(): attribute name must be string
    

    The culprit is that calling dir on one of the modules in cffi returns a few attributes that are integers, and fail when passed into getattr. There is already a try catch block around this, so either this should be extended to catch TypeErrors or it should be checked that all attribute names are strings.

    Tested on freezegun 0.3.3 and 0.3.5, with cffi 1.4.2

    opened by mmailhot 12
  • freeze_time might leave some instances patched after exit

    freeze_time might leave some instances patched after exit

    Module A gets imported inside freeze_time context manager Module A imports datetime.datetime (patched with freezegun). Context manager exists and unpatches all modules it has tracked in undo_changes.

    The problem is that module A still has FakeDatetime instead of datetime.datetime, which results in something like that if it gets called:

        return cls.times_to_freeze[-1]
    IndexError: list index out of range
    

    Sorry, I have no test to show this bug.

    opened by coagulant 12
  • Freezegun breaks isinstance() checks on existing objects.

    Freezegun breaks isinstance() checks on existing objects.

    If you have a date object that was created before freezing time, you cannot then do an isinstance check against datetime.date:

    >>> date = datetime.date.today()
    >>> freezer = freeze_time('2011-01-01')
    >>> freezer.start()
    >>> isinstance(date, datetime.date)
    False
    >>>
    

    This is because at the point you call the isinstance, the value of datetime.date is <class 'freezegun.api.FakeDate'>, of which date is not a subclass.

    opened by schinckel 12
  • freeze_time class decoration causes problems with subclasses and Python 3.11.1

    freeze_time class decoration causes problems with subclasses and Python 3.11.1

    Hi,

    I have discovered that the way freezegun.freeze_time decorates unittest.TestCase classes causes Problems in Python 3.11.1 (yes, the micro version) if you create a subclass of a class with the decorator and you use unittest.TestCase.addClassCleanup() in setUpClass() (as Djangos SimpleTestCase classes do, that's how I stumbled on this problem).

    The change in Python 3.11.1 is python/cpython#99645. While the problem only surfaces in that special combination, I do believe the right place to fix this is this library, as the freezegun decorator is what triggers this behavior.

    To demonstrate the problem, let me first show a contrived example of test case classes:

    @freeze_time("2019-04-14 12:26:00")
    class FrozenTestCase(unittest.TestCase):
        @classmethod
        def setUpClass(cls):
            print("BaseTest.setUpClass:", cls)
            super().setUpClass()
        
        def test_something(self):
            print(self.id(), datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S"))
    
    
    class FrozenSubTestCase(FrozenTestCase):
        def test_something_else(self):
            print(self.id(), datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S"))
    

    Now if you run the test suite, you'll see that both test methods will always get the frozen time (as expected), but setUpClass() will get the base class even in the subclass. Here's the output (full class paths removed for brevity):

    BaseTest.setUpClass: <class 'FrozenTestCase'>
    FrozenSubTestCase.test_something 2019-04-14 12:26:00
    FrozenSubTestCase.test_something_else 2019-04-14 12:26:00
    BaseTest.setUpClass: <class 'FrozenTestCase'>
    FrozenTestCase.test_something 2019-04-14 12:26:00
    

    I have checked that just removing the freeze_time decorator restores the expected behavior (setUpClass receives the subclass when run for the subclass) and that this also happens if the method is defined in yet a base class (e.g. Djangos SimpleTestCase).

    While certainly odd, The above class works the same way as it does in Python 3.11.1. The problem starts if you have a call to addClassCleanup() in your base class. python/cpython#99645 means that only those registered for the exact class are called, and setUpClass() for the subclass now receives the wrong class (the parent). Our sub-testcase now registers a second cleanup for the parent instead of its own class.

    If we add a cleanup function to the base class:

    @freeze_time("2019-04-14 12:26:00")
    class FrozenTestCase(unittest.TestCase):
        @classmethod
        def custom_cleanup(cls):
            print("Custom cleanup!", cls)
    
        @classmethod
        def setUpClass(cls):
            print("BaseTest.setUpClass:", cls)
            super().setUpClass()
            cls.addClassCleanup(cls.custom_cleanup)
    ...
    

    and run the test suite again, you get the following output (again trimmed the output for brevity):

    BaseTest.setUpClass: <class 'FrozenTestCase'>
    FrozenSubTestCase.test_something 2019-04-14 12:26:00
    FrozenSubTestCase.test_something_else 2019-04-14 12:26:00
    BaseTest.setUpClass: <class 'FrozenTestCase'>
    FrozenTestCase.test_something 2019-04-14 12:26:00
    Custom cleanup! <class 'FrozenTestCase'>
    Custom cleanup! <class 'FrozenTestCase'>
    

    Notice that the cleanup function is now called twice for the base class, but not at all for the subclass. Sure enough, if you run this with 3.11.0, you get:

    BaseTest.setUpClass: <class 'FrozenTestCase'>
    FrozenSubTestCase.test_something 2019-04-14 12:26:00
    FrozenSubTestCase.test_something_else 2019-04-14 12:26:00
    Custom cleanup! <class 'FrozenTestCase'>
    BaseTest.setUpClass: <class 'FrozenTestCase'>
    FrozenTestCase.test_something 2019-04-14 12:26:00
    Custom cleanup! <class 'FrozenTestCase'>
    

    ... sure enough, setUpClass() still gets the wrong class, but it's not a problem yet, as cleanups for all base classes are called.

    Unfortunately I'm not quite sure how to correctly solve this issue, as I have not found a way to "correctly" decorate a class and wrap class methods so that they get the correct classes.

    opened by mathiasertl 0
  • freeze_time not working, if module name starts with

    freeze_time not working, if module name starts with "git"

    The @time_freeze decorator does not work, when a module name starts with git and the test imports from that module. Renaming the module (i.e. the folder and imports) to any string, which does not contains those three letters at the beginning, works.

    I could reproduce the error with Python 3.10, see this minmal example.

    Minimal Example Code

    Only freezegun as external dependency

    git_module_name/minimal.py,

    from datetime import datetime as dt
    
    
    def what_date_is_it_right_now():
        return dt.now()
    

    other_module_name/minimal.py

    (exactly the same content in both)

    from datetime import datetime as dt
    
    
    def what_date_is_it_right_now():
        return dt.now()
    

    test/test_minimal.py

    from datetime import datetime
    from unittest import TestCase
    
    from freezegun import freeze_time
    
    from git_module_name.mininmal import what_date_is_it_right_now as what_date_is_it_right_now_git
    from other_module_name.mininmal import what_date_is_it_right_now as what_date_is_it_right_now_other
    
    
    class TimeTest(TestCase):
        @freeze_time("2001-02-03")
        def test_what_date_is_it_right_now_git(self):
            returned_time = what_date_is_it_right_now_git()
            self.assertEqual(returned_time, datetime.now())
    
        @freeze_time("2001-02-03")
        def test_what_date_is_it_right_now_other(self):
            returned_time = what_date_is_it_right_now_other()
            self.assertEqual(returned_time, datetime.now())
    

    Test Result

    Running python -m unittest tests.test_minimal.TimeTest results in the first test failing and the second one passing:

    F. 
    ======================================================================
    FAIL: test_what_date_is_it_right_now_git (tests.test_minimal.TimeTest)
    ----------------------------------------------------------------------
    Traceback (most recent call last):
      File "E:\git\review\freezegun_minimal_example\.venv\lib\site-packages\freezegun\api.py", line 809, in wrapper
        result = func(*args, **kwargs)
      File "E:\git\review\freezegun_minimal_example\tests\test_minimal.py", line 14, in test_what_date_is_it_right_now_git
        self.assertEqual(returned_time, datetime.now())
    AssertionError: datetime.datetime(2022, 11, 29, 11, 25, 35, 237124) != FakeDatetime(2001, 2, 3, 0, 0)
    
    ----------------------------------------------------------------------
    Ran 2 tests in 0.073s
    
    FAILED (failures=1)
    
    opened by the-working-rene 0
  • Update gh actions 11 2022

    Update gh actions 11 2022

    Objectives

    1. Make tox run locally
      • remove py3.6 from tox envs
    2. Make GitHub Actions run on all compatible PyPy versions
      • update setup to v4 (to support PyPy's new version annotation, e.g. pypy3.x)
      • added implementation type (CPython/PyPy)
      • changed versions from floats to strings (otherwise 3.10 would be interpreted as 3.1)
    opened by micromoses 0
  • freeze_time broken between 1.2.1 and 1.2.2

    freeze_time broken between 1.2.1 and 1.2.2

    The behavior of freeze_time is broken with the change to 1.2.2. Setup: Python 3.10.3 on MacOS 12.5.1 with M1 using django test of Django 3.2. The following setup worked with multplie freezegun releases < 1.2.2:

    @freeze_time("2017-01-20")
    class GenericProductOfferMixin(ProductTestMixin):
            def generic_setup(self'):
            import datetime
            assert datetime.date.today() == datetime.date(2017, 1, 20)
    

    but raises an assertion error with 1.2.2. The actual stacktrace (leaving out the assertion) is: File "/Users/bernhard/.pyenv/versions/django_3_2/lib/python3.10/site-packages/freezegun/api.py", line 732, in stop freeze_factories.pop() IndexError: pop from empty list

    opened by bernhardboehmer 0
  • Adding `prompt_toolkit` to DEFAULT_IGNORE_LIST

    Adding `prompt_toolkit` to DEFAULT_IGNORE_LIST

    Ignoring this library will allow IPython and ipdb's prompts to behave normally even when time is frozen. This solves for issue https://github.com/spulec/freezegun/issues/450 as well as this SO question.

    In the meantime, this problem can also be solved by adding the following configuration:

    freezegun.configure(extend_ignore_list=['prompt_toolkit'])
    
    opened by micromoses 0
  • `freeze_time` doesn't work with pydantic

    `freeze_time` doesn't work with pydantic

    Overview

    It seems that freezegun.freeze_time patch is incompatible with pydantic imports, because of some datetime classes re-definition. Minimal working example:

    import freezegun
    
    
    def main():
        with freezegun.freeze_time('2022-10-10') as frozen_time:
            import pydantic
        print('Hello, world')
    
    
    if __name__ == '__main__':
        main()
    

    This code throws following error:

    Traceback (most recent call last):
      File "main.py", line 11, in <module>
        main()
      File "main.py", line 6, in main
        import pydantic
      File "pydantic/__init__.py", line 2, in init pydantic.__init__
      File "pydantic/dataclasses.py", line 56, in init pydantic.dataclasses
        # +=======+=======+=======+
      File "pydantic/error_wrappers.py", line 4, in init pydantic.error_wrappers
      File "pydantic/json.py", line 14, in init pydantic.json
      File "pydantic/types.py", line 1162, in init pydantic.types
    TypeError: metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases
    

    Requirements.txt

    freezegun==1.2.2
    pydantic==1.10.2
    python-dateutil==2.8.2
    six==1.16.0
    typing_extensions==4.4.0
    
    opened by Tehtehteh 1
Owner
Steve Pulec
Steve Pulec
Green is a clean, colorful, fast python test runner.

Green -- A clean, colorful, fast python test runner. Features Clean - Low redundancy in output. Result statistics for each test is vertically aligned.

Nathan Stocks 756 Dec 22, 2022
Scalable user load testing tool written in Python

Locust Locust is an easy to use, scriptable and scalable performance testing tool. You define the behaviour of your users in regular Python code, inst

Locust.io 20.4k Jan 8, 2023
A cross-platform GUI automation Python module for human beings. Used to programmatically control the mouse & keyboard.

PyAutoGUI PyAutoGUI is a cross-platform GUI automation Python module for human beings. Used to programmatically control the mouse & keyboard. pip inst

Al Sweigart 7.6k Jan 1, 2023
splinter - python test framework for web applications

splinter - python tool for testing web applications splinter is an open source tool for testing web applications using Python. It lets you automate br

Cobra Team 2.6k Dec 27, 2022
HTTP client mocking tool for Python - inspired by Fakeweb for Ruby

HTTPretty 1.0.5 HTTP Client mocking tool for Python created by Gabriel Falcão . It provides a full fake TCP socket module. Inspired by FakeWeb Github

Gabriel Falcão 2k Jan 6, 2023
A utility for mocking out the Python Requests library.

Responses A utility library for mocking out the requests Python library. Note Responses requires Python 2.7 or newer, and requests >= 2.0 Installing p

Sentry 3.8k Jan 2, 2023
A test fixtures replacement for Python

factory_boy factory_boy is a fixtures replacement based on thoughtbot's factory_bot. As a fixtures replacement tool, it aims to replace static, hard t

FactoryBoy project 3k Jan 5, 2023
Mixer -- Is a fixtures replacement. Supported Django, Flask, SqlAlchemy and custom python objects.

The Mixer is a helper to generate instances of Django or SQLAlchemy models. It's useful for testing and fixture replacement. Fast and convenient test-

Kirill Klenov 871 Dec 25, 2022
Faker is a Python package that generates fake data for you.

Faker is a Python package that generates fake data for you. Whether you need to bootstrap your database, create good-looking XML documents, fill-in yo

Daniele Faraglia 15.2k Jan 1, 2023
Mimesis is a high-performance fake data generator for Python, which provides data for a variety of purposes in a variety of languages.

Mimesis - Fake Data Generator Description Mimesis is a high-performance fake data generator for Python, which provides data for a variety of purposes

Isaak Uchakaev 3.8k Jan 1, 2023
Coroutine-based concurrency library for Python

gevent Read the documentation online at http://www.gevent.org. Post issues on the bug tracker, discuss and ask open ended questions on the mailing lis

gevent 5.9k Dec 28, 2022
Radically simplified static file serving for Python web apps

WhiteNoise Radically simplified static file serving for Python web apps With a couple of lines of config WhiteNoise allows your web app to serve its o

Dave Evans 2.1k Jan 8, 2023
livereload server in python (MAINTAINERS NEEDED)

LiveReload Reload webpages on changes, without hitting refresh in your browser. Installation python-livereload is for web developers who know Python,

Hsiaoming Yang 977 Dec 14, 2022
A screamingly fast Python 2/3 WSGI server written in C.

bjoern: Fast And Ultra-Lightweight HTTP/1.1 WSGI Server A screamingly fast, ultra-lightweight WSGI server for CPython 2 and CPython 3, written in C us

Jonas Haag 2.9k Dec 21, 2022
Waitress - A WSGI server for Python 2 and 3

Waitress Waitress is a production-quality pure-Python WSGI server with very acceptable performance. It has no dependencies except ones which live in t

Pylons Project 1.2k Dec 30, 2022
Python HTTP Server

Python HTTP Server Preview Languange and Code Editor: How to run? Download the zip first. Open the http.py and wait 1-2 seconds. You will see __pycach

SonLyte 16 Oct 21, 2021
PyQaver is a PHP like WebServer for Python.

PyQaver is a PHP like WebServer for Python.

Dev Bash 7 Apr 25, 2022
Robyn is an async Python backend server with a runtime written in Rust, btw.

Robyn is an async Python backend server with a runtime written in Rust, btw. Python server running on top of of Rust Async RunTime. Installation

Sanskar Jethi 1.8k Dec 30, 2022
Let your Python tests travel through time

FreezeGun: Let your Python tests travel through time FreezeGun is a library that allows your Python tests to travel through time by mocking the dateti

Steve Pulec 3.5k Jan 9, 2023
Travel through time in your tests.

time-machine Travel through time in your tests. A quick example: import datetime as dt

Adam Johnson 373 Dec 27, 2022