Python Unittest Module

PythonPythonBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

Objectives:

  • Learn how to use Python's unittest module

Files Created: teststock.py

In this exercise, you will explore the basic mechanics of using Python's unittest modules.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) python(("`Python`")) -.-> python/FileHandlingGroup(["`File Handling`"]) python(("`Python`")) -.-> python/ControlFlowGroup(["`Control Flow`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) python(("`Python`")) -.-> python/ModulesandPackagesGroup(["`Modules and Packages`"]) python(("`Python`")) -.-> python/ObjectOrientedProgrammingGroup(["`Object-Oriented Programming`"]) python/BasicConceptsGroup -.-> python/comments("`Comments`") python/FileHandlingGroup -.-> python/with_statement("`Using with Statement`") python/ControlFlowGroup -.-> python/conditional_statements("`Conditional Statements`") python/ControlFlowGroup -.-> python/for_loops("`For Loops`") python/DataStructuresGroup -.-> python/lists("`Lists`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/FunctionsGroup -.-> python/function_definition("`Function Definition`") python/ModulesandPackagesGroup -.-> python/importing_modules("`Importing Modules`") python/ModulesandPackagesGroup -.-> python/standard_libraries("`Common Standard Libraries`") python/ObjectOrientedProgrammingGroup -.-> python/classes_objects("`Classes and Objects`") python/ObjectOrientedProgrammingGroup -.-> python/encapsulation("`Encapsulation`") python/FunctionsGroup -.-> python/build_in_functions("`Build-in Functions`") subgraph Lab Skills python/comments -.-> lab-132508{{"`Python Unittest Module`"}} python/with_statement -.-> lab-132508{{"`Python Unittest Module`"}} python/conditional_statements -.-> lab-132508{{"`Python Unittest Module`"}} python/for_loops -.-> lab-132508{{"`Python Unittest Module`"}} python/lists -.-> lab-132508{{"`Python Unittest Module`"}} python/tuples -.-> lab-132508{{"`Python Unittest Module`"}} python/function_definition -.-> lab-132508{{"`Python Unittest Module`"}} python/importing_modules -.-> lab-132508{{"`Python Unittest Module`"}} python/standard_libraries -.-> lab-132508{{"`Python Unittest Module`"}} python/classes_objects -.-> lab-132508{{"`Python Unittest Module`"}} python/encapsulation -.-> lab-132508{{"`Python Unittest Module`"}} python/build_in_functions -.-> lab-132508{{"`Python Unittest Module`"}} end

Preliminaries

In previous exercises, you created a file stock.py that contained a Stock class. In a separate file, teststock.py, define the following testing code:

## teststock.py

import unittest
import stock

class TestStock(unittest.TestCase):
    def test_create(self):
        s = stock.Stock('GOOG', 100, 490.1)
        self.assertEqual(s.name, 'GOOG')
        self.assertEqual(s.shares, 100)
        self.assertEqual(s.price, 490.1)

if __name__ == '__main__':
    unittest.main()

Make sure you can run the file:

python3 teststock.py
.
------------------------------------------------------------------```
Ran 1 tests in 0.001s

OK

Unit testing

Using the code in teststock.py as a guide, extend the TestStock class with tests for the following:

  • Test that you can create a Stock using keyword arguments such as Stock(name='GOOG',shares=100,price=490.1).
  • Test that the cost property returns a correct value
  • Test that the sell() method correctly updates the shares.
  • Test that the from_row() class method creates a new instance from good data.
  • Test that the __repr__() method creates a proper representation string.
  • Test the comparison operator method __eq__()

Unit tests with expected errors

Suppose you wanted to write a unit test that checks for an exception. Here is how you can do it:

class TestStock(unittest.TestCase):
    ...
    def test_bad_shares(self):
        s = stock.Stock('GOOG', 100, 490.1)
        with self.assertRaises(TypeError):
             s.shares = '50'
    ...

Using this test as a guide, write unit tests for the following failure modes:

  • Test that setting shares to a string raises a TypeError
  • Test that setting shares to a negative number raises a ValueError
  • Test that setting price to a string raises a TypeError
  • Test that setting price to a negative number raises a ValueError
  • Test that setting a non-existent attribute share raises an AttributeError

In total, you should have around a dozen unit tests when you're done.

Important Note

For later use in the course, you will want to have a fully working stock.py and teststock.py file. Save your work in progress if you have to, but you are strongly encouraged to copy the code from Solutions/5_6 if things are still broken at this point.

We're going to use the teststock.py file as a tool for improving the Stock code later. You'll want it on hand to make sure that the new code behaves the same way as the old code.

Summary

Congratulations! You have completed the Python Unittest Module lab. You can practice more labs in LabEx to improve your skills.

Other Python Tutorials you may like