Skip to content
This repository has been archived by the owner on Sep 17, 2023. It is now read-only.

03a Tests

scotwk edited this page May 13, 2015 · 1 revision

Write a test

In your note app a tests.py file was created for you, but it is empty. Time to make your first test.

import datetime

from django.utils import timezone
from django.test import TestCase

from .models import Note

class NoteMethodTests(TestCase):

    def test_was_published_recently(self):
    """
    was_published_recently() should return False for notes whose pub_date is in the future.
    """
        time = timezone.now() + datetime.timedelta(days=30)
        future_note = Note(pub_date=time)
        self.assertEqual(future_note.was_published_recently(), False)

Run the test

$ ./manage.py test
Creating test database for alias 'default'...
F
======================================================================
FAIL: test_was_published_recently (note.tests.NoteMethodTests)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/vagrant/Projects/elevennote/elevennote/note/tests.py", line 18, in test_was_published_recently
     self.assertEqual(future_note.was_published_recently(), False)
AssertionError: True != False

----------------------------------------------------------------------
Ran 1 test in 0.001s

FAILED (failures=1)
Destroying test database for alias 'default'...

Note the "creating the test database" part. Whenever you run a test Django creates a new test database and destroys it after tests are done running. This means your tests will never impact your real database.

Fix the model

Fix your method in note/models.py so that it doesn't think articles in the future have been published:

def was_published_recently(self):
    now = timezone.now()
    return now - timedelta(days=1) <= self.pub_date <= now

Re-run the test

$ ./manage.py test

Note that you can also run one app's test like:

$ ./manage.py test note