Skip to content

Marina Mele's site

Reflections on family, values, and personal growth

Menu
  • Home
  • About
Menu

Django testing: Doctests and Unittests

Posted on March 9, 2014September 26, 2014 by Marina Mele

In this post, I introduce testing in Django and discuss the two common ways of performing tests: using Doctests and using the library unittest.

You’ll learn how to start writing your first test as well as the main differences between these two ways of testing.

Note: this post uses the old Test Suit, used in Django < 1.6. This is because I prefer how it discovers my test files. If you don’t like it… wait for a post on Nose, which will come soon 🙂

Introduction to Django Testing

There are two different types of tests:

– Unit tests are isolated tests that cover a very small and specific area of code, like a single function of your application.

– Integration tests are larger tests that cover multiple aspects of your application, and ensure that all its functionalities are well integrated with each other.

I recommend you focus on unit tests. They are much easier to write and debug, and the more unit tests you have, the less integration tests you’ll need to write. Moreover, unit tests should be faster, so write a looot of them 🙂

You’ll see that inside each app folder of your project there is a tests.py file. Here, we will substitute this file by a directory named tests that will contain our tests, grouped in different files depending on what they are testing, i.e. models, views, forms, etc. Don’t forget to create an empty __init__.py file inside this folder, to indicate it is as a module.

$ cd myapp
$ rm tests.py
$ mkdir tests
$ cd tests
$ touch __init__.py tests_forms.py tests_models.py tests_views.py

To run your tests you should type:

$ python manage.py test myapp

In my case, I got an error saying

Creating test database for alias ‘default’…
Got an error creating the test database: permission denied to create database

Type ‘yes’ if you would like to try deleting the test database ‘test_myprojectdb’, or ‘no’ to cancel: 

This was because I was using PostgreSQL and the postgres user defined in my settings.py, with a given username, file didn’t have permissions to create a database. If it your case, you can solve this by giving that user the requested permissions:

$ psql -h localhost
# ALTER USER username CREATEDB;
# \q

This time, your tests should run correctly.

Testing-terminal


This post focuses on testing using the old Test Suite. If you are using Django 1.6 you can obtain the old behavior by including the following in your settings.py file

TEST_RUNNER = ‘django.test.simple.DjangoTestSuiteRunner’

There are to different ways of writing a test using: Doctests and Unittests. We’ll explain each of them in detail.

Doctests

Doctests are tests written inside a string. They can be placed either in one of the test files inside the test folder, or in the models.py file. These two places are the ones that the test runner will look for doctests. An example of such a test is given in the Django docs:


File: marinamele_doctest_django_example.py
------------------------------------------

# Based on Example in https://docs.djangoproject.com/en/1.5/topics/testing/doctests/

from django.db import models

class Animal(models.Model):
    """
    An animal that makes noise

    # Create an animal
    >>> lion = Animal.objects.create(name="lion", sound="roar")
    
    # Test it makes the correct noise
    >>> lion.speak()
    'The lion says "roar"'
    """
    name = models.CharField(max_length=20)
    sound = models.CharField(max_length=20)

    def speak(self):
        return 'The %s says "%s"' % (self.name, self.sound)
  

Notice that the doctest format is simply the output of your Pyhton shell. Therefore, if you are testing in your shell and it works, you can make a simple copy and paste to create the doctest 🙂

If you place doctests in the tests folder, in a file named mydoctests.py, you’ll have to edit the __init__.py file to indicate the test runner that that file contains doctests. Open the __init__.py file and write:

import mydoctests
__test__ = {‘Doctest’: mydoctests}

Moreover, when you run your doctests with

$ python manage.py test myapp

you will see something like

Ran 1 test in 0.005s OK

which indicates that all your doctests were ok. Yes, the test runner sees all your doctests as a single one test. This is why I like better the second option for writing tests 🙂

Unittests

On the other hand, we can write tests using the library unittest. An example of a unit test is:


File: marinamele_unittest_example.py
------------------------------------

from django.test import TestCase

class TestExample(TestCase):
  """
  Here you can define multiple tests, but all must begin
  with test_
  """
  def setUp(self):
    """
    Optional. Define here your initial setup for your tests
    """
    self.a = "my test"
  
  def tearDown(self):
    """
    Optional. This will be executed after running your tests
    """
    del self.a
    
  def test_example(self):
    self.assertEqual("my test", self.a)
    
  def test_example2(self):
    b = 2
    self.assertNotEqual(b, "two")


Note that we import django.test.TestCase, which enhances the unittest.TestCase class, and then create our tests as functions. We can also use the setUp function to define a initial context in which all these tests will be run and an ending tearDown function that will be executed at the end of each test.

Also mention that your test functions in each TestCase instance has to begin with test_. Moreover, in order to the test runner find your Unittests, you must import the file that contains your unittests in the __init__.py file. For example, if you write unittests in the tests_models.py you should include in your __init__.py file the following line:from tests_models import *When you run your tests with$ python manage.py test myappyou will see if each of your unittest has passed or not, in contrast with Doctests.

Hope it is useful! 🙂
+1 if you want to read more about testing in Django!

Learn how to perform Doctests and Unittest in #Django http://t.co/fwZjpITgOk
— Marina Mele (@Marina_Mele) March 9, 2014

 

Marina Melé
Marina Mele

Marina Mele has experience in artificial intelligence implementation and has led tech teams for over a decade. On her personal blog (marinamele.com), she writes about personal growth, family values, AI, and other topics she’s passionate about. Marina also publishes a weekly AI newsletter featuring the latest advancements and innovations in the field (marinamele.substack.com)

Leave a Reply Cancel reply

You must be logged in to post a comment.

Categories

  • Personal Growth and Development
  • Artificial Intelligence
  • Mindful Parenting and Family Life
  • Productivity and Time Management
  • Mindfulness and Wellness
  • Values and Life Lessons
  • Posts en català
  • Other things to learn

Recent Posts

  • BlueSky Social – A Sneak Peek at the Future of Social Media
  • The Incredible Journey of AI Image Generation
  • AI and Fundamental Rights: How the AI Act Aims to Protect Individuals
  • Overcoming Regrets: Finding the Strength to Move Forward
  • Thinking Outside the Box: Creative Problem-Solving with Critical Thinking

RSS

  • Entries RSS
Follow @marina_mele
  • Cookie Policy
  • Privacy Policy
©2023 Marina Mele's site | Built using WordPress and Responsive Blogily theme by Superb
This website uses cookies to improve your experience. If you keep navigating through this website, we'll assume you're ok with this, but you can opt-out if you wish.Accept Read More
Privacy & Cookies Policy

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may affect your browsing experience.
Necessary
Always Enabled
Necessary cookies are absolutely essential for the website to function properly. This category only includes cookies that ensures basic functionalities and security features of the website. These cookies do not store any personal information.
Non-necessary
Any cookies that may not be particularly necessary for the website to function and is used specifically to collect user personal data via analytics, ads, other embedded contents are termed as non-necessary cookies. It is mandatory to procure user consent prior to running these cookies on your website.
SAVE & ACCEPT