← Back to team overview

canonical-django team mailing list archive

Re: Django testing best practices

 

James Westby:
> We weren't sure about appropriate tests for the basics of models, such
> as creating an object and checking that it has an attribute that was
> defined via a field. This is hampered as in my testing some things
> about the field, such as limits on the length of a string don't seem
> to be enforced in a test environment (with the sqlite3 backend).

This is a difficult problem, and one I've run into a few times.  The
general permissiveness of sqlite3 (and the lack of reimplementation of
the various constraints within the ORM) has led to situations where I've
deployed a fixture to staging only to find it won't work with the limits
I put on my models.  I have, in some cases, re-implemented length
constraints in my views.  

> As we add more behaviour to models we will be testing that, and it was
> agreed that this was where most of the logic should be pushed too, so
> views are as simple as possible.

I have this feeling that models ought to have more methods than we
typically give them.  Often when we refactor some complicated query
logic out of a view function, we leave it in our views.py; but perhaps
we ought to be moving more testable representation logic into our
models.

This specifically is something that has little in the way of good
concrete examples out in the wild.  None of the tutorials for Django put
much of anything beyond fields and __unicode__() in the models, for
example.

models.py is also "special" in the django world because it gets imported
at startup, while the views are only brought in when the urlconfs first
dispatch to them.  That's why, for example, you tend to put your
event/signal handlers in models.py.  I feel like there's room for
improved hygiene here.

> Django has facilities for testing that a view rendered using a
> particular template, and the paramaters that were passed to a template,
> and we agreed that it would be worthwhile trying to take advantage of
> that.

The Django test client is superb, and I love it to bits.

> If there are lots of ideas then I will collate them in to a wiki page
> that we can maintain we learn more.

I would love a good wiki resource for this, maybe even out on a public
wiki somewhere.

-- 
Nick Moffitt



Follow ups

References