Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Check read block size, fixes #15 #16

Merged
merged 1 commit into from
Oct 25, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 1 addition & 5 deletions corsikaio/file.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@
ParticleEvent = namedtuple('ParticleEvent', ['header', 'particles', 'longitudinal', 'end'])



class CorsikaFile:

def __init__(self, path):
Expand Down Expand Up @@ -67,18 +66,15 @@ def __next__(self):
self._run_end = parse_run_end(block)
raise StopIteration()

if len(block) < BLOCK_SIZE_BYTES:
raise StopIteration

if block[:4] != b'EVTH':
raise IOError('EVTH block expected but found {}'.format(block[:4]))

event_header = parse_event_header(block)[0]

block = self.read_block()
data_bytes = bytearray()
long_bytes = bytearray()

block = self.read_block()
while block[:4] != b'EVTE':

if block[:4] == b'LONG':
Expand Down
6 changes: 5 additions & 1 deletion corsikaio/io.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,4 +70,8 @@ def read_block(f, buffer_size=None):
if (pos + 4) % (buffer_size + 8) == 0:
f.read(8)

return f.read(BLOCK_SIZE_BYTES)
block = f.read(BLOCK_SIZE_BYTES)
if len(block) < BLOCK_SIZE_BYTES:
raise IOError("Read less bytes than expected, file seems to be truncated")

return block
23 changes: 23 additions & 0 deletions tests/test_file.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
import pytest


def test_version():
from corsikaio import CorsikaFile

Expand Down Expand Up @@ -66,3 +69,23 @@ def test_particle_longi():
e = next(f)

assert e.header['event_number'] == 1


def test_truncated(tmp_path):
'''Test we raise a meaningful error for a truncated file

Truncated files might happen if corsika crashes or the disk is full.

Regression test for cta-observatory/pycorsikaio#15
'''
from corsikaio import CorsikaParticleFile
path = tmp_path / "truncated.dat"

with open("tests/resources/corsika757_particle", "rb") as f:
with path.open("wb") as out:
out.write(f.read(273 * 10))

with pytest.raises(IOError, match="seems to be truncated"):
with CorsikaParticleFile(path) as f:
for _ in f:
pass