GithubHelp home page GithubHelp logo

Freezegun fails with Django about freezegun HOT 8 CLOSED

spulec avatar spulec commented on July 16, 2024
Freezegun fails with Django

from freezegun.

Comments (8)

hexsprite avatar hexsprite commented on July 16, 2024

Looks like freezegun has an incomplete implementation of datetime.now. It needs to support the tz argument for that to work.

I've had another problem with Django as well. In django.db.models.fields both DateField, DateTimeField have to_python methods that check is the value passed isinstance of datetime.datetime or datetime.date

For some reason real datetimes can get passed to it and this causes isinstance() to return False causing a failure. Maybe it's not clear where freezegun should be imported to avoid that but for now I have monkeypatched the to_python to check for both freezegun and real datetime objects.

from freezegun.

lorin avatar lorin commented on July 16, 2024

@hexsprite Is your monkey-patch workaround available somewhere? I'm also running into a problem on Django because the to_python method fails:

  File "/Users/lorin/.virtualenvs/myvenv/src/django/django/db/models/query.py", line 1593, in insert_query
    return query.get_compiler(using=using).execute_sql(return_id)
  File "/Users/lorin/.virtualenvs/myvenv/src/django/django/db/models/sql/compiler.py", line 909, in execute_sql
    for sql, params in self.as_sql():
  File "/Users/lorin/.virtualenvs/myvenv/src/django/django/db/models/sql/compiler.py", line 872, in as_sql
    for obj in self.query.objs
  File "/Users/lorin/.virtualenvs/myvenv/src/django/django/db/models/fields/__init__.py", line 292, in get_db_prep_save
    prepared=False)
  File "/Users/lorin/.virtualenvs/myvenv/src/django/django/db/models/fields/__init__.py", line 717, in get_db_prep_value
    value = self.get_prep_value(value)
  File "/Users/lorin/.virtualenvs/myvenv/src/django/django/db/models/fields/__init__.py", line 712, in get_prep_value
    return self.to_python(value)
  File "/Users/lorin/.virtualenvs/myvenv/src/django/django/db/models/fields/__init__.py", line 684, in to_python
    raise exceptions.ValidationError(msg)
django.core.exceptions.ValidationError: [u"'2013-01-24 21:31:16.235381' value has an invalid date format. It must be in YYYY-MM-DD format."]

from freezegun.

hexsprite avatar hexsprite commented on July 16, 2024

@lorin it ain't pretty but it works for me...

not sure if there's a more elegant way of getting around an isinstance() check in the original code...

import datetime
import freezegun
import logging
import warnings
from django.conf import settings
from django.db.models.fields import DateField, DateTimeField
from django.utils import timezone

log = logging.getLogger(__name__)


def monkeypatch_fields_for_freezegun():
    _original_datefield_to_python = DateField.to_python
    _original_datetimefield_to_python = DateTimeField.to_python

    log.warn("monkey patching Django Date fields for freezegun support")

    def _datefield_to_python(self, value):
        if isinstance(value, freezegun.api.real_datetime):
            if settings.USE_TZ and timezone.is_aware(value):
                # Convert aware datetimes to the default time zone
                # before casting them to dates (#17742).
                default_timezone = timezone.get_default_timezone()
                value = timezone.make_naive(value, default_timezone)
            return value.date()
        if isinstance(value, freezegun.api.real_date):
            return value
        return _original_datefield_to_python(self, value)

    def _datetimefield_to_python(self, value):
        if isinstance(value, freezegun.api.real_datetime):
            return value
        if isinstance(value, freezegun.api.real_date):
            value = datetime.datetime(value.year, value.month, value.day)
            if settings.USE_TZ:
                # For backwards compatibility, interpret naive datetimes in
                # local time. This won't work during DST change, but we can't
                # do much about it, so we let the exceptions percolate up the
                # call stack.
                warnings.warn("DateTimeField received a naive datetime (%s)"
                              " while time zone support is active." % value,
                              RuntimeWarning)
                default_timezone = timezone.get_default_timezone()
                value = timezone.make_aware(value, default_timezone)
            return value
        return _original_datetimefield_to_python(self, value)

    DateField.to_python = _datefield_to_python
    DateTimeField.to_python = _datetimefield_to_python

monkeypatch_fields_for_freezegun()

from freezegun.

spulec avatar spulec commented on July 16, 2024

now() not accepting timezones is definitely a bug and should be fixed.

I'm not able to recreate the django saving bug though. isinstance() checks should all pass for the current version of freezegun.

from freezegun.

hexsprite avatar hexsprite commented on July 16, 2024

if I get a moment I'll try to create a minimal test case that demonstrates the isinstance() issue

from freezegun.

spulec avatar spulec commented on July 16, 2024

That would be great. Thanks.

from freezegun.

spulec avatar spulec commented on July 16, 2024

I think that a lot of these issues should be fixed in the newest release. Freezegun now only mocks datetime/date when activated. I haven't actually tested with django yet though.

from freezegun.

spulec avatar spulec commented on July 16, 2024

I think this should all be fixed with the latest release.

from freezegun.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo 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.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.