Coverage for tests/test_datastore.py: 17%
823 statements
« prev ^ index » next coverage.py v6.4, created at 2022-05-24 02:27 -0700
« prev ^ index » next coverage.py v6.4, created at 2022-05-24 02:27 -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 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 <http://www.gnu.org/licenses/>.
22import os
23import shutil
24import tempfile
25import time
26import unittest
27from dataclasses import dataclass
29import lsst.utils.tests
30import yaml
31from lsst.daf.butler import (
32 Config,
33 DatasetTypeNotSupportedError,
34 DatastoreCacheManager,
35 DatastoreCacheManagerConfig,
36 DatastoreConfig,
37 DatastoreDisabledCacheManager,
38 DatastoreValidationError,
39 DimensionUniverse,
40 FileDataset,
41 NamedKeyDict,
42 StorageClass,
43 StorageClassFactory,
44)
45from lsst.daf.butler.formatters.yaml import YamlFormatter
46from lsst.daf.butler.tests import (
47 BadNoWriteFormatter,
48 BadWriteFormatter,
49 DatasetTestHelper,
50 DatastoreTestHelper,
51 DummyRegistry,
52 MetricsExample,
53)
54from lsst.resources import ResourcePath
55from lsst.utils import doImport
57TESTDIR = os.path.dirname(__file__)
60def makeExampleMetrics(use_none=False):
61 if use_none:
62 array = None
63 else:
64 array = [563, 234, 456.7, 105, 2054, -1045]
65 return MetricsExample(
66 {"AM1": 5.2, "AM2": 30.6},
67 {"a": [1, 2, 3], "b": {"blue": 5, "red": "green"}},
68 array,
69 )
72@dataclass(frozen=True)
73class Named:
74 name: str
77class FakeDataCoordinate(NamedKeyDict):
78 """A fake hashable frozen DataCoordinate built from a simple dict."""
80 @classmethod
81 def from_dict(cls, dataId):
82 new = cls()
83 for k, v in dataId.items():
84 new[Named(k)] = v
85 return new.freeze()
87 def __hash__(self) -> int:
88 return hash(frozenset(self.items()))
91class TransactionTestError(Exception):
92 """Specific error for transactions, to prevent misdiagnosing
93 that might otherwise occur when a standard exception is used.
94 """
96 pass
99class DatastoreTestsBase(DatasetTestHelper, DatastoreTestHelper):
100 """Support routines for datastore testing"""
102 root = None
104 @classmethod
105 def setUpClass(cls):
106 # Storage Classes are fixed for all datastores in these tests
107 scConfigFile = os.path.join(TESTDIR, "config/basic/storageClasses.yaml")
108 cls.storageClassFactory = StorageClassFactory()
109 cls.storageClassFactory.addFromConfig(scConfigFile)
111 # Read the Datastore config so we can get the class
112 # information (since we should not assume the constructor
113 # name here, but rely on the configuration file itself)
114 datastoreConfig = DatastoreConfig(cls.configFile)
115 cls.datastoreType = doImport(datastoreConfig["cls"])
116 cls.universe = DimensionUniverse()
118 def setUp(self):
119 self.setUpDatastoreTests(DummyRegistry, DatastoreConfig)
121 def tearDown(self):
122 if self.root is not None and os.path.exists(self.root):
123 shutil.rmtree(self.root, ignore_errors=True)
126class DatastoreTests(DatastoreTestsBase):
127 """Some basic tests of a simple datastore."""
129 hasUnsupportedPut = True
131 def testConfigRoot(self):
132 full = DatastoreConfig(self.configFile)
133 config = DatastoreConfig(self.configFile, mergeDefaults=False)
134 newroot = "/random/location"
135 self.datastoreType.setConfigRoot(newroot, config, full)
136 if self.rootKeys:
137 for k in self.rootKeys:
138 self.assertIn(newroot, config[k])
140 def testConstructor(self):
141 datastore = self.makeDatastore()
142 self.assertIsNotNone(datastore)
143 self.assertIs(datastore.isEphemeral, self.isEphemeral)
145 def testConfigurationValidation(self):
146 datastore = self.makeDatastore()
147 sc = self.storageClassFactory.getStorageClass("ThingOne")
148 datastore.validateConfiguration([sc])
150 sc2 = self.storageClassFactory.getStorageClass("ThingTwo")
151 if self.validationCanFail:
152 with self.assertRaises(DatastoreValidationError):
153 datastore.validateConfiguration([sc2], logFailures=True)
155 dimensions = self.universe.extract(("visit", "physical_filter"))
156 dataId = {"instrument": "dummy", "visit": 52, "physical_filter": "V"}
157 ref = self.makeDatasetRef("metric", dimensions, sc, dataId, conform=False)
158 datastore.validateConfiguration([ref])
160 def testParameterValidation(self):
161 """Check that parameters are validated"""
162 sc = self.storageClassFactory.getStorageClass("ThingOne")
163 dimensions = self.universe.extract(("visit", "physical_filter"))
164 dataId = {"instrument": "dummy", "visit": 52, "physical_filter": "V"}
165 ref = self.makeDatasetRef("metric", dimensions, sc, dataId, conform=False)
166 datastore = self.makeDatastore()
167 data = {1: 2, 3: 4}
168 datastore.put(data, ref)
169 newdata = datastore.get(ref)
170 self.assertEqual(data, newdata)
171 with self.assertRaises(KeyError):
172 newdata = datastore.get(ref, parameters={"missing": 5})
174 def testBasicPutGet(self):
175 metrics = makeExampleMetrics()
176 datastore = self.makeDatastore()
178 # Create multiple storage classes for testing different formulations
179 storageClasses = [
180 self.storageClassFactory.getStorageClass(sc)
181 for sc in ("StructuredData", "StructuredDataJson", "StructuredDataPickle")
182 ]
184 dimensions = self.universe.extract(("visit", "physical_filter"))
185 dataId = {"instrument": "dummy", "visit": 52, "physical_filter": "V"}
187 for sc in storageClasses:
188 ref = self.makeDatasetRef("metric", dimensions, sc, dataId, conform=False)
189 print("Using storageClass: {}".format(sc.name))
190 datastore.put(metrics, ref)
192 # Does it exist?
193 self.assertTrue(datastore.exists(ref))
195 # Get
196 metricsOut = datastore.get(ref, parameters=None)
197 self.assertEqual(metrics, metricsOut)
199 uri = datastore.getURI(ref)
200 self.assertEqual(uri.scheme, self.uriScheme)
202 # Get a component -- we need to construct new refs for them
203 # with derived storage classes but with parent ID
204 for comp in ("data", "output"):
205 compRef = ref.makeComponentRef(comp)
206 output = datastore.get(compRef)
207 self.assertEqual(output, getattr(metricsOut, comp))
209 uri = datastore.getURI(compRef)
210 self.assertEqual(uri.scheme, self.uriScheme)
212 storageClass = sc
214 # Check that we can put a metric with None in a component and
215 # get it back as None
216 metricsNone = makeExampleMetrics(use_none=True)
217 dataIdNone = {"instrument": "dummy", "visit": 54, "physical_filter": "V"}
218 refNone = self.makeDatasetRef("metric", dimensions, sc, dataIdNone, conform=False)
219 datastore.put(metricsNone, refNone)
221 comp = "data"
222 for comp in ("data", "output"):
223 compRef = refNone.makeComponentRef(comp)
224 output = datastore.get(compRef)
225 self.assertEqual(output, getattr(metricsNone, comp))
227 # Check that a put fails if the dataset type is not supported
228 if self.hasUnsupportedPut:
229 sc = StorageClass("UnsupportedSC", pytype=type(metrics))
230 ref = self.makeDatasetRef("unsupportedType", dimensions, sc, dataId)
231 with self.assertRaises(DatasetTypeNotSupportedError):
232 datastore.put(metrics, ref)
234 # These should raise
235 ref = self.makeDatasetRef("metrics", dimensions, storageClass, dataId, id=10000)
236 with self.assertRaises(FileNotFoundError):
237 # non-existing file
238 datastore.get(ref)
240 # Get a URI from it
241 uri = datastore.getURI(ref, predict=True)
242 self.assertEqual(uri.scheme, self.uriScheme)
244 with self.assertRaises(FileNotFoundError):
245 datastore.getURI(ref)
247 def testTrustGetRequest(self):
248 """Check that we can get datasets that registry knows nothing about."""
250 datastore = self.makeDatastore()
252 # Skip test if the attribute is not defined
253 if not hasattr(datastore, "trustGetRequest"):
254 return
256 metrics = makeExampleMetrics()
258 i = 0
259 for sc_name in ("StructuredData", "StructuredComposite"):
260 i += 1
261 datasetTypeName = f"metric{i}"
263 if sc_name == "StructuredComposite":
264 disassembled = True
265 else:
266 disassembled = False
268 # Start datastore in default configuration of using registry
269 datastore.trustGetRequest = False
271 # Create multiple storage classes for testing with or without
272 # disassembly
273 sc = self.storageClassFactory.getStorageClass(sc_name)
274 dimensions = self.universe.extract(("visit", "physical_filter"))
275 dataId = {"instrument": "dummy", "visit": 52 + i, "physical_filter": "V"}
277 ref = self.makeDatasetRef(datasetTypeName, dimensions, sc, dataId, conform=False)
278 datastore.put(metrics, ref)
280 # Does it exist?
281 self.assertTrue(datastore.exists(ref))
283 # Get
284 metricsOut = datastore.get(ref)
285 self.assertEqual(metrics, metricsOut)
287 # Get the URI(s)
288 primaryURI, componentURIs = datastore.getURIs(ref)
289 if disassembled:
290 self.assertIsNone(primaryURI)
291 self.assertEqual(len(componentURIs), 3)
292 else:
293 self.assertIn(datasetTypeName, primaryURI.path)
294 self.assertFalse(componentURIs)
296 # Delete registry entry so now we are trusting
297 datastore.removeStoredItemInfo(ref)
299 # Now stop trusting and check that things break
300 datastore.trustGetRequest = False
302 # Does it exist?
303 self.assertFalse(datastore.exists(ref))
305 with self.assertRaises(FileNotFoundError):
306 datastore.get(ref)
308 with self.assertRaises(FileNotFoundError):
309 datastore.get(ref.makeComponentRef("data"))
311 # URI should fail unless we ask for prediction
312 with self.assertRaises(FileNotFoundError):
313 datastore.getURIs(ref)
315 predicted_primary, predicted_disassembled = datastore.getURIs(ref, predict=True)
316 if disassembled:
317 self.assertIsNone(predicted_primary)
318 self.assertEqual(len(predicted_disassembled), 3)
319 for uri in predicted_disassembled.values():
320 self.assertEqual(uri.fragment, "predicted")
321 self.assertIn(datasetTypeName, uri.path)
322 else:
323 self.assertIn(datasetTypeName, predicted_primary.path)
324 self.assertFalse(predicted_disassembled)
325 self.assertEqual(predicted_primary.fragment, "predicted")
327 # Now enable registry-free trusting mode
328 datastore.trustGetRequest = True
330 # Try again to get it
331 metricsOut = datastore.get(ref)
332 self.assertEqual(metricsOut, metrics)
334 # Does it exist?
335 self.assertTrue(datastore.exists(ref))
337 # Get a component
338 comp = "data"
339 compRef = ref.makeComponentRef(comp)
340 output = datastore.get(compRef)
341 self.assertEqual(output, getattr(metrics, comp))
343 # Get the URI -- if we trust this should work even without
344 # enabling prediction.
345 primaryURI2, componentURIs2 = datastore.getURIs(ref)
346 self.assertEqual(primaryURI2, primaryURI)
347 self.assertEqual(componentURIs2, componentURIs)
349 def testDisassembly(self):
350 """Test disassembly within datastore."""
351 metrics = makeExampleMetrics()
352 if self.isEphemeral:
353 # in-memory datastore does not disassemble
354 return
356 # Create multiple storage classes for testing different formulations
357 # of composites. One of these will not disassemble to provide
358 # a reference.
359 storageClasses = [
360 self.storageClassFactory.getStorageClass(sc)
361 for sc in (
362 "StructuredComposite",
363 "StructuredCompositeTestA",
364 "StructuredCompositeTestB",
365 "StructuredCompositeReadComp",
366 "StructuredData", # No disassembly
367 "StructuredCompositeReadCompNoDisassembly",
368 )
369 ]
371 # Create the test datastore
372 datastore = self.makeDatastore()
374 # Dummy dataId
375 dimensions = self.universe.extract(("visit", "physical_filter"))
376 dataId = {"instrument": "dummy", "visit": 428, "physical_filter": "R"}
378 for i, sc in enumerate(storageClasses):
379 with self.subTest(storageClass=sc.name):
380 # Create a different dataset type each time round
381 # so that a test failure in this subtest does not trigger
382 # a cascade of tests because of file clashes
383 ref = self.makeDatasetRef(f"metric_comp_{i}", dimensions, sc, dataId, conform=False)
385 disassembled = sc.name not in {"StructuredData", "StructuredCompositeReadCompNoDisassembly"}
387 datastore.put(metrics, ref)
389 baseURI, compURIs = datastore.getURIs(ref)
390 if disassembled:
391 self.assertIsNone(baseURI)
392 self.assertEqual(set(compURIs), {"data", "output", "summary"})
393 else:
394 self.assertIsNotNone(baseURI)
395 self.assertEqual(compURIs, {})
397 metrics_get = datastore.get(ref)
398 self.assertEqual(metrics_get, metrics)
400 # Retrieve the composite with read parameter
401 stop = 4
402 metrics_get = datastore.get(ref, parameters={"slice": slice(stop)})
403 self.assertEqual(metrics_get.summary, metrics.summary)
404 self.assertEqual(metrics_get.output, metrics.output)
405 self.assertEqual(metrics_get.data, metrics.data[:stop])
407 # Retrieve a component
408 data = datastore.get(ref.makeComponentRef("data"))
409 self.assertEqual(data, metrics.data)
411 # On supported storage classes attempt to access a read
412 # only component
413 if "ReadComp" in sc.name:
414 cRef = ref.makeComponentRef("counter")
415 counter = datastore.get(cRef)
416 self.assertEqual(counter, len(metrics.data))
418 counter = datastore.get(cRef, parameters={"slice": slice(stop)})
419 self.assertEqual(counter, stop)
421 datastore.remove(ref)
423 def testRegistryCompositePutGet(self):
424 """Tests the case where registry disassembles and puts to datastore."""
425 metrics = makeExampleMetrics()
426 datastore = self.makeDatastore()
428 # Create multiple storage classes for testing different formulations
429 # of composites
430 storageClasses = [
431 self.storageClassFactory.getStorageClass(sc)
432 for sc in (
433 "StructuredComposite",
434 "StructuredCompositeTestA",
435 "StructuredCompositeTestB",
436 )
437 ]
439 dimensions = self.universe.extract(("visit", "physical_filter"))
440 dataId = {"instrument": "dummy", "visit": 428, "physical_filter": "R"}
442 for sc in storageClasses:
443 print("Using storageClass: {}".format(sc.name))
444 ref = self.makeDatasetRef("metric", dimensions, sc, dataId, conform=False)
446 components = sc.delegate().disassemble(metrics)
447 self.assertTrue(components)
449 compsRead = {}
450 for compName, compInfo in components.items():
451 compRef = self.makeDatasetRef(
452 ref.datasetType.componentTypeName(compName),
453 dimensions,
454 components[compName].storageClass,
455 dataId,
456 conform=False,
457 )
459 print("Writing component {} with {}".format(compName, compRef.datasetType.storageClass.name))
460 datastore.put(compInfo.component, compRef)
462 uri = datastore.getURI(compRef)
463 self.assertEqual(uri.scheme, self.uriScheme)
465 compsRead[compName] = datastore.get(compRef)
467 # We can generate identical files for each storage class
468 # so remove the component here
469 datastore.remove(compRef)
471 # combine all the components we read back into a new composite
472 metricsOut = sc.delegate().assemble(compsRead)
473 self.assertEqual(metrics, metricsOut)
475 def prepDeleteTest(self, n_refs=1):
476 metrics = makeExampleMetrics()
477 datastore = self.makeDatastore()
478 # Put
479 dimensions = self.universe.extract(("visit", "physical_filter"))
480 sc = self.storageClassFactory.getStorageClass("StructuredData")
481 refs = []
482 for i in range(n_refs):
483 dataId = FakeDataCoordinate.from_dict(
484 {"instrument": "dummy", "visit": 638 + i, "physical_filter": "U"}
485 )
486 ref = self.makeDatasetRef("metric", dimensions, sc, dataId, conform=False)
487 datastore.put(metrics, ref)
489 # Does it exist?
490 self.assertTrue(datastore.exists(ref))
492 # Get
493 metricsOut = datastore.get(ref)
494 self.assertEqual(metrics, metricsOut)
495 refs.append(ref)
497 return datastore, *refs
499 def testRemove(self):
500 datastore, ref = self.prepDeleteTest()
502 # Remove
503 datastore.remove(ref)
505 # Does it exist?
506 self.assertFalse(datastore.exists(ref))
508 # Do we now get a predicted URI?
509 uri = datastore.getURI(ref, predict=True)
510 self.assertEqual(uri.fragment, "predicted")
512 # Get should now fail
513 with self.assertRaises(FileNotFoundError):
514 datastore.get(ref)
515 # Can only delete once
516 with self.assertRaises(FileNotFoundError):
517 datastore.remove(ref)
519 def testForget(self):
520 datastore, ref = self.prepDeleteTest()
522 # Remove
523 datastore.forget([ref])
525 # Does it exist (as far as we know)?
526 self.assertFalse(datastore.exists(ref))
528 # Do we now get a predicted URI?
529 uri = datastore.getURI(ref, predict=True)
530 self.assertEqual(uri.fragment, "predicted")
532 # Get should now fail
533 with self.assertRaises(FileNotFoundError):
534 datastore.get(ref)
536 # Forgetting again is a silent no-op
537 datastore.forget([ref])
539 # Predicted URI should still point to the file.
540 self.assertTrue(uri.exists())
542 def testTransfer(self):
543 metrics = makeExampleMetrics()
545 dimensions = self.universe.extract(("visit", "physical_filter"))
546 dataId = {"instrument": "dummy", "visit": 2048, "physical_filter": "Uprime"}
548 sc = self.storageClassFactory.getStorageClass("StructuredData")
549 ref = self.makeDatasetRef("metric", dimensions, sc, dataId, conform=False)
551 inputDatastore = self.makeDatastore("test_input_datastore")
552 outputDatastore = self.makeDatastore("test_output_datastore")
554 inputDatastore.put(metrics, ref)
555 outputDatastore.transfer(inputDatastore, ref)
557 metricsOut = outputDatastore.get(ref)
558 self.assertEqual(metrics, metricsOut)
560 def testBasicTransaction(self):
561 datastore = self.makeDatastore()
562 storageClass = self.storageClassFactory.getStorageClass("StructuredData")
563 dimensions = self.universe.extract(("visit", "physical_filter"))
564 nDatasets = 6
565 dataIds = [{"instrument": "dummy", "visit": i, "physical_filter": "V"} for i in range(nDatasets)]
566 data = [
567 (
568 self.makeDatasetRef("metric", dimensions, storageClass, dataId, conform=False),
569 makeExampleMetrics(),
570 )
571 for dataId in dataIds
572 ]
573 succeed = data[: nDatasets // 2]
574 fail = data[nDatasets // 2 :]
575 # All datasets added in this transaction should continue to exist
576 with datastore.transaction():
577 for ref, metrics in succeed:
578 datastore.put(metrics, ref)
579 # Whereas datasets added in this transaction should not
580 with self.assertRaises(TransactionTestError):
581 with datastore.transaction():
582 for ref, metrics in fail:
583 datastore.put(metrics, ref)
584 raise TransactionTestError("This should propagate out of the context manager")
585 # Check for datasets that should exist
586 for ref, metrics in succeed:
587 # Does it exist?
588 self.assertTrue(datastore.exists(ref))
589 # Get
590 metricsOut = datastore.get(ref, parameters=None)
591 self.assertEqual(metrics, metricsOut)
592 # URI
593 uri = datastore.getURI(ref)
594 self.assertEqual(uri.scheme, self.uriScheme)
595 # Check for datasets that should not exist
596 for ref, _ in fail:
597 # These should raise
598 with self.assertRaises(FileNotFoundError):
599 # non-existing file
600 datastore.get(ref)
601 with self.assertRaises(FileNotFoundError):
602 datastore.getURI(ref)
604 def testNestedTransaction(self):
605 datastore = self.makeDatastore()
606 storageClass = self.storageClassFactory.getStorageClass("StructuredData")
607 dimensions = self.universe.extract(("visit", "physical_filter"))
608 metrics = makeExampleMetrics()
610 dataId = {"instrument": "dummy", "visit": 0, "physical_filter": "V"}
611 refBefore = self.makeDatasetRef("metric", dimensions, storageClass, dataId, conform=False)
612 datastore.put(metrics, refBefore)
613 with self.assertRaises(TransactionTestError):
614 with datastore.transaction():
615 dataId = {"instrument": "dummy", "visit": 1, "physical_filter": "V"}
616 refOuter = self.makeDatasetRef("metric", dimensions, storageClass, dataId, conform=False)
617 datastore.put(metrics, refOuter)
618 with datastore.transaction():
619 dataId = {"instrument": "dummy", "visit": 2, "physical_filter": "V"}
620 refInner = self.makeDatasetRef("metric", dimensions, storageClass, dataId, conform=False)
621 datastore.put(metrics, refInner)
622 # All datasets should exist
623 for ref in (refBefore, refOuter, refInner):
624 metricsOut = datastore.get(ref, parameters=None)
625 self.assertEqual(metrics, metricsOut)
626 raise TransactionTestError("This should roll back the transaction")
627 # Dataset(s) inserted before the transaction should still exist
628 metricsOut = datastore.get(refBefore, parameters=None)
629 self.assertEqual(metrics, metricsOut)
630 # But all datasets inserted during the (rolled back) transaction
631 # should be gone
632 with self.assertRaises(FileNotFoundError):
633 datastore.get(refOuter)
634 with self.assertRaises(FileNotFoundError):
635 datastore.get(refInner)
637 def _prepareIngestTest(self):
638 storageClass = self.storageClassFactory.getStorageClass("StructuredData")
639 dimensions = self.universe.extract(("visit", "physical_filter"))
640 metrics = makeExampleMetrics()
641 dataId = {"instrument": "dummy", "visit": 0, "physical_filter": "V"}
642 ref = self.makeDatasetRef("metric", dimensions, storageClass, dataId, conform=False)
643 return metrics, ref
645 def runIngestTest(self, func, expectOutput=True):
646 metrics, ref = self._prepareIngestTest()
647 # The file will be deleted after the test.
648 # For symlink tests this leads to a situation where the datastore
649 # points to a file that does not exist. This will make os.path.exist
650 # return False but then the new symlink will fail with
651 # FileExistsError later in the code so the test still passes.
652 with lsst.utils.tests.getTempFilePath(".yaml", expectOutput=expectOutput) as path:
653 with open(path, "w") as fd:
654 yaml.dump(metrics._asdict(), stream=fd)
655 func(metrics, path, ref)
657 def testIngestNoTransfer(self):
658 """Test ingesting existing files with no transfer."""
659 for mode in (None, "auto"):
661 # Some datastores have auto but can't do in place transfer
662 if mode == "auto" and "auto" in self.ingestTransferModes and not self.canIngestNoTransferAuto:
663 continue
665 with self.subTest(mode=mode):
666 datastore = self.makeDatastore()
668 def succeed(obj, path, ref):
669 """Ingest a file already in the datastore root."""
670 # first move it into the root, and adjust the path
671 # accordingly
672 path = shutil.copy(path, datastore.root.ospath)
673 path = os.path.relpath(path, start=datastore.root.ospath)
674 datastore.ingest(FileDataset(path=path, refs=ref), transfer=mode)
675 self.assertEqual(obj, datastore.get(ref))
677 def failInputDoesNotExist(obj, path, ref):
678 """Can't ingest files if we're given a bad path."""
679 with self.assertRaises(FileNotFoundError):
680 datastore.ingest(
681 FileDataset(path="this-file-does-not-exist.yaml", refs=ref), transfer=mode
682 )
683 self.assertFalse(datastore.exists(ref))
685 def failOutsideRoot(obj, path, ref):
686 """Can't ingest files outside of datastore root unless
687 auto."""
688 if mode == "auto":
689 datastore.ingest(FileDataset(path=os.path.abspath(path), refs=ref), transfer=mode)
690 self.assertTrue(datastore.exists(ref))
691 else:
692 with self.assertRaises(RuntimeError):
693 datastore.ingest(FileDataset(path=os.path.abspath(path), refs=ref), transfer=mode)
694 self.assertFalse(datastore.exists(ref))
696 def failNotImplemented(obj, path, ref):
697 with self.assertRaises(NotImplementedError):
698 datastore.ingest(FileDataset(path=path, refs=ref), transfer=mode)
700 if mode in self.ingestTransferModes:
701 self.runIngestTest(failOutsideRoot)
702 self.runIngestTest(failInputDoesNotExist)
703 self.runIngestTest(succeed)
704 else:
705 self.runIngestTest(failNotImplemented)
707 def testIngestTransfer(self):
708 """Test ingesting existing files after transferring them."""
709 for mode in ("copy", "move", "link", "hardlink", "symlink", "relsymlink", "auto"):
710 with self.subTest(mode=mode):
711 datastore = self.makeDatastore(mode)
713 def succeed(obj, path, ref):
714 """Ingest a file by transferring it to the template
715 location."""
716 datastore.ingest(FileDataset(path=os.path.abspath(path), refs=ref), transfer=mode)
717 self.assertEqual(obj, datastore.get(ref))
719 def failInputDoesNotExist(obj, path, ref):
720 """Can't ingest files if we're given a bad path."""
721 with self.assertRaises(FileNotFoundError):
722 # Ensure the file does not look like it is in
723 # datastore for auto mode
724 datastore.ingest(
725 FileDataset(path="../this-file-does-not-exist.yaml", refs=ref), transfer=mode
726 )
727 self.assertFalse(datastore.exists(ref), f"Checking not in datastore using mode {mode}")
729 def failNotImplemented(obj, path, ref):
730 with self.assertRaises(NotImplementedError):
731 datastore.ingest(FileDataset(path=os.path.abspath(path), refs=ref), transfer=mode)
733 if mode in self.ingestTransferModes:
734 self.runIngestTest(failInputDoesNotExist)
735 self.runIngestTest(succeed, expectOutput=(mode != "move"))
736 else:
737 self.runIngestTest(failNotImplemented)
739 def testIngestSymlinkOfSymlink(self):
740 """Special test for symlink to a symlink ingest"""
741 metrics, ref = self._prepareIngestTest()
742 # The aim of this test is to create a dataset on disk, then
743 # create a symlink to it and finally ingest the symlink such that
744 # the symlink in the datastore points to the original dataset.
745 for mode in ("symlink", "relsymlink"):
746 if mode not in self.ingestTransferModes:
747 continue
749 print(f"Trying mode {mode}")
750 with lsst.utils.tests.getTempFilePath(".yaml") as realpath:
751 with open(realpath, "w") as fd:
752 yaml.dump(metrics._asdict(), stream=fd)
753 with lsst.utils.tests.getTempFilePath(".yaml") as sympath:
754 os.symlink(os.path.abspath(realpath), sympath)
756 datastore = self.makeDatastore()
757 datastore.ingest(FileDataset(path=os.path.abspath(sympath), refs=ref), transfer=mode)
759 uri = datastore.getURI(ref)
760 self.assertTrue(uri.isLocal, f"Check {uri.scheme}")
761 self.assertTrue(os.path.islink(uri.ospath), f"Check {uri} is a symlink")
763 linkTarget = os.readlink(uri.ospath)
764 if mode == "relsymlink":
765 self.assertFalse(os.path.isabs(linkTarget))
766 else:
767 self.assertEqual(linkTarget, os.path.abspath(realpath))
769 # Check that we can get the dataset back regardless of mode
770 metric2 = datastore.get(ref)
771 self.assertEqual(metric2, metrics)
773 # Cleanup the file for next time round loop
774 # since it will get the same file name in store
775 datastore.remove(ref)
777 def testExportImportRecords(self):
778 """Test for export_records and import_records methods."""
780 datastore = self.makeDatastore("test_datastore")
782 # For now only the FileDatastore can be used for this test.
783 # ChainedDatastore that only includes InMemoryDatastores have to be
784 # skipped as well.
785 for name in datastore.names:
786 if not name.startswith("InMemoryDatastore"):
787 break
788 else:
789 raise unittest.SkipTest("in-memory datastore does not support record export/import")
791 metrics = makeExampleMetrics()
792 dimensions = self.universe.extract(("visit", "physical_filter"))
793 sc = self.storageClassFactory.getStorageClass("StructuredData")
795 refs = []
796 for visit in (2048, 2049, 2050):
797 dataId = {"instrument": "dummy", "visit": visit, "physical_filter": "Uprime"}
798 ref = self.makeDatasetRef("metric", dimensions, sc, dataId, conform=False)
799 datastore.put(metrics, ref)
800 refs.append(ref)
802 for exported_refs in (refs, refs[1:]):
803 n_refs = len(exported_refs)
804 records = datastore.export_records(exported_refs)
805 self.assertGreater(len(records), 0)
806 self.assertTrue(set(records.keys()) <= set(datastore.names))
807 # In a ChainedDatastore each FileDatastore will have a complete set
808 for datastore_name in records:
809 record_data = records[datastore_name]
810 self.assertEqual(len(record_data.records), n_refs)
812 # Use the same datastore name to import relative path.
813 datastore2 = self.makeDatastore("test_datastore")
815 records = datastore.export_records(refs[1:])
816 datastore2.import_records(records)
818 with self.assertRaises(FileNotFoundError):
819 data = datastore2.get(refs[0])
820 data = datastore2.get(refs[1])
821 self.assertIsNotNone(data)
822 data = datastore2.get(refs[2])
823 self.assertIsNotNone(data)
826class PosixDatastoreTestCase(DatastoreTests, unittest.TestCase):
827 """PosixDatastore specialization"""
829 configFile = os.path.join(TESTDIR, "config/basic/butler.yaml")
830 uriScheme = "file"
831 canIngestNoTransferAuto = True
832 ingestTransferModes = (None, "copy", "move", "link", "hardlink", "symlink", "relsymlink", "auto")
833 isEphemeral = False
834 rootKeys = ("root",)
835 validationCanFail = True
837 def setUp(self):
838 # Override the working directory before calling the base class
839 self.root = tempfile.mkdtemp(dir=TESTDIR)
840 super().setUp()
843class PosixDatastoreNoChecksumsTestCase(PosixDatastoreTestCase):
844 """Posix datastore tests but with checksums disabled."""
846 configFile = os.path.join(TESTDIR, "config/basic/posixDatastoreNoChecksums.yaml")
848 def testChecksum(self):
849 """Ensure that checksums have not been calculated."""
851 datastore = self.makeDatastore()
852 storageClass = self.storageClassFactory.getStorageClass("StructuredData")
853 dimensions = self.universe.extract(("visit", "physical_filter"))
854 metrics = makeExampleMetrics()
856 dataId = {"instrument": "dummy", "visit": 0, "physical_filter": "V"}
857 ref = self.makeDatasetRef("metric", dimensions, storageClass, dataId, conform=False)
859 # Configuration should have disabled checksum calculation
860 datastore.put(metrics, ref)
861 infos = datastore.getStoredItemsInfo(ref)
862 self.assertIsNone(infos[0].checksum)
864 # Remove put back but with checksums enabled explicitly
865 datastore.remove(ref)
866 datastore.useChecksum = True
867 datastore.put(metrics, ref)
869 infos = datastore.getStoredItemsInfo(ref)
870 self.assertIsNotNone(infos[0].checksum)
873class TrashDatastoreTestCase(PosixDatastoreTestCase):
874 """Restrict trash test to FileDatastore."""
876 configFile = os.path.join(TESTDIR, "config/basic/butler.yaml")
878 def testTrash(self):
879 datastore, *refs = self.prepDeleteTest(n_refs=10)
881 # Trash one of them.
882 ref = refs.pop()
883 uri = datastore.getURI(ref)
884 datastore.trash(ref)
885 self.assertTrue(uri.exists(), uri) # Not deleted yet
886 datastore.emptyTrash()
887 self.assertFalse(uri.exists(), uri)
889 # Trash it again should be fine.
890 datastore.trash(ref)
892 # Trash multiple items at once.
893 subset = [refs.pop(), refs.pop()]
894 datastore.trash(subset)
895 datastore.emptyTrash()
897 # Remove a record and trash should do nothing.
898 # This is execution butler scenario.
899 ref = refs.pop()
900 uri = datastore.getURI(ref)
901 datastore._table.delete(["dataset_id"], {"dataset_id": ref.id})
902 self.assertTrue(uri.exists())
903 datastore.trash(ref)
904 datastore.emptyTrash()
905 self.assertTrue(uri.exists())
907 # Switch on trust and it should delete the file.
908 datastore.trustGetRequest = True
909 datastore.trash([ref])
910 self.assertFalse(uri.exists())
912 # Remove multiples at once in trust mode.
913 subset = [refs.pop() for i in range(3)]
914 datastore.trash(subset)
915 datastore.trash(refs.pop()) # Check that a single ref can trash
918class CleanupPosixDatastoreTestCase(DatastoreTestsBase, unittest.TestCase):
919 configFile = os.path.join(TESTDIR, "config/basic/butler.yaml")
921 def setUp(self):
922 # Override the working directory before calling the base class
923 self.root = tempfile.mkdtemp(dir=TESTDIR)
924 super().setUp()
926 def testCleanup(self):
927 """Test that a failed formatter write does cleanup a partial file."""
928 metrics = makeExampleMetrics()
929 datastore = self.makeDatastore()
931 storageClass = self.storageClassFactory.getStorageClass("StructuredData")
933 dimensions = self.universe.extract(("visit", "physical_filter"))
934 dataId = {"instrument": "dummy", "visit": 52, "physical_filter": "V"}
936 ref = self.makeDatasetRef("metric", dimensions, storageClass, dataId, conform=False)
938 # Determine where the file will end up (we assume Formatters use
939 # the same file extension)
940 expectedUri = datastore.getURI(ref, predict=True)
941 self.assertEqual(expectedUri.fragment, "predicted")
943 self.assertEqual(expectedUri.getExtension(), ".yaml", f"Is there a file extension in {expectedUri}")
945 # Try formatter that fails and formatter that fails and leaves
946 # a file behind
947 for formatter in (BadWriteFormatter, BadNoWriteFormatter):
948 with self.subTest(formatter=formatter):
950 # Monkey patch the formatter
951 datastore.formatterFactory.registerFormatter(ref.datasetType, formatter, overwrite=True)
953 # Try to put the dataset, it should fail
954 with self.assertRaises(Exception):
955 datastore.put(metrics, ref)
957 # Check that there is no file on disk
958 self.assertFalse(expectedUri.exists(), f"Check for existence of {expectedUri}")
960 # Check that there is a directory
961 dir = expectedUri.dirname()
962 self.assertTrue(dir.exists(), f"Check for existence of directory {dir}")
964 # Force YamlFormatter and check that this time a file is written
965 datastore.formatterFactory.registerFormatter(ref.datasetType, YamlFormatter, overwrite=True)
966 datastore.put(metrics, ref)
967 self.assertTrue(expectedUri.exists(), f"Check for existence of {expectedUri}")
968 datastore.remove(ref)
969 self.assertFalse(expectedUri.exists(), f"Check for existence of now removed {expectedUri}")
972class InMemoryDatastoreTestCase(DatastoreTests, unittest.TestCase):
973 """PosixDatastore specialization"""
975 configFile = os.path.join(TESTDIR, "config/basic/inMemoryDatastore.yaml")
976 uriScheme = "mem"
977 hasUnsupportedPut = False
978 ingestTransferModes = ()
979 isEphemeral = True
980 rootKeys = None
981 validationCanFail = False
984class ChainedDatastoreTestCase(PosixDatastoreTestCase):
985 """ChainedDatastore specialization using a POSIXDatastore"""
987 configFile = os.path.join(TESTDIR, "config/basic/chainedDatastore.yaml")
988 hasUnsupportedPut = False
989 canIngestNoTransferAuto = False
990 ingestTransferModes = ("copy", "hardlink", "symlink", "relsymlink", "link", "auto")
991 isEphemeral = False
992 rootKeys = (".datastores.1.root", ".datastores.2.root")
993 validationCanFail = True
996class ChainedDatastoreMemoryTestCase(InMemoryDatastoreTestCase):
997 """ChainedDatastore specialization using all InMemoryDatastore"""
999 configFile = os.path.join(TESTDIR, "config/basic/chainedDatastore2.yaml")
1000 validationCanFail = False
1003class DatastoreConstraintsTests(DatastoreTestsBase):
1004 """Basic tests of constraints model of Datastores."""
1006 def testConstraints(self):
1007 """Test constraints model. Assumes that each test class has the
1008 same constraints."""
1009 metrics = makeExampleMetrics()
1010 datastore = self.makeDatastore()
1012 sc1 = self.storageClassFactory.getStorageClass("StructuredData")
1013 sc2 = self.storageClassFactory.getStorageClass("StructuredDataJson")
1014 dimensions = self.universe.extract(("visit", "physical_filter", "instrument"))
1015 dataId = {"visit": 52, "physical_filter": "V", "instrument": "DummyCamComp"}
1017 # Write empty file suitable for ingest check (JSON and YAML variants)
1018 testfile_y = tempfile.NamedTemporaryFile(suffix=".yaml")
1019 testfile_j = tempfile.NamedTemporaryFile(suffix=".json")
1020 for datasetTypeName, sc, accepted in (
1021 ("metric", sc1, True),
1022 ("metric2", sc1, False),
1023 ("metric33", sc1, True),
1024 ("metric2", sc2, True),
1025 ):
1026 # Choose different temp file depending on StorageClass
1027 testfile = testfile_j if sc.name.endswith("Json") else testfile_y
1029 with self.subTest(datasetTypeName=datasetTypeName, storageClass=sc.name, file=testfile.name):
1030 ref = self.makeDatasetRef(datasetTypeName, dimensions, sc, dataId, conform=False)
1031 if accepted:
1032 datastore.put(metrics, ref)
1033 self.assertTrue(datastore.exists(ref))
1034 datastore.remove(ref)
1036 # Try ingest
1037 if self.canIngest:
1038 datastore.ingest(FileDataset(testfile.name, [ref]), transfer="link")
1039 self.assertTrue(datastore.exists(ref))
1040 datastore.remove(ref)
1041 else:
1042 with self.assertRaises(DatasetTypeNotSupportedError):
1043 datastore.put(metrics, ref)
1044 self.assertFalse(datastore.exists(ref))
1046 # Again with ingest
1047 if self.canIngest:
1048 with self.assertRaises(DatasetTypeNotSupportedError):
1049 datastore.ingest(FileDataset(testfile.name, [ref]), transfer="link")
1050 self.assertFalse(datastore.exists(ref))
1053class PosixDatastoreConstraintsTestCase(DatastoreConstraintsTests, unittest.TestCase):
1054 """PosixDatastore specialization"""
1056 configFile = os.path.join(TESTDIR, "config/basic/posixDatastoreP.yaml")
1057 canIngest = True
1059 def setUp(self):
1060 # Override the working directory before calling the base class
1061 self.root = tempfile.mkdtemp(dir=TESTDIR)
1062 super().setUp()
1065class InMemoryDatastoreConstraintsTestCase(DatastoreConstraintsTests, unittest.TestCase):
1066 """InMemoryDatastore specialization"""
1068 configFile = os.path.join(TESTDIR, "config/basic/inMemoryDatastoreP.yaml")
1069 canIngest = False
1072class ChainedDatastoreConstraintsNativeTestCase(PosixDatastoreConstraintsTestCase):
1073 """ChainedDatastore specialization using a POSIXDatastore and constraints
1074 at the ChainedDatstore"""
1076 configFile = os.path.join(TESTDIR, "config/basic/chainedDatastorePa.yaml")
1079class ChainedDatastoreConstraintsTestCase(PosixDatastoreConstraintsTestCase):
1080 """ChainedDatastore specialization using a POSIXDatastore"""
1082 configFile = os.path.join(TESTDIR, "config/basic/chainedDatastoreP.yaml")
1085class ChainedDatastoreMemoryConstraintsTestCase(InMemoryDatastoreConstraintsTestCase):
1086 """ChainedDatastore specialization using all InMemoryDatastore"""
1088 configFile = os.path.join(TESTDIR, "config/basic/chainedDatastore2P.yaml")
1089 canIngest = False
1092class ChainedDatastorePerStoreConstraintsTests(DatastoreTestsBase, unittest.TestCase):
1093 """Test that a chained datastore can control constraints per-datastore
1094 even if child datastore would accept."""
1096 configFile = os.path.join(TESTDIR, "config/basic/chainedDatastorePb.yaml")
1098 def setUp(self):
1099 # Override the working directory before calling the base class
1100 self.root = tempfile.mkdtemp(dir=TESTDIR)
1101 super().setUp()
1103 def testConstraints(self):
1104 """Test chained datastore constraints model."""
1105 metrics = makeExampleMetrics()
1106 datastore = self.makeDatastore()
1108 sc1 = self.storageClassFactory.getStorageClass("StructuredData")
1109 sc2 = self.storageClassFactory.getStorageClass("StructuredDataJson")
1110 dimensions = self.universe.extract(("visit", "physical_filter", "instrument"))
1111 dataId1 = {"visit": 52, "physical_filter": "V", "instrument": "DummyCamComp"}
1112 dataId2 = {"visit": 52, "physical_filter": "V", "instrument": "HSC"}
1114 # Write empty file suitable for ingest check (JSON and YAML variants)
1115 testfile_y = tempfile.NamedTemporaryFile(suffix=".yaml")
1116 testfile_j = tempfile.NamedTemporaryFile(suffix=".json")
1118 for typeName, dataId, sc, accept, ingest in (
1119 ("metric", dataId1, sc1, (False, True, False), True),
1120 ("metric2", dataId1, sc1, (False, False, False), False),
1121 ("metric2", dataId2, sc1, (True, False, False), False),
1122 ("metric33", dataId2, sc2, (True, True, False), True),
1123 ("metric2", dataId1, sc2, (False, True, False), True),
1124 ):
1126 # Choose different temp file depending on StorageClass
1127 testfile = testfile_j if sc.name.endswith("Json") else testfile_y
1129 with self.subTest(datasetTypeName=typeName, dataId=dataId, sc=sc.name):
1130 ref = self.makeDatasetRef(typeName, dimensions, sc, dataId, conform=False)
1131 if any(accept):
1132 datastore.put(metrics, ref)
1133 self.assertTrue(datastore.exists(ref))
1135 # Check each datastore inside the chained datastore
1136 for childDatastore, expected in zip(datastore.datastores, accept):
1137 self.assertEqual(
1138 childDatastore.exists(ref),
1139 expected,
1140 f"Testing presence of {ref} in datastore {childDatastore.name}",
1141 )
1143 datastore.remove(ref)
1145 # Check that ingest works
1146 if ingest:
1147 datastore.ingest(FileDataset(testfile.name, [ref]), transfer="link")
1148 self.assertTrue(datastore.exists(ref))
1150 # Check each datastore inside the chained datastore
1151 for childDatastore, expected in zip(datastore.datastores, accept):
1152 # Ephemeral datastores means InMemory at the moment
1153 # and that does not accept ingest of files.
1154 if childDatastore.isEphemeral:
1155 expected = False
1156 self.assertEqual(
1157 childDatastore.exists(ref),
1158 expected,
1159 f"Testing presence of ingested {ref} in datastore {childDatastore.name}",
1160 )
1162 datastore.remove(ref)
1163 else:
1164 with self.assertRaises(DatasetTypeNotSupportedError):
1165 datastore.ingest(FileDataset(testfile.name, [ref]), transfer="link")
1167 else:
1168 with self.assertRaises(DatasetTypeNotSupportedError):
1169 datastore.put(metrics, ref)
1170 self.assertFalse(datastore.exists(ref))
1172 # Again with ingest
1173 with self.assertRaises(DatasetTypeNotSupportedError):
1174 datastore.ingest(FileDataset(testfile.name, [ref]), transfer="link")
1175 self.assertFalse(datastore.exists(ref))
1178class DatastoreCacheTestCase(DatasetTestHelper, unittest.TestCase):
1179 """Tests for datastore caching infrastructure."""
1181 @classmethod
1182 def setUpClass(cls):
1183 cls.storageClassFactory = StorageClassFactory()
1184 cls.universe = DimensionUniverse()
1186 # Ensure that we load the test storage class definitions.
1187 scConfigFile = os.path.join(TESTDIR, "config/basic/storageClasses.yaml")
1188 cls.storageClassFactory.addFromConfig(scConfigFile)
1190 def setUp(self):
1191 self.id = 0
1193 # Create a root that we can use for caching tests.
1194 self.root = tempfile.mkdtemp(dir=TESTDIR)
1196 # Create some test dataset refs and associated test files
1197 sc = self.storageClassFactory.getStorageClass("StructuredDataDict")
1198 dimensions = self.universe.extract(("visit", "physical_filter"))
1199 dataId = {"instrument": "dummy", "visit": 52, "physical_filter": "V"}
1201 # Create list of refs and list of temporary files
1202 n_datasets = 10
1203 self.refs = [
1204 self.makeDatasetRef(f"metric{n}", dimensions, sc, dataId, conform=False)
1205 for n in range(n_datasets)
1206 ]
1208 root_uri = ResourcePath(self.root, forceDirectory=True)
1209 self.files = [root_uri.join(f"file{n}.txt") for n in range(n_datasets)]
1211 # Create test files.
1212 for uri in self.files:
1213 uri.write(b"0123456789")
1215 # Create some composite refs with component files.
1216 sc = self.storageClassFactory.getStorageClass("StructuredData")
1217 self.composite_refs = [
1218 self.makeDatasetRef(f"composite{n}", dimensions, sc, dataId, conform=False) for n in range(3)
1219 ]
1220 self.comp_files = []
1221 self.comp_refs = []
1222 for n, ref in enumerate(self.composite_refs):
1223 component_refs = []
1224 component_files = []
1225 for component in sc.components:
1226 component_ref = ref.makeComponentRef(component)
1227 file = root_uri.join(f"composite_file-{n}-{component}.txt")
1228 component_refs.append(component_ref)
1229 component_files.append(file)
1230 file.write(b"9876543210")
1232 self.comp_files.append(component_files)
1233 self.comp_refs.append(component_refs)
1235 def tearDown(self):
1236 if self.root is not None and os.path.exists(self.root):
1237 shutil.rmtree(self.root, ignore_errors=True)
1239 def _make_cache_manager(self, config_str: str) -> DatastoreCacheManager:
1240 config = Config.fromYaml(config_str)
1241 return DatastoreCacheManager(DatastoreCacheManagerConfig(config), universe=self.universe)
1243 def testNoCacheDir(self):
1244 config_str = """
1245cached:
1246 root: null
1247 cacheable:
1248 metric0: true
1249 """
1250 cache_manager = self._make_cache_manager(config_str)
1252 # Look inside to check we don't have a cache directory
1253 self.assertIsNone(cache_manager._cache_directory)
1255 self.assertCache(cache_manager)
1257 # Test that the cache directory is marked temporary
1258 self.assertTrue(cache_manager.cache_directory.isTemporary)
1260 def testNoCacheDirReversed(self):
1261 """Use default caching status and metric1 to false"""
1262 config_str = """
1263cached:
1264 root: null
1265 default: true
1266 cacheable:
1267 metric1: false
1268 """
1269 cache_manager = self._make_cache_manager(config_str)
1271 self.assertCache(cache_manager)
1273 def testExplicitCacheDir(self):
1274 config_str = f"""
1275cached:
1276 root: '{self.root}'
1277 cacheable:
1278 metric0: true
1279 """
1280 cache_manager = self._make_cache_manager(config_str)
1282 # Look inside to check we do have a cache directory.
1283 self.assertEqual(cache_manager.cache_directory, ResourcePath(self.root, forceDirectory=True))
1285 self.assertCache(cache_manager)
1287 # Test that the cache directory is not marked temporary
1288 self.assertFalse(cache_manager.cache_directory.isTemporary)
1290 def assertCache(self, cache_manager):
1291 self.assertTrue(cache_manager.should_be_cached(self.refs[0]))
1292 self.assertFalse(cache_manager.should_be_cached(self.refs[1]))
1294 uri = cache_manager.move_to_cache(self.files[0], self.refs[0])
1295 self.assertIsInstance(uri, ResourcePath)
1296 self.assertIsNone(cache_manager.move_to_cache(self.files[1], self.refs[1]))
1298 # Check presence in cache using ref and then using file extension.
1299 self.assertFalse(cache_manager.known_to_cache(self.refs[1]))
1300 self.assertTrue(cache_manager.known_to_cache(self.refs[0]))
1301 self.assertFalse(cache_manager.known_to_cache(self.refs[1], self.files[1].getExtension()))
1302 self.assertTrue(cache_manager.known_to_cache(self.refs[0], self.files[0].getExtension()))
1304 # Cached file should no longer exist but uncached file should be
1305 # unaffected.
1306 self.assertFalse(self.files[0].exists())
1307 self.assertTrue(self.files[1].exists())
1309 # Should find this file and it should be within the cache directory.
1310 with cache_manager.find_in_cache(self.refs[0], ".txt") as found:
1311 self.assertTrue(found.exists())
1312 self.assertIsNotNone(found.relative_to(cache_manager.cache_directory))
1314 # Should not be able to find these in cache
1315 with cache_manager.find_in_cache(self.refs[0], ".fits") as found:
1316 self.assertIsNone(found)
1317 with cache_manager.find_in_cache(self.refs[1], ".fits") as found:
1318 self.assertIsNone(found)
1320 def testNoCache(self):
1321 cache_manager = DatastoreDisabledCacheManager("", universe=self.universe)
1322 for uri, ref in zip(self.files, self.refs):
1323 self.assertFalse(cache_manager.should_be_cached(ref))
1324 self.assertIsNone(cache_manager.move_to_cache(uri, ref))
1325 self.assertFalse(cache_manager.known_to_cache(ref))
1326 with cache_manager.find_in_cache(ref, ".txt") as found:
1327 self.assertIsNone(found, msg=f"{cache_manager}")
1329 def _expiration_config(self, mode: str, threshold: int) -> str:
1330 return f"""
1331cached:
1332 default: true
1333 expiry:
1334 mode: {mode}
1335 threshold: {threshold}
1336 cacheable:
1337 unused: true
1338 """
1340 def testCacheExpiryFiles(self):
1341 threshold = 2 # Keep at least 2 files.
1342 mode = "files"
1343 config_str = self._expiration_config(mode, threshold)
1345 cache_manager = self._make_cache_manager(config_str)
1347 # Check that an empty cache returns unknown for arbitrary ref
1348 self.assertFalse(cache_manager.known_to_cache(self.refs[0]))
1350 # Should end with datasets: 2, 3, 4
1351 self.assertExpiration(cache_manager, 5, threshold + 1)
1352 self.assertIn(f"{mode}={threshold}", str(cache_manager))
1354 # Check that we will not expire a file that is actively in use.
1355 with cache_manager.find_in_cache(self.refs[2], ".txt") as found:
1356 self.assertIsNotNone(found)
1358 # Trigger cache expiration that should remove the file
1359 # we just retrieved. Should now have: 3, 4, 5
1360 cached = cache_manager.move_to_cache(self.files[5], self.refs[5])
1361 self.assertIsNotNone(cached)
1363 # Cache should still report the standard file count.
1364 self.assertEqual(cache_manager.file_count, threshold + 1)
1366 # Add additional entry to cache.
1367 # Should now have 4, 5, 6
1368 cached = cache_manager.move_to_cache(self.files[6], self.refs[6])
1369 self.assertIsNotNone(cached)
1371 # Is the file still there?
1372 self.assertTrue(found.exists())
1374 # Can we read it?
1375 data = found.read()
1376 self.assertGreater(len(data), 0)
1378 # Outside context the file should no longer exist.
1379 self.assertFalse(found.exists())
1381 # File count should not have changed.
1382 self.assertEqual(cache_manager.file_count, threshold + 1)
1384 # Dataset 2 was in the exempt directory but because hardlinks
1385 # are used it was deleted from the main cache during cache expiry
1386 # above and so should no longer be found.
1387 with cache_manager.find_in_cache(self.refs[2], ".txt") as found:
1388 self.assertIsNone(found)
1390 # And the one stored after it is also gone.
1391 with cache_manager.find_in_cache(self.refs[3], ".txt") as found:
1392 self.assertIsNone(found)
1394 # But dataset 4 is present.
1395 with cache_manager.find_in_cache(self.refs[4], ".txt") as found:
1396 self.assertIsNotNone(found)
1398 # Adding a new dataset to the cache should now delete it.
1399 cache_manager.move_to_cache(self.files[7], self.refs[7])
1401 with cache_manager.find_in_cache(self.refs[2], ".txt") as found:
1402 self.assertIsNone(found)
1404 def testCacheExpiryDatasets(self):
1405 threshold = 2 # Keep 2 datasets.
1406 mode = "datasets"
1407 config_str = self._expiration_config(mode, threshold)
1409 cache_manager = self._make_cache_manager(config_str)
1410 self.assertExpiration(cache_manager, 5, threshold + 1)
1411 self.assertIn(f"{mode}={threshold}", str(cache_manager))
1413 def testCacheExpiryDatasetsComposite(self):
1414 threshold = 2 # Keep 2 datasets.
1415 mode = "datasets"
1416 config_str = self._expiration_config(mode, threshold)
1418 cache_manager = self._make_cache_manager(config_str)
1420 n_datasets = 3
1421 for i in range(n_datasets):
1422 for component_file, component_ref in zip(self.comp_files[i], self.comp_refs[i]):
1423 cached = cache_manager.move_to_cache(component_file, component_ref)
1424 self.assertIsNotNone(cached)
1425 self.assertTrue(cache_manager.known_to_cache(component_ref))
1426 self.assertTrue(cache_manager.known_to_cache(component_ref.makeCompositeRef()))
1427 self.assertTrue(cache_manager.known_to_cache(component_ref, component_file.getExtension()))
1429 self.assertEqual(cache_manager.file_count, 6) # 2 datasets each of 3 files
1431 # Write two new non-composite and the number of files should drop.
1432 self.assertExpiration(cache_manager, 2, 5)
1434 def testCacheExpirySize(self):
1435 threshold = 55 # Each file is 10 bytes
1436 mode = "size"
1437 config_str = self._expiration_config(mode, threshold)
1439 cache_manager = self._make_cache_manager(config_str)
1440 self.assertExpiration(cache_manager, 10, 6)
1441 self.assertIn(f"{mode}={threshold}", str(cache_manager))
1443 def assertExpiration(self, cache_manager, n_datasets, n_retained):
1444 """Insert the datasets and then check the number retained."""
1445 for i in range(n_datasets):
1446 cached = cache_manager.move_to_cache(self.files[i], self.refs[i])
1447 self.assertIsNotNone(cached)
1449 self.assertEqual(cache_manager.file_count, n_retained)
1451 # The oldest file should not be in the cache any more.
1452 for i in range(n_datasets):
1453 with cache_manager.find_in_cache(self.refs[i], ".txt") as found:
1454 if i >= n_datasets - n_retained:
1455 self.assertIsInstance(found, ResourcePath)
1456 else:
1457 self.assertIsNone(found)
1459 def testCacheExpiryAge(self):
1460 threshold = 1 # Expire older than 2 seconds
1461 mode = "age"
1462 config_str = self._expiration_config(mode, threshold)
1464 cache_manager = self._make_cache_manager(config_str)
1465 self.assertIn(f"{mode}={threshold}", str(cache_manager))
1467 # Insert 3 files, then sleep, then insert more.
1468 for i in range(2):
1469 cached = cache_manager.move_to_cache(self.files[i], self.refs[i])
1470 self.assertIsNotNone(cached)
1471 time.sleep(2.0)
1472 for j in range(4):
1473 i = 2 + j # Continue the counting
1474 cached = cache_manager.move_to_cache(self.files[i], self.refs[i])
1475 self.assertIsNotNone(cached)
1477 # Only the files written after the sleep should exist.
1478 self.assertEqual(cache_manager.file_count, 4)
1479 with cache_manager.find_in_cache(self.refs[1], ".txt") as found:
1480 self.assertIsNone(found)
1481 with cache_manager.find_in_cache(self.refs[2], ".txt") as found:
1482 self.assertIsInstance(found, ResourcePath)
1485if __name__ == "__main__": 1485 ↛ 1486line 1485 didn't jump to line 1486, because the condition on line 1485 was never true
1486 unittest.main()