Coverage for tests/test_server.py: 16%
195 statements
« prev ^ index » next coverage.py v7.4.4, created at 2024-03-26 02:48 -0700
« prev ^ index » next coverage.py v7.4.4, created at 2024-03-26 02:48 -0700
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 response = self.client.get("/")
99 self.assertEqual(response.status_code, 200)
100 self.assertEqual(response.json()["name"], "butler")
102 def test_dimension_universe(self):
103 universe = self.butler.dimensions
104 self.assertEqual(universe.namespace, "daf_butler")
106 def test_get_dataset_type(self):
107 bias_type = self.butler.get_dataset_type("bias")
108 self.assertEqual(bias_type.name, "bias")
110 with self.assertRaises(MissingDatasetTypeError):
111 self.butler_without_error_propagation.get_dataset_type("not_bias")
113 def test_find_dataset(self):
114 storage_class = self.storageClassFactory.getStorageClass("Exposure")
116 ref = self.butler.find_dataset("bias", collections="imported_g", detector=1, instrument="Cam1")
117 self.assertIsInstance(ref, DatasetRef)
118 self.assertEqual(ref.id, uuid.UUID("e15ab039-bc8b-4135-87c5-90902a7c0b22"))
119 self.assertFalse(ref.dataId.hasRecords())
121 # Try again with variation of parameters.
122 ref_new = self.butler.find_dataset(
123 "bias",
124 {"detector": 1},
125 collections="imported_g",
126 instrument="Cam1",
127 dimension_records=True,
128 )
129 self.assertEqual(ref_new, ref)
130 self.assertTrue(ref_new.dataId.hasRecords())
132 ref_new = self.butler.find_dataset(
133 ref.datasetType,
134 DataCoordinate.standardize(detector=1, instrument="Cam1", universe=self.butler.dimensions),
135 collections="imported_g",
136 storage_class=storage_class,
137 )
138 self.assertEqual(ref_new, ref)
140 ref2 = self.butler.get_dataset(ref.id)
141 self.assertEqual(ref2, ref)
143 # Use detector name to find it.
144 ref3 = self.butler.find_dataset(
145 ref.datasetType,
146 collections="imported_g",
147 instrument="Cam1",
148 full_name="Aa",
149 )
150 self.assertEqual(ref2, ref3)
152 # Try expanded refs.
153 self.assertFalse(ref.dataId.hasRecords())
154 expanded = self.butler.get_dataset(ref.id, dimension_records=True)
155 self.assertTrue(expanded.dataId.hasRecords())
157 # The test datasets are all Exposure so storage class conversion
158 # can not be tested until we fix that. For now at least test the
159 # code paths.
160 bias = self.butler.get_dataset(ref.id, storage_class=storage_class)
161 self.assertEqual(bias.datasetType.storageClass, storage_class)
163 # Unknown dataset should not fail.
164 self.assertIsNone(self.butler.get_dataset(uuid.uuid4()))
165 self.assertIsNone(self.butler.get_dataset(uuid.uuid4(), storage_class="NumpyArray"))
167 def test_instantiate_via_butler_http_search(self):
168 """Ensure that the primary Butler constructor's automatic search logic
169 correctly locates and reads the configuration file and ends up with a
170 RemoteButler pointing to the correct URL
171 """
173 # This is kind of a fragile test. Butler's search logic does a lot of
174 # manipulations involving creating new ResourcePaths, and ResourcePath
175 # doesn't use httpx so we can't easily inject the TestClient in there.
176 # We don't have an actual valid HTTP URL to give to the constructor
177 # because the test instance of the server is accessed via ASGI.
178 #
179 # Instead we just monkeypatch the HTTPResourcePath 'read' method and
180 # hope that all ResourcePath HTTP reads during construction are going
181 # to the server under test.
182 def override_read(http_resource_path):
183 return self.client.get(http_resource_path.geturl()).content
185 server_url = f"https://test.example/api/butler/repo/{TEST_REPOSITORY_NAME}/"
187 with patch.object(HttpResourcePath, "read", override_read):
188 # Add access key to environment variables. RemoteButler
189 # instantiation will throw an error if access key is not
190 # available.
191 with mock_env({_EXPLICIT_BUTLER_ACCESS_TOKEN_ENVIRONMENT_KEY: "fake-access-token"}):
192 butler = Butler(
193 server_url,
194 collections=["collection1", "collection2"],
195 run="collection2",
196 )
197 butler_factory = LabeledButlerFactory({"server": server_url})
198 factory_created_butler = butler_factory.create_butler(label="server", access_token="token")
199 self.assertIsInstance(butler, RemoteButler)
200 self.assertIsInstance(factory_created_butler, RemoteButler)
201 self.assertEqual(butler._server_url, server_url)
202 self.assertEqual(factory_created_butler._server_url, server_url)
204 self.assertEqual(butler.collections, ("collection1", "collection2"))
205 self.assertEqual(butler.run, "collection2")
207 def test_get(self):
208 dataset_type = "test_metric_comp"
209 data_id = {"instrument": "DummyCamComp", "visit": 423}
210 collections = "ingest/run"
211 # Test get() of a DatasetRef.
212 ref = self.butler.find_dataset(dataset_type, data_id, collections=collections)
213 metric = self.butler.get(ref)
214 self.assertIsInstance(metric, MetricsExample)
215 self.assertEqual(metric.summary, MetricTestRepo.METRICS_EXAMPLE_SUMMARY)
217 # Test get() by DataId.
218 data_id_metric = self.butler.get(dataset_type, dataId=data_id, collections=collections)
219 self.assertEqual(metric, data_id_metric)
220 # Test get() by DataId dict augmented with kwargs.
221 kwarg_metric = self.butler.get(
222 dataset_type, dataId={"instrument": "DummyCamComp"}, collections=collections, visit=423
223 )
224 self.assertEqual(metric, kwarg_metric)
225 # Test get() by DataId DataCoordinate augmented with kwargs.
226 coordinate = DataCoordinate.make_empty(self.butler.dimensions)
227 kwarg_data_coordinate_metric = self.butler.get(
228 dataset_type, dataId=coordinate, collections=collections, instrument="DummyCamComp", visit=423
229 )
230 self.assertEqual(metric, kwarg_data_coordinate_metric)
231 # Test get() of a non-existent DataId.
232 invalid_data_id = {"instrument": "NotAValidlInstrument", "visit": 423}
233 with self.assertRaises(DatasetNotFoundError):
234 self.butler_without_error_propagation.get(
235 dataset_type, dataId=invalid_data_id, collections=collections
236 )
238 # Test get() by DataId with default collections.
239 butler_with_default_collection = self.butler._clone(collections="ingest/run")
240 default_collection_metric = butler_with_default_collection.get(dataset_type, dataId=data_id)
241 self.assertEqual(metric, default_collection_metric)
243 # Test get() by DataId with no collections specified.
244 with self.assertRaises(NoDefaultCollectionError):
245 self.butler_without_error_propagation.get(dataset_type, dataId=data_id)
247 # Test looking up a non-existent ref
248 invalid_ref = ref.replace(id=uuid.uuid4())
249 with self.assertRaises(DatasetNotFoundError):
250 self.butler_without_error_propagation.get(invalid_ref)
252 with self.assertRaises(RuntimeError):
253 self.butler_without_error_propagation.get(self.dataset_with_corrupted_data)
255 # Test storage class override
256 new_sc = self.storageClassFactory.getStorageClass("MetricsConversion")
258 def check_sc_override(converted):
259 self.assertNotEqual(type(metric), type(converted))
260 self.assertIsInstance(converted, new_sc.pytype)
261 self.assertEqual(metric, converted)
263 check_sc_override(self.butler.get(ref, storageClass=new_sc))
265 # Test storage class override via DatasetRef.
266 check_sc_override(self.butler.get(ref.overrideStorageClass("MetricsConversion")))
267 # Test storage class override via DatasetType.
268 check_sc_override(
269 self.butler.get(
270 ref.datasetType.overrideStorageClass(new_sc), dataId=data_id, collections=collections
271 )
272 )
274 # Test component override via DatasetRef.
275 component_ref = ref.makeComponentRef("summary")
276 component_data = self.butler.get(component_ref)
277 self.assertEqual(component_data, MetricTestRepo.METRICS_EXAMPLE_SUMMARY)
279 # Test overriding both storage class and component via DatasetRef.
280 converted_component_data = self.butler.get(component_ref, storageClass="DictConvertibleModel")
281 self.assertIsInstance(converted_component_data, DictConvertibleModel)
282 self.assertEqual(converted_component_data.content, MetricTestRepo.METRICS_EXAMPLE_SUMMARY)
284 # Test component override via DatasetType.
285 dataset_type_component_data = self.butler.get(
286 component_ref.datasetType, component_ref.dataId, collections=collections
287 )
288 self.assertEqual(dataset_type_component_data, MetricTestRepo.METRICS_EXAMPLE_SUMMARY)
290 def test_getURIs_no_components(self):
291 # This dataset does not have components, and should return one URI.
292 def check_uri(uri: ResourcePath):
293 self.assertIsNotNone(uris.primaryURI)
294 self.assertEqual(uris.primaryURI.scheme, "https")
295 self.assertEqual(uris.primaryURI.read(), b"123")
297 uris = self.butler.getURIs(self.simple_dataset_ref)
298 self.assertEqual(len(uris.componentURIs), 0)
299 check_uri(uris.primaryURI)
301 check_uri(self.butler.getURI(self.simple_dataset_ref))
303 def test_getURIs_multiple_components(self):
304 # This dataset has multiple components, so we should get back multiple
305 # URIs.
306 dataset_type = "test_metric_comp"
307 data_id = {"instrument": "DummyCamComp", "visit": 423}
308 collections = "ingest/run"
310 def check_uris(uris: DatasetRefURIs):
311 self.assertIsNone(uris.primaryURI)
312 self.assertEqual(len(uris.componentURIs), 3)
313 path = uris.componentURIs["summary"]
314 self.assertEqual(path.scheme, "https")
315 data = path.read()
316 self.assertEqual(data, b"AM1: 5.2\nAM2: 30.6\n")
318 uris = self.butler.getURIs(dataset_type, dataId=data_id, collections=collections)
319 check_uris(uris)
321 # Calling getURI on a multi-file dataset raises an exception
322 with self.assertRaises(RuntimeError):
323 self.butler.getURI(dataset_type, dataId=data_id, collections=collections)
325 # getURIs does NOT respect component overrides on the DatasetRef,
326 # instead returning the parent's URIs. Unclear if this is "correct"
327 # from a conceptual point of view, but this matches DirectButler
328 # behavior.
329 ref = self.butler.find_dataset(dataset_type, data_id=data_id, collections=collections)
330 componentRef = ref.makeComponentRef("summary")
331 componentUris = self.butler.getURIs(componentRef)
332 check_uris(componentUris)
334 def test_auth_check(self):
335 # This is checking that the unit-test middleware for validating the
336 # authentication headers is working. It doesn't test actual server
337 # functionality -- in a real deployment, the authentication headers are
338 # handled by GafaelfawrIngress, not our app.
339 with self.assertRaises(UnhandledServerError) as cm:
340 self.client.get("/v1/dataset_type/int")
341 self.assertEqual(cm.exception.__cause__.status_code, 401)
343 def test_exception_logging(self):
344 app = create_app()
346 def raise_error():
347 raise RuntimeError("An unhandled error")
349 app.dependency_overrides[butler_factory_dependency] = raise_error
350 client = TestClient(app, raise_server_exceptions=False)
352 with patch.object(safir.dependencies.logger, "logger_dependency") as mock_logger_dep:
353 mock_logger = NonCallableMock(["aerror"])
355 async def noop():
356 pass
358 mock_logger.aerror.return_value = noop()
360 async def get_logger():
361 return mock_logger
363 mock_logger_dep.return_value = get_logger()
364 client.get(
365 "/api/butler/repo/something/v1/dataset_type/int",
366 headers={"X-Auth-Request-User": "user-name", "X-Butler-Client-Request-Id": "request-id"},
367 )
368 mock_logger_dep.assert_called_once()
370 mock_logger.aerror.assert_called_once()
371 args, kwargs = mock_logger.aerror.call_args
372 self.assertIsInstance(kwargs["exc_info"], RuntimeError)
373 self.assertEqual(kwargs["clientRequestId"], "request-id")
374 self.assertEqual(kwargs["user"], "user-name")
377def _create_corrupted_dataset(repo: MetricTestRepo) -> DatasetRef:
378 run = "corrupted-run"
379 ref = repo.addDataset({"instrument": "DummyCamComp", "visit": 423}, run=run)
380 uris = repo.butler.getURIs(ref)
381 oneOfTheComponents = list(uris.componentURIs.values())[0]
382 oneOfTheComponents.write("corrupted data")
383 return ref
386def _create_simple_dataset(butler: Butler) -> DatasetRef:
387 dataset_type = addDatasetType(butler, "test_int", {"instrument", "visit"}, "int")
388 ref = butler.put(123, dataset_type, dataId={"instrument": "DummyCamComp", "visit": 423}, run="ingest/run")
389 return ref
392if __name__ == "__main__":
393 unittest.main()