DEV Community

Wenlo
Wenlo

Posted on AI-assisted

Separate a parser, a fixture, and tests into a small project

A single script is convenient until parsing logic, example data and tests start changing for different reasons. This small project separates the reusable parser from the test runner. Its fixture stays fictional and its input format stays deliberately narrow.

Run the example

I ran this multi-file example in PythonIDE on an English iPhone simulator. All log entries are fictional. Save the first block as check_project.py and the second as parser_core.py next to it.

# Run this file from the supplied project folder.
import unittest
from parser_core import parse, summarize

FIXTURE = [
    'GET /home 200 40ms',
    'POST /checkout 500 900ms',
    'bad line',
    'GET /missing 404 20ms',
]

class ParserChecks(unittest.TestCase):
    def test_fixture(self):
        report = summarize(FIXTURE)
        self.assertEqual(report['accepted'], 3)
        self.assertEqual(report['rejected'], [3])
        self.assertEqual(report['server_errors'], 1)
        self.assertAlmostEqual(report['error_rate'], 1/3)
        self.assertEqual(report['median_ms'], 40)

    def test_empty(self):
        report = summarize([])
        self.assertEqual(report['accepted'], 0)
        self.assertIsNone(report['error_rate'])
        self.assertIsNone(report['median_ms'])

    def test_shape_and_status(self):
        for text in ['GET /x 999 1ms', 'GET /x 200 -1ms',
                     'GET /x 200 1ms trailing']:
            self.assertIsNone(parse(text))
        self.assertIsNotNone(parse('GET /x 404 0ms'))

    def test_no_input_mutation(self):
        original = FIXTURE.copy()
        summarize(FIXTURE)
        self.assertEqual(FIXTURE, original)

if __name__ == '__main__':
    suite = unittest.defaultTestLoader.loadTestsFromTestCase(ParserChecks)
    result = unittest.TextTestRunner(verbosity=2).run(suite)
    if not result.wasSuccessful():
        raise SystemExit(1)
Enter fullscreen mode Exit fullscreen mode

PythonIDE editor showing the fictional request fixture and first tests

PythonIDE editor showing the final tests and the unittest runner

The reusable module: parser_core.py

import re
from statistics import median

PATTERN = re.compile(r'(GET|POST) (/[\w/-]*) (\d{3}) (\d+)ms')

def parse(line):
    match = PATTERN.fullmatch(line)
    if not match:
        return None
    method, path, status, duration = match.groups()
    status, duration = int(status), int(duration)
    if not 100 <= status < 600:
        return None
    return method, path, status, duration

def summarize(lines):
    rows, rejected = [], []
    for number, line in enumerate(lines, 1):
        row = parse(line)
        if row is None:
            rejected.append(number)
        else:
            rows.append(row)
    errors = sum(500 <= row[2] < 600 for row in rows)
    return {'accepted': len(rows), 'rejected': rejected,
            'server_errors': errors,
            'error_rate': errors / len(rows) if rows else None,
            'median_ms': median(row[3] for row in rows) if rows else None}
Enter fullscreen mode Exit fullscreen mode

PythonIDE editor showing the reusable parser and summary module

Read the behavior and its boundaries

The project contains parser_core.py, check_project.py and README.md. Importing parser_core defines functions without running a report or starting a UI. parse validates a whole line and the HTTP status range; summarize records rejected positions and treats an empty accepted set as missing statistics rather than zero.

The test fixture contains a successful request, a 500, a malformed line and a 404. It should yield three accepted records, one rejected position, one server error, an error rate of one third and a median of 40 ms. Separate tests cover empty input, trailing text, invalid status, negative duration and input immutability. A 404 is accepted data but is not a server error.

Open the project folder and run check_project.py beside parser_core.py. A missing-module error may indicate that only one file was imported or that the search path differs; it is not evidence that the parser needs a package installation. The filename parser_core is intentional and avoids shadowing a standard module such as statistics.

Observed run: all four tests passed: empty input, fictional fixture, no input mutation, and line shape/status validation. The module and runner were opened from the same project folder.

PythonIDE console showing all four parser tests passed

Try one change

Add an empty line in the middle of the fixture and update only the expected rejected positions. Then add support for PUT with a failing test first, and keep the documented accepted format in sync.

I build PythonIDE, a Python coding app for iPhone and iPad. AI assisted with drafting and translation; the code and four passing tests were checked in PythonIDE on an iPhone simulator.

View on the App Store

Top comments (1)

Collapse
 
userxnom profile image
Abdullah Naseer •

The test I would steal from this is the no-input-mutation one — it is the check most small parsers never get, and it is exactly the bug that shows up months later when the same fixture list gets reused across tests.

I also like that the fixture is deliberately hostile in miniature: a 500, a malformed line and a 404 in four lines, so the rejected positions are part of the contract, not an afterthought.

One question: the fixture covers shape, but what about a line that parses cleanly yet carries an absurd value — say a 200 with a 999999ms latency? Does summarize's median just absorb it, or would you cap/clamp latencies before they reach the stats? That is the boundary I always end up adding after the first real log file.