Merge pull request #2254 from bagerard/fix_complex_datetime_field_invalid_string_set

fix complex datetime field invalid string set
This commit is contained in:
Bastien Gérard 2020-04-25 22:17:20 +02:00 committed by GitHub
commit f5f8b730b5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 22 additions and 1 deletions

View File

@ -8,6 +8,7 @@ Development
- (Fill this out as you fix issues and develop your features).
- ATTENTION: Drop support for Python2
- Add Mongo 4.0 to Travis
- Fix error when setting a string as a ComplexDateTimeField #2253
- Bump development Status classifier to Production/Stable #2232
- Improve Queryset.get to avoid confusing MultipleObjectsReturned message in case multiple match are found #630
- Fixed a bug causing inaccurate query results, while combining ``__raw__`` and regular filters for the same field #2264

View File

@ -677,7 +677,10 @@ class ComplexDateTimeField(StringField):
super().__set__(instance, value)
value = instance._data[self.name]
if value is not None:
instance._data[self.name] = self._convert_from_datetime(value)
if isinstance(value, datetime.datetime):
instance._data[self.name] = self._convert_from_datetime(value)
else:
instance._data[self.name] = value
def validate(self, value):
value = self.to_python(value)

View File

@ -4,6 +4,8 @@ import itertools
import math
import re
import pytest
from mongoengine import *
from tests.utils import MongoDBTestCase
@ -191,3 +193,18 @@ class ComplexDateTimeFieldTest(MongoDBTestCase):
fetched_log = Log.objects.with_id(log.id)
assert fetched_log.timestamp >= NOW
def test_setting_bad_value_does_not_raise_unless_validate_is_called(self):
# test regression of #2253
class Log(Document):
timestamp = ComplexDateTimeField()
Log.drop_collection()
log = Log(timestamp="garbage")
with pytest.raises(ValidationError):
log.validate()
with pytest.raises(ValidationError):
log.save()