Coverage for tests/test_timespan.py: 11%
Shortcuts on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
Shortcuts on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1# This file is part of daf_butler.
2#
3# Developed for the LSST Data Management System.
4# This product includes software developed by the LSST Project
5# (http://www.lsst.org).
6# See the COPYRIGHT file at the top-level directory of this distribution
7# for details of code ownership.
8#
9# This program is free software: you can redistribute it and/or modify
10# it under the terms of the GNU General Public License as published by
11# the Free Software Foundation, either version 3 of the License, or
12# (at your option) any later version.
13#
14# This program is distributed in the hope that it will be useful,
15# but WITHOUT ANY WARRANTY; without even the implied warranty of
16# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17# GNU General Public License for more details.
18#
19# You should have received a copy of the GNU General Public License
20# along with this program. If not, see <http://www.gnu.org/licenses/>.
22import unittest
23import itertools
24import warnings
26import astropy.time
27import astropy.utils.exceptions
29# As of astropy 4.2, the erfa interface is shipped independently and
30# ErfaWarning is no longer an AstropyWarning
31try:
32 import erfa
33except ImportError:
34 erfa = None
36from lsst.daf.butler import Timespan
37from lsst.daf.butler.core.time_utils import TimeConverter
40class TimespanTestCase(unittest.TestCase):
41 """Tests for the `Timespan` class.
43 Test coverage for the `TimespanDatabaseRepresentation` classes is handled
44 by the tests for `Database` and its subclasses.
45 """
47 def setUp(self):
48 start = astropy.time.Time('2020-01-01T00:00:00', format="isot", scale="tai")
49 offset = astropy.time.TimeDelta(60, format="sec")
50 self.timestamps = [start + offset*n for n in range(3)]
51 self.timespans = [Timespan(begin=None, end=None)]
52 self.timespans.extend(Timespan(begin=None, end=t) for t in self.timestamps)
53 self.timespans.extend(Timespan(begin=t, end=None) for t in self.timestamps)
54 self.timespans.extend(Timespan(begin=t, end=t) for t in self.timestamps)
55 self.timespans.extend(Timespan(begin=a, end=b)
56 for a, b in itertools.combinations(self.timestamps, 2))
58 def testEmpty(self):
59 """Test various ways to construct an empty timespan, and that
60 operations on empty timespans yield the expected behavior.
61 """
62 self.assertEqual(
63 Timespan.makeEmpty(),
64 Timespan(Timespan.EMPTY, Timespan.EMPTY),
65 )
66 self.assertEqual(
67 Timespan.makeEmpty(),
68 Timespan(self.timestamps[1], self.timestamps[0]),
69 )
70 self.assertEqual(
71 Timespan.makeEmpty(),
72 Timespan(Timespan.EMPTY, self.timestamps[0]),
73 )
74 self.assertEqual(
75 Timespan.makeEmpty(),
76 Timespan(self.timestamps[0], Timespan.EMPTY),
77 )
78 self.assertEqual(
79 Timespan.makeEmpty(),
80 Timespan(self.timestamps[0], self.timestamps[0], padInstantaneous=False)
81 )
82 empty = Timespan.makeEmpty()
83 for t in self.timestamps:
84 with self.subTest(t=str(t)):
85 self.assertFalse(empty < t)
86 self.assertFalse(empty > t)
87 self.assertFalse(t < empty)
88 self.assertFalse(t > empty)
89 self.assertFalse(empty.contains(t))
90 for t in self.timespans:
91 with self.subTest(t=str(t)):
92 self.assertTrue(t.contains(empty))
93 self.assertFalse(t.overlaps(empty))
94 self.assertFalse(empty.overlaps(t))
95 self.assertEqual(empty.contains(t), t.isEmpty())
96 self.assertFalse(empty < t)
97 self.assertFalse(t < empty)
98 self.assertFalse(empty > t)
99 self.assertFalse(t > empty)
101 def testFromInstant(self):
102 """Test construction of instantaneous timespans.
103 """
104 self.assertEqual(Timespan.fromInstant(self.timestamps[0]),
105 Timespan(self.timestamps[0], self.timestamps[0]))
107 def testInvalid(self):
108 """Test that we reject timespans that should not exist.
109 """
110 with self.assertRaises(ValueError):
111 Timespan(TimeConverter().max_time, None)
112 with self.assertRaises(ValueError):
113 Timespan(TimeConverter().max_time, TimeConverter().max_time)
114 with self.assertRaises(ValueError):
115 Timespan(None, TimeConverter().epoch)
116 with self.assertRaises(ValueError):
117 Timespan(TimeConverter().epoch, TimeConverter().epoch)
118 t = TimeConverter().nsec_to_astropy(TimeConverter().max_nsec - 1)
119 with self.assertRaises(ValueError):
120 Timespan(t, t)
121 with self.assertRaises(ValueError):
122 Timespan.fromInstant(t)
124 def testStrings(self):
125 """Test __str__ against expected values and __repr__ with eval
126 round-tripping.
127 """
128 for ts in self.timespans:
129 # Uncomment the next line and run this test directly for the most
130 # important test: human inspection.
131 # print(str(ts), repr(ts))
132 if ts.isEmpty():
133 self.assertEqual("(empty)", str(ts))
134 else:
135 self.assertIn(", ", str(ts))
136 if ts.begin is None:
137 self.assertTrue(str(ts).startswith("(-∞, "))
138 else:
139 self.assertTrue(str(ts).startswith(f"[{ts.begin.tai.isot}, "))
140 if ts.end is None:
141 self.assertTrue(str(ts).endswith(", ∞)"))
142 else:
143 self.assertTrue(str(ts).endswith(f", {ts.end.tai.isot})"))
144 self.assertEqual(eval(repr(ts)), ts)
146 def testOperationConsistency(self):
147 """Test that overlaps, contains, intersection, and difference are
148 consistent.
149 """
150 for a, b in itertools.combinations_with_replacement(self.timespans, 2):
151 with self.subTest(a=str(a), b=str(b)):
152 c1 = a.intersection(b)
153 c2 = b.intersection(a)
154 diffs1 = tuple(a.difference(b))
155 diffs2 = tuple(b.difference(a))
156 if a == b:
157 self.assertFalse(diffs1)
158 self.assertFalse(diffs2)
159 self.assertTrue(a.contains(b))
160 self.assertTrue(b.contains(a))
161 if a.contains(b):
162 self.assertTrue(a.overlaps(b) or b.isEmpty())
163 self.assertFalse(diffs2)
164 if b.contains(a):
165 self.assertTrue(b.overlaps(a) or a.isEmpty())
166 self.assertFalse(diffs1)
167 if diffs1 is not None:
168 for t in diffs1:
169 self.assertTrue(a.overlaps(t))
170 self.assertFalse(b.overlaps(t))
171 if diffs2 is not None:
172 for t in diffs2:
173 self.assertTrue(b.overlaps(t))
174 self.assertFalse(a.overlaps(t))
175 self.assertEqual(c1, c2)
176 if a.overlaps(b):
177 self.assertTrue(b.overlaps(a))
178 self.assertFalse(c1.isEmpty())
179 else:
180 self.assertTrue(a < b or a > b or a.isEmpty() or b.isEmpty())
181 self.assertFalse(b.overlaps(a))
182 self.assertTrue(c1.isEmpty())
183 if diffs1 is not None:
184 self.assertEqual(diffs1, (a,))
185 if diffs2 is not None:
186 self.assertEqual(diffs2, (b,))
188 def testPrecision(self):
189 """Test that we only use nanosecond precision for equality."""
190 ts1 = self.timespans[-1]
191 ts2 = Timespan(begin=ts1.begin + astropy.time.TimeDelta(1e-10, format="sec"), end=ts1.end)
192 self.assertEqual(ts1, ts2)
194 self.assertEqual(Timespan(begin=None, end=None), Timespan(begin=None, end=None))
195 self.assertEqual(Timespan(begin=None, end=ts1.end), Timespan(begin=None, end=ts1.end))
197 ts2 = Timespan(begin=ts1.begin + astropy.time.TimeDelta(1e-8, format="sec"), end=ts1.end)
198 self.assertNotEqual(ts1, ts2)
200 ts2 = Timespan(begin=None, end=ts1.end)
201 self.assertNotEqual(ts1, ts2)
203 t1 = Timespan(begin=astropy.time.Time(2456461.0, val2=0.06580758101851847, format="jd", scale="tai"),
204 end=astropy.time.Time(2456461.0, val2=0.06617994212962963, format="jd", scale="tai"))
205 t2 = Timespan(begin=astropy.time.Time(2456461.0, val2=0.06580758101851858, format="jd", scale="tai"),
206 end=astropy.time.Time(2456461.0, val2=0.06617994212962963, format="jd", scale="tai"))
207 self.assertEqual(t1, t2)
209 # Ensure that == and != work properly
210 self.assertTrue(t1 == t2, f"Equality of {t1} and {t2}")
211 self.assertFalse(t1 != t2, f"Check != is false for {t1} and {t2}")
213 def testTimescales(self):
214 """Test time scale conversion occurs on comparison."""
215 ts1 = Timespan(begin=astropy.time.Time('2013-06-17 13:34:45.775000', scale='tai', format='iso'),
216 end=astropy.time.Time('2013-06-17 13:35:17.947000', scale='tai', format='iso'))
217 ts2 = Timespan(begin=astropy.time.Time('2013-06-17T13:34:10.775', scale='utc', format='isot'),
218 end=astropy.time.Time('2013-06-17T13:34:42.947', scale='utc', format='isot'))
219 self.assertEqual(ts1, ts2, f"Compare {ts1} with {ts2}")
221 def testFuture(self):
222 """Check that we do not get warnings from future dates."""
224 # Astropy will give "dubious year" for UTC five years in the future
225 # so hide these expected warnings from the test output
226 with warnings.catch_warnings():
227 warnings.simplefilter("ignore", category=astropy.utils.exceptions.AstropyWarning)
228 if erfa is not None:
229 warnings.simplefilter("ignore", category=erfa.ErfaWarning)
230 ts1 = Timespan(begin=astropy.time.Time(self.timestamps[0], scale='utc', format='iso'),
231 end=astropy.time.Time('2099-06-17 13:35:17.947000', scale='utc', format='iso'))
232 ts2 = Timespan(begin=astropy.time.Time(self.timestamps[0], scale='utc', format='iso'),
233 end=astropy.time.Time('2099-06-17 13:35:17.947000', scale='utc', format='iso'))
235 # unittest can't test for no warnings so we run the test and
236 # trigger our own warning and count all the warnings
237 with self.assertWarns(Warning) as cm:
238 self.assertEqual(ts1, ts2)
239 warnings.warn("deliberate")
240 self.assertEqual(str(cm.warning), "deliberate")
242 def testJson(self):
243 ts1 = Timespan(begin=astropy.time.Time('2013-06-17 13:34:45.775000', scale='tai', format='iso'),
244 end=astropy.time.Time('2013-06-17 13:35:17.947000', scale='tai', format='iso'))
245 json_str = ts1.to_json()
246 ts_json = Timespan.from_json(json_str)
247 self.assertEqual(ts_json, ts1)
250if __name__ == "__main__": 250 ↛ 251line 250 didn't jump to line 251, because the condition on line 250 was never true
251 unittest.main()