From 4870488324ed616aaea632194ee59283c9fa6bdd Mon Sep 17 00:00:00 2001 From: JoFrhwld Date: Fri, 3 Nov 2023 10:54:07 -0400 Subject: [PATCH] better exceptions for .first, .last --- src/aligned_textgrid/mixins/mixins.py | 22 ++++++++++++---------- tests/test_sequences/test_sequences.py | 19 +++++++++++++++++++ 2 files changed, 31 insertions(+), 10 deletions(-) diff --git a/src/aligned_textgrid/mixins/mixins.py b/src/aligned_textgrid/mixins/mixins.py index 5055397..cfdcd02 100644 --- a/src/aligned_textgrid/mixins/mixins.py +++ b/src/aligned_textgrid/mixins/mixins.py @@ -11,24 +11,26 @@ class PrecedenceMixins: Attributes: first (SequenceInterval): The first interval in the subset list - last (SequenceInterval): The last interval in the subset list + last (SequenceInterval): The last interval in the subset list """ @property def first(self): - if hasattr(self, "subset_list"): + if hasattr(self, "subset_list") and len(self.subset_list) > 0: return self.subset_list[0] - else: - raise Exception(f"{type(self).__name__} does not\ - have the attribute .first") - + if hasattr(self, "subset_list"): + raise IndexError(f"{type(self).__name__} with label "\ + f"'{self.label}' subset list is empty.") + raise AttributeError(f"{type(self).__name__} is not indexable.") + @property def last(self): - if hasattr(self, "subset_list"): + if hasattr(self, "subset_list") and len(self.subset_list) > 0: return self.subset_list[-1] - else: - raise Exception(f"{type(self).__name__} does not\ - have the attribute .first") + if hasattr(self, "subset_list"): + raise IndexError(f"{type(self).__name__} with label "\ + f"'{self.label}' subset list is empty.") + raise AttributeError(f"{type(self).__name__} is not indexable.") def set_fol( self, next_int): diff --git a/tests/test_sequences/test_sequences.py b/tests/test_sequences/test_sequences.py index 9737b4d..6ee2d90 100644 --- a/tests/test_sequences/test_sequences.py +++ b/tests/test_sequences/test_sequences.py @@ -1,8 +1,10 @@ import pytest from aligned_textgrid.sequences.sequences import * +from aligned_textgrid.points.points import SequencePoint from aligned_textgrid.sequences.tiers import * import numpy as np from praatio.utilities.constants import Interval +from praatio.utilities.constants import Point class TestSequenceIntervalDefault: """_Test default behavior of SequenceInterval_ @@ -295,6 +297,23 @@ def test_first_last(self): last_interval = upper1[-1] assert upper1.last is last_interval + def test_first_last_errors(self): + upper1 = self.UpperClass(Interval(0,10,"upper")) + point1 = SequencePoint(Point(0, "point")) + + with pytest.raises(IndexError): + upper1.first + + with pytest.raises(IndexError): + upper1.last + + with pytest.raises(AttributeError): + point1.first + + with pytest.raises(AttributeError): + point1.last + + def test_subset_pop(self): upper1 = self.UpperClass(Interval(0,10,"upper")) lower1 = self.LowerClass(Interval(0,5,"lower1"))