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