Programming with Python · free preview

Testing and Packaging

Turn assertions into organized tests, see how pytest discovers them, split code into your own modules, and learn how projects are packaged and installed.

1. Overview

Overview

2. Tests as Assertions

Tests as Assertions

3. pytest Discovers the Rest

pytest Discovers the Rest

4. Splitting Code into Modules

Splitting Code into Modules

5. Packaging for Others

Packaging for Others

6. Turn Assertions into Tests

Turn Assertions into Tests

7. Your Own Module

Your Own Module

8. Match pytest discovery

Which file/function pair will pytest collect by default for testing stats.mean?

9. A test suite from function to loop output

Run two tests for to_celsius: freezing water and body temperature. Predict each test's compared value, the assertion result, and the two pass lines.

Example. A test suite from function to loop output

Problem. Run two tests for to_celsius: freezing water and body temperature. Predict each test's compared value, the assertion result, and the two pass lines.

Correct solution.

python
def to_celsius(fahrenheit):
    return (fahrenheit - 32) * 5 / 9

def test_freezing():
    assert round(to_celsius(32)) == 0

def test_body_temperature():
    assert round(to_celsius(98.6), 1) == 37.0

for test in [test_freezing, test_body_temperature]:
    test()
    print(f"{test.__name__} passed")

关键提醒。

Input is the function to_celsius and two test functions.

Trace:

  1. to_celsius(32) computes (32 - 32) * 5 / 9, which is 0.0; round(0.0) is 0, so test_freezing passes.
  2. to_celsius(98.6) computes (98.6 - 32) * 5 / 9, which is approximately 37.0; rounding to one decimal gives 37.0, so test_body_temperature passes.
  3. Each test function returns None after its assertion succeeds.
  4. The loop prints the discovered function's __name__ after each successful call.

Expected output:

Output

test_freezing passed
test_body_temperature passed

10. Retrieval practice

A project stores mean(values) in stats.py and tests it in test_stats.py. Which file names and function names does pytest collect, what does a test use to pass or fail, and what is the minimum module-versus-package difference for import stats?

python
stats.py
test_stats.py

11. Mastery check

You have a script stats.py with def mean(values): return sum(values) / len(values). Write the two test functions, the file name pytest should collect, the import line those tests need, and the minimum [project] fields for a wheel. Then state the expected result for test_mean on [2, 4].

python
def mean(values):
    return sum(values) / len(values)

Practice this interactively

Free account · instant grading · spaced review that schedules itself.

Start this course for free