TDD a log line parser
Parse structured log lines of the format [TIMESTAMP] LEVEL: message into a typed object using test-driven development. You must write all five tests before writing a single line of implementation. The exercise is about the discipline of the process, not the complexity of the problem.
Why this matters
TDD feels slower until the moment you need to change something. Writing tests first forces you to think about the interface before the implementation; and interfaces that are easy to test are almost always easier to use. The log parser is deliberately simple so the entire mental budget goes on learning the red-green-refactor rhythm.
Before you start
- Python with pytest installed, or TypeScript with Vitest
- Understanding of what a test assertion is
- No prior TDD experience required; this is a first-principles exercise
- A text editor with good test runner integration (VS Code with pytest extension works well)
Step-by-step guide
- 1
Define the interface (no implementation yet)
Write the function signature only: parse_log(line: str) -> LogEntry where LogEntry is a dataclass or TypedDict with timestamp: datetime, level: str, and message: str. Do not write any logic; just the signature and the type. This is the contract your tests will verify.
- 2
Write all five tests (red)
Write: test_parses_info_level, test_parses_error_level, test_extracts_timestamp, test_extracts_message_with_spaces, and test_raises_on_malformed_input. Run them; all should fail (red). If any pass without implementation, your test is wrong.
- 3
Write the minimum implementation (green)
Write the simplest code that makes all five tests pass. Do not handle edge cases that are not tested. Do not add logging, error codes, or configuration. The implementation should be shorter than the tests; that is a good sign.
- 4
Refactor (still green)
Now improve the implementation without changing the tests. Extract the regex pattern as a constant. Give the error message a clear description of what was malformed. Run the tests after every change; if a test fails, undo and try again.
- 5
Add two edge case tests and make them pass
Add tests for: a log line with a colon in the message (common failure point), and a timestamp in a slightly different format. Watch them fail, fix the implementation, watch them pass. This is the full TDD loop; you have now done it seven times.