Paul Watts
First Officer, JOLT Labs.


https://github.com/paulcwatts/codefellows-django-testing


python manage.py test Running all tests:
python manage.py test
Running tests from one app
python manage.py test notes
Running tests from one class:
python manage.py test notes.tests.ViewTest
Running a single test:
python manage.py test notes.tests.ViewTest.test_empty_list
class ModelsTest(TestCase):
def test_ordering(self):
"Notes are ordered most recent first."
now = datetime.utcnow()
# We want to be deliberate about the timestamps, so we're not
# at the mercy of the test timing.
note1 = Note.objects.create(note='Older note', timestamp=now - timedelta(days=1))
note2 = Note.objects.create(note='Newer note', timestamp=now)
self.assertQuerysetEqual(Note.objects.all(), [note2.pk, note1.pk],
transform=lambda note: note.pk)

Error
Traceback (most recent call last):
File "/Users/paulw/Work/me/codefellows-django-testing/notes/tests/test_models.py", line 18, in test_ordering
transform=lambda note: note.pk)
File "/Users/paulw/.virtualenvs/codefellows/lib/python2.7/site-packages/django/test/testcases.py", line 827, in assertQuerysetEqual
raise ValueError("Trying to compare non-ordered queryset "
ValueError: Trying to compare non-ordered queryset against more than one ordered values
class Note(models.Model):
note = models.CharField(max_length=2000)
timestamp = models.DateTimeField(auto_now=True)
class Meta:
ordering = ('-timestamp',)
def get_absolute_url(self):
return reverse('note-detail', kwargs={'pk': self.pk})
def __unicode__(self):
return self.note
When you can't test using Django
JavaScript-heavy sites
Single page applications
class BrowserTest(LiveServerTestCase):
@classmethod
def setUpClass(cls):
cls.selenium = getattr(webdriver, WEBDRIVER_CLASS_NAME)()
super(BrowserTest, cls).setUpClass()
@classmethod
def tearDownClass(cls):
cls.selenium.quit()
super(BrowserTest, cls).tearDownClass()
def test_autofocus_add(self):
"Tests that the textarea in the add form is autofocused."
self.selenium.get('{0}{1}'.format(self.live_server_url, reverse('note-add')))
textarea = self.selenium.find_element_by_name("note")
active = self.selenium.switch_to_active_element()
self.assertEqual(textarea, active,
"textarea should be focused, but {0} is instead".format(
active.tag_name
))
Traceback (most recent call last): File "/Users/paulw/Work/me/codefellows-django-testing/notes/tests/test_browser.py", line 39, in test_autofocus_add active.tag_name AssertionError: textarea should be focused, but body is instead
class NoteForm(forms.ModelForm):note = forms.CharField(widget=forms.Textarea(attrs={'autofocus': ''}))
Useful when creating reusable packages
Tests setup.py
Easily test against different environments/Django versions
Python 3.3 support!
Formatting checking with PEP8/flake8


By Paul Watts
My slides for the "Testing Django" talk at Code Fellows. Example code: https://github.com/paulcwatts/codefellows-django-testing