pyBiocFileCache 0.6.1__tar.gz → 0.6.2__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. {pybiocfilecache-0.6.1 → pybiocfilecache-0.6.2}/CHANGELOG.md +4 -2
  2. {pybiocfilecache-0.6.1 → pybiocfilecache-0.6.2}/PKG-INFO +1 -1
  3. {pybiocfilecache-0.6.1 → pybiocfilecache-0.6.2}/docs/changelog.md +4 -2
  4. {pybiocfilecache-0.6.1 → pybiocfilecache-0.6.2}/src/pyBiocFileCache.egg-info/PKG-INFO +1 -1
  5. {pybiocfilecache-0.6.1 → pybiocfilecache-0.6.2}/src/pyBiocFileCache.egg-info/SOURCES.txt +0 -1
  6. {pybiocfilecache-0.6.1 → pybiocfilecache-0.6.2}/src/pybiocfilecache/cache.py +112 -40
  7. {pybiocfilecache-0.6.1 → pybiocfilecache-0.6.2}/src/pybiocfilecache/models.py +1 -1
  8. {pybiocfilecache-0.6.1 → pybiocfilecache-0.6.2}/src/pybiocfilecache/utils.py +13 -3
  9. pybiocfilecache-0.6.2/tests/test_cache.py +139 -0
  10. pybiocfilecache-0.6.1/src/pybiocfilecache/exceptions.py +0 -31
  11. pybiocfilecache-0.6.1/tests/test_cache.py +0 -69
  12. {pybiocfilecache-0.6.1 → pybiocfilecache-0.6.2}/.coveragerc +0 -0
  13. {pybiocfilecache-0.6.1 → pybiocfilecache-0.6.2}/.github/workflows/publish-pypi.yml +0 -0
  14. {pybiocfilecache-0.6.1 → pybiocfilecache-0.6.2}/.github/workflows/run-tests.yml +0 -0
  15. {pybiocfilecache-0.6.1 → pybiocfilecache-0.6.2}/.gitignore +0 -0
  16. {pybiocfilecache-0.6.1 → pybiocfilecache-0.6.2}/.pre-commit-config.yaml +0 -0
  17. {pybiocfilecache-0.6.1 → pybiocfilecache-0.6.2}/.readthedocs.yml +0 -0
  18. {pybiocfilecache-0.6.1 → pybiocfilecache-0.6.2}/AUTHORS.md +0 -0
  19. {pybiocfilecache-0.6.1 → pybiocfilecache-0.6.2}/CONTRIBUTING.rst +0 -0
  20. {pybiocfilecache-0.6.1 → pybiocfilecache-0.6.2}/LICENSE.txt +0 -0
  21. {pybiocfilecache-0.6.1 → pybiocfilecache-0.6.2}/README.md +0 -0
  22. {pybiocfilecache-0.6.1 → pybiocfilecache-0.6.2}/docs/Makefile +0 -0
  23. {pybiocfilecache-0.6.1 → pybiocfilecache-0.6.2}/docs/_static/.gitignore +0 -0
  24. {pybiocfilecache-0.6.1 → pybiocfilecache-0.6.2}/docs/authors.md +0 -0
  25. {pybiocfilecache-0.6.1 → pybiocfilecache-0.6.2}/docs/best_practices.md +0 -0
  26. {pybiocfilecache-0.6.1 → pybiocfilecache-0.6.2}/docs/conf.py +0 -0
  27. {pybiocfilecache-0.6.1 → pybiocfilecache-0.6.2}/docs/contributing.rst +0 -0
  28. {pybiocfilecache-0.6.1 → pybiocfilecache-0.6.2}/docs/index.md +0 -0
  29. {pybiocfilecache-0.6.1 → pybiocfilecache-0.6.2}/docs/license.rst +0 -0
  30. {pybiocfilecache-0.6.1 → pybiocfilecache-0.6.2}/docs/readme.md +0 -0
  31. {pybiocfilecache-0.6.1 → pybiocfilecache-0.6.2}/docs/requirements.txt +0 -0
  32. {pybiocfilecache-0.6.1 → pybiocfilecache-0.6.2}/pyproject.toml +0 -0
  33. {pybiocfilecache-0.6.1 → pybiocfilecache-0.6.2}/setup.cfg +0 -0
  34. {pybiocfilecache-0.6.1 → pybiocfilecache-0.6.2}/setup.py +0 -0
  35. {pybiocfilecache-0.6.1 → pybiocfilecache-0.6.2}/src/pyBiocFileCache.egg-info/dependency_links.txt +0 -0
  36. {pybiocfilecache-0.6.1 → pybiocfilecache-0.6.2}/src/pyBiocFileCache.egg-info/not-zip-safe +0 -0
  37. {pybiocfilecache-0.6.1 → pybiocfilecache-0.6.2}/src/pyBiocFileCache.egg-info/requires.txt +0 -0
  38. {pybiocfilecache-0.6.1 → pybiocfilecache-0.6.2}/src/pyBiocFileCache.egg-info/top_level.txt +0 -0
  39. {pybiocfilecache-0.6.1 → pybiocfilecache-0.6.2}/src/pybiocfilecache/__init__.py +0 -0
  40. {pybiocfilecache-0.6.1 → pybiocfilecache-0.6.2}/src/pybiocfilecache/config.py +0 -0
  41. {pybiocfilecache-0.6.1 → pybiocfilecache-0.6.2}/src/pybiocfilecache/const.py +0 -0
  42. {pybiocfilecache-0.6.1 → pybiocfilecache-0.6.2}/tests/conftest.py +0 -0
  43. {pybiocfilecache-0.6.1 → pybiocfilecache-0.6.2}/tests/data/test1.txt +0 -0
  44. {pybiocfilecache-0.6.1 → pybiocfilecache-0.6.2}/tests/data/test2.txt +0 -0
  45. {pybiocfilecache-0.6.1 → pybiocfilecache-0.6.2}/tox.ini +0 -0
@@ -1,9 +1,11 @@
1
1
  # Changelog
2
2
 
3
- ## Version 0.6.1
3
+ ## Version 0.6.1 - 0.6.2
4
4
 
5
5
  - Generate rid's that match with R's cache.
6
- - remove rname pattern checks.
6
+ - Remove rname pattern checks.
7
+ - Add functions to access metadata table.
8
+ - Add function to add web urls and download them if needed.
7
9
  - Rename GitHub actions for consistency with the rest of the packages.
8
10
 
9
11
  ## Version 0.6.0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: pyBiocFileCache
3
- Version: 0.6.1
3
+ Version: 0.6.2
4
4
  Summary: File based cache for resources and metadata
5
5
  Home-page: https://github.com/epiviz/pyBiocFileCache
6
6
  Author: jkanche
@@ -1,9 +1,11 @@
1
1
  # Changelog
2
2
 
3
- ## Version 0.6.1
3
+ ## Version 0.6.1 - 0.6.2
4
4
 
5
5
  - Generate rid's that match with R's cache.
6
- - remove rname pattern checks.
6
+ - Remove rname pattern checks.
7
+ - Add functions to access metadata table.
8
+ - Add function to add web urls and download them if needed.
7
9
  - Rename GitHub actions for consistency with the rest of the packages.
8
10
 
9
11
  ## Version 0.6.0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: pyBiocFileCache
3
- Version: 0.6.1
3
+ Version: 0.6.2
4
4
  Summary: File based cache for resources and metadata
5
5
  Home-page: https://github.com/epiviz/pyBiocFileCache
6
6
  Author: jkanche
@@ -34,7 +34,6 @@ src/pybiocfilecache/__init__.py
34
34
  src/pybiocfilecache/cache.py
35
35
  src/pybiocfilecache/config.py
36
36
  src/pybiocfilecache/const.py
37
- src/pybiocfilecache/exceptions.py
38
37
  src/pybiocfilecache/models.py
39
38
  src/pybiocfilecache/utils.py
40
39
  tests/conftest.py
@@ -11,20 +11,14 @@ from sqlalchemy.pool import QueuePool
11
11
 
12
12
  from .config import CacheConfig
13
13
  from .const import SCHEMA_VERSION
14
- from .exceptions import (
15
- BiocCacheError,
16
- InvalidRnameError,
17
- NoFpathError,
18
- RnameExistsError,
19
- RpathTimeoutError,
20
- )
21
- from .models import Base, Resource
14
+ from .models import Base, Metadata, Resource
22
15
  from .utils import (
23
16
  calculate_file_hash,
24
17
  copy_or_move,
25
18
  create_tmp_dir,
19
+ download_web_file,
26
20
  generate_id,
27
- validate_rname,
21
+ generate_uuid,
28
22
  )
29
23
 
30
24
  __author__ = "Jayaram Kancherla"
@@ -65,7 +59,6 @@ class BiocFileCache:
65
59
  db_schema_version = self._setup_database()
66
60
 
67
61
  if db_schema_version != SCHEMA_VERSION:
68
- print(db_schema_version)
69
62
  raise RuntimeError(f"Database version is not {SCHEMA_VERSION}.")
70
63
 
71
64
  self._last_cleanup = datetime.now()
@@ -111,13 +104,15 @@ class BiocFileCache:
111
104
 
112
105
  return SCHEMA_VERSION
113
106
 
114
- def _get_detached_resource(self, session: Session, resource: Resource) -> Optional[Resource]:
107
+ def _get_detached_resource(
108
+ self, session: Session, obj: Union[Resource, Metadata]
109
+ ) -> Optional[Union[Resource, Metadata]]:
115
110
  """Get a detached copy of a resource."""
116
- if resource is None:
111
+ if obj is None:
117
112
  return None
118
- session.refresh(resource)
119
- session.expunge(resource)
120
- return resource
113
+ session.refresh(obj)
114
+ session.expunge(obj)
115
+ return obj
121
116
 
122
117
  def __enter__(self) -> "BiocFileCache":
123
118
  return self
@@ -142,10 +137,10 @@ class BiocFileCache:
142
137
  finally:
143
138
  session.close()
144
139
 
145
- def _validate_rname(self, rname: str) -> None:
146
- """Validate resource name format."""
147
- if not validate_rname(rname, self.config.rname_pattern):
148
- raise InvalidRnameError(f"Resource name '{rname}' doesn't match pattern " f"'{self.config.rname_pattern}'")
140
+ # def _validate_rname(self, rname: str) -> None:
141
+ # """Validate resource name format."""
142
+ # if not validate_rname(rname, self.config.rname_pattern):
143
+ # raise Exception(f"Resource name '{rname}' doesn't match pattern " f"'{self.config.rname_pattern}'")
149
144
 
150
145
  def _should_cleanup(self) -> bool:
151
146
  """Check if cache cleanup should be performed.
@@ -196,16 +191,25 @@ class BiocFileCache:
196
191
  self._last_cleanup = datetime.now()
197
192
  return removed
198
193
 
199
- def get(self, rname: str) -> Optional[Resource]:
194
+ def get(self, rname: str = None, rid: str = None) -> Optional[Resource]:
200
195
  """Get resource by name from cache.
201
196
 
202
197
  Args:
203
198
  rname:
204
199
  Name to identify the resource in cache.
205
200
 
201
+ rid:
202
+ Resource id to search by.
203
+
206
204
  """
205
+ if rname is None and rid is None:
206
+ raise ValueError("either 'rname' or 'rid' must be provided.")
207
+
207
208
  with self.get_session() as session:
208
- resource = session.query(Resource).filter(Resource.rname == rname).first()
209
+ if rname is not None:
210
+ resource = session.query(Resource).filter(Resource.rname == rname).first()
211
+ elif rid is not None:
212
+ resource = session.query(Resource).filter(Resource.rid == rid).first()
209
213
 
210
214
  if resource is not None:
211
215
  # Check if path exists with timeout
@@ -213,7 +217,7 @@ class BiocFileCache:
213
217
  timeout = 30
214
218
  while not Path(str(resource.rpath)).exists():
215
219
  if time() - start >= timeout:
216
- raise RpathTimeoutError(
220
+ raise TimeoutError(
217
221
  f"For resource: '{rname}' the rpath does not exist " f"after {timeout} seconds."
218
222
  )
219
223
  sleep(0.1)
@@ -229,10 +233,11 @@ class BiocFileCache:
229
233
  self,
230
234
  rname: str,
231
235
  fpath: Union[str, Path],
232
- rtype: Literal["local", "web", "relative"] = "local",
236
+ rtype: Literal["local", "web", "relative"] = "relative",
233
237
  action: Literal["copy", "move", "asis"] = "copy",
234
238
  expires: Optional[datetime] = None,
235
- ext: bool = False,
239
+ download: bool = True,
240
+ ext: bool = True,
236
241
  ) -> Resource:
237
242
  """Add a resource to the cache.
238
243
 
@@ -252,29 +257,41 @@ class BiocFileCache:
252
257
  How to handle the file ("copy", "move", or "asis").
253
258
  Defaults to ``copy``.
254
259
 
260
+ download:
261
+ Whether to download the resource.
262
+ Only used if 'rtype' is "web".
263
+
255
264
  expires:
256
265
  Optional expiration datetime.
257
266
  If None, resource never expires.
258
267
 
259
268
  ext:
260
269
  Whether to use filepath extension when storing in cache.
261
- Defaults to `False`.
270
+ Defaults to `True`.
262
271
 
263
272
  Returns:
264
273
  The `Resource` object added to the cache.
265
274
  """
266
275
  # self._validate_rname(rname)
267
- fpath = Path(fpath)
268
-
269
- if not fpath.exists():
270
- raise NoFpathError(f"Resource at '{fpath}' does not exist")
276
+ fpath = Path(fpath) if rtype != "web" else fpath
271
277
 
272
278
  if self.get(rname) is not None:
273
- raise RnameExistsError(f"Resource '{rname}' already exists")
279
+ raise FileExistsError(f"Resource '{rname}' already exists")
280
+
281
+ if rtype == "web":
282
+ outpath = download_web_file(fpath, Path(fpath).name, download)
283
+ action = "copy"
284
+ else:
285
+ outpath = Path(fpath)
286
+
287
+ if action == "asis":
288
+ logger.warning("If action='asis', rtype must be 'local'.")
289
+ rtype = "local"
274
290
 
275
291
  # Generate paths and check size
276
292
  rid = generate_id(size=len(self))
277
- rpath = self.config.cache_dir / f"{rid}{fpath.suffix if ext else ''}" if action != "asis" else fpath
293
+ uuid = generate_uuid()
294
+ rpath = self.config.cache_dir / f"{uuid}_{outpath.name if ext else outpath.stem}" if action != "asis" else fpath
278
295
 
279
296
  # Create resource record
280
297
  resource = Resource(
@@ -292,7 +309,7 @@ class BiocFileCache:
292
309
  session.commit()
293
310
 
294
311
  try:
295
- copy_or_move(fpath, rpath, rname, action, False)
312
+ copy_or_move(outpath, rpath, rname, action, False)
296
313
 
297
314
  # Calculate and store checksum
298
315
  resource.etag = calculate_file_hash(rpath, self.config.hash_algorithm)
@@ -303,7 +320,7 @@ class BiocFileCache:
303
320
  except Exception as e:
304
321
  session.delete(resource)
305
322
  session.commit()
306
- raise BiocCacheError("Failed to add resource") from e
323
+ raise Exception("Failed to add resource") from e
307
324
 
308
325
  def add_batch(self, resources: List[Dict[str, Any]]) -> List[Resource]:
309
326
  """Add multiple resources in a single transaction.
@@ -349,7 +366,7 @@ class BiocFileCache:
349
366
  """
350
367
  fpath = Path(fpath)
351
368
  if not fpath.exists():
352
- raise NoFpathError(f"File '{fpath}' does not exist")
369
+ raise FileNotFoundError(f"File '{fpath}' does not exist")
353
370
 
354
371
  with self.get_session() as session:
355
372
  resource = session.query(Resource).filter(Resource.rname == rname).first()
@@ -369,7 +386,7 @@ class BiocFileCache:
369
386
 
370
387
  except Exception as e:
371
388
  session.rollback()
372
- raise BiocCacheError("Failed to update resource") from e
389
+ raise Exception("Failed to update resource") from e
373
390
 
374
391
  def remove(self, rname: str) -> None:
375
392
  """Remove a resource from cache by name.
@@ -381,7 +398,7 @@ class BiocFileCache:
381
398
  Name to identify the resource in cache.
382
399
 
383
400
  Raises:
384
- BiocCacheError: If resource removal fails
401
+ Exception: If resource removal fails
385
402
  """
386
403
  with self.get_session() as session:
387
404
  resource = session.query(Resource).filter(Resource.rname == rname).first()
@@ -399,7 +416,7 @@ class BiocFileCache:
399
416
 
400
417
  except Exception as e:
401
418
  session.rollback()
402
- raise BiocCacheError(f"Failed to remove resource '{rname}'") from e
419
+ raise Exception(f"Failed to remove resource '{rname}'") from e
403
420
 
404
421
  def list_resources(self, rtype: Optional[str] = None, expired: Optional[bool] = None) -> List[Resource]:
405
422
  """List resources in the cache with optional filtering.
@@ -564,7 +581,7 @@ class BiocFileCache:
564
581
  True if purge was successful, False otherwise.
565
582
 
566
583
  Raises:
567
- BiocCacheError: If purge fails and force=False.
584
+ Exception: If purge fails and force=False.
568
585
  """
569
586
  try:
570
587
  with self.get_session() as session:
@@ -577,7 +594,7 @@ class BiocFileCache:
577
594
  except Exception as e:
578
595
  if not force:
579
596
  session.rollback()
580
- raise BiocCacheError(f"Failed to remove file for resource '{resource.rname}'") from e
597
+ raise Exception(f"Failed to remove file for resource '{resource.rname}'") from e
581
598
  logger.warning(f"Failed to remove file for resource '{resource.rname}': {e}")
582
599
 
583
600
  session.commit()
@@ -598,7 +615,7 @@ class BiocFileCache:
598
615
 
599
616
  except Exception as e:
600
617
  if not force:
601
- raise BiocCacheError("Failed to purge cache") from e
618
+ raise Exception("Failed to purge cache") from e
602
619
 
603
620
  logger.error("Database cleanup failed, forcing file removal", exc_info=e)
604
621
  for file in self.config.cache_dir.iterdir():
@@ -616,3 +633,58 @@ class BiocFileCache:
616
633
  def __len__(self):
617
634
  with self.get_session() as session:
618
635
  return session.query(Resource).count()
636
+
637
+ def check_metadata_key(self, key: str) -> bool:
638
+ """Check if a key exists in the metadata table.
639
+
640
+ Args:
641
+ key:
642
+ Key to search.
643
+
644
+ Returns:
645
+ True if the key exists, else False.
646
+ """
647
+ with self.get_session() as session:
648
+ return session.query(Metadata).filter(Metadata.key == key).count() != 0
649
+
650
+ def get_metadata(self, key: str):
651
+ """Add a new metadata key"""
652
+ with self.get_session() as session:
653
+ meta = session.query(Metadata).filter(Metadata.key == key).first()
654
+ if meta is not None:
655
+ return self._get_detached_resource(session, meta)
656
+
657
+ return None
658
+
659
+ def add_metadata(self, key: str, value: str):
660
+ """Add a new metadata key"""
661
+ exists = self.get_metadata(key=key)
662
+
663
+ if exists is None:
664
+ meta = Metadata(key=key, value=value)
665
+
666
+ with self.get_session() as session:
667
+ try:
668
+ session.add(meta)
669
+ session.commit()
670
+ return self._get_detached_resource(session, meta)
671
+ except Exception as e:
672
+ session.delete(meta)
673
+ session.commit()
674
+ raise Exception("Failed to add metadata") from e
675
+ else:
676
+ raise Exception(f"'key'={key} already exists in metadata.")
677
+
678
+ def remove_metadata(self, key: str) -> None:
679
+ """Remove a metadata key."""
680
+ with self.get_session() as session:
681
+ meta = session.query(Metadata).filter(Metadata.key == key).first()
682
+
683
+ if meta is not None:
684
+ try:
685
+ session.delete(meta)
686
+ session.commit()
687
+
688
+ except Exception as e:
689
+ session.rollback()
690
+ raise Exception(f"Failed to remove key '{key}'") from e
@@ -73,4 +73,4 @@ class Resource(Base):
73
73
  expires = Column(DateTime, default=None)
74
74
 
75
75
  def __repr__(self) -> str:
76
- return f"<Resource(rid='{self.rid}', rname='{self.rname}')>"
76
+ return f"<Resource(rid='{self.rid}', rname='{self.rname}', rpath='{self.rpath}')>"
@@ -2,14 +2,13 @@ import hashlib
2
2
  import logging
3
3
  import re
4
4
  import tempfile
5
+ import urllib.request
5
6
  import uuid
6
7
  import zlib
7
8
  from pathlib import Path
8
9
  from shutil import copy2, move
9
10
  from typing import Literal
10
11
 
11
- from .exceptions import BiocCacheError
12
-
13
12
  __author__ = "Jayaram Kancherla"
14
13
  __copyright__ = "Jayaram Kancherla"
15
14
  __license__ = "MIT"
@@ -86,4 +85,15 @@ def copy_or_move(
86
85
  elif action == "asis":
87
86
  pass
88
87
  except Exception as e:
89
- raise BiocCacheError(f"Failed to store resource '{rname}' from '{source}' to '{target}'") from e
88
+ raise Exception(f"Failed to store resource '{rname}' from '{source}' to '{target}'") from e
89
+
90
+
91
+ def download_web_file(url: str, filename: str, download: bool):
92
+ tmp_dir = create_tmp_dir()
93
+ outpath = tmp_dir / filename
94
+ if download:
95
+ urllib.request.urlretrieve(str(url), str(outpath))
96
+ else:
97
+ open(str(outpath), "a").close()
98
+
99
+ return outpath
@@ -0,0 +1,139 @@
1
+ import os
2
+ import shutil
3
+
4
+ from datetime import timedelta
5
+ from pybiocfilecache import BiocFileCache, CacheConfig
6
+ from pathlib import Path
7
+ import pytest
8
+ import tempfile
9
+
10
+ __author__ = "jkanche"
11
+ __copyright__ = "jkanche"
12
+ __license__ = "MIT"
13
+
14
+ CACHE_DIR = tempfile.mkdtemp() + "/cache"
15
+
16
+
17
+ def test_create_cache():
18
+ bfc = BiocFileCache(CACHE_DIR)
19
+ assert os.path.exists(CACHE_DIR)
20
+
21
+ bfc.check_metadata_key("schema_version")
22
+
23
+ bfc.purge()
24
+
25
+
26
+ def test_add_get_list_operations():
27
+ bfc = BiocFileCache(CACHE_DIR)
28
+
29
+ rtrip = bfc.add("test1", os.getcwd() + "/tests/data/test1.txt")
30
+ rec1 = bfc.get("test1")
31
+ assert rec1 is not None
32
+
33
+ bfc.add("test2", os.getcwd() + "/tests/data/test2.txt")
34
+ rec2 = bfc.get("test2")
35
+ assert rec2 is not None
36
+
37
+ frec1 = open(rec1.rpath, "r").read().strip()
38
+ assert frec1 == "test1"
39
+
40
+ frec2 = open(rec2.rpath, "r").read().strip()
41
+ assert frec2 == "test2"
42
+
43
+ shutil.copy(os.getcwd() + "/tests/data/test2.txt", os.getcwd() + "/tests/data/test3.txt")
44
+ bfc.add("test3_asis", os.getcwd() + "/tests/data/test3.txt", action="asis")
45
+ rec3 = bfc.get("test3_asis")
46
+ assert rec3 is not None
47
+ assert rec3.rpath == os.getcwd() + "/tests/data/test3.txt"
48
+
49
+ frec3 = open(rec3.rpath, "r").read().strip()
50
+ assert frec3 == "test2"
51
+
52
+ rtrip = bfc.list_resources()
53
+ assert len(rtrip) == 3
54
+
55
+ downurl = "https://bioconductor.org/packages/stats/bioc/BiocFileCache/BiocFileCache_2024_stats.tab"
56
+ add_url = bfc.add(rname="download_link", fpath=downurl, rtype="web")
57
+
58
+ row = bfc.get(rid=add_url.rid)
59
+ assert row.fpath == downurl
60
+
61
+ rtrip = bfc.list_resources()
62
+ assert len(rtrip) == 4
63
+
64
+ bfc.purge()
65
+
66
+
67
+ def test_remove_operations():
68
+ bfc = BiocFileCache(CACHE_DIR)
69
+
70
+ bfc.add("test1", os.getcwd() + "/tests/data/test1.txt")
71
+ rec1 = bfc.get("test1")
72
+ assert rec1 is not None
73
+
74
+ bfc.add("test2", os.getcwd() + "/tests/data/test2.txt")
75
+ rec2 = bfc.get("test2")
76
+ assert rec2 is not None
77
+
78
+ bfc.remove("test1")
79
+ rec1 = bfc.get("test1")
80
+ assert rec1 is None
81
+
82
+ bfc.purge()
83
+
84
+ def test_meta_operations():
85
+ bfc = BiocFileCache(CACHE_DIR)
86
+
87
+ bfc.add("test1", os.getcwd() + "/tests/data/test1.txt")
88
+ rec1 = bfc.get("test1")
89
+ assert rec1 is not None
90
+
91
+ with pytest.raises(Exception):
92
+ bfc.add_metadata("schema_version", "something")
93
+
94
+ bfc.check_metadata_key("schema_version")
95
+
96
+ bfc.add_metadata("language", "python")
97
+
98
+ downurl = "https://bioconductor.org/packages/stats/bioc/BiocFileCache/BiocFileCache_2024_stats.tab"
99
+ add_url = bfc.add(rname="download_link", fpath=downurl, rtype="web")
100
+
101
+ rec = bfc.get_metadata("schema_version")
102
+ assert rec.value == "0.99.4"
103
+
104
+ rec = bfc.get_metadata("language")
105
+ assert rec.value == "python"
106
+
107
+ rtrip = bfc.list_resources()
108
+ assert len(rtrip) == 2
109
+
110
+ bfc.purge()
111
+
112
+ def test_cache_with_config():
113
+ # Create custom configuration
114
+ config = CacheConfig(
115
+ cache_dir=Path(CACHE_DIR),
116
+ cleanup_interval=timedelta(days=7),
117
+ )
118
+
119
+ bfc = BiocFileCache(config=config)
120
+
121
+ bfc.check_metadata_key("schema_version")
122
+
123
+ bfc.add("test1", os.getcwd() + "/tests/data/test1.txt")
124
+ rec1 = bfc.get("test1")
125
+ assert rec1 is not None
126
+
127
+ rtrip = bfc.list_resources()
128
+ assert len(rtrip) == 1
129
+
130
+ bfc.update("test1", os.getcwd() + "/tests/data/test2.txt")
131
+ rec1 = bfc.get("test1")
132
+ assert rec1 is not None
133
+
134
+ rtrip = bfc.list_resources()
135
+ assert len(rtrip) == 1
136
+
137
+ bfc.cleanup()
138
+
139
+ bfc.purge()
@@ -1,31 +0,0 @@
1
- __author__ = "Jayaram Kancherla"
2
- __copyright__ = "Jayaram Kancherla"
3
- __license__ = "MIT"
4
-
5
-
6
- class BiocCacheError(Exception):
7
- """Base exception for BiocFileCache errors."""
8
-
9
-
10
- class NoFpathError(BiocCacheError):
11
- """Source file does not exist."""
12
-
13
-
14
- class RnameExistsError(BiocCacheError):
15
- """Resource name already exists in cache."""
16
-
17
-
18
- class RpathTimeoutError(BiocCacheError):
19
- """Resource path does not exist after timeout."""
20
-
21
-
22
- class CacheSizeLimitError(BiocCacheError):
23
- """Cache size limit would be exceeded."""
24
-
25
-
26
- class ResourceValidationError(BiocCacheError):
27
- """Resource failed validation check."""
28
-
29
-
30
- class InvalidRnameError(BiocCacheError):
31
- """Invalid resource name format."""
@@ -1,69 +0,0 @@
1
- import os
2
- import shutil
3
-
4
- from pybiocfilecache import BiocFileCache
5
-
6
- __author__ = "jkanche"
7
- __copyright__ = "jkanche"
8
- __license__ = "MIT"
9
-
10
- CACHE_DIR = os.getcwd() + "/cache"
11
-
12
-
13
- def test_create_cache():
14
- bfc = BiocFileCache(CACHE_DIR)
15
- assert os.path.exists(CACHE_DIR)
16
-
17
- bfc.purge()
18
-
19
-
20
- def test_add_get_list_operations():
21
- bfc = BiocFileCache(CACHE_DIR)
22
-
23
- rtrip = bfc.add("test1", os.getcwd() + "/tests/data/test1.txt")
24
- print("rtrip: ", rtrip)
25
- rec1 = bfc.get("test1")
26
- print("rec1: ", rec1)
27
- assert rec1 is not None
28
-
29
- bfc.add("test2", os.getcwd() + "/tests/data/test2.txt")
30
- rec2 = bfc.get("test2")
31
- assert rec2 is not None
32
-
33
- frec1 = open(rec1.rpath, "r").read().strip()
34
- assert frec1 == "test1"
35
-
36
- frec2 = open(rec2.rpath, "r").read().strip()
37
- assert frec2 == "test2"
38
-
39
- shutil.copy(os.getcwd() + "/tests/data/test2.txt", os.getcwd() + "/tests/data/test3.txt")
40
- bfc.add("test3_asis", os.getcwd() + "/tests/data/test3.txt", action="asis")
41
- rec3 = bfc.get("test3_asis")
42
- assert rec3 is not None
43
- assert rec3.rpath == os.getcwd() + "/tests/data/test3.txt"
44
-
45
- frec3 = open(rec3.rpath, "r").read().strip()
46
- assert frec3 == "test2"
47
-
48
- rtrip = bfc.list_resources()
49
- assert len(rtrip) == 3
50
-
51
- bfc.purge()
52
-
53
-
54
- def test_remove_operations():
55
- bfc = BiocFileCache(CACHE_DIR)
56
-
57
- bfc.add("test1", os.getcwd() + "/tests/data/test1.txt")
58
- rec1 = bfc.get("test1")
59
- assert rec1 is not None
60
-
61
- bfc.add("test2", os.getcwd() + "/tests/data/test2.txt")
62
- rec2 = bfc.get("test2")
63
- assert rec2 is not None
64
-
65
- bfc.remove("test1")
66
- rec1 = bfc.get("test1")
67
- assert rec1 is None
68
-
69
- bfc.purge()
File without changes