GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • DevCircleRESOURCES
  • The library
  • Your learning map
  • Courses
  • Open source & documentation
  • About the library
  • Contact & corrections
  • Privacy
  • Legal notice
  • RSS feed

This view

  • Original page
  • New address

GeezerVison is showing developercircleresources.com — Pytest tutorial: test the edges of a small parser

Project note 22

Pytest tutorial: test the edges of a small parser

Test a price parser with normal input, invalid input, and a temporary file instead of checking only the happy path.

Updated November 8, 2026Python 3.11+; pytest 8.3.5

Before you start

  • Python venv
Save your progress
Pytest tutorial: input cases to function to assertions
The working model for this project. Follow the guide below for the complete example.

A parser test ought to spell out which inputs the program takes and which it turns away. Verifying a single successful value protects you very little against an empty string, a currency symbol, or a value carrying more precision than the application supports.

Install a known test version

Activate a virtual environment with Python 3.11+ and add pytest==8.3.5 via python -m pip install pytest==8.3.5. Write the code below to test_price.py and execute python -m pytest -q test_price.py.

The contract is intentionally tight. A price is a string of 1 to 30 ASCII digits, which may be followed by one or two decimal places. It cannot be negative, and the parser returns integer cents. Commas, signs, exponent notation, and leading or trailing whitespace all get rejected.

import re
import pytest

def price_to_cents(text):
    if not isinstance(text, str) or not re.fullmatch(r"[0-9]{1,30}(?:\.[0-9]{1,2})?", text):
        raise ValueError("expected 1 to 30 digits and at most two decimal places")
    whole, _, fraction = text.partition(".")
    return int(whole) * 100 + int(fraction.ljust(2, "0"))

@pytest.mark.parametrize("text,expected", [
    ("12", 1200), ("0.5", 50), ("12.50", 1250), ("0", 0),
    ("123456789012345678901234567890.12", 12345678901234567890123456789012),
])
def test_valid_price(text, expected):
    assert price_to_cents(text) == expected

@pytest.mark.parametrize("text", [
    "", "-1", "1.234", "NaN", "$2", " 2 ", None, 12,
    "1234567890123456789012345678901",
])
def test_invalid_price(text):
    with pytest.raises(ValueError):
        price_to_cents(text)

def test_price_from_file(tmp_path):
    source = tmp_path / "price.txt"
    source.write_text("7.50", encoding="utf-8")
    assert price_to_cents(source.read_text(encoding="utf-8")) == 750

Read the test cases as a contract

Whole dollar figures, values with one or two decimal places, zero, and the longest allowed integer make up the five passing inputs. Alongside those, nine rejection checks exercise malformed text, non-string types, and an overly long number. A separate temporary-file check confirms that file-backed input flows through the exact same parsing logic, bringing the suite to fifteen passing assertions.

With pytest.mark.parametrize, one behavioral check runs against many inputs. Every case should earn its place. Twenty different positive integers would contribute less than a single boundary case, such as a blank string.

Pinning the assertion to pytest.raises(ValueError) verifies that rejection happens for the right reason. Catching any generic exception could let an accidental TypeError pass, whereas a specific check locks in the public behavior callers expect.

Scroll sideways if the columns extend beyond the frame.

Test category in test_price.py Inputs covered Why the boundary matters
Whole and fractional strings (5 cases) "12", "0.5", "12.50", "0", and 30-digit "1234...90.12" Verifies missing decimal point, single fractional digit padding ("5" -> 50), two digits, zero, and upper digit bound
Malformed strings (6 cases) "", "-1", "1.234", "NaN", "$2", " 2 " Rejects empty input, negative signs, >2 decimal places, non-digits, currency symbols, and unstripped whitespace
Non-string types (2 cases) None, 12 Ensures isinstance(text, str) raises ValueError instead of TypeError inside re.fullmatch
Length overflow (1 case) 31-digit "1234567890123456789012345678901" Confirms the {1,30} integer-digit cap is enforced
File round-trip (1 case) tmp_path / "price.txt" containing "7.50" Exercises UTF-8 file I/O into price_to_cents without touching the working tree

Catch a precision bug before it becomes a contract

The long value is deliberate. Turning the string into a Decimal is exact, but multiplying by 100 follows the current decimal context. At the default 28-digit precision, int(Decimal("123456789012345678901234567890.12") * 100) yields 12345678901234567890123456790000, dropping the final cents.

Instead of relying on floating-point or decimal multiplication, the implementation splits whole and fractional parts and computes the result with integer math. Right-padding turns a fractional digit like 5 into 50, while whole numbers receive 00. Capping inputs at a 30-digit boundary simply scopes this exercise; real production limits must match your database schema and business rules.

Avoid repeating the implementation in the assertion

Notice that the expected cents are typed out literally. Had the test computed its expected answer with the same parsing expression the function uses, one bug could live in both places and go unnoticed. A worthwhile test brings an expectation of its own.

Keeping the parser and its test suite together in the same file makes this walkthrough easy to execute. When working in a production codebase, extract the parsing logic into its own module and import it into the test file; your behavioral assertions will stay identical after the move.

Make a deliberate regression

Change the fractional quantifier in the regular expression from {1,2} to {1,3}. The 1.234 case should fail because the parser no longer follows its contract. Restore it and run the tests again. A test suite that never fails under an intentional bug may be checking the wrong thing.

Next, settle whether surrounding spaces should be accepted. If so, write an explicit successful case first and only then touch the implementation. When the source is a strict export format, rejecting spaces may be the wiser policy. The tests expose that policy; they do not choose it for you.

Use fixtures for resources, not mystery

Requesting the tmp_path fixture gives the test a clean, isolated scratch folder on disk. Because the test writes its own sample file inside that directory, it never risks clobbering local project files or failing when launched from a different working directory.

This parser needs no mocks. They earn their keep at slow or unreliable boundaries, such as a remote service. Mocking every internal function can leave tests green even after the real components have stopped working together.

Next, automate the same command inside a Python continuous-integration workflow. For broader ingestion pipelines, combine these boundary checks with the CSV import contract so rejected records retain clear diagnostic reasons in the output.

Source: Python decimal arithmetic and precision, pytest parametrization documentation and temporary directories.

Download the complete example. Save the file before running it; the guide above names the required runtime.

Keep building

  • How to contribute to open source with a small first patch

    Choose a maintained project, reproduce one issue, and prepare a focused contribution that is easy to review.

  • JavaScript unit testing with the Node.js test runner

    Write dependency-free tests for a cart total, including the invalid values that ordinary examples miss.

  • Resolve a Git merge conflict without guessing

    Reproduce a conflict in a disposable repository, choose the intended result, and verify the final history.

You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.