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