Coverage for tests / test_timespan.py: 11%
165 statements
« prev ^ index » next coverage.py v7.13.5, created at 2026-04-17 08:49 +0000
« prev ^ index » next coverage.py v7.13.5, created at 2026-04-17 08:49 +0000
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 software is dual licensed under the GNU General Public License and also
10# under a 3-clause BSD license. Recipients may choose which of these licenses
11# to use; please see the files gpl-3.0.txt and/or bsd_license.txt,
12# respectively. If you choose the GPL option then the following text applies
13# (but note that there is still no warranty even if you opt for BSD instead):
14#
15# This program is free software: you can redistribute it and/or modify
16# it under the terms of the GNU General Public License as published by
17# the Free Software Foundation, either version 3 of the License, or
18# (at your option) any later version.
19#
20# This program is distributed in the hope that it will be useful,
21# but WITHOUT ANY WARRANTY; without even the implied warranty of
22# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23# GNU General Public License for more details.
24#
25# You should have received a copy of the GNU General Public License
26# along with this program. If not, see <http://www.gnu.org/licenses/>.
28import itertools
29import unittest
30import warnings
32import astropy.time
33import astropy.utils.exceptions
35# As of astropy 4.2, the erfa interface is shipped independently and
36# ErfaWarning is no longer an AstropyWarning
37try:
38 import erfa
39except ImportError:
40 erfa = None
42import pydantic
44from lsst.daf.butler import Timespan
45from lsst.daf.butler.time_utils import TimeConverter
48class TimespanTestCase(unittest.TestCase):
49 """Tests for the `Timespan` class.
51 Test coverage for the `TimespanDatabaseRepresentation` classes is handled
52 by the tests for `Database` and its subclasses.
53 """
55 def setUp(self):
56 start = astropy.time.Time("2020-01-01T00:00:00", format="isot", scale="tai")
57 offset = astropy.time.TimeDelta(60, format="sec")
58 self.timestamps = [start + offset * n for n in range(3)]
59 self.timespans = [Timespan(begin=None, end=None)]
60 self.timespans.extend(Timespan(begin=None, end=t) for t in self.timestamps)
61 self.timespans.extend(Timespan(begin=t, end=None) for t in self.timestamps)
62 self.timespans.extend(Timespan(begin=t, end=t) for t in self.timestamps)
63 self.timespans.extend(Timespan(begin=a, end=b) for a, b in itertools.combinations(self.timestamps, 2))
65 def testEmpty(self):
66 """Test various ways to construct an empty timespan, and that
67 operations on empty timespans yield the expected behavior.
68 """
69 self.assertEqual(
70 Timespan.makeEmpty(),
71 Timespan(Timespan.EMPTY, Timespan.EMPTY),
72 )
73 self.assertEqual(
74 Timespan.makeEmpty(),
75 Timespan(self.timestamps[1], self.timestamps[0]),
76 )
77 self.assertEqual(
78 Timespan.makeEmpty(),
79 Timespan(Timespan.EMPTY, self.timestamps[0]),
80 )
81 self.assertEqual(
82 Timespan.makeEmpty(),
83 Timespan(self.timestamps[0], Timespan.EMPTY),
84 )
85 self.assertEqual(
86 Timespan.makeEmpty(), Timespan(self.timestamps[0], self.timestamps[0], padInstantaneous=False)
87 )
88 empty = Timespan.makeEmpty()
89 for t in self.timestamps:
90 with self.subTest(t=str(t)):
91 self.assertFalse(empty < t)
92 self.assertFalse(empty > t)
93 self.assertFalse(t < empty)
94 self.assertFalse(t > empty)
95 self.assertFalse(empty.contains(t))
96 for t in self.timespans:
97 with self.subTest(t=str(t)):
98 self.assertTrue(t.contains(empty))
99 self.assertFalse(t.overlaps(empty))
100 self.assertFalse(empty.overlaps(t))
101 self.assertEqual(empty.contains(t), t.isEmpty())
102 self.assertFalse(empty < t)
103 self.assertFalse(t < empty)
104 self.assertFalse(empty > t)
105 self.assertFalse(t > empty)
107 def testFromInstant(self):
108 """Test construction of instantaneous timespans."""
109 self.assertEqual(
110 Timespan.fromInstant(self.timestamps[0]), Timespan(self.timestamps[0], self.timestamps[0])
111 )
113 def testInvalid(self):
114 """Test that we reject timespans that should not exist."""
115 with self.assertRaises(ValueError):
116 Timespan(TimeConverter().max_time, None)
117 with self.assertRaises(ValueError):
118 Timespan(TimeConverter().max_time, TimeConverter().max_time)
119 with self.assertRaises(ValueError):
120 Timespan(None, TimeConverter().epoch)
121 with self.assertRaises(ValueError):
122 Timespan(TimeConverter().epoch, TimeConverter().epoch)
123 t = TimeConverter().nsec_to_astropy(TimeConverter().max_nsec - 1)
124 with self.assertRaises(ValueError):
125 Timespan(t, t)
126 with self.assertRaises(ValueError):
127 Timespan.fromInstant(t)
129 def testStrings(self):
130 """Test __str__ against expected values and __repr__ with eval
131 round-tripping.
132 """
133 timespans = self.timespans
135 # Add timespan that includes Julian day high precision version.
136 timespans.append(
137 Timespan(
138 begin=astropy.time.Time(2458850.0, -0.49930555555555556, format="jd", scale="tai"),
139 end=astropy.time.Time(2458850.0, -0.4986111111111111, format="jd", scale="tai"),
140 )
141 )
143 for ts in timespans:
144 # Uncomment the next line and run this test directly for the most
145 # important test: human inspection.
146 # print(str(ts), repr(ts))
147 if ts.isEmpty():
148 self.assertEqual("(empty)", str(ts))
149 else:
150 self.assertIn(", ", str(ts))
151 if ts.begin is None:
152 self.assertTrue(str(ts).startswith("(-∞, "))
153 else:
154 self.assertTrue(str(ts).startswith(f"[2020-01-01T00:{ts.begin.tai.strftime('%M')}:00, "))
155 if ts.end is None:
156 self.assertTrue(str(ts).endswith(", ∞)"))
157 else:
158 self.assertTrue(str(ts).endswith(f", 2020-01-01T00:{ts.end.tai.strftime('%M')}:00)"))
159 self.assertEqual(eval(repr(ts)), ts)
161 def testOperationConsistency(self):
162 """Test that overlaps, contains, intersection, and difference are
163 consistent.
164 """
165 for a, b in itertools.combinations_with_replacement(self.timespans, 2):
166 with self.subTest(a=str(a), b=str(b)):
167 c1 = a.intersection(b)
168 c2 = b.intersection(a)
169 diffs1 = tuple(a.difference(b))
170 diffs2 = tuple(b.difference(a))
171 if a == b:
172 self.assertFalse(diffs1)
173 self.assertFalse(diffs2)
174 self.assertTrue(a.contains(b))
175 self.assertTrue(b.contains(a))
176 if a.contains(b):
177 self.assertTrue(a.overlaps(b) or b.isEmpty())
178 self.assertFalse(diffs2)
179 if b.contains(a):
180 self.assertTrue(b.overlaps(a) or a.isEmpty())
181 self.assertFalse(diffs1)
182 if diffs1 is not None:
183 for t in diffs1:
184 self.assertTrue(a.overlaps(t))
185 self.assertFalse(b.overlaps(t))
186 if diffs2 is not None:
187 for t in diffs2:
188 self.assertTrue(b.overlaps(t))
189 self.assertFalse(a.overlaps(t))
190 self.assertEqual(c1, c2)
191 if a.overlaps(b):
192 self.assertTrue(b.overlaps(a))
193 self.assertFalse(c1.isEmpty())
194 else:
195 self.assertTrue(a < b or a > b or a.isEmpty() or b.isEmpty())
196 self.assertFalse(b.overlaps(a))
197 self.assertTrue(c1.isEmpty())
198 if diffs1 is not None:
199 self.assertEqual(diffs1, (a,))
200 if diffs2 is not None:
201 self.assertEqual(diffs2, (b,))
203 def testPrecision(self):
204 """Test that we only use nanosecond precision for equality."""
205 ts1 = self.timespans[-1]
206 ts2 = Timespan(begin=ts1.begin + astropy.time.TimeDelta(1e-10, format="sec"), end=ts1.end)
207 self.assertEqual(ts1, ts2)
209 self.assertEqual(Timespan(begin=None, end=None), Timespan(begin=None, end=None))
210 self.assertEqual(Timespan(begin=None, end=ts1.end), Timespan(begin=None, end=ts1.end))
212 ts2 = Timespan(begin=ts1.begin + astropy.time.TimeDelta(1e-8, format="sec"), end=ts1.end)
213 self.assertNotEqual(ts1, ts2)
215 ts2 = Timespan(begin=None, end=ts1.end)
216 self.assertNotEqual(ts1, ts2)
218 t1 = Timespan(
219 begin=astropy.time.Time(2456461.0, val2=0.06580758101851847, format="jd", scale="tai"),
220 end=astropy.time.Time(2456461.0, val2=0.06617994212962963, format="jd", scale="tai"),
221 )
222 t2 = Timespan(
223 begin=astropy.time.Time(2456461.0, val2=0.06580758101851858, format="jd", scale="tai"),
224 end=astropy.time.Time(2456461.0, val2=0.06617994212962963, format="jd", scale="tai"),
225 )
226 self.assertEqual(t1, t2)
228 # Ensure that == and != work properly
229 self.assertTrue(t1 == t2, f"Equality of {t1} and {t2}")
230 self.assertFalse(t1 != t2, f"Check != is false for {t1} and {t2}")
232 def testTimescales(self):
233 """Test time scale conversion occurs on comparison."""
234 ts1 = Timespan(
235 begin=astropy.time.Time("2013-06-17 13:34:45.775000", scale="tai", format="iso"),
236 end=astropy.time.Time("2013-06-17 13:35:17.947000", scale="tai", format="iso"),
237 )
238 ts2 = Timespan(
239 begin=astropy.time.Time("2013-06-17T13:34:10.775", scale="utc", format="isot"),
240 end=astropy.time.Time("2013-06-17T13:34:42.947", scale="utc", format="isot"),
241 )
242 self.assertEqual(ts1, ts2, f"Compare {ts1} with {ts2}")
244 def testFuture(self):
245 """Check that we do not get warnings from future dates."""
246 # Astropy will give "dubious year" for UTC five years in the future
247 # so hide these expected warnings from the test output
248 with warnings.catch_warnings():
249 warnings.simplefilter("ignore", category=astropy.utils.exceptions.AstropyWarning)
250 if erfa is not None:
251 warnings.simplefilter("ignore", category=erfa.ErfaWarning)
252 ts1 = Timespan(
253 begin=astropy.time.Time(self.timestamps[0], scale="utc", format="iso"),
254 end=astropy.time.Time("2099-06-17 13:35:17.947000", scale="utc", format="iso"),
255 )
256 ts2 = Timespan(
257 begin=astropy.time.Time(self.timestamps[0], scale="utc", format="iso"),
258 end=astropy.time.Time("2099-06-17 13:35:17.947000", scale="utc", format="iso"),
259 )
261 # unittest can't test for no warnings so we run the test and
262 # trigger our own warning and count all the warnings
263 with self.assertWarns(Warning) as cm:
264 self.assertEqual(ts1, ts2)
265 warnings.warn("deliberate", stacklevel=1)
266 self.assertEqual(str(cm.warning), "deliberate")
268 def test_serialization(self):
269 ts = Timespan(
270 begin=astropy.time.Time("2013-06-17 13:34:45.775000", scale="tai", format="iso"),
271 end=astropy.time.Time("2013-06-17 13:35:17.947000", scale="tai", format="iso"),
272 )
273 adapter = pydantic.TypeAdapter(Timespan)
274 self.assertIn("TAI", adapter.json_schema()["description"])
275 json_roundtripped = adapter.validate_json(adapter.dump_json(ts))
276 self.assertIsInstance(json_roundtripped, Timespan)
277 self.assertEqual(json_roundtripped, ts)
278 python_roundtripped = adapter.validate_python(adapter.dump_python(ts))
279 self.assertIsInstance(json_roundtripped, Timespan)
280 self.assertEqual(python_roundtripped, ts)
281 with self.assertRaises(ValueError):
282 adapter.validate_python(12)
283 with self.assertRaises(ValueError):
284 adapter.validate_json({})
286 def test_day_obs(self):
287 data = (
288 ((20240201, 0), ("2024-02-01T00:00:00.0", "2024-02-02T00:00:00.0")),
289 ((19801011, 3600), ("1980-10-11T01:00:00.0", "1980-10-12T01:00:00.0")),
290 ((20481231, -7200), ("2048-12-30T22:00:00.0", "2048-12-31T22:00:00.0")),
291 ((20481231, 7200), ("2048-12-31T02:00:00.0", "2049-01-01T02:00:00.0")),
292 )
293 for input, output in data:
294 ts1 = Timespan.from_day_obs(input[0], input[1])
295 ts2 = Timespan(
296 begin=astropy.time.Time(output[0], scale="tai", format="isot"),
297 end=astropy.time.Time(output[1], scale="tai", format="isot"),
298 )
299 self.assertEqual(ts1, ts2)
301 with self.assertRaises(ValueError):
302 Timespan.from_day_obs(19690101)
305if __name__ == "__main__":
306 unittest.main()