cuckcoding.pro
Menu

Validate a JSON configuration file with Python and unittest

The demo server should listen on port 8080. The agent has helpfully accepted the configuration {"port": true}. In Python, that is close enough to one for some checks. Build the reader that catches it before someone spends an afternoon wondering who started a server on port 1.

Before you start
Python 3, a terminal and an empty folder. Save each named file there.
What to verify
Read a real settings file and demonstrate which values the application accepts.

Write the contract before the reader

Save this as settings.json. For this exercise a port is a JSON integer between 1 and 65535, inclusive. A missing field is a configuration error. Decide those rules before asking the agent to write anything. Otherwise it may invent a default, or quietly convert the string "80".

settings.json
{"port": 8080}

Other keys are allowed so an unrelated feature can add its own settings later.

Keep parsing and validation in one small reader

Save settings.py. Accepting an open text stream lets the same function read a disk file or an in-memory test. The JSON library handles malformed syntax. The next two checks handle valid JSON with the wrong shape or an invalid port.

settings.py
import json


def read_port(stream):
    data = json.load(stream)
    if not isinstance(data, dict):
        raise ValueError("expected a JSON object")
    value = data.get("port")
    if type(value) is not int or not 1 <= value <= 65535:
        raise ValueError("port must be an integer from 1 to 65535")
    return value

The exact type test is deliberate. In Python a boolean is also an instance of int. A generic integer check would let true sneak past the lower boundary.

Give the agent examples it can get wrong

Save the test module next to the reader. Group boundary cases with subTest so a failed run shows which input broke. Exercise both endpoints, the common case, a missing field, a boolean and a fractional value. Keep malformed JSON in its own test so changing the error path is visible.

test_settings.py
from io import StringIO
import json
import unittest

from settings import read_port


class PortTests(unittest.TestCase):
    def test_valid(self):
        for port in (1, 8080, 65535):
            with self.subTest(port=port):
                self.assertEqual(read_port(StringIO(json.dumps({"port": port}))), port)

    def test_invalid(self):
        for raw in ('{}', '[]', '{"port":true}', '{"port":"80"}',
                    '{"port":0}', '{"port":65536}', '{"port":3.5}'):
            with self.subTest(raw=raw):
                with self.assertRaises(ValueError):
                    read_port(StringIO(raw))

    def test_broken_syntax(self):
        with self.assertRaises(json.JSONDecodeError):
            read_port(StringIO('{"port":'))

StringIO runs the same parser as the disk example. These tests can be run repeatedly without editing a shared config file.

Run the suite, then try the actual file

Run both commands from the exercise folder. The suite should report three successful test methods. The second command prints 8080. Change the field in settings.json to true and rerun only the second command. It should stop with the range error.

Terminal
python3 -m unittest -v test_settings
python3 -c 'from settings import read_port; f = open("settings.json", encoding="utf-8"); print(read_port(f)); f.close()'

Put 8080 back. Ask the agent what would break if it replaced the exact type check with isinstance, then run the tests against that proposed change.

Try this prompt with your agent

Prompt
Add a timeout_ms field with the same style of validation. First propose the unit, limits and missing-field behavior. Add one boundary test and one type-confusion test before changing the loader.

A trap worth catching

Rejecting a value and failing to open a file are different failures. Keep the filename in the code that opens the stream so a path typo does not get reported as an invalid port.

Official documentation