Skip to content

Problems with mock related to datetime.utcnow() #94497

Closed as not planned
Closed as not planned
@jefer94

Description

@jefer94

Feature or enhancement

Is necessary fix the function isinstance or MagicMock can work together, of instead can mock a method of inmutable class a least when you have in a development environment

# django.utils.timezone

def now():
    return datetime.utcnow().replace(tzinfo=utc)
# django.contrib.auth.models

class User:
    date_joined = models.DateTimeField(_('date joined'), default=timezone.now)
# django.db.models.fields

class DateTimeField:
    def to_python(self, value):
        if isinstance(value, datetime.datetime):
            ...
# test case 1

# TypeError: cannot set 'utcnow' attribute of immutable type 'datetime.datetime'
@patch('datetime.datetime.utcnow', MagicMock())  
def test_():
    ...
# test case 2

class DatetimeMock(datetime.datetime):
    @classmethod
    def utcnow(cls):
        ...

# E       - [{'date_joined': DatetimeMock(2022, 7, 1, 0, 0, tzinfo=<UTC>),
# E       ?                  ^       ^^^^             ^  ^
# E       
# E       + [{'date_joined': datetime.datetime(2022, 7, 1, 16, 47, 39, 294114, tzinfo=<UTC>),
# E       ?                  ^       ^^^^^^^^^             ^^  ^^ ++++++++++++
@patch('datetime.datetime.utcnow', DatetimeMock)  
def test_():
    ...
# test case 3

mock = MagicMock(wraps=datetime.datetime)
mock.utcnow.return_value = NOW

# TypeError: Mixer (authenticate.UserInvite): isinstance() arg 2 must be a type, a tuple of types, or a union
@patch('datetime.datetime', mock)
def test_():
    ...

Pitch

I just need can mock it, I think the solution of pass this issue to the team of @django is a bad idea because this problem should be replicated by other teams and the root the problem is in python, not in the other teams

Metadata

Metadata

Assignees

No one assigned

    Labels

    stdlibPython modules in the Lib dirtype-featureA feature request or enhancement

    Projects

    Status

    Done

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions