Introduction to Django REST Framework, an easy way to build REST framework in Django
Testing In Django
-
Upload
daniel-greenfeld -
Category
Self Improvement
-
view
2.652 -
download
2
description
Transcript of Testing In Django
Testing in Django
Why and how you should test in Django
Code without tests is broken as designed
Jacob Kaplan-Moss
The Pinax Example
http://code.pinax.com/tasks Problem: Anyone with account could edit ticket status.
The Pinax Example
Example of why this needed to be changed: • User adds ticket to a release already under feature
freeze. • User moves it to resolved.
• Core developers have to remember every ticket.
The Pinax Example
Easy fix: • Django already supports groups and permissions
• add a new permission method to the state_transition
tuple
The Pinax Example
Works!• Looks fine in my browser!
• Looks fine in James Tauber's browser!
Flashback
Pycon 2009
• Daniel Mizyrycki, pythonista and hang glider enthusiast
• Nixes the ability for anonymous users to add/modify
tasks • Writes two tests to confirm his change works
ERROR - Test Fail!
The Pinax Example
Daniel's tests toss out an error!
• Anonymous users break • is_task_manager method doesn't allow for task
viewing by anonymous users • Fix is easy:
Code without tests is broken as designed
Jacob Kaplan-Moss
What about...
Selenium...Windchill...Nose...Twill...Your test system of choice...
All good stuff but outside the scope of this presentation.
Doctest or Unittest?
My pros and cons of Doctest
Pros • Easy to learn
• Documents your code
• Is pretty with RST
Cons • Kinda hard to maintain
• Weirdness on
assertions
My pattern for Django unit tests
• Via Django Admin, add some sample data • In tasks application, mkdir fixtures
• Via command line:
./manage.py dumpdata tasks >
apps/tasks/fixtures/test_tasks.json
My pattern for Django unit tests
1.mkdir 'tests' folder in tasks2.touch test_authentication.py in tasks/tests 3.touch __init__.py folder in tasks/tests4.edit __init__.py to include:
from test_authentication.py import *
My pattern for Django unit tests
The test setup:
My pattern for Django unit tests
The test:
My pattern for Django unit tests
Run the test!
python manage.py test tasks
A bigger test
See how each method I write tests a different thing. Seems like a good pattern right now.
But you always find your old tests look silly.
You get better at writing tests the more you do it.
Things I like about tests
• Avoidance of embarrassment • Looks good
• The rush
Questions? Comments?