Comments (12)
I have the same issue with 0.3.7, I am using a pytest fixture that uses "freeze_time":
@pytest.yield_fixture
def frozen_clock():
with freeze_time("2012-01-14 12:00:01.123"):
yield
One of the tests that does not use this fixture hits this issue when using structlog and datetime.utcnow():
rdv_load_test_agent\tunnel.py:475: in load
data = await self._send_message('LOAD', path=bpt_file)
C:\Python35\Lib\contextlib.py:77: in __exit__
self.gen.throw(type, value, traceback)
rdv_load_test_agent\tunnel.py:112: in monitor_transaction
event_log.info(event, outcome=outcome, duration=duration, **kwds)
..\venvs\rdv_lta_pagagne\lib\site-packages\structlog\_base.py:176: in _proxy_to_logger
args, kw = self._process_event(method_name, event, event_kw)
..\venvs\rdv_lta_pagagne\lib\site-packages\structlog\_base.py:136: in _process_event
event_dict = proc(self._logger, method_name, event_dict)
..\venvs\rdv_lta_pagagne\lib\site-packages\structlog\processors.py:213: in stamper
event_dict[key] = now_method().isoformat() + 'Z'
..\venvs\rdv_lta_pagagne\lib\site-packages\freezegun\api.py:191: in utcnow
result = cls._time_to_freeze()
cls = <class 'freezegun.api.FakeDatetime'>
@classmethod
def _time_to_freeze(cls):
> return cls.times_to_freeze[-1]()
E IndexError: list index out of range
If this can help, here is the code in structlog that gets and uses "utcnow":
now_method = getattr(datetime.datetime, 'utcnow' if utc else 'now')
if fmt is None:
def stamper(self, _, __, event_dict):
event_dict[key] = calendar.timegm(time.gmtime())
return event_dict
elif fmt.upper() == 'ISO':
if utc:
def stamper(self, _, __, event_dict):
event_dict[key] = now_method().isoformat() + 'Z'
return event_dict
from freezegun.
Thanks for opening! I have recreated the issue.
This is a result of a performance improvement that was made with ac163a5. Clearly we will need to rethink a better way to do that.
For now, you can try using an older version.
from freezegun.
I was getting the same bug in some cases with Python 2.7, I tried downgrading to fix the issue. The problem was still happening on 0.2.3, but was fixed when I downgraded to 0.2.2. So I bet the issue is not due to ac163a5, but rather a change between 0.2.2 and 0.2.3.
Once it's in the corrupted state, we can repro with calls to datetime.datetime.utcnow()
, here's the partial stack trace from 0.2.3:
env/local/lib/python2.7/site-packages/freezegun/api.py:137: in utcnow
result = cls._time_to_freeze()
env/local/lib/python2.7/site-packages/freezegun/api.py:142: in _time_to_freeze
return cls.times_to_freeze[-1]
E IndexError: list index out of range
from freezegun.
@UberFarmer Do you have a test case for it breaking on 0.2.3? My test cases all pass on 0.2.5
(obviously we still need to fix in master too, but I just want to ensure I understand the issue fully)
from freezegun.
Turns out my bug may be caused by a different set of events than @spulec , but the symptoms are the same once it happens.
I can't get a really nice repro for you, but here's some more info. When a certain set of dependencies are installed (not sure exactly which combination, but some are definitely related to werkzeug/flask), trying to test the following code causes freezegun 0.2.3+ to enter a corrupted state. Once it's in the corrupted state, it behaves as specified in my previous comment.
from freezegun import freeze_time
import unittest
class FreezegunTestCase(unittest.TestCase):
@freeze_time('2015-01-01')
def test_break_freezegun(self):
pass
> py.test -rs --tb short test.py
=========================================================================================== test session starts ============================================================================================
platform linux2 -- Python 2.7.9 -- py-1.4.30 -- pytest-2.6.4
plugins: flask
collected 1 items
test_freezegun.py F
================================================================================================= FAILURES =================================================================================================
__________________________________________________________________________________ FreezegunTestCase.test_break_freezegun __________________________________________________________________________________
env/local/lib/python2.7/site-packages/freezegun/api.py:302: in wrapper
with self:
env/local/lib/python2.7/site-packages/freezegun/api.py:218: in __enter__
self.start()
env/local/lib/python2.7/site-packages/freezegun/api.py:250: in start
if attribute_value == real_datetime:
env/local/lib/python2.7/site-packages/werkzeug/local.py:360: in <lambda>
__eq__ = lambda x, o: x._get_current_object() == o
env/local/lib/python2.7/site-packages/werkzeug/local.py:297: in _get_current_object
return self.__local()
env/local/lib/python2.7/site-packages/flask/globals.py:34: in _find_app
raise RuntimeError('working outside of application context')
E RuntimeError: working outside of application context
===================================================================================== 1 failed in -19180615.45 seconds =====================================================================================
Even if we don't know the cause, it looks like this problem could likely be fixed through better exception handling in the freezegun _freeze_time::start()
function, so even when an unexpected exception is raised, freezegun doesn't enter a bad state.
from freezegun.
Same issue with freezegun==0.3.5, ok with 0.3.4. Sorry I do not ave clean code sample to demonstrate my case. It's difficult to isolate because it happens in kind of complex test :/
from freezegun.
I submitted PR #119 which fixes the issue @coagulant reported (including a test which reproduces it). Can you take a look @spulec and check if you like the way it's solved?
There is another case I found that is not fixed, but I couldn't find a solution for:
def test_import_after_start():
with freeze_time('2012-01-14'):
from datetime import datetime as our_imported_datetime
assert our_imported_datetime.now().year == 2012
assert our_imported_datetime.now().month == 1
assert our_imported_datetime.now().day == 14
assert our_imported_datetime.now().year != 2012
assert our_imported_datetime.now().month != 1
assert our_imported_datetime.now().day != 14
Since our_imported_datetime
it's not a module attribute, it can't be unpatched. Any ideas?
from freezegun.
this should be fixed with #119
from freezegun.
I'm having the exact same issue as @GDICommander
from freezegun.
Is there a workaround for this? Version 0.2.2
is not installable.
from freezegun.
Hm, after fixing other failing tests, this works too. Looks like an exception is not handled somewhere.
from freezegun.
Here is my attempt to fix this: #155
from freezegun.
Related Issues (20)
- 1.3.0: `freezegun/__init__.py` is missing new version number HOT 1
- [Discussion] about freezing asyncio HOT 7
- ``PermissionError: [Errno 1] Operation not permitted`` appears when upgrading to ``1.3.0`` HOT 7
- Freezegun doesn't mock pointers to date functions HOT 1
- Tag for 1.2.2 is missing HOT 1
- Python 3.12: Deprecation warnings related to datetime.datetime.utcfromtimestamp HOT 2
- Time is not freezed when using `uvloop` event loop
- unsupported operand type(s) for +: 'FakeDatetime' and 'FakeDatetime'
- Datetime and Time packages do not have the same behavior when being frozen HOT 4
- timezone free datetime.datetime.fromtimestamp returns original datetime.datetime HOT 1
- Adding a return value to tick()
- Could have some problem with Django with TIME_ZONE setting
- Test regressions on Python 3.13.0b1 HOT 2
- `FakeDatetime`'s `timestamp()` is not consistent with `datetime().timestamp()` HOT 1
- consider overriding == on FakeDatetimeMeta HOT 2
- Freeze time doesn't work with FastAPI + pydantic V2 HOT 2
- [Bug] `tz_offset` shifts `datetime` which is instantiated with `tz` argument
- Possible to patch user-defined functions?
- FG incorrectly causes monotonic time to go back
- Huge performance degradation on Py 3.12
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from freezegun.