Creating an application without test cases is half done. Even though you take a lot of care while developing the application, there might be a chance of encountering errors at some point. Writing test cases will always leave us at a safe point.
In this section, we are going to write unit test cases for some tasks in our survey application. Add the following test case code to survey/tests.py
file:
import unittest import requests from bs4 import BeautifulSoup from survey import db from survey.models import Question class TestSurveyApp(unittest.TestCase): def setUp(self): db.drop_all() db.create_all() def test_defaults(self): question = Question('Are you from India?') db.session.add(question) db.session.commit() self.assertEqual(question.number_of_yes_votes, 0) self.assertEqual(question.number_of_no_votes, 0) self.assertEqual(question.number_of_maybe_votes, 0) def test_votes(self): question = Question('Are you from India?') question.vote('yes') db.session.add(question) db.session.commit() self.assertEqual(question.number_of_yes_votes, 1) self.assertEqual(question.number_of_no_votes, 0) self.assertEqual(question.number_of_maybe_votes, 0) def test_title(self): title = "Welcome to Survey Application" response = requests.get("http://127.0.0.1:5000/") soup = BeautifulSoup(response.text) self.assertEqual(soup.title.get_text(), title)
We can see the following from the preceding block of code:
setUp()
method in the TestSurveyApp
drops all the existing tables and creates them for every test case.test_defaults
test case will test the defaults of the Question
object that was created. If the defaults do not match the expected inputs, the test case fails.test_votes()
will up-vote a specific choice for a survey and test whether the voted choice gets incremented and other choices remain the same.test_title()
will test whether the title of a response matches with the expected title. It uses the BeautifulSoup
library to access the title from the response contents.3.137.212.71