Exercise 7.1

Objectives:

  • Learn the basics of using Python’s unit testing tools.

Files Created:

  • teststock.py

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

(a) Preliminaries

In earlier exercises, you wrote a file stock.py that contained a Stock class. For this exercise, it assumed that you’re using the code written for Exercise 6.2. If, for some reason, that’s not working, you might want to copy the solution from Solutions/6_2 to your working directory.

(b) Writing Unit Tests

In a separate file teststock.py, write a set a unit tests for the Stock class. To get you started, here is a small fragment of code that tests instance creation:

# 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()

Run your unit tests. You should get some output that looks like this:

.
 ----------------------------------------------------------------------
Ran 1 tests in 0.000s

OK

Once you’re satisifed that it works, write additional unit tests that check for the following:

  • Make sure the s.cost property returns the correct value (49010.0)

  • Make sure the s.sell() method works correctly. It should return the number of shares remaining and decrement the value of s.shares accordingly.

  • Make sure that the s.shares attribute can’t be set to a non-integer value.

For the last part, you’re going to need to check that an exception is raised. An easy way to do that is with code like this:

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

(c) Challenge

Write a separate set of unit tests for the read_portfolio() function in stock.py

Links