lsst.obs.base  20.0.0-48-gd64a390+cf2ddfd0ca
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  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"""
242  if self.curatedCalibrationDatasetTypes is None:
243  raise unittest.SkipTest("Class requests disabling of writeCuratedCalibrations test")
244 
246 
247  butler = Butler(self.root, writeable=False)
248  for datasetTypeName in self.curatedCalibrationDatasetTypes:
249  with self.subTest(dtype=datasetTypeName):
250  found = list(
251  butler.registry.queryDatasetAssociations(
252  datasetTypeName,
253  collections=self.instrumentClass.makeCalibrationCollectionName(),
254  )
255  )
256  self.assertGreater(len(found), 0, f"Checking {datasetTypeName}")
257 
258  def testDefineVisits(self):
259  if self.visits is None:
260  self.skipTest("Expected visits were not defined.")
261  self._ingestRaws(transfer="link")
262 
263  # Calling defineVisits tests the implementation of the butler command line interface "define-visits"
264  # subcommand. Functions in the script folder are generally considered protected and should not be used
265  # as public api.
266  script.defineVisits(self.root, config_file=None, collections=self.outputRun,
267  instrument=self.instrumentName)
268 
269  # Test that we got the visits we expected.
270  butler = Butler(self.root, run=self.outputRun)
271  visits = butler.registry.queryDataIds(["visit"]).expanded().toSet()
272  self.assertCountEqual(visits, self.visits.keys())
273  instr = getInstrument(self.instrumentName, butler.registry)
274  camera = instr.getCamera()
275  for foundVisit, (expectedVisit, expectedExposures) in zip(visits, self.visits.items()):
276  # Test that this visit is associated with the expected exposures.
277  foundExposures = butler.registry.queryDataIds(["exposure"], dataId=expectedVisit
278  ).expanded().toSet()
279  self.assertCountEqual(foundExposures, expectedExposures)
280  # Test that we have a visit region, and that it contains all of the
281  # detector+visit regions.
282  self.assertIsNotNone(foundVisit.region)
283  detectorVisitDataIds = butler.registry.queryDataIds(["visit", "detector"], dataId=expectedVisit
284  ).expanded().toSet()
285  self.assertEqual(len(detectorVisitDataIds), len(camera))
286  for dataId in detectorVisitDataIds:
287  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: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: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:206
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:240
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:202
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:258
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:233
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