
Test every split, then test the ending. Keep one decoder per stream, assert exact text across splits, and reject unfinished characters at the real end of input. Save the slide (PNG)
é is valid UTF-8 encoded as b"\xc3\xa9", but decoding b"\xc3" and b"\xa9" independently rejects it under strict decoding. Switching those calls to errors="replace" produces replacement characters instead of the original text.
A streaming regression test must verify exact reconstructed text across chunk boundaries. It must also check that an unfinished character raises an error through the application's real end-of-stream path.
Transport chunks are not character boundaries.
Start with a known byte payload, split it at every possible position, and assert the exact output. Then test truncated input separately. A whole-buffer test exercises neither state across chunks nor finalization of an incomplete character.
Keep one decoder alive for the whole stream
An incremental decoder can hold an incomplete byte sequence until the next chunk arrives. With strict error handling, an incomplete but otherwise valid prefix is allowed while more bytes can arrive. At end of stream, that same unfinished sequence becomes an error.
These are separate contracts:
- Complete input: preserve the exact text, regardless of chunk boundaries.
- Truncated input: raise
UnicodeDecodeErrorwhen the stream is finalized.
Replacement decoding is a policy choice for malformed input, not a substitute for preserving state. If valid bytes acquire replacement characters solely because they arrived in separate chunks, the decoding implementation is wrong even when replacement is the intended error policy.
Save this isolated regression test
Save the following as test_stream_utf8.py. It uses only Python's standard library and creates no files or network connections.
The fixture includes a deliberately broken decoder so the failure mechanism remains visible. Its regression payload contains one-, two-, three-, and four-byte UTF-8 characters.
import codecs
import unittest
TEXT = "Aé€🙂Z"
WIRE = TEXT.encode("utf-8")
def decode_per_chunk(chunks, *, errors="strict"):
# Deliberately broken: every chunk starts a new decoder.
return "".join(chunk.decode("utf-8", errors=errors)
for chunk in chunks)
def decode_chunks(chunks):
decoder = codecs.getincrementaldecoder("utf-8")(
errors="strict"
)
parts = []
for chunk in chunks:
parts.append(decoder.decode(chunk, final=False))
parts.append(decoder.decode(b"", final=True))
return "".join(parts)
class StreamingUtf8Tests(unittest.TestCase):
def test_broken_decoder_passes_whole_buffer_only(self):
self.assertEqual(decode_per_chunk([WIRE]), TEXT)
# Split between the two bytes encoding é.
chunks = [WIRE[:2], WIRE[2:]]
with self.assertRaises(UnicodeDecodeError):
decode_per_chunk(chunks)
def test_replacement_hides_the_boundary_error(self):
chunks = [WIRE[:2], WIRE[2:]]
actual = decode_per_chunk(chunks, errors="replace")
self.assertNotEqual(actual, TEXT)
self.assertIn("\ufffd", actual)
def test_every_single_split_preserves_exact_text(self):
for split in range(len(WIRE) + 1):
with self.subTest(split=split):
chunks = [WIRE[:split], WIRE[split:]]
self.assertEqual(decode_chunks(chunks), TEXT)
def test_one_byte_chunks_and_empty_chunks(self):
chunks = [b""]
for byte in WIRE:
chunks.extend([bytes([byte]), b""])
self.assertEqual(decode_chunks(chunks), TEXT)
def test_truncated_character_fails_on_finalization(self):
prefix = "Aé€"
truncated = (
prefix.encode("utf-8")
+ "🙂".encode("utf-8")[:-1]
)
decoder = codecs.getincrementaldecoder("utf-8")(
errors="strict"
)
# The unfinished character is buffered, not yet rejected.
self.assertEqual(
decoder.decode(truncated, final=False), prefix
)
with self.assertRaises(UnicodeDecodeError):
decoder.decode(b"", final=True)
# The wrapper must also perform that final flush.
with self.assertRaises(UnicodeDecodeError):
decode_chunks([truncated])
if __name__ == "__main__":
unittest.main()
The expected result is that all five test methods pass. The deliberately broken decoder is expected to raise or corrupt text, and the tests assert those failures.
Why exact text and finalization both matter
The single-split test uses the original string as its oracle. Checking only that decoding does not raise would let replacement decoding pass despite altered text.
A decoder can return text without preserving it.
Each split gets a fresh decoder, while both chunks within that split share its state. Including split positions zero and len(WIRE) also exercises empty chunks at the beginning and end.
The byte-at-a-time test adds a different stress case: a four-byte character arrives across four calls, with empty chunks interspersed. An empty chunk does not mean the stream has ended; the explicit finalization call does.
The truncation test checks the opposite boundary. Before finalization, the missing byte might still arrive. After finalization, waiting is no longer valid. If the implementation forgets to flush its decoder, it can return the complete prefix and silently omit the unfinished character.
End of stream is a decoding operation, not just a loop condition.
Use this boundary checklist in code review
| Signal | What to verify | Failure it exposes |
|---|---|---|
| State lifetime | One decoder instance spans one stream | Independent decoding of partial characters |
| Exact output | Reconstructed text equals the known original | Replacement characters or dropped text |
| Chunk independence | Every single split and byte-at-a-time delivery work | Assumptions about transport boundaries |
| Finalization | End of input explicitly flushes the decoder | Buffered, truncated input disappearing silently |
I would use these tests as a focused gate for changes to streaming decoding. They check the bytes supplied, the text returned, and the exception at end of input. I would not treat a passing result as proof of the entire transport integration.
Connect the fixture to the code you actually ship
Keep decode_per_chunk as a small demonstration. Replace the body of decode_chunks with an adapter to your implementation, and run every relevant test through that adapter: every single split, byte-at-a-time delivery with empty chunks, and truncated input.
If your API yields text fragments, join those fragments only for the assertion. The production implementation can continue yielding incrementally; the helper above collects output to keep the test readable.
The direct incremental-decoder assertions in the truncation test demonstrate Python's behavior: buffering before finalization and rejection afterward. The assertions that call the adapted decode_chunks test your production behavior.
Connect that adapter to the application's actual end-of-stream path, including its final flush, then run the suite locally or in CI:
python -m unittest -v test_stream_utf8.py
A test that bypasses that path will not catch a missing flush there. If your contract intentionally uses replacement decoding, retain exact-output checks for valid input and add separate expectations for malformed input under that policy.
This fixture exhausts every single split of one payload, not every possible chunk partition or UTF-8 input. It also does not establish behavior for malformed byte sequences beyond an incomplete final character.
Save the field guide

A field guide distilled from this article. The text version follows below.
Text version
- A new chunk arrives: A character's bytes may span more than one chunk. Keep one incremental decoder alive for the stream so incomplete sequences can wait for the next chunk.
- Decoded text comes back: Decoding can succeed while replacement characters alter the text. Compare reconstructed output with the known original so silent replacement or dropped text cannot pass.
- Chunk boundaries change: A whole-buffer pass does not exercise state across chunks. Test every single split, then byte-at-a-time delivery with empty chunks to expose assumptions about boundaries.
- The stream ends: An unfinished character can remain buffered until finalization. Run truncated input through the application's actual final flush and assert UnicodeDecodeError so missing bytes cannot disappear silently.
Split the two bytes of é: The article's broken decoder rejects é when its two bytes are decoded independently under strict decoding. Switching to replacement decoding produces replacement characters instead of the original text.
This fixture covers every single split of one payload, not every chunk partition or UTF-8 input. Passing does not prove the entire transport integration.