This is an archived version of the course. Please find the latest version of the course on the main webpage.

Chapter 8: Unit testing

Running multiple tests

face Josiah Wang

Earlier in Lesson 10, we defined a new BattleCar. And since we are obviously good software engineers, we wrote a test case to test the .attack() method.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import unittest

from car import Wheel, Car, BattleCar

class BattleCarTest(unittest.TestCase):
    def setUp(self):
        diameter = 38
        resistance = 0.5
        num_of_wheels = 4
        wheels = [Wheel(diameter, resistance) for i in range(num_of_wheels)]

        self.battle_car = BattleCar("The Terminator", 2020, True, wheels,
                               strength=5)

        self.opponent_car = Car("Honda Civic", 2015, True, wheels)

    def test_battlecar_attack(self):
        self.opponent_car.accelerate(50)
        self.assertEqual(self.opponent_car.speed, 49)

        self.battle_car.accelerate(40)
        self.assertEqual(self.battle_car.speed, 39)

        self.battle_car.attack(self.opponent_car)
        self.assertEqual(self.opponent_car.speed, 45)

If you put this code into the same test_car.py from earlier and run it, you should see that the test runner runs all three tests (test_accelerate() and test_decelerate() from CarTest, and test_battlecar_attack() from BattleCarTest).

Automatically run tests in multiple files

You might prefer to have your BattleCarTest in a separate file (say test_battlecar.py), while keeping CarTest in test_car.py. If you don’t tell unittest which test to run, it will try to automatically discover any files that start with test and loads all tests from the files.

Let’s say you have both test_car.py, test_battlecar.py and of course your code to test car.py in the same directory.

user@MACHINE:~$ python -m unittest -v
Ok
test_battlecar_attack (test_battlecar.BattleCarTest) ... ok
test_accelerate (test_car.CarTest) ... ok
test_decelerate (test_car.CarTest) ... ok

----------------------------------------------------------------------
Ran 3 tests in 0.000s

OK
user@MACHINE:~$