Skip to content

Commit

Permalink
Python: Detect invalid magic when instantiating SeekingReader
Browse files Browse the repository at this point in the history
  • Loading branch information
achim-k committed Sep 11, 2023
1 parent 8ac076a commit 89090b0
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 2 deletions.
3 changes: 2 additions & 1 deletion python/mcap/mcap/reader.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@
Schema,
Statistics,
)
from .stream_reader import MAGIC_SIZE, StreamReader, breakup_chunk
from .stream_reader import MAGIC_SIZE, StreamReader, breakup_chunk, read_magic
from .summary import Summary


Expand Down Expand Up @@ -249,6 +249,7 @@ def __init__(
decoder_factories: Iterable[DecoderFactory] = (),
):
super().__init__(decoder_factories=decoder_factories)
read_magic(ReadDataStream(stream, calculate_crc=False))
self._stream = stream
self._validate_crcs = validate_crcs
self._summary: Optional[Summary] = None
Expand Down
16 changes: 15 additions & 1 deletion python/mcap/tests/test_reader.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
import pytest

from mcap.decoder import DecoderFactory
from mcap.exceptions import DecoderNotFoundError
from mcap.exceptions import DecoderNotFoundError, InvalidMagic
from mcap.reader import McapReader, NonSeekingReader, SeekingReader, make_reader
from mcap.records import Channel, Message, Schema
from mcap.writer import IndexType, Writer
Expand Down Expand Up @@ -238,3 +238,17 @@ def test_no_summary_not_seeking(tmpdir: Path):
assert len(list(NonSeekingReader(f).iter_attachments())) == 1
with open(filepath, "rb") as f:
assert len(list(NonSeekingReader(f).iter_metadata())) == 1


def test_detect_invalid_initial_magic(tmpdir: Path):
filepath = tmpdir / "invalid_magic.mcap"
with open(filepath, "w") as f:
f.write("some bytes longer than the initial magic bytes")

with open(filepath, "rb") as f:
with pytest.raises(InvalidMagic):
SeekingReader(f)

with open(filepath, "rb") as f:
with pytest.raises(InvalidMagic):
NonSeekingReader(f).get_header()

0 comments on commit 89090b0

Please sign in to comment.