Coverage for tests/test_nightReport.py: 23%
137 statements
« prev ^ index » next coverage.py v7.5.1, created at 2024-05-10 04:13 -0700
« prev ^ index » next coverage.py v7.5.1, created at 2024-05-10 04:13 -0700
1# This file is part of summit_utils.
2#
3# Developed for the LSST Data Management System.
4# This product includes software developed by the LSST Project
5# (https://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 <https://www.gnu.org/licenses/>.
22import datetime
23import itertools
24import os
25import tempfile
26import unittest
27from unittest import mock
29import matplotlib as mpl
30from astro_metadata_translator import ObservationInfo
31from numpy.random import shuffle
33import lsst.utils.tests
35mpl.use("Agg")
37import lsst.summit.utils.butlerUtils as butlerUtils # noqa: E402
38from lsst.summit.utils.nightReport import ColorAndMarker, NightReport # noqa: E402
41class NightReportTestCase(lsst.utils.tests.TestCase):
42 @classmethod
43 def setUpClass(cls):
44 try:
45 cls.butler = butlerUtils.makeDefaultLatissButler()
46 except FileNotFoundError:
47 raise unittest.SkipTest("Skipping tests that require the LATISS butler repo.")
49 cls.dayObs = 20200314 # has 377 images and data also exists on the TTS & summit
51 # Do the init in setUpClass because this takes about 35s for 20200314
52 cls.report = NightReport(cls.butler, cls.dayObs)
53 # number of images isn't necessarily the same as the number for the
54 # the dayObs in the registry becacuse of the test stands/summit
55 # having partial data, so get the number of images from the length
56 # of the scraped data. Not ideal, but best that can be done due to
57 # only having partial days in the test datasets.
58 cls.nImages = len(cls.report.data.keys())
59 cls.seqNums = list(cls.report.data.keys())
61 def test_saveAndLoad(self):
62 """Test that a NightReport can save itself, and be loaded back."""
63 writeDir = tempfile.mkdtemp()
64 saveFile = os.path.join(writeDir, f"testNightReport_{self.dayObs}.pickle")
65 self.report.save(saveFile)
66 self.assertTrue(os.path.exists(saveFile))
68 loaded = NightReport(self.butler, self.dayObs, saveFile)
69 self.assertIsInstance(loaded, lsst.summit.utils.nightReport.NightReport)
70 self.assertGreaterEqual(len(loaded.data), 1)
71 self.assertEqual(loaded.dayObs, self.dayObs)
73 # TODO: add a self.assertRaises on a mismatched dayObs
75 def test_getSortedData(self):
76 """Test the _getSortedData returns the seqNums in order."""
77 shuffledKeys = list(self.report.data.keys())
78 shuffle(shuffledKeys)
79 shuffledData = {k: self.report.data[k] for k in shuffledKeys}
81 sortedData = self.report._getSortedData(shuffledData)
82 sortedKeys = sorted(list(sortedData.keys()))
83 self.assertEqual(sortedKeys, list(self.report.data.keys()))
84 return
86 def test_getExpRecordDictForDayObs(self):
87 """Test getExpRecordDictForDayObs.
89 Test it returns a dict of dicts, keyed by integer seqNums.
90 """
91 expRecDict = self.report.getExpRecordDictForDayObs(self.dayObs)
92 self.assertIsInstance(expRecDict, dict)
93 self.assertGreaterEqual(len(expRecDict), 1)
95 # check all the keys are ints
96 seqNums = list(expRecDict.keys())
97 self.assertTrue(all(isinstance(s, int) for s in seqNums))
99 # check all the values are dicts
100 self.assertTrue(all(isinstance(expRecDict[s], dict) for s in seqNums))
101 return
103 def test_getObsInfoAndMetadataForSeqNum(self):
104 """Test that getObsInfoAndMetadataForSeqNum returns the correct
105 types.
106 """
107 seqNum = self.seqNums[0]
108 obsInfo, md = self.report.getObsInfoAndMetadataForSeqNum(seqNum)
109 self.assertIsInstance(obsInfo, ObservationInfo)
110 self.assertIsInstance(md, dict)
111 return
113 def test_rebuild(self):
114 """Test that rebuild does nothing, as no data will be being added.
116 NB Do not call full=True on this, as it will double the length of the
117 tests and they're already extremely slow.
118 """
119 lenBefore = len(self.report.data)
120 self.report.rebuild()
121 self.assertEqual(len(self.report.data), lenBefore)
122 return
124 def test_getExposureMidpoint(self):
125 """Test the exposure midpoint calculation"""
126 # we would like a non-zero exptime exposure really
127 seqNumToUse = 0
128 for seqNum in self.report.data.keys():
129 expTime = self.report.data[seqNum]["exposure_time"]
130 if expTime > 0:
131 seqNumToUse = seqNum
132 break
134 midPoint = self.report.getExposureMidpoint(seqNumToUse)
135 record = self.report.data[seqNumToUse]
137 if expTime == 0:
138 self.assertGreaterEqual(midPoint, record["datetime_begin"].to_datetime())
139 self.assertLessEqual(midPoint, record["datetime_end"].to_datetime())
140 else:
141 self.assertGreater(midPoint, record["datetime_begin"].to_datetime())
142 self.assertLess(midPoint, record["datetime_end"].to_datetime())
143 return
145 def test_getTimeDeltas(self):
146 """Test the time delta calculation returns a dict."""
147 dts = self.report.getTimeDeltas()
148 self.assertIsInstance(dts, dict)
149 return
151 def test_makeStarColorAndMarkerMap(self):
152 """Test the color map maker returns a dict of ColorAndMarker
153 objects.
154 """
155 cMap = self.report.makeStarColorAndMarkerMap(self.report.stars)
156 self.assertEqual(len(cMap), len(self.report.stars))
157 self.assertIsInstance(cMap, dict)
158 values = list(cMap.values())
159 self.assertTrue(all(isinstance(value, ColorAndMarker) for value in values))
160 return
162 def test_printObsTable(self):
163 """Test that a the printObsTable() method prints out the correct
164 number of lines.
165 """
166 with mock.patch("sys.stdout") as fake_stdout:
167 self.report.printObsTable()
169 # newline for each row plus header line, plus the line with dashes
170 self.assertEqual(len(fake_stdout.mock_calls), 2 * (self.nImages + 2))
172 def test_plotPerObjectAirMass(self):
173 """Test that a the per-object airmass plots runs."""
174 # We assume matplotlib is making plots, so just check that these
175 # don't crash.
177 # Default plotting:
178 self.report.plotPerObjectAirMass()
179 # plot with only one object as a str not a list of str
180 self.report.plotPerObjectAirMass(objects=self.report.stars[0])
181 # plot with first two objects as a list
182 self.report.plotPerObjectAirMass(objects=self.report.stars[0:2])
183 # flip y axis option
184 self.report.plotPerObjectAirMass(airmassOneAtTop=True)
185 # flip and select stars
186 self.report.plotPerObjectAirMass(objects=self.report.stars[0], airmassOneAtTop=True) # both
188 def test_makeAltAzCoveragePlot(self):
189 """Test that a the polar coverage plotting code runs."""
190 # We assume matplotlib is making plots, so just check that these
191 # don't crash.
193 # test the default case
194 self.report.makeAltAzCoveragePlot()
195 # plot with only one object as a str not a list of str
196 self.report.makeAltAzCoveragePlot(objects=self.report.stars[0])
197 # plot with first two objects as a list
198 self.report.makeAltAzCoveragePlot(objects=self.report.stars[0:2])
199 # test turning lines off
200 self.report.makeAltAzCoveragePlot(objects=self.report.stars[0:2], withLines=False)
202 def test_calcShutterTimes(self):
203 timings = self.report.calcShutterTimes()
204 if not timings:
205 return # if the day has no on-sky observations, this returns None
206 efficiency = 100 * (timings["scienceTimeTotal"] / timings["nightLength"])
207 self.assertGreater(efficiency, 0)
208 self.assertLessEqual(efficiency, 100)
210 def test_getDatesForSeqNums(self):
211 dateTimeDict = self.report.getDatesForSeqNums()
212 self.assertIsInstance(dateTimeDict, dict)
213 self.assertTrue(all(isinstance(seqNum, int) for seqNum in dateTimeDict.keys()))
214 self.assertTrue(all(isinstance(seqNum, datetime.datetime) for seqNum in dateTimeDict.values()))
216 def test_doesNotRaise(self):
217 """Tests for things which are hard to test, so just make sure they
218 run.
219 """
220 self.report.printShutterTimes()
221 for sample, includeRaw in itertools.product((True, False), (True, False)):
222 self.report.printAvailableKeys(sample=sample, includeRaw=includeRaw)
223 self.report.printObsTable()
224 for threshold, includeCalibs in itertools.product((0, 1, 10), (True, False)):
225 self.report.printObsGaps(threshold=threshold, includeCalibs=includeCalibs)
227 def test_internals(self):
228 startNum = self.report.getObservingStartSeqNum()
229 self.assertIsInstance(startNum, int)
230 self.assertGreater(startNum, 0) # the day starts at 1, so zero would be an error of some sort
232 starsFromGetter = self.report.getObservedObjects()
233 self.assertIsInstance(starsFromGetter, list)
234 self.assertSetEqual(set(starsFromGetter), set(self.report.stars))
236 starsFromGetter = self.report.getObservedObjects(ignoreTileNum=True)
237 self.assertLessEqual(len(starsFromGetter), len(self.report.stars))
239 # check the internal color map has the right number of items
240 self.assertEqual(len(self.report.cMap), len(starsFromGetter))
243class TestMemory(lsst.utils.tests.MemoryTestCase):
244 pass
247def setup_module(module):
248 lsst.utils.tests.init()
251if __name__ == "__main__": 251 ↛ 252line 251 didn't jump to line 252, because the condition on line 251 was never true
252 lsst.utils.tests.init()
253 unittest.main()