Let your Python tests travel through time

Related tags

Testing freezegun
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
Given some test cases, this program automatically queries the oracle and tests your Cshanty compiler!

The Diviner A complement to The Oracle for compilers class. Given some test cases, this program automatically queries the oracle and tests your compil

Grant Holmes 2 Jan 29, 2022
pytest plugin that let you automate actions and assertions with test metrics reporting executing plain YAML files

pytest-play pytest-play is a codeless, generic, pluggable and extensible automation tool, not necessarily test automation only, based on the fantastic

pytest-dev 67 Dec 1, 2022
User-oriented Web UI browser tests in Python

Selene - User-oriented Web UI browser tests in Python (Selenide port) Main features: User-oriented API for Selenium Webdriver (code like speak common

Iakiv Kramarenko 575 Jan 2, 2023
Data-Driven Tests for Python Unittest

DDT (Data-Driven Tests) allows you to multiply one test case by running it with different test data, and make it appear as multiple test cases. Instal

null 424 Nov 28, 2022
LuluTest is a Python framework for creating automated browser tests.

LuluTest LuluTest is an open source browser automation framework using Python and Selenium. It is relatively lightweight in that it mostly provides wr

Erik Whiting 14 Sep 26, 2022
Automated tests for OKAY websites in Python (Selenium) - user friendly version

Okay Selenium Testy Aplikace určená k testování produkčních webů společnosti OKAY s.r.o. Závislosti K běhu aplikace je potřeba mít v počítači nainstal

Viktor Bem 0 Oct 1, 2022
pytest splinter and selenium integration for anyone interested in browser interaction in tests

Splinter plugin for the pytest runner Install pytest-splinter pip install pytest-splinter Features The plugin provides a set of fixtures to use splin

pytest-dev 238 Nov 14, 2022
The pytest framework makes it easy to write small tests, yet scales to support complex functional testing

The pytest framework makes it easy to write small tests, yet scales to support complex functional testing for applications and libraries. An example o

pytest-dev 9.6k Jan 2, 2023
a plugin for py.test that changes the default look and feel of py.test (e.g. progressbar, show tests that fail instantly)

pytest-sugar pytest-sugar is a plugin for pytest that shows failures and errors instantly and shows a progress bar. Requirements You will need the fol

Teemu 963 Dec 28, 2022
:game_die: Pytest plugin to randomly order tests and control random.seed

pytest-randomly Pytest plugin to randomly order tests and control random.seed. Features All of these features are on by default but can be disabled wi

pytest-dev 471 Dec 30, 2022
Selects tests affected by changed files. Continous test runner when used with pytest-watch.

This is a pytest plug-in which automatically selects and re-executes only tests affected by recent changes. How is this possible in dynamic language l

Tibor Arpas 614 Dec 30, 2022
Docker-based integration tests

Docker-based integration tests Description Simple pytest fixtures that help you write integration tests with Docker and docker-compose. Specify all ne

Avast 326 Dec 27, 2022
To automate the generation and validation tests of COSE/CBOR Codes and it's base45/2D Code representations

To automate the generation and validation tests of COSE/CBOR Codes and it's base45/2D Code representations, a lot of data has to be collected to ensure the variance of the tests. This respository was established to collect a lot of different test data and related test cases of different member states in a standardized manner. Each member state can generate a folder in this section.

null 160 Jul 25, 2022
Show surprise when tests are passing

pytest-pikachu pytest-pikachu prints ascii art of Surprised Pikachu when all tests pass. Installation $ pip install pytest-pikachu Usage Pass the --p

Charlie Hornsby 13 Apr 15, 2022
Django-google-optimize is a Django application designed to make running server side Google Optimize A/B tests easy.

Django-google-optimize Django-google-optimize is a Django application designed to make running Google Optimize A/B tests easy. Here is a tutorial on t

Adin Hodovic 39 Oct 25, 2022
Run ISP speed tests and save results

SpeedMon Automatically run periodic internet speed tests and save results to a variety of storage backends. Supported Backends InfluxDB v1 InfluxDB v2

Matthew Carey 9 May 8, 2022
Statistical tests for the sequential locality of graphs

Statistical tests for the sequential locality of graphs You can assess the statistical significance of the sequential locality of an adjacency matrix

null 2 Nov 23, 2021
Fail tests that take too long to run

GitHub | PyPI | Issues pytest-fail-slow is a pytest plugin for making tests fail that take too long to run. It adds a --fail-slow DURATION command-lin

John T. Wodder II 4 Nov 27, 2022
a wrapper around pytest for executing tests to look for test flakiness and runtime regression

bubblewrap a wrapper around pytest for assessing flakiness and runtime regressions a cs implementations practice project How to Run: First, install de

Anna Nagy 1 Aug 5, 2021