How to Build a Simple Binary Protocol Parser Mock in Python
Defines a mock binary protocol with field definitions, encoding, and decoding to simulate network packet parsing for A/B testing and experiment setup.
Python code
38 linesclass SimpleProtocol:
def __init__(self, name, version):
self.name = name
self.version = version
self.fields = []
def add_field(self, field_name, field_size):
self.fields.append((field_name, field_size))
def parse(self, data):
if len(data) != sum(size for _, size in self.fields):
raise ValueError("Data length mismatch")
offset = 0
result = {}
for field_name, field_size in self.fields:
result[field_name] = int.from_bytes(data[offset:offset + field_size], byteorder="big")
offset += field_size
return result
def build(self, values):
data = b""
for field_name, field_size in self.fields:
value = values[field_name]
data += value.to_bytes(field_size, byteorder="big")
return data
if __name__ == "__main__":
proto = SimpleProtocol("MockPacket", "1.0")
proto.add_field("header", 1)
proto.add_field("payload", 4)
proto.add_field("checksum", 2)
packet = proto.build({"header": 0xAB, "payload": 0x12345678, "checksum": 0xCDEF})
print("Raw:", packet.hex())
parsed = proto.parse(packet)
print("Parsed:", parsed)
Output
Raw: ab12345678cdef
Parsed: {'header': 171, 'payload': 305419896, 'checksum': 52719}
How it works
The SimpleProtocol class stores field names and sizes, then uses int.from_bytes and int.to_bytes to encode/decode big-endian integers. The parse method validates the data length against the sum of field sizes to catch malformed inputs. This mock allows deterministic packet generation and parsing, which is essential for testing protocol logic without real network dependencies. The code is self-contained, relying only on the Python standard library, and is easily extended with more fields or different byte orders.
Common mistakes
- Mismatching field sizes and data length, causing ValueError at parse time
- Using the wrong byte order (e.g., little-endian when the protocol requires big-endian)
- Assuming values fit within the specified field size, leading to OverflowError
Variations
- Supporting little-endian by adding a byteorder parameter to __init__
- Using struct.pack and struct.unpack for fixed-size fields instead of int.to_bytes
Real-world use cases
- Mocking network packet generation for A/B testing message handling logic before deploying to production.
- Simulating experiment event payloads in offline batch tests to validate decoder changes.
- Creating deterministic test fixtures for performance benchmarks of binary serialization libraries.
Sponsored
More from A/B testing & experimentation
Keep learning
Related tutorials and quizzes for this topic.