Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ability to check current frozen time configuration #562

Open
plaa opened this issue Nov 28, 2024 · 0 comments
Open

Ability to check current frozen time configuration #562

plaa opened this issue Nov 28, 2024 · 0 comments

Comments

@plaa
Copy link

plaa commented Nov 28, 2024

It would be useful if test code could check the current frozen time configuration (e.g. is time currently frozen, what packages are ignored, is real_asyncio set or not). Currently it can only be done by introspecting internal details.

For example, I just implemented a assert_with_retry helper function which waits for a condition to become true (when a background asyncio task is performing some operation). It took me a long time to realize freeze_time was causing asyncio.sleep to lock up, causing tests to freeze up. I wanted to avoid the pain from other developers, so I started looking at how can I detect frozen time without real_asyncio=True option. I ended up writing the functions below (which are way less than ideal) and having assert_with_retry raise an exception with clear instructions in case it was called with frozen time without real_asyncio. It would have been great to have a stable API from which to check them.

import asyncio
import freezegun


def is_time_frozen() -> bool:
    """Check whether time is currently frozen."""
    return len(freezegun.api.freeze_factories) > 0


_cached_event_loop_class: type[asyncio.AbstractEventLoop] | None = None


def is_time_frozen_with_real_asyncio() -> bool:
    global _cached_event_loop_class  # noqa: PLW0603
    if _cached_event_loop_class is None:
        event_loop = asyncio.new_event_loop()
        event_loop.close()
        _cached_event_loop_class = type(event_loop)
    s = repr(_cached_event_loop_class.time)
    # Freezegun sets the event loop .time method to a lambda function which uses
    # the real tick method. This is detected based on the method name "freeze_time"
    # being in the function repr. The file test_freezegun_helper.py includes tests
    # so this does not break during a library upgrade.
    return "freeze_time" in s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant