Coverage for tests/test_server.py: 16%
200 statements
« prev ^ index » next coverage.py v7.4.4, created at 2024-04-19 10:52 +0000
« prev ^ index » next coverage.py v7.4.4, created at 2024-04-19 10:52 +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 os.path
29import unittest
30import uuid
32from lsst.daf.butler.tests.dict_convertible_model import DictConvertibleModel
34try:
35 # Failing to import any of these should disable the tests.
36 import safir.dependencies.logger
37 from fastapi.testclient import TestClient
38 from lsst.daf.butler.remote_butler import RemoteButler
39 from lsst.daf.butler.remote_butler._authentication import _EXPLICIT_BUTLER_ACCESS_TOKEN_ENVIRONMENT_KEY
40 from lsst.daf.butler.remote_butler.server import create_app
41 from lsst.daf.butler.remote_butler.server._dependencies import butler_factory_dependency
42 from lsst.daf.butler.tests.server import TEST_REPOSITORY_NAME, UnhandledServerError, create_test_server
43except ImportError:
44 create_test_server = None
46from unittest.mock import NonCallableMock, patch
48from lsst.daf.butler import (
49 Butler,
50 DataCoordinate,
51 DatasetNotFoundError,
52 DatasetRef,
53 LabeledButlerFactory,
54 MissingDatasetTypeError,
55 NoDefaultCollectionError,
56 StorageClassFactory,
57)
58from lsst.daf.butler.datastore import DatasetRefURIs
59from lsst.daf.butler.tests import DatastoreMock, addDatasetType
60from lsst.daf.butler.tests.utils import MetricsExample, MetricTestRepo, mock_env
61from lsst.resources import ResourcePath
62from lsst.resources.http import HttpResourcePath
64TESTDIR = os.path.abspath(os.path.dirname(__file__))
67@unittest.skipIf(create_test_server is None, "Server dependencies not installed.")
68class ButlerClientServerTestCase(unittest.TestCase):
69 """Test for Butler client/server."""
71 @classmethod
72 def setUpClass(cls):
73 server_instance = cls.enterClassContext(create_test_server(TESTDIR))
74 cls.client = server_instance.client
75 cls.butler = server_instance.remote_butler
76 cls.butler_without_error_propagation = server_instance.remote_butler_without_error_propagation
78 cls.storageClassFactory = StorageClassFactory()
80 cls.repo = MetricTestRepo.create_from_butler(
81 server_instance.direct_butler, server_instance.config_file_path
82 )
83 # Add a file with corrupted data for testing error conditions
84 cls.dataset_with_corrupted_data = _create_corrupted_dataset(cls.repo)
85 # All of the datasets that come with MetricTestRepo are disassembled
86 # composites. Add a simple dataset for testing the common case.
87 cls.simple_dataset_ref = _create_simple_dataset(server_instance.direct_butler)
89 # Populate the test server.
90 # The DatastoreMock is required because the datasets referenced in
91 # these imports do not point at real files.
92 direct_butler = server_instance.direct_butler
93 DatastoreMock.apply(direct_butler)
94 direct_butler.import_(filename=os.path.join(TESTDIR, "data", "registry", "base.yaml"))
95 direct_butler.import_(filename=os.path.join(TESTDIR, "data", "registry", "datasets.yaml"))
97 def test_health_check(self):
98 try:
99 import importlib.metadata
101 importlib.metadata.metadata("lsst.daf.butler")
102 except ModuleNotFoundError:
103 raise self.skipTest("Standard python package metadata not available. Butler not pip installed.")
104 response = self.client.get("/")
105 self.assertEqual(response.status_code, 200)
106 self.assertEqual(response.json()["name"], "butler")
108 def test_dimension_universe(self):
109 universe = self.butler.dimensions
110 self.assertEqual(universe.namespace, "daf_butler")
112 def test_get_dataset_type(self):
113 bias_type = self.butler.get_dataset_type("bias")
114 self.assertEqual(bias_type.name, "bias")
116 with self.assertRaises(MissingDatasetTypeError):
117 self.butler_without_error_propagation.get_dataset_type("not_bias")
119 def test_find_dataset(self):
120 storage_class = self.storageClassFactory.getStorageClass("Exposure")
122 ref = self.butler.find_dataset("bias", collections="imported_g", detector=1, instrument="Cam1")
123 self.assertIsInstance(ref, DatasetRef)
124 self.assertEqual(ref.id, uuid.UUID("e15ab039-bc8b-4135-87c5-90902a7c0b22"))
125 self.assertFalse(ref.dataId.hasRecords())
127 # Try again with variation of parameters.
128 ref_new = self.butler.find_dataset(
129 "bias",
130 {"detector": 1},
131 collections="imported_g",
132 instrument="Cam1",
133 dimension_records=True,
134 )
135 self.assertEqual(ref_new, ref)
136 self.assertTrue(ref_new.dataId.hasRecords())
138 ref_new = self.butler.find_dataset(
139 ref.datasetType,
140 DataCoordinate.standardize(detector=1, instrument="Cam1", universe=self.butler.dimensions),
141 collections="imported_g",
142 storage_class=storage_class,
143 )
144 self.assertEqual(ref_new, ref)
146 ref2 = self.butler.get_dataset(ref.id)
147 self.assertEqual(ref2, ref)
149 # Use detector name to find it.
150 ref3 = self.butler.find_dataset(
151 ref.datasetType,
152 collections="imported_g",
153 instrument="Cam1",
154 full_name="Aa",
155 )
156 self.assertEqual(ref2, ref3)
158 # Try expanded refs.
159 self.assertFalse(ref.dataId.hasRecords())
160 expanded = self.butler.get_dataset(ref.id, dimension_records=True)
161 self.assertTrue(expanded.dataId.hasRecords())
163 # The test datasets are all Exposure so storage class conversion
164 # can not be tested until we fix that. For now at least test the
165 # code paths.
166 bias = self.butler.get_dataset(ref.id, storage_class=storage_class)
167 self.assertEqual(bias.datasetType.storageClass, storage_class)
169 # Unknown dataset should not fail.
170 self.assertIsNone(self.butler.get_dataset(uuid.uuid4()))
171 self.assertIsNone(self.butler.get_dataset(uuid.uuid4(), storage_class="NumpyArray"))
173 def test_instantiate_via_butler_http_search(self):
174 """Ensure that the primary Butler constructor's automatic search logic
175 correctly locates and reads the configuration file and ends up with a
176 RemoteButler pointing to the correct URL
177 """
179 # This is kind of a fragile test. Butler's search logic does a lot of
180 # manipulations involving creating new ResourcePaths, and ResourcePath
181 # doesn't use httpx so we can't easily inject the TestClient in there.
182 # We don't have an actual valid HTTP URL to give to the constructor
183 # because the test instance of the server is accessed via ASGI.
184 #
185 # Instead we just monkeypatch the HTTPResourcePath 'read' method and
186 # hope that all ResourcePath HTTP reads during construction are going
187 # to the server under test.
188 def override_read(http_resource_path):
189 return self.client.get(http_resource_path.geturl()).content
191 server_url = f"https://test.example/api/butler/repo/{TEST_REPOSITORY_NAME}/"
193 with patch.object(HttpResourcePath, "read", override_read):
194 # Add access key to environment variables. RemoteButler
195 # instantiation will throw an error if access key is not
196 # available.
197 with mock_env({_EXPLICIT_BUTLER_ACCESS_TOKEN_ENVIRONMENT_KEY: "fake-access-token"}):
198 butler = Butler(
199 server_url,
200 collections=["collection1", "collection2"],
201 run="collection2",
202 )
203 butler_factory = LabeledButlerFactory({"server": server_url})
204 factory_created_butler = butler_factory.create_butler(label="server", access_token="token")
205 self.assertIsInstance(butler, RemoteButler)
206 self.assertIsInstance(factory_created_butler, RemoteButler)
207 self.assertEqual(butler._connection.server_url, server_url)
208 self.assertEqual(factory_created_butler._connection.server_url, server_url)
210 self.assertEqual(butler.collections, ("collection1", "collection2"))
211 self.assertEqual(butler.run, "collection2")
213 def test_get(self):
214 dataset_type = "test_metric_comp"
215 data_id = {"instrument": "DummyCamComp", "visit": 423}
216 collections = "ingest/run"
217 # Test get() of a DatasetRef.
218 ref = self.butler.find_dataset(dataset_type, data_id, collections=collections)
219 metric = self.butler.get(ref)
220 self.assertIsInstance(metric, MetricsExample)
221 self.assertEqual(metric.summary, MetricTestRepo.METRICS_EXAMPLE_SUMMARY)
223 # Test get() by DataId.
224 data_id_metric = self.butler.get(dataset_type, dataId=data_id, collections=collections)
225 self.assertEqual(metric, data_id_metric)
226 # Test get() by DataId dict augmented with kwargs.
227 kwarg_metric = self.butler.get(
228 dataset_type, dataId={"instrument": "DummyCamComp"}, collections=collections, visit=423
229 )
230 self.assertEqual(metric, kwarg_metric)
231 # Test get() by DataId DataCoordinate augmented with kwargs.
232 coordinate = DataCoordinate.make_empty(self.butler.dimensions)
233 kwarg_data_coordinate_metric = self.butler.get(
234 dataset_type, dataId=coordinate, collections=collections, instrument="DummyCamComp", visit=423
235 )
236 self.assertEqual(metric, kwarg_data_coordinate_metric)
237 # Test get() of a non-existent DataId.
238 invalid_data_id = {"instrument": "NotAValidlInstrument", "visit": 423}
239 with self.assertRaises(DatasetNotFoundError):
240 self.butler_without_error_propagation.get(
241 dataset_type, dataId=invalid_data_id, collections=collections
242 )
244 # Test get() by DataId with default collections.
245 butler_with_default_collection = self.butler._clone(collections="ingest/run")
246 default_collection_metric = butler_with_default_collection.get(dataset_type, dataId=data_id)
247 self.assertEqual(metric, default_collection_metric)
249 # Test get() by DataId with no collections specified.
250 with self.assertRaises(NoDefaultCollectionError):
251 self.butler_without_error_propagation.get(dataset_type, dataId=data_id)
253 # Test looking up a non-existent ref
254 invalid_ref = ref.replace(id=uuid.uuid4())
255 with self.assertRaises(DatasetNotFoundError):
256 self.butler_without_error_propagation.get(invalid_ref)
258 with self.assertRaises(RuntimeError):
259 self.butler_without_error_propagation.get(self.dataset_with_corrupted_data)
261 # Test storage class override
262 new_sc = self.storageClassFactory.getStorageClass("MetricsConversion")
264 def check_sc_override(converted):
265 self.assertNotEqual(type(metric), type(converted))
266 self.assertIsInstance(converted, new_sc.pytype)
267 self.assertEqual(metric, converted)
269 check_sc_override(self.butler.get(ref, storageClass=new_sc))
271 # Test storage class override via DatasetRef.
272 check_sc_override(self.butler.get(ref.overrideStorageClass("MetricsConversion")))
273 # Test storage class override via DatasetType.
274 check_sc_override(
275 self.butler.get(
276 ref.datasetType.overrideStorageClass(new_sc), dataId=data_id, collections=collections
277 )
278 )
280 # Test component override via DatasetRef.
281 component_ref = ref.makeComponentRef("summary")
282 component_data = self.butler.get(component_ref)
283 self.assertEqual(component_data, MetricTestRepo.METRICS_EXAMPLE_SUMMARY)
285 # Test overriding both storage class and component via DatasetRef.
286 converted_component_data = self.butler.get(component_ref, storageClass="DictConvertibleModel")
287 self.assertIsInstance(converted_component_data, DictConvertibleModel)
288 self.assertEqual(converted_component_data.content, MetricTestRepo.METRICS_EXAMPLE_SUMMARY)
290 # Test component override via DatasetType.
291 dataset_type_component_data = self.butler.get(
292 component_ref.datasetType, component_ref.dataId, collections=collections
293 )
294 self.assertEqual(dataset_type_component_data, MetricTestRepo.METRICS_EXAMPLE_SUMMARY)
296 def test_getURIs_no_components(self):
297 # This dataset does not have components, and should return one URI.
298 def check_uri(uri: ResourcePath):
299 self.assertIsNotNone(uris.primaryURI)
300 self.assertEqual(uris.primaryURI.scheme, "https")
301 self.assertEqual(uris.primaryURI.read(), b"123")
303 uris = self.butler.getURIs(self.simple_dataset_ref)
304 self.assertEqual(len(uris.componentURIs), 0)
305 check_uri(uris.primaryURI)
307 check_uri(self.butler.getURI(self.simple_dataset_ref))
309 def test_getURIs_multiple_components(self):
310 # This dataset has multiple components, so we should get back multiple
311 # URIs.
312 dataset_type = "test_metric_comp"
313 data_id = {"instrument": "DummyCamComp", "visit": 423}
314 collections = "ingest/run"
316 def check_uris(uris: DatasetRefURIs):
317 self.assertIsNone(uris.primaryURI)
318 self.assertEqual(len(uris.componentURIs), 3)
319 path = uris.componentURIs["summary"]
320 self.assertEqual(path.scheme, "https")
321 data = path.read()
322 self.assertEqual(data, b"AM1: 5.2\nAM2: 30.6\n")
324 uris = self.butler.getURIs(dataset_type, dataId=data_id, collections=collections)
325 check_uris(uris)
327 # Calling getURI on a multi-file dataset raises an exception
328 with self.assertRaises(RuntimeError):
329 self.butler.getURI(dataset_type, dataId=data_id, collections=collections)
331 # getURIs does NOT respect component overrides on the DatasetRef,
332 # instead returning the parent's URIs. Unclear if this is "correct"
333 # from a conceptual point of view, but this matches DirectButler
334 # behavior.
335 ref = self.butler.find_dataset(dataset_type, data_id=data_id, collections=collections)
336 componentRef = ref.makeComponentRef("summary")
337 componentUris = self.butler.getURIs(componentRef)
338 check_uris(componentUris)
340 def test_auth_check(self):
341 # This is checking that the unit-test middleware for validating the
342 # authentication headers is working. It doesn't test actual server
343 # functionality -- in a real deployment, the authentication headers are
344 # handled by GafaelfawrIngress, not our app.
345 with self.assertRaises(UnhandledServerError) as cm:
346 self.client.get("/v1/dataset_type/int")
347 self.assertEqual(cm.exception.__cause__.status_code, 401)
349 def test_exception_logging(self):
350 app = create_app()
352 def raise_error():
353 raise RuntimeError("An unhandled error")
355 app.dependency_overrides[butler_factory_dependency] = raise_error
356 client = TestClient(app, raise_server_exceptions=False)
358 with patch.object(safir.dependencies.logger, "logger_dependency") as mock_logger_dep:
359 mock_logger = NonCallableMock(["aerror"])
361 async def noop():
362 pass
364 mock_logger.aerror.return_value = noop()
366 async def get_logger():
367 return mock_logger
369 mock_logger_dep.return_value = get_logger()
370 client.get(
371 "/api/butler/repo/something/v1/dataset_type/int",
372 headers={"X-Auth-Request-User": "user-name", "X-Butler-Client-Request-Id": "request-id"},
373 )
374 mock_logger_dep.assert_called_once()
376 mock_logger.aerror.assert_called_once()
377 args, kwargs = mock_logger.aerror.call_args
378 self.assertIsInstance(kwargs["exc_info"], RuntimeError)
379 self.assertEqual(kwargs["clientRequestId"], "request-id")
380 self.assertEqual(kwargs["user"], "user-name")
383def _create_corrupted_dataset(repo: MetricTestRepo) -> DatasetRef:
384 run = "corrupted-run"
385 ref = repo.addDataset({"instrument": "DummyCamComp", "visit": 423}, run=run)
386 uris = repo.butler.getURIs(ref)
387 oneOfTheComponents = list(uris.componentURIs.values())[0]
388 oneOfTheComponents.write("corrupted data")
389 return ref
392def _create_simple_dataset(butler: Butler) -> DatasetRef:
393 dataset_type = addDatasetType(butler, "test_int", {"instrument", "visit"}, "int")
394 ref = butler.put(123, dataset_type, dataId={"instrument": "DummyCamComp", "visit": 423}, run="ingest/run")
395 return ref
398if __name__ == "__main__":
399 unittest.main()