Skip to content

Oct 11: Quiz 3b, Testing Modules

Learning Objectives

After today's class, you should be able to:

  • Explain how to use the from keyword in an import statement.
  • Describe how functions in a test module use assert statements.

Announcements

HW7 Debrief

  • Using while True and break (or return)
  • random.randint() versus random.random()
  • print_stats() should have used a for loop!

Quiz 3b

  • Log in as student
  • Only two windows:
    1. Thonny
    2. Web browser
  • Web traffic monitored
  • Log out when finished

Ch08 Preview

  • Difference between a script and a module
  • Importing a module from the same folder
  • The __pycache__ folder (auto generated)

Example tests for HW7.2

An assert statement is used to see if each function call returns the expected tuple.

test_division.py
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
from division import divide

def test_divide_0_by_10():
    assert divide(0, 10) == (0, 0)

def test_divide_134_by_7():
    assert divide(134, 7) == (19, 1)

def test_divide_56_by_57():
    assert divide(56, 57) == (0, 56)

def test_divide_56_by_16():
    assert divide(56, 16) == (3, 8)

Example tests for HW7.5

The capsys argument (provided by pytest) automatically captures system output and error messages.

test_even_more.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
from even_more_stats import print_stats

def test_one_player(capsys):
    stats = [('Jefferson', 706, 88, 57)]
    print_stats(stats)
    out, err = capsys.readouterr()
    assert out == (
        "Jefferson scored 706 points, grabbed 88 rebounds, and made 57 assists.\n"
        "Total Points:   706\n"
        "Total Rebounds: 88\n"
        "Total Assists:  57\n"
    )
    assert err == ""

def test_two_players(capsys):
    stats = [('Hazell', 615, 62, 62), ('Tucker', 551, 137, 17)]
    print_stats(stats)
    out, err = capsys.readouterr()
    assert out == (
        "Hazell scored 615 points, grabbed 62 rebounds, and made 62 assists.\n"
        "Tucker scored 551 points, grabbed 137 rebounds, and made 17 assists.\n"
        "Total Points:   1166\n"
        "Total Rebounds: 199\n"
        "Total Assists:  79\n"
    )
    assert err == ""