Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pytest won't convert date field to datetime.date object in Django

I have this simple query written in Django and I want to run my tests with pytest.

results = (self.base_query
                   .order_by('service_date')
                   .extra({'sd': "date(service_date)"})
                   .values('sd')
                   .annotate(created_count=Sum('pax_number')))

print 'RESULTS: ', results

When I run my tests with Django's test runner: python manage.py test, I get the expected result:

RESULTS:  <QuerySet [{'created_count': 14, 'sd': datetime.date(2017, 2, 24)}]>

But when I do it with pytest -s, I get:

RESULTS:  <QuerySet [{'created_count': 14, 'sd': u'2017-02-24'}]>

Why isn't pytest converting dates like Django's test runner?

like image 313
intelis Avatar asked Mar 08 '17 07:03

intelis


1 Answers

I get the nice datetime.date() behaviour when I do the query against a postgresql database, but the u'2017-02-24' behaviour when running against a SQLLite database backend, so I expect that the problem is that for whatever reason when you are running with pytest you are using a different database backend from when you are running from python manage.py test.

Update (after a small bit of research)

SQLLite does not have a native date time data type, and can store date time values using TEXT, REAL or INTEGER data types. You then use the date functions to display your date as you want.

In particular the date() SQLLite function returns a string, which is in fact equivalent to strftime('%Y-%m-%d', ...). So I would expect the python library providing bindings to this also to return a string.

Normal SQL / postgresql however does have native date time types. And the date() function there returns a date object. So it makes sense that the python library handling these database types would return a datetime.date object too.

like image 183
daphtdazz Avatar answered Sep 28 '22 06:09

daphtdazz