──────────────────────────────────────

36. Python Project Workspace · Build and Check a Supplies Pack Planner

Put a reusable calculation beside a guarded CLI and test the calculation with unittest.

Lesson files · lessons/modules-and-workspaces/pack-planner-project

Before you start
- Keep a calculation in a separate module and import it.
- Check a function with a unit test.
- Read the help and default for an option.

By the end
- Round up partly filled packs while keeping the count for exact multiples.
- Test the partial pack in its own test method and run both tests.
- Point to the files that own the calculation, the command options and the tests.

Where you can use it
When a supplier changes pack sizes, rerun the command with the new size and use the tests to check the rounding rule.

Keep packs_needed in pack_rules.py and import it in both main.py and test_pack_rules.py. Use integer division after adding pack_size minus one to round up any partly full pack. Exact multiples keep their pack count. A unittest.TestCase subclass defines tests as methods whose names start with test_. Use self.assertEqual(actual, expected) to check the function’s return value. Studio’s test mode runs those methods for you. In a local folder with the files, run python3 -m unittest -v to discover them and python3 main.py --help to see the CLI options.

Predict
How many boxes of four do five items need?
- One.
- Two.

Worked example (example.py)

from io import StringIO
import unittest


def boxes_needed(items):
    return (items + 3) // 4


class BoxTests(unittest.TestCase):
    def test_partial_box(self):
        self.assertEqual(boxes_needed(5), 2)


suite = unittest.defaultTestLoader.loadTestsFromTestCase(BoxTests)
result = unittest.TextTestRunner(stream=StringIO()).run(suite)
print(result.wasSuccessful())


Example result
True

Fix packs_needed so a partly full pack counts as a whole pack. Keep main.py’s argument and output format. In test_pack_rules.py, add test_partial_pack that checks one group with thirteen items needs two packs at the default size. In Studio, enter the group and item counts as a single line such as 3 5. You can add --pack-size 6 or enter tests to run your suite.

Starter program (starter.py)

files = {
    "pack_rules.py": '''def packs_needed(groups, each, pack_size=12):
    items = groups * each
    return items // pack_size
''',
    "main.py": '''import argparse
from pack_rules import packs_needed


def main():
    parser = argparse.ArgumentParser(prog="pack-planner", description="Plan supplies in packs.")
    parser.add_argument("groups", type=int, help="Number of groups to supply")
    parser.add_argument("each", type=int, help="Items needed per group")
    parser.add_argument("--pack-size", type=int, default=12, help="Items in one pack")
    options = parser.parse_args()
    if options.groups < 0 or options.each < 0 or options.pack_size < 1:
        parser.error("Use non-negative counts and a positive pack size.")
    print(f"Packs needed: {packs_needed(options.groups, options.each, options.pack_size)}")


if __name__ == "__main__":
    main()
''',
    "test_pack_rules.py": '''import unittest
from pack_rules import packs_needed


class PackRulesTests(unittest.TestCase):
    def test_exact_pack(self):
        self.assertEqual(packs_needed(2, 6), 1)

''',
    "check_packs.py": '''from io import StringIO
from unittest import defaultTestLoader, TextTestRunner
from test_pack_rules import PackRulesTests

suite = defaultTestLoader.loadTestsFromTestCase(PackRulesTests)
result = TextTestRunner(stream=StringIO()).run(suite)
print(f"Tests run: {result.testsRun}")
print(f"All passed: {result.wasSuccessful()}")
''',
}

# Studio makes the files available for this run.
from pathlib import Path
from runpy import run_path
from tempfile import TemporaryDirectory
import sys


def run_project(files, entry, args=()):
    with TemporaryDirectory() as folder:
        for filename, source in files.items():
            Path(folder, filename).write_text(source, encoding="utf-8")
        saved_args = sys.argv
        sys.argv = [entry, *args]
        sys.path.insert(0, folder)
        try:
            run_path(str(Path(folder, entry)), run_name="__main__")
        finally:
            sys.argv = saved_args
            sys.path.remove(folder)
            for filename in files:
                sys.modules.pop(Path(filename).stem, None)

arguments = input().split()
if arguments == ["tests"]:
    run_project(files, "check_packs.py")
else:
    run_project(files, "main.py", arguments)


Starter input
3 5

Hint
Return (items + pack_size - 1) // pack_size and use self.assertEqual(packs_needed(1, 13), 2) in the new test.

Case 1. Try the sample
Input
3 5
Expected output
Packs needed: 2

Case 2. Use a different pack size
Input
4 3 --pack-size 5
Expected output
Packs needed: 3

Case 3. Run both tests
Input
tests
Expected output
Tests run: 2
All passed: True

Project checklist
Run the sample case.

Project checklist
Try one different case and explain what happened.

Marking criterion
Program behaviour (4 points)
Each required behaviour works on the supplied cases.

Marking criterion
Use of the lesson concept (3 points)
The code uses the main idea in a clear, purposeful way.

Marking criterion
Test evidence (2 points)
The reflection describes a case, its expected result and what happened.

Marking criterion
Explanation (1 points)
The learner explains a change or design decision in their own words.

Stretch
Add a test that expects zero packs for zero groups, then try the same case through the command-line tool.

The ZIP includes added practice files for this lesson. Open its lesson folder and read the included instructions.

Reflect
Which files would change if you rewrote the help text? Which would change if you changed the calculation rule?

Check your prediction
Two. The fifth item needs the start of a second box.
