Coverage for tests/test_server.py: 18%
220 statements
« prev ^ index » next coverage.py v7.4.0, created at 2024-01-25 10:48 +0000
« prev ^ index » next coverage.py v7.4.0, created at 2024-01-25 10:48 +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 import HTTPException
38 from fastapi.testclient import TestClient
39 from lsst.daf.butler.remote_butler import RemoteButler, RemoteButlerFactory
40 from lsst.daf.butler.remote_butler._authentication import _EXPLICIT_BUTLER_ACCESS_TOKEN_ENVIRONMENT_KEY
41 from lsst.daf.butler.remote_butler.server import create_app
42 from lsst.daf.butler.remote_butler.server._dependencies import butler_factory_dependency
43 from lsst.daf.butler.tests.server_utils import add_auth_header_check_middleware
44 from lsst.resources.s3utils import clean_test_environment_for_s3, getS3Client
45 from moto import mock_s3
46except ImportError:
47 TestClient = None
48 create_app = None
50from unittest.mock import NonCallableMock, patch
52from lsst.daf.butler import (
53 Butler,
54 DataCoordinate,
55 DatasetRef,
56 LabeledButlerFactory,
57 MissingDatasetTypeError,
58 NoDefaultCollectionError,
59 StorageClassFactory,
60)
61from lsst.daf.butler._butler_instance_options import ButlerInstanceOptions
62from lsst.daf.butler.datastore import DatasetRefURIs
63from lsst.daf.butler.tests import DatastoreMock, addDatasetType
64from lsst.daf.butler.tests.utils import (
65 MetricsExample,
66 MetricTestRepo,
67 makeTestTempDir,
68 mock_env,
69 removeTestTempDir,
70)
71from lsst.resources import ResourcePath
72from lsst.resources.http import HttpResourcePath
74TESTDIR = os.path.abspath(os.path.dirname(__file__))
76TEST_REPOSITORY_NAME = "testrepo"
79def _make_test_client(app, raise_server_exceptions=True):
80 client = TestClient(app, raise_server_exceptions=raise_server_exceptions)
81 return client
84def _make_remote_butler(http_client, *, collections: str | None = None):
85 options = None
86 if collections is not None:
87 options = ButlerInstanceOptions(collections=collections)
88 factory = RemoteButlerFactory(f"https://test.example/api/butler/repo/{TEST_REPOSITORY_NAME}", http_client)
89 return factory.create_butler_for_access_token("fake-access-token", butler_options=options)
92@unittest.skipIf(TestClient is None or create_app is None, "FastAPI not installed.")
93class ButlerClientServerTestCase(unittest.TestCase):
94 """Test for Butler client/server."""
96 @classmethod
97 def setUpClass(cls):
98 # Set up a mock S3 environment using Moto. Moto also monkeypatches the
99 # `requests` library so that any HTTP requests to presigned S3 URLs get
100 # redirected to the mocked S3.
101 # Note that all files are stored in memory.
102 cls.enterClassContext(clean_test_environment_for_s3())
103 cls.enterClassContext(mock_s3())
104 bucket_name = "anybucketname" # matches s3Datastore.yaml
105 getS3Client().create_bucket(Bucket=bucket_name)
107 cls.storageClassFactory = StorageClassFactory()
109 # First create a butler and populate it.
110 cls.root = makeTestTempDir(TESTDIR)
111 cls.repo = MetricTestRepo(
112 root=cls.root,
113 configFile=os.path.join(TESTDIR, "config/basic/butler-s3store.yaml"),
114 forceConfigRoot=False,
115 )
116 # Add a file with corrupted data for testing error conditions
117 cls.dataset_with_corrupted_data = _create_corrupted_dataset(cls.repo)
118 # All of the datasets that come with MetricTestRepo are disassembled
119 # composites. Add a simple dataset for testing the common case.
120 cls.simple_dataset_ref = _create_simple_dataset(cls.repo.butler)
122 # Override the server's Butler initialization to point at our test repo
123 server_butler_factory = LabeledButlerFactory({TEST_REPOSITORY_NAME: cls.root})
125 app = create_app()
126 app.dependency_overrides[butler_factory_dependency] = lambda: server_butler_factory
127 add_auth_header_check_middleware(app)
129 # Set up the RemoteButler that will connect to the server
130 cls.client = _make_test_client(app)
131 cls.butler = _make_remote_butler(cls.client)
132 cls.butler_with_default_collection = _make_remote_butler(cls.client, collections="ingest/run")
133 # By default, the TestClient instance raises any unhandled exceptions
134 # from the server as if they had originated in the client to ease
135 # debugging. However, this can make it appear that error propagation
136 # is working correctly when in a real deployment the server exception
137 # would cause a 500 Internal Server Error. This instance of the butler
138 # is set up so that any unhandled server exceptions do return a 500
139 # status code.
140 cls.butler_without_error_propagation = _make_remote_butler(
141 _make_test_client(app, raise_server_exceptions=False)
142 )
144 # Populate the test server.
145 # The DatastoreMock is required because the datasets referenced in
146 # these imports do not point at real files.
147 DatastoreMock.apply(cls.repo.butler)
148 cls.repo.butler.import_(filename=os.path.join(TESTDIR, "data", "registry", "base.yaml"))
149 cls.repo.butler.import_(filename=os.path.join(TESTDIR, "data", "registry", "datasets.yaml"))
151 @classmethod
152 def tearDownClass(cls):
153 removeTestTempDir(cls.root)
155 def test_health_check(self):
156 response = self.client.get("/")
157 self.assertEqual(response.status_code, 200)
158 self.assertEqual(response.json()["name"], "butler")
160 def test_dimension_universe(self):
161 universe = self.butler.dimensions
162 self.assertEqual(universe.namespace, "daf_butler")
164 def test_get_dataset_type(self):
165 bias_type = self.butler.get_dataset_type("bias")
166 self.assertEqual(bias_type.name, "bias")
168 with self.assertRaises(MissingDatasetTypeError):
169 self.butler_without_error_propagation.get_dataset_type("not_bias")
171 def test_find_dataset(self):
172 storage_class = self.storageClassFactory.getStorageClass("Exposure")
174 ref = self.butler.find_dataset("bias", collections="imported_g", detector=1, instrument="Cam1")
175 self.assertIsInstance(ref, DatasetRef)
176 self.assertEqual(ref.id, uuid.UUID("e15ab039-bc8b-4135-87c5-90902a7c0b22"))
177 self.assertFalse(ref.dataId.hasRecords())
179 # Try again with variation of parameters.
180 ref_new = self.butler.find_dataset(
181 "bias",
182 {"detector": 1},
183 collections="imported_g",
184 instrument="Cam1",
185 dimension_records=True,
186 )
187 self.assertEqual(ref_new, ref)
188 self.assertTrue(ref_new.dataId.hasRecords())
190 ref_new = self.butler.find_dataset(
191 ref.datasetType,
192 DataCoordinate.standardize(detector=1, instrument="Cam1", universe=self.butler.dimensions),
193 collections="imported_g",
194 storage_class=storage_class,
195 )
196 self.assertEqual(ref_new, ref)
198 ref2 = self.butler.get_dataset(ref.id)
199 self.assertEqual(ref2, ref)
201 # Use detector name to find it.
202 ref3 = self.butler.find_dataset(
203 ref.datasetType,
204 collections="imported_g",
205 instrument="Cam1",
206 full_name="Aa",
207 )
208 self.assertEqual(ref2, ref3)
210 # Try expanded refs.
211 self.assertFalse(ref.dataId.hasRecords())
212 expanded = self.butler.get_dataset(ref.id, dimension_records=True)
213 self.assertTrue(expanded.dataId.hasRecords())
215 # The test datasets are all Exposure so storage class conversion
216 # can not be tested until we fix that. For now at least test the
217 # code paths.
218 bias = self.butler.get_dataset(ref.id, storage_class=storage_class)
219 self.assertEqual(bias.datasetType.storageClass, storage_class)
221 # Unknown dataset should not fail.
222 self.assertIsNone(self.butler.get_dataset(uuid.uuid4()))
223 self.assertIsNone(self.butler.get_dataset(uuid.uuid4(), storage_class="NumpyArray"))
225 def test_instantiate_via_butler_http_search(self):
226 """Ensure that the primary Butler constructor's automatic search logic
227 correctly locates and reads the configuration file and ends up with a
228 RemoteButler pointing to the correct URL
229 """
231 # This is kind of a fragile test. Butler's search logic does a lot of
232 # manipulations involving creating new ResourcePaths, and ResourcePath
233 # doesn't use httpx so we can't easily inject the TestClient in there.
234 # We don't have an actual valid HTTP URL to give to the constructor
235 # because the test instance of the server is accessed via ASGI.
236 #
237 # Instead we just monkeypatch the HTTPResourcePath 'read' method and
238 # hope that all ResourcePath HTTP reads during construction are going
239 # to the server under test.
240 def override_read(http_resource_path):
241 return self.client.get(http_resource_path.geturl()).content
243 server_url = f"https://test.example/api/butler/repo/{TEST_REPOSITORY_NAME}/"
245 with patch.object(HttpResourcePath, "read", override_read):
246 # Add access key to environment variables. RemoteButler
247 # instantiation will throw an error if access key is not
248 # available.
249 with mock_env({_EXPLICIT_BUTLER_ACCESS_TOKEN_ENVIRONMENT_KEY: "fake-access-token"}):
250 butler = Butler(
251 server_url,
252 collections=["collection1", "collection2"],
253 run="collection2",
254 )
255 butler_factory = LabeledButlerFactory({"server": server_url})
256 factory_created_butler = butler_factory.create_butler(label="server", access_token="token")
257 self.assertIsInstance(butler, RemoteButler)
258 self.assertIsInstance(factory_created_butler, RemoteButler)
259 self.assertEqual(butler._server_url, server_url)
260 self.assertEqual(factory_created_butler._server_url, server_url)
262 self.assertEqual(butler.collections, ("collection1", "collection2"))
263 self.assertEqual(butler.run, "collection2")
265 def test_get(self):
266 dataset_type = "test_metric_comp"
267 data_id = {"instrument": "DummyCamComp", "visit": 423}
268 collections = "ingest/run"
269 # Test get() of a DatasetRef.
270 ref = self.butler.find_dataset(dataset_type, data_id, collections=collections)
271 metric = self.butler.get(ref)
272 self.assertIsInstance(metric, MetricsExample)
273 self.assertEqual(metric.summary, MetricTestRepo.METRICS_EXAMPLE_SUMMARY)
275 # Test get() by DataId.
276 data_id_metric = self.butler.get(dataset_type, dataId=data_id, collections=collections)
277 self.assertEqual(metric, data_id_metric)
278 # Test get() by DataId dict augmented with kwargs.
279 kwarg_metric = self.butler.get(
280 dataset_type, dataId={"instrument": "DummyCamComp"}, collections=collections, visit=423
281 )
282 self.assertEqual(metric, kwarg_metric)
283 # Test get() by DataId DataCoordinate augmented with kwargs.
284 coordinate = DataCoordinate.make_empty(self.butler.dimensions)
285 kwarg_data_coordinate_metric = self.butler.get(
286 dataset_type, dataId=coordinate, collections=collections, instrument="DummyCamComp", visit=423
287 )
288 self.assertEqual(metric, kwarg_data_coordinate_metric)
289 # Test get() of a non-existent DataId.
290 invalid_data_id = {"instrument": "NotAValidlInstrument", "visit": 423}
291 with self.assertRaises(LookupError):
292 self.butler_without_error_propagation.get(
293 dataset_type, dataId=invalid_data_id, collections=collections
294 )
296 # Test get() by DataId with default collections.
297 default_collection_metric = self.butler_with_default_collection.get(dataset_type, dataId=data_id)
298 self.assertEqual(metric, default_collection_metric)
300 # Test get() by DataId with no collections specified.
301 with self.assertRaises(NoDefaultCollectionError):
302 self.butler_without_error_propagation.get(dataset_type, dataId=data_id)
304 # Test looking up a non-existent ref
305 invalid_ref = ref.replace(id=uuid.uuid4())
306 with self.assertRaises(LookupError):
307 self.butler_without_error_propagation.get(invalid_ref)
309 with self.assertRaises(RuntimeError):
310 self.butler_without_error_propagation.get(self.dataset_with_corrupted_data)
312 # Test storage class override
313 new_sc = self.storageClassFactory.getStorageClass("MetricsConversion")
315 def check_sc_override(converted):
316 self.assertNotEqual(type(metric), type(converted))
317 self.assertIsInstance(converted, new_sc.pytype)
318 self.assertEqual(metric, converted)
320 check_sc_override(self.butler.get(ref, storageClass=new_sc))
322 # Test storage class override via DatasetRef.
323 check_sc_override(self.butler.get(ref.overrideStorageClass("MetricsConversion")))
324 # Test storage class override via DatasetType.
325 check_sc_override(
326 self.butler.get(
327 ref.datasetType.overrideStorageClass(new_sc), dataId=data_id, collections=collections
328 )
329 )
331 # Test component override via DatasetRef.
332 component_ref = ref.makeComponentRef("summary")
333 component_data = self.butler.get(component_ref)
334 self.assertEqual(component_data, MetricTestRepo.METRICS_EXAMPLE_SUMMARY)
336 # Test overriding both storage class and component via DatasetRef.
337 converted_component_data = self.butler.get(component_ref, storageClass="DictConvertibleModel")
338 self.assertIsInstance(converted_component_data, DictConvertibleModel)
339 self.assertEqual(converted_component_data.content, MetricTestRepo.METRICS_EXAMPLE_SUMMARY)
341 # Test component override via DatasetType.
342 dataset_type_component_data = self.butler.get(
343 component_ref.datasetType, component_ref.dataId, collections=collections
344 )
345 self.assertEqual(dataset_type_component_data, MetricTestRepo.METRICS_EXAMPLE_SUMMARY)
347 def test_getURIs_no_components(self):
348 # This dataset does not have components, and should return one URI.
349 def check_uri(uri: ResourcePath):
350 self.assertIsNotNone(uris.primaryURI)
351 self.assertEqual(uris.primaryURI.scheme, "https")
352 self.assertEqual(uris.primaryURI.read(), b"123")
354 uris = self.butler.getURIs(self.simple_dataset_ref)
355 self.assertEqual(len(uris.componentURIs), 0)
356 check_uri(uris.primaryURI)
358 check_uri(self.butler.getURI(self.simple_dataset_ref))
360 def test_getURIs_multiple_components(self):
361 # This dataset has multiple components, so we should get back multiple
362 # URIs.
363 dataset_type = "test_metric_comp"
364 data_id = {"instrument": "DummyCamComp", "visit": 423}
365 collections = "ingest/run"
367 def check_uris(uris: DatasetRefURIs):
368 self.assertIsNone(uris.primaryURI)
369 self.assertEqual(len(uris.componentURIs), 3)
370 path = uris.componentURIs["summary"]
371 self.assertEqual(path.scheme, "https")
372 data = path.read()
373 self.assertEqual(data, b"AM1: 5.2\nAM2: 30.6\n")
375 uris = self.butler.getURIs(dataset_type, dataId=data_id, collections=collections)
376 check_uris(uris)
378 # Calling getURI on a multi-file dataset raises an exception
379 with self.assertRaises(RuntimeError):
380 self.butler.getURI(dataset_type, dataId=data_id, collections=collections)
382 # getURIs does NOT respect component overrides on the DatasetRef,
383 # instead returning the parent's URIs. Unclear if this is "correct"
384 # from a conceptual point of view, but this matches DirectButler
385 # behavior.
386 ref = self.butler.find_dataset(dataset_type, data_id=data_id, collections=collections)
387 componentRef = ref.makeComponentRef("summary")
388 componentUris = self.butler.getURIs(componentRef)
389 check_uris(componentUris)
391 def test_auth_check(self):
392 # This is checking that the unit-test middleware for validating the
393 # authentication headers is working. It doesn't test actual server
394 # functionality -- in a real deployment, the authentication headers are
395 # handled by GafaelfawrIngress, not our app.
396 with self.assertRaises(HTTPException) as cm:
397 self.client.get("/v1/dataset_type/int")
398 self.assertEqual(cm.exception.status_code, 401)
400 def test_exception_logging(self):
401 app = create_app()
403 def raise_error():
404 raise RuntimeError("An unhandled error")
406 app.dependency_overrides[butler_factory_dependency] = raise_error
407 client = _make_test_client(app, raise_server_exceptions=False)
409 with patch.object(safir.dependencies.logger, "logger_dependency") as mock_logger_dep:
410 mock_logger = NonCallableMock(["aerror"])
412 async def noop():
413 pass
415 mock_logger.aerror.return_value = noop()
417 async def get_logger():
418 return mock_logger
420 mock_logger_dep.return_value = get_logger()
421 client.get(
422 "/api/butler/repo/something/v1/dataset_type/int",
423 headers={"X-Auth-Request-User": "user-name", "X-Butler-Client-Request-Id": "request-id"},
424 )
425 mock_logger_dep.assert_called_once()
427 mock_logger.aerror.assert_called_once()
428 args, kwargs = mock_logger.aerror.call_args
429 self.assertIsInstance(kwargs["exc_info"], RuntimeError)
430 self.assertEqual(kwargs["clientRequestId"], "request-id")
431 self.assertEqual(kwargs["user"], "user-name")
434def _create_corrupted_dataset(repo: MetricTestRepo) -> DatasetRef:
435 run = "corrupted-run"
436 ref = repo.addDataset({"instrument": "DummyCamComp", "visit": 423}, run=run)
437 uris = repo.butler.getURIs(ref)
438 oneOfTheComponents = list(uris.componentURIs.values())[0]
439 oneOfTheComponents.write("corrupted data")
440 return ref
443def _create_simple_dataset(butler: Butler) -> DatasetRef:
444 dataset_type = addDatasetType(butler, "test_int", {"instrument", "visit"}, "int")
445 ref = butler.put(123, dataset_type, dataId={"instrument": "DummyCamComp", "visit": 423})
446 return ref
449if __name__ == "__main__":
450 unittest.main()