Writing Your First Test
Writing a simple function to test
Suppose a utils.py file defines a function that doubles a number. This is a plain, predictable piece of logic that makes an ideal first test.
Example: Writing a simple function to test
Suppose a utils.py file defines a function that doubles a number. This is a plain, predictable piece of logic that makes an ideal first test.
def double(value):
return value * 2
{# Django-only code -- models.py/views.py/urls.py/settings.py
snippets, or template markup using Django template tags/variables
-- can't run standalone via Judge0 or the browser preview, since
it needs a real Django project. Only this course's pure-Python
examples (example_lang == 'python', no Django imports) are
actually runnable, so those still get the button below. #}
Writing the test method
The test imports the function, calls it with a known input, and asserts the output equals the expected result using assertEqual.
Note: Name the test after the behavior it checks, e.g. test_double_returns_twice_the_value.
Example: Writing the test method
The test imports the function, calls it with a known input, and asserts the output equals the expected result using assertEqual.
from django.test import TestCase
from myapp.utils import double
class DoubleTests(TestCase):
def test_double_returns_twice_the_value(self):
self.assertEqual(double(5), 10)
{# Django-only code -- models.py/views.py/urls.py/settings.py
snippets, or template markup using Django template tags/variables
-- can't run standalone via Judge0 or the browser preview, since
it needs a real Django project. Only this course's pure-Python
examples (example_lang == 'python', no Django imports) are
actually runnable, so those still get the button below. #}
Running the test
python manage.py test runs every discovered test in the project and prints a dot for each pass, or a traceback for each failure.
Example: Running the test
python manage.py test runs every discovered test in the project and prints a dot for each pass, or a traceback for each failure.
python manage.py test
⚠️ Run this command in your terminal.
- Testing implementation details (internal variable names) instead of observable behavior (return values, output).
- Writing a test with no assertion at all, so it always passes no matter what.
- Not running the test after writing it, so a typo goes unnoticed.
- A test method calls code with known input and asserts the result using self.assertX methods.
- Every test should focus on one specific behavior.
- Run python manage.py test after writing a test to confirm it actually executes and passes.
- A good first test is simple: check that a function returns what you expect.
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: