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

Possible to patch user-defined functions? #555

Open
jenstroeger opened this issue Jul 25, 2024 · 2 comments
Open

Possible to patch user-defined functions? #555

jenstroeger opened this issue Jul 25, 2024 · 2 comments

Comments

@jenstroeger
Copy link

This is a great tool and idea, thank you! But… ☺️

From the Usage description here:

[…] 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.

However, in my case I’ve got a subclass of Python’s datetime class that overloads the __new__ function:

import datetime as datetime_

class datetime(datetime_.datetime):
    """A custom ``datetime`` class that enforces UTC aware objects."""

    def __new__(cls, year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0):
        return super().__new__(
            cls, year, month, day, hour, minute, second, microsecond, tzinfo or datetime_.timezone.utc
        )

The purpose is to enforce aware datetime objects, and requires user to use this custom datetime class instead of Python’s.

However, this approach goes around freezegun which monkeypatches only the above methods. Because I’d really like to switch to using this package (and pytest-freezer or pytest-freezegun) I wanted to ask if you’d consider adding support to patch user-supplied functions?

Problem is that Python’s datetime.__new__ is immutable, so we can’t patch that. But, if I could have the above __new__ patched and freezegun’s features — that’d be great!

@jnrbsn
Copy link

jnrbsn commented Dec 12, 2024

@jenstroeger What did you end up doing to solve your problem? I had a similar issue with a subclass of datetime. I ended up writing a relatively simple wrapper around freezegun that also patches the now() method on my subclass.

@jenstroeger
Copy link
Author

@jnrbsn yes pretty much — I wrote a context manager that monkey-patches my subclass’s __new__ and then a pytest fixture that uses that context manager, roughly like so:

@contextlib.contextmanager
def freezling(dt):
    fun = my_custom_module.datetime.__new__
    my_custom_module.datetime.__new__ = lambda *args, **kwargs: dt 

    try:
        yield dt
    finally:
        my_custom_module.datetime.__new__ = fun


@pytest.fixture(name="freezling")
def _freezling(request: pytest.FixtureRequest):
    with freezling(request.param) as dt:
        yield dt

and I can use that fixture to “freeze time” on my own datetime subclass:

@pytest.mark.parametrize("freezling", [datetime.strptime("20240316T14:12:00", "%Y%m%dT%H:%M:%S")], indirect=True)
def test_something():
    ....

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

2 participants