Part 2 Tasks

As in Part 1, create a separate branch and merge request for each sub-task below, following the same recipe from Part 1: Git Basics.

Task 0: Create a new repository

Create a fresh, empty project on GitLab and generate a practice package into it, exactly as in Part 1 Tasks Task 1 — same steps (remember to untick “Initialize repository with a README”), only the template URL differs:

cookiecutter https://github.com/spirousschuh/cookiecutter-git-workshop-testing

Then connect it to your GitLab project (git init → git add . → git commit → git remote add origin ... → git push -u origin main), create a virtual environment, and install the package.

Important

Install it with the [test] suffix this time:

pip install -e ".[test]"

The plain pip install -e . you used in Part 1 installs only what the package needs to run. The tools needed to test it — pytest and matplotlib — are declared separately in pyproject.toml as optional “test” dependencies, so that people who merely use the package don’t have to download them. The [test] part asks for those as well. Without it, every command in this part fails with pytest: command not found or ModuleNotFoundError: No module named 'matplotlib'.

The quotes matter on macOS/Linux — without them, some shells try to interpret the square brackets themselves.

Your generated project looks like this:

git_workshop_testing/          <- project folder ("outer")
   git_workshop_testing/       <- the Python package ("inner")
      __init__.py
      cli.py
      processing.py
   tests/
      test_cli.py
      test_processing.py
   pyproject.toml
   tox.ini
   .gitlab-ci.yml
   README.md
   sample_picture.jpg

Running the tests

Before writing any tests, make sure you can run the ones that already exist. From your project folder (the outer one, with your virtual environment active):

pytest

You should see something like:

===================== test session starts ======================
collected 4 items

tests/test_cli.py ..                                      [ 50%]
tests/test_processing.py ..                               [100%]

====================== 4 passed in 0.21s =======================

Each dot is one passing test.

Note

All four pass already — but one of them, test_invert_image_two_pixel, is an empty stub that doesn’t check anything yet. A test that asserts nothing always passes, which is exactly why Part 2: Testing insists the assertion is what makes it a test. You’ll fill it in in Task 1.

If you get no tests ran you’re probably in the wrong directory; if you get command not found or a ModuleNotFoundError, see Troubleshooting.

You can also run tests from PyCharm: right-click the tests folder in the project tree → Run ‘pytest in tests’. The results appear in a panel with green ticks and red crosses.

What a failure looks like. When a test fails, pytest shows you the exact line and the two values that didn’t match:

==================== FAILURES ==========================
______________ test_invert_image_one_pixel _____________

    expected_pixel = (255, 255, 255)
>   assert inverted_image.getpixel((0, 0)) == expected_pixel
E   assert (0, 0, 0) == (255, 255, 255)

tests/test_processing.py:18: AssertionError
================ 1 failed, 2 passed in 0.38s ===========

Read it as: on line 18, the left-hand value was (0, 0, 0) but (255, 255, 255) was expected. That’s the whole skill — a failing test tells you what it got and what it wanted.

Task 1: Unit tests

Open tests/test_processing.py. It tests invert_image, which lives in the inner package folder at git_workshop_testing/processing.py and turns an image into its color-negative.

  1. Understand the function. Read invert_image, then read the existing test test_invert_image_one_pixel — reading a function’s test is often the fastest way to understand what it’s supposed to do.

    The test builds a tiny one-pixel image from scratch rather than loading a file (recall the “bring your own test data” rule from Part 2: Testing). Reading it line by line:

    test_image = Image.fromarray(
        np.array([[[0, 0, 0, 0]]], dtype=np.uint8)).convert('RGB')
    

    The nested brackets are rows, then pixels, then the four color channels of one pixel (red, green, blue, transparency) — so this is an image one row tall and one pixel wide, and that pixel is black (0, 0, 0). Image.fromarray turns those raw numbers into an actual image object.

    assert inverted_image.getpixel((0, 0)) == expected_pixel
    

    getpixel((0, 0)) reads back the pixel at column 0, row 0. Inverting black gives white, hence (255, 255, 255).

  2. Extend the existing test. It ends with # TODO: Please, check the size of the output image. Add a second assertion checking that inverting a 1×1 image gives back a 1×1 image — an image’s dimensions are available as .size, which is a pair of numbers (width, height).

  3. Add a second unit test. Below it is a stub:

    def test_invert_image_two_pixel():
        pass
    

    Replace the pass (it’s a placeholder meaning “do nothing” — leave it in and your test will pass without testing anything) with a test for a two-pixel image, following the same given/when/then shape. To make an image two pixels wide, add a second pixel to the inner list; try making it white ([255, 255, 255, 255]) so the two pixels invert to different values.

    Note

    Two Python rules that will bite you here if you’ve not written Python before: the body of a function must be indented consistently (4 spaces is standard, and PyCharm does it for you), and pytest only finds functions whose names start with test_.

Run pytest after each change. Commit and merge as usual.

Task 2: Refactoring

Now that invert_image is properly tested, refactor it. The Pillow library (already a dependency of your package) has image inversion built in — there’s no need to hand-roll it with numpy. Rewrite invert_image to use ImageOps.invert instead.

You’ll need to make it available at the top of processing.py by adding an import — the statement that pulls in code from elsewhere:

from PIL import ImageOps

Important

Run pytest before you start (everything green) and again after your rewrite. That’s the entire point of this task: if the tests still pass, you’ve shown the behavior didn’t change even though the implementation completely did. This is only safe to do confidently because you wrote those tests in Task 1.

If a test now fails, don’t delete it — the failure is telling you the new version behaves differently. Check what ImageOps.invert returns for your test image compared to the old code.

Task 3: TDD — crop an image

Implement image cropping from scratch, test-first:

  1. Write a unit test in test_processing.py for a cropping function that doesn’t exist yet — think of the simplest image and crop you can check by hand (a two-pixel image cropped to one pixel, say). Reuse the image- building setup from your Task 1 tests.

  2. Run pytest and watch it fail. Expect this to look different from a normal failure: since the function doesn’t exist at all, the import at the top of the file fails, so pytest reports a collection error (ImportError: cannot import name 'crop_image') rather than a neat assertion mismatch. That’s still “the test fails” — it’s step one of TDD.

  3. Now write the cropping function in processing.py (Pillow images have a .crop() method), and re-run until green.

  4. Once the pure function works, do the same for the command line: add a test in tests/test_cli.py for a crop command, then implement that command in cli.py. Copy the structure of the existing CLI tests and commands — they show how CliRunner invokes a command and checks result.exit_code.

Continuous integration

Your generated package includes a .gitlab-ci.yml file, which tells GitLab to run your tests automatically on every push (this is the CI concept from Part 2: Testing).

How do you know it worked? After pushing, open your project on GitLab and go to Build → Pipelines in the left sidebar. You’ll see an entry for your commit that turns green when the tests pass, or red when they fail — click it to read the log. Try pushing a deliberately broken test once to see a red pipeline, then fix it.

Note

CI only runs if your project is in the kiwi-git-workshops group, which has the build machines (“runners”) attached. If the Pipelines page stays empty, ask your instructor to move or add your project there.

Once you’re comfortable testing and refactoring your own code, move on to Part 3: Documentation.