NML Says

Unit Testing Python

Return to main lesson

Here is a Python example of a test script: The to programs you will see are quoted from https://blog.logrocket.com/node-js-express-test-driven-development-jest/, as JavaScript, then adapted and converted to Python.

Example 1. A Test Suite, ~/exercises/osd0/logrocket/logrocketpy/testsuite.py
 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
26
27
28
29
30
31
32
33
34
35
36
'''
    testsuite.py
'''
import unittest
from rocket import *

class Testing(unittest.TestCase):

    def test_calc_age(self):
        self.assertEqual(calc_age(2000), 25)
        self.assertEqual(calc_age(1999), 26)

    def test_create_box(self):
        self.assertEqual(create_rect(10, 10), 100)
        self.assertEqual(create_rect(55, 55), 3025)

    def test_power_level(self):
        self.assertTrue(power_level(9001))
        self.assertFalse(power_level(8999))

    def test_can_drive(self):
        self.assertRegex(can_drive(2000), "^Full")
        self.assertRegex(can_drive(2010), "^NO")

    def test_work_schedule(self):
        e1 = ('Monday', 'Tuesday', 'Wednesday,', 'Thursday')
        e0 = ('Friday', 'Saturday', 'Sunday,', 'Monday')

        self.assertEqual(work_schedule(len(e0), len(e1)), 8)

    def test_add_numbers(self):  # unittest, name arbitrary 
        self.assertEqual(add_numbers(42, 7), 49)
        self.assertEqual(add_numbers(-12, 42), -30)

if __name__ == '__main__':
    unittest.main()
Example 2. A Program to be Tested, ~/exercises/osd0/logrocket/logrocketpy/rocket.py
 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
26
27
28
29
30
31
32
33
34
35
36
37
'''
    rocket.py
'''
from datetime import datetime

def calc_age(dob):
    year = datetime.now().year
    return year - dob

def create_rect(a, b):
    return a * b

def can_drive(dob):
    statuteF = 18
    statuteP = 16
    age = calc_age(dob)

    if age >= statuteF:
        return 'Full Driving License'
    elif age >= statuteP:
        return 'Provisional License'
    else:
        return 'NO!'

def power_level(a):
    threshold = 9000
    return a > threshold

def work_schedule(empl0, empl1):
    return empl1 + empl1


'''
    We pretend that this is either a library of functions
    or
    a program (yet to be written below) that uses these functions
'''

Return to main lesson