Testing a Reader with In-Memory Input

An in-memory input can exercise parsing behavior while avoiding files when the reader accepts a stream or iterable.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Choose representative records
  2. Keep one test for the real interface
  3. Expose short reads without making a test depend on timing
  4. Simulate exhaustion and errors as distinct outcomes

Choose representative records

A parser can receive two normal lines and a final line without a terminator in a test. This verifies the parser's line iteration behavior without depending on the working directory.

Keep one test for the real interface

A fake text stream supplies decoded strings directly. It does not check how the real program opens a file, chooses an encoding, or reports a missing path. Add an integration test for the real file boundary.[1]

Expose short reads without making a test depend on timing

A reader for a six-byte header can receive two bytes and then four. A test double can return those pieces through the standard read interface. A double that always returns entire requested blocks would miss the reader's aggregation behavior. See reading a fixed-size block.

Planned chunks: [AB, CDEF]
First call obtains AB
Second call obtains CDEF
Parsed header bytes: ABCDEF

Simulate exhaustion and errors as distinct outcomes

Return a proper end-of-input signal after AB to test truncation. Simulate the interface's I/O error independently to test diagnostic handling. Keep at least one test using the real transport or stream type when its adapter matters.

References

  1. Python Software Foundation, unittest: Unit Testing Framework ↩