lsst.obs.base  20.0.0-54-gba713e9+a7d430d1e1
ingest_tests.py
Go to the documentation of this file.
1 # This file is part of obs_base.
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/>.
21 
22 """Base class for writing Gen3 raw data ingest tests.
23 """
24 
25 __all__ = ("IngestTestBase",)
26 
27 import abc
28 import tempfile
29 import unittest
30 import os
31 import shutil
32 
33 import lsst.afw.cameraGeom
34 from lsst.daf.butler import Butler
35 from lsst.daf.butler.cli.butler import cli as butlerCli
36 from lsst.daf.butler.cli.utils import LogCliRunner
37 import lsst.obs.base
38 from lsst.utils import doImport
39 from .utils import getInstrument
40 from . import script
41 
42 
43 class IngestTestBase(metaclass=abc.ABCMeta):
44  """Base class for tests of gen3 ingest. Subclass from this, then
45  `unittest.TestCase` to get a working test suite.
46  """
47 
48  ingestDir = ""
49  """Root path to ingest files into. Typically `obs_package/tests/`; the
50  actual directory will be a tempdir under this one.
51  """
52 
53  dataIds = []
54  """list of butler data IDs of files that should have been ingested."""
55 
56  file = ""
57  """Full path to a file to ingest in tests."""
58 
59  rawIngestTask = "lsst.obs.base.RawIngestTask"
60  """The task to use in the Ingest test."""
61 
62  curatedCalibrationDatasetTypes = None
63  """List or tuple of Datasets types that should be present after calling
64  writeCuratedCalibrations. If `None` writeCuratedCalibrations will
65  not be called and the test will be skipped."""
66 
67  defineVisitsTask = lsst.obs.base.DefineVisitsTask
68  """The task to use to define visits from groups of exposures.
69  This is ignored if ``visits`` is `None`.
70  """
71 
72  visits = {}
73  """A dictionary mapping visit data IDs the lists of exposure data IDs that
74  are associated with them.
75  If this is empty (but not `None`), visit definition will be run but no
76  visits will be expected (e.g. because no exposures are on-sky
77  observations).
78  """
79 
80  outputRun = "raw"
81  """The name of the output run to use in tests.
82  """
83 
84  @property
85  @abc.abstractmethod
87  """The fully qualified instrument class name.
88 
89  Returns
90  -------
91  `str`
92  The fully qualified instrument class name.
93  """
94  pass
95 
96  @property
97  def instrumentClass(self):
98  """The instrument class."""
99  return doImport(self.instrumentClassName)
100 
101  @property
102  def instrumentName(self):
103  """The name of the instrument.
104 
105  Returns
106  -------
107  `str`
108  The name of the instrument.
109  """
110  return self.instrumentClass.getName()
111 
112  def setUp(self):
113  # Use a temporary working directory
114  self.root = tempfile.mkdtemp(dir=self.ingestDir)
115  self._createRepo()
116 
117  # Register the instrument and its static metadata
118  self._registerInstrument()
119 
120  def tearDown(self):
121  if os.path.exists(self.root):
122  shutil.rmtree(self.root, ignore_errors=True)
123 
124  def verifyIngest(self, files=None, cli=False):
125  """
126  Test that RawIngestTask ingested the expected files.
127 
128  Parameters
129  ----------
130  files : `list` [`str`], or None
131  List of files to be ingested, or None to use ``self.file``
132  """
133  butler = Butler(self.root, run=self.outputRun)
134  datasets = butler.registry.queryDatasets(self.outputRun, collections=...)
135  self.assertEqual(len(list(datasets)), len(self.dataIds))
136  for dataId in self.dataIds:
137  exposure = butler.get(self.outputRun, dataId)
138  metadata = butler.get("raw.metadata", dataId)
139  self.assertEqual(metadata.toDict(), exposure.getMetadata().toDict())
140 
141  # Since components follow a different code path we check that
142  # WCS match and also we check that at least the shape
143  # of the image is the same (rather than doing per-pixel equality)
144  wcs = butler.get("raw.wcs", dataId)
145  self.assertEqual(wcs, exposure.getWcs())
146 
147  rawImage = butler.get("raw.image", dataId)
148  self.assertEqual(rawImage.getBBox(), exposure.getBBox())
149 
150  self.checkRepo(files=files)
151 
152  def checkRepo(self, files=None):
153  """Check the state of the repository after ingest.
154 
155  This is an optional hook provided for subclasses; by default it does
156  nothing.
157 
158  Parameters
159  ----------
160  files : `list` [`str`], or None
161  List of files to be ingested, or None to use ``self.file``
162  """
163  pass
164 
165  def _createRepo(self):
166  """Use the Click `testing` module to call the butler command line api
167  to create a repository."""
168  runner = LogCliRunner()
169  result = runner.invoke(butlerCli, ["create", self.root])
170  self.assertEqual(result.exit_code, 0, f"output: {result.output} exception: {result.exception}")
171 
172  def _ingestRaws(self, transfer):
173  """Use the Click `testing` module to call the butler command line api
174  to ingest raws.
175 
176  Parameters
177  ----------
178  transfer : `str`
179  The external data transfer type.
180  """
181  runner = LogCliRunner()
182  result = runner.invoke(butlerCli, ["ingest-raws", self.root, self.file,
183  "--output-run", self.outputRun,
184  "--transfer", transfer,
185  "--ingest-task", self.rawIngestTask])
186  self.assertEqual(result.exit_code, 0, f"output: {result.output} exception: {result.exception}")
187 
188  def _registerInstrument(self):
189  """Use the Click `testing` module to call the butler command line api
190  to register the instrument."""
191  runner = LogCliRunner()
192  result = runner.invoke(butlerCli, ["register-instrument", self.root, self.instrumentClassName])
193  self.assertEqual(result.exit_code, 0, f"output: {result.output} exception: {result.exception}")
194 
195  def _writeCuratedCalibrations(self):
196  """Use the Click `testing` module to call the butler command line api
197  to write curated calibrations."""
198  runner = LogCliRunner()
199  result = runner.invoke(butlerCli, ["write-curated-calibrations", self.root, self.instrumentName])
200  self.assertEqual(result.exit_code, 0, f"output: {result.output} exception: {result.exception}")
201 
202  def testLink(self):
203  self._ingestRaws(transfer="link")
204  self.verifyIngest()
205 
206  def testSymLink(self):
207  self._ingestRaws(transfer="symlink")
208  self.verifyIngest()
209 
210  def testCopy(self):
211  self._ingestRaws(transfer="copy")
212  self.verifyIngest()
213 
214  def testHardLink(self):
215  try:
216  self._ingestRaws(transfer="hardlink")
217  self.verifyIngest()
218  except PermissionError as err:
219  raise unittest.SkipTest("Skipping hard-link test because input data"
220  " is on a different filesystem.") from err
221 
222  def testInPlace(self):
223  """Test that files already in the directory can be added to the
224  registry in-place.
225  """
226  # symlink into repo root manually
227  butler = Butler(self.root, run=self.outputRun)
228  newPath = butler.datastore.root.join(os.path.basename(self.file))
229  os.symlink(os.path.abspath(self.file), newPath.ospath)
230  self._ingestRaws(transfer=None)
231  self.verifyIngest()
232 
234  """Re-ingesting the same data into the repository should fail.
235  """
236  self._ingestRaws(transfer="symlink")
237  with self.assertRaises(Exception):
238  self._ingestRaws(transfer="symlink")
239 
241  """Test that we can ingest the curated calibrations, and read them
242  with `loadCamera` both before and after.
243  """
244  if self.curatedCalibrationDatasetTypes is None:
245  raise unittest.SkipTest("Class requests disabling of writeCuratedCalibrations test")
246 
247  butler = Butler(self.root, writeable=False)
248  collection = self.instrumentClass.makeCalibrationCollectionName()
249 
250  # Trying to load a camera with a data ID not known to the registry
251  # is an error, because we can't get any temporal information.
252  with self.assertRaises(LookupError):
253  lsst.obs.base.loadCamera(butler, self.dataIds[0], collections=collection)
254 
255  # Ingest raws in order to get some exposure records.
256  self._ingestRaws(transfer="auto")
257 
258  # Load camera should returned an unversioned camera because there's
259  # nothing in the repo.
260  camera, isVersioned = lsst.obs.base.loadCamera(butler, self.dataIds[0], collections=collection)
261  self.assertFalse(isVersioned)
262  self.assertIsInstance(camera, lsst.afw.cameraGeom.Camera)
263 
265 
266  # Make a new butler instance to make sure we don't have any stale
267  # caches (e.g. of DatasetTypes). Note that we didn't give
268  # _writeCuratedCalibrations the butler instance we had, because it's
269  # trying to test the CLI interface anyway.
270  butler = Butler(self.root, writeable=False)
271 
272  for datasetTypeName in self.curatedCalibrationDatasetTypes:
273  with self.subTest(dtype=datasetTypeName):
274  found = list(
275  butler.registry.queryDatasetAssociations(
276  datasetTypeName,
277  collections=collection,
278  )
279  )
280  self.assertGreater(len(found), 0, f"Checking {datasetTypeName}")
281 
282  # Load camera should returned the versioned camera from the repo.
283  camera, isVersioned = lsst.obs.base.loadCamera(butler, self.dataIds[0], collections=collection)
284  self.assertTrue(isVersioned)
285  self.assertIsInstance(camera, lsst.afw.cameraGeom.Camera)
286 
287  def testDefineVisits(self):
288  if self.visits is None:
289  self.skipTest("Expected visits were not defined.")
290  self._ingestRaws(transfer="link")
291 
292  # Calling defineVisits tests the implementation of the butler command line interface "define-visits"
293  # subcommand. Functions in the script folder are generally considered protected and should not be used
294  # as public api.
295  script.defineVisits(self.root, config_file=None, collections=self.outputRun,
296  instrument=self.instrumentName)
297 
298  # Test that we got the visits we expected.
299  butler = Butler(self.root, run=self.outputRun)
300  visits = butler.registry.queryDataIds(["visit"]).expanded().toSet()
301  self.assertCountEqual(visits, self.visits.keys())
302  instr = getInstrument(self.instrumentName, butler.registry)
303  camera = instr.getCamera()
304  for foundVisit, (expectedVisit, expectedExposures) in zip(visits, self.visits.items()):
305  # Test that this visit is associated with the expected exposures.
306  foundExposures = butler.registry.queryDataIds(["exposure"], dataId=expectedVisit
307  ).expanded().toSet()
308  self.assertCountEqual(foundExposures, expectedExposures)
309  # Test that we have a visit region, and that it contains all of the
310  # detector+visit regions.
311  self.assertIsNotNone(foundVisit.region)
312  detectorVisitDataIds = butler.registry.queryDataIds(["visit", "detector"], dataId=expectedVisit
313  ).expanded().toSet()
314  self.assertEqual(len(detectorVisitDataIds), len(camera))
315  for dataId in detectorVisitDataIds:
316  self.assertTrue(foundVisit.region.contains(dataId.region))
lsst.obs.base.ingest_tests.IngestTestBase.verifyIngest
def verifyIngest(self, files=None, cli=False)
Definition: ingest_tests.py:124
lsst.obs.base.ingest_tests.IngestTestBase.setUp
def setUp(self)
Definition: ingest_tests.py:112
lsst.obs.base.utils.getInstrument
def getInstrument(instrumentName, registry=None)
Definition: utils.py:131
lsst.obs.base.ingest_tests.IngestTestBase.testHardLink
def testHardLink(self)
Definition: ingest_tests.py:214
lsst.obs.base.ingest_tests.IngestTestBase.testInPlace
def testInPlace(self)
Definition: ingest_tests.py:222
lsst.obs.base.ingest_tests.IngestTestBase.testCopy
def testCopy(self)
Definition: ingest_tests.py:210
lsst.obs.base.ingest_tests.IngestTestBase.visits
dictionary visits
Definition: ingest_tests.py:72
lsst.obs.base.ingest_tests.IngestTestBase.ingestDir
string ingestDir
Definition: ingest_tests.py:48
lsst.obs.base.ingest_tests.IngestTestBase.instrumentName
def instrumentName(self)
Definition: ingest_tests.py:102
lsst.obs.base.ingest_tests.IngestTestBase.dataIds
list dataIds
Definition: ingest_tests.py:53
lsst.obs.base.ingest_tests.IngestTestBase.tearDown
def tearDown(self)
Definition: ingest_tests.py:120
lsst.obs.base.ingest_tests.IngestTestBase.testSymLink
def testSymLink(self)
Definition: ingest_tests.py:206
lsst.obs.base.ingest_tests.IngestTestBase._ingestRaws
def _ingestRaws(self, transfer)
Definition: ingest_tests.py:172
lsst.obs.base.ingest_tests.IngestTestBase.testWriteCuratedCalibrations
def testWriteCuratedCalibrations(self)
Definition: ingest_tests.py:240
lsst.obs.base.ingest_tests.IngestTestBase._registerInstrument
def _registerInstrument(self)
Definition: ingest_tests.py:188
lsst::utils
lsst.obs.base.defineVisits.DefineVisitsTask
Definition: defineVisits.py:281
lsst.obs.base.ingest_tests.IngestTestBase.instrumentClass
def instrumentClass(self)
Definition: ingest_tests.py:97
lsst.obs.base.ingest_tests.IngestTestBase._createRepo
def _createRepo(self)
Definition: ingest_tests.py:165
lsst.obs.base.ingest_tests.IngestTestBase.curatedCalibrationDatasetTypes
curatedCalibrationDatasetTypes
Definition: ingest_tests.py:62
lsst.obs.base.ingest_tests.IngestTestBase.root
root
Definition: ingest_tests.py:114
lsst.obs.base.ingest_tests.IngestTestBase.testLink
def testLink(self)
Definition: ingest_tests.py:202
lsst.obs.base.ingest_tests.IngestTestBase.file
string file
Definition: ingest_tests.py:56
lsst.obs.base.ingest_tests.IngestTestBase.testDefineVisits
def testDefineVisits(self)
Definition: ingest_tests.py:287
lsst.obs.base.ingest_tests.IngestTestBase._writeCuratedCalibrations
def _writeCuratedCalibrations(self)
Definition: ingest_tests.py:195
lsst.obs.base.ingest_tests.IngestTestBase.outputRun
string outputRun
Definition: ingest_tests.py:80
lsst.obs.base.ingest_tests.IngestTestBase.checkRepo
def checkRepo(self, files=None)
Definition: ingest_tests.py:152
lsst.obs.base.ingest_tests.IngestTestBase.testFailOnConflict
def testFailOnConflict(self)
Definition: ingest_tests.py:233
lsst.obs.base.ingest_tests.IngestTestBase
Definition: ingest_tests.py:43
lsst.obs.base.ingest_tests.IngestTestBase.instrumentClassName
def instrumentClassName(self)
Definition: ingest_tests.py:86
lsst.obs.base
Definition: __init__.py:1