Five testing questions
Might it be better to create a new
Userand assign toself.userinsetUpClassrather thansetUp? From what I can tell, that would meanUser.objects.create(username='test')being executed only once when tests are run. (Perhaps any gain is negligable)Is the purpose of
self.assertTrue(isinstance(post, Post))purely learning, or might you have this assertion in production test code?In
test_list_viewI was wondering how you might go about testing that the correct number of items is displayed, e.g. create three posts and check that three are rendered. I suppose the obvious way would be to check for three<li>HTML tags inreq.rendered_content, but that seems a bit wrong. How would you do this? (Is it even a good test to write?)With reference to the lesson text "When our code raises Http404, that actually just causes Django to render the 404 template and provide a status_code of 404. It doesn't, however, bubble the Http404 error all the way up to our test runner or the requesting user.", what is meant by "requesting user"?
Why does running the tests involve running the migrations? It seems like it'd be sensible for the test runner to simply do
syncdb-if you see what I mean?
Thanks
Answers
Perhaps? Knowing about, and using
setUp, and it's effect of being run before each test, is useful and a more common approach, so that's why it was covered. My goal isn't to teach you to be excellent testers (or really master any one area) but to be decent Django developers all around :) There will always be optimizations to any technique.It's just a good sanity check, really. Make sure the instance is what you think it is. This comes in pretty handy if you have a lot of metaclasses or extended models, too.
You could check the context for the
object_listobject and check it's length. I think that's atreq.contextbut I could be wrong. I haven't messed with that variable lately so I'm fuzzy on the name.The user that's requesting the view. This'll either be a logged in user or an anonymous user. They don't get the actual exception that
Http404extends, they get a response with a status code of 404 and a template.I agree, it would make more sense. That's not how the test runner currently does it, though. With all of the changes coming to South and Django in the near future, this is likely to change, though.