Coding Journal

My journey to become a Full Stack Developer

cover image

First tests in my Django app

Aug. 4, 2019, 7:33 p.m.

When I started creating the blog app I knew nothing about testing. But as I started learning testing  I decided to add tests to the app gradually. So now, writing these blog posts and recreating the app for this purpose, I decided to write tests. It would be better to use Test Driven Development approach, but as I've already got two views, I'm writing the tests now.  
My tests are by no means perfect. But I'm writing them here to have notes also for myself. 

The first tests are really simple.

I'm checking if the response from the page has status 200 and I'm also checking if the correct temple is used by Django. 


In the app, we have already got a tests.py file and in the file, we have also imported TestCase form Django tests. Django TestCase is a subclass of Python's unittest TestCase class. 


First I'm creating a class and a method. The name of the method must start with test_. 

So I want to check if the main page uses base.html file. 

I'm writing a very similar test to test About page 


I wrote two classes and every class has got a method. In both classes, methods are very similar.

I'm using Django test client that works as a web browser and allows me to test my views. And I'm making a GET request on the path ('/') in the HomePageTest and ('/about/') in the AboutPageTest.

Then I'm using unittest method self.assertEqual  to test if our response is equal to 200. HTTP 200 is a success response. 
Them I'm checking with self.assertTemplateUsed method, if the template used in response is 'base.html' in the first test and 'blog/about.html' in the second test. 

In command line I'm writing:

and 2 tests are running and passing. 


Each dot below "System check identified no issues (0 silenced)." represents the passed test. 

If I remove one slash from the second test in self.client.get('/about') one of the tests won't pass and the output will be 

Now  we've got letter F for fail and one dot for the passed test.
We can also read which test failed and there is a piece of information about the error. 

The more I'm learning about tests the more convinced I am to write them. And I really regret not learning how to write them much earlier. 

 

Tagged in : django blog-tutorial

my photo

written by

Makneta

Avid learner, Python / Django and CSS Art ethusiast.

Similar posts

All posts