Models DateField to_python method no longer supports mock dates.
|Reported by:||hugo@…||Owned by:||auvipy|
|Component:||Database layer (models, ORM)||Version:||1.6|
|Cc:||hugo@…, charettes||Triage Stage:||Accepted|
|Has patch:||yes||Needs documentation:||no|
|Needs tests:||no||Patch needs improvement:||yes|
In between 1.4 and 1.5 a change was made to django.db.models.fields.DateField.to_python method that broke the use of mock dates in unit testing. This makes testing of models with mock dates impossible.
The to_python method in the DateField (and DateTimeField) is used to parse field input into the relevant python type. In the case of a DateField this involves checking for datetime.date and datetime.datetime types, and in the event of neither of these matching, it is assumed that the input is a string and an attempt is made to parse the value.
The parse_date function internally performs a regex match, and therefore implicitly expects a string argument. If the argument is not a string an error is raised.
This causes a problem when attempting to mock a date or datetime object for testing purposes. Using the method described (see http://bit.ly/1bYLdIC) tests will fail as the FakeDate mock fails all of the above (it is neither datetime nor date, and is not a string). I have submitted a question on StackOverflow (see http://bit.ly/187sUU9) which describes a concrete example.
In Django 1.4.x a mock Date / DateTime object could be used as prior to the parse_date check a call was made to "django.utils.encoding.smart_str", which converted the FakeDate to a parseable string.
Steps to reproduce:
Create a model with a DateField
Create a test that saves the model using datetime.date.today() as the field value (should pass)
Create a second test that uses a FakeDate (see http://bit.ly/1bYLdIC) to mock the datetime.date and provide a fake today() implementation
This second test should fail with "TypeError: expected string or buffer", as the FakeDate cannot be parsed.
Repeat this test with the 1.4.x branch - test should pass.
Change History (27)
comment:1 Changed 17 months ago by hugo@…
- Component changed from Uncategorized to Database layer (models, ORM)
- Needs documentation unset
- Needs tests unset
- Patch needs improvement unset
Changed 17 months ago by hugorodgerbrown
comment:25 Changed 6 weeks ago by auvipy
- Owner changed from nobody to auvipy
- Status changed from new to assigned