diff --git a/PQAnalysis/io/moldescriptor_reader.py b/PQAnalysis/io/moldescriptor_reader.py index fdda37eb..b08a0ce3 100644 --- a/PQAnalysis/io/moldescriptor_reader.py +++ b/PQAnalysis/io/moldescriptor_reader.py @@ -61,6 +61,9 @@ def read(self) -> Residues: ------ MoldescriptorReaderError If the number of columns in the header of a mol type is not 3. + MoldescriptorReaderError + If a mol type declares more atoms than atom lines follow + before the end of the file. """ with open(self.filename, 'r', encoding='utf-8') as f: lines = f.readlines() @@ -103,6 +106,17 @@ def read(self) -> Residues: n_atoms = int(splitted_line[1]) + if counter + n_atoms + 1 > len(lines): + self.logger.error( + ( + f"The mol type {splitted_line[0]} declares " + f"{n_atoms} atoms, but only " + f"{len(lines) - counter - 1} atom lines follow " + "before the end of the file.\n" + ), + exception=MoldescriptorReaderError + ) + mol_types.append( self._read_mol_type( lines[counter:counter + n_atoms + 1], diff --git a/tests/data/readMoldescriptor/moldescriptor_tooFewAtoms.dat b/tests/data/readMoldescriptor/moldescriptor_tooFewAtoms.dat new file mode 100644 index 00000000..eb2e57a8 --- /dev/null +++ b/tests/data/readMoldescriptor/moldescriptor_tooFewAtoms.dat @@ -0,0 +1,4 @@ +# Molecule 1 + H2O 3 0.0 + O 0 -0.65966 + H 1 0.32983 diff --git a/tests/data/readMoldescriptor/moldescriptor_tooFewAtoms_midFile.dat b/tests/data/readMoldescriptor/moldescriptor_tooFewAtoms_midFile.dat new file mode 100644 index 00000000..0ad46b7f --- /dev/null +++ b/tests/data/readMoldescriptor/moldescriptor_tooFewAtoms_midFile.dat @@ -0,0 +1,5 @@ + H2O 3 0.0 + O 0 -0.65966 + H 1 0.32983 + AR 1 0.0 + Ar 2 0.0 diff --git a/tests/io/test_moldescriptorReader.py b/tests/io/test_moldescriptorReader.py index fec8fdae..826b1276 100644 --- a/tests/io/test_moldescriptorReader.py +++ b/tests/io/test_moldescriptorReader.py @@ -115,3 +115,25 @@ def test_read(self, test_with_data_dir): assert str( exception.value ) == "The number of columns in the header of a mol type must be 3.\nGot 2 columns instead in text: ' H2O 3'\n" + + @pytest.mark.parametrize( + "example_dir", + ["readMoldescriptor"], + indirect=False + ) + def test_read_too_few_atom_lines(self, test_with_data_dir): + reader = MoldescriptorReader("moldescriptor_tooFewAtoms.dat") + with pytest.raises(MoldescriptorReaderError) as exception: + reader.read() + assert str(exception.value) == ( + "The mol type H2O declares 3 atoms, but only 2 atom lines " + "follow before the end of the file.\n" + ) + + reader = MoldescriptorReader("moldescriptor_tooFewAtoms_midFile.dat") + with pytest.raises(MoldescriptorReaderError) as exception: + reader.read() + assert str(exception.value) == ( + "The mol type Ar declares 2 atoms, but only 0 atom lines " + "follow before the end of the file.\n" + )