This fetch and cache utils allows sharing between different process.
(
dirpath: Union[str, pathlib.Path],
name: str,
url: str,
process_fn: Callable[[Dict[str, Any]], Dict[str, Any]],
)
| 33 | |
| 34 | |
| 35 | def fetch_and_cache( |
| 36 | dirpath: Union[str, pathlib.Path], |
| 37 | name: str, |
| 38 | url: str, |
| 39 | process_fn: Callable[[Dict[str, Any]], Dict[str, Any]], |
| 40 | ) -> Dict[str, Any]: |
| 41 | """ |
| 42 | This fetch and cache utils allows sharing between different process. |
| 43 | """ |
| 44 | pathlib.Path(dirpath).mkdir(exist_ok=True) |
| 45 | |
| 46 | path = os.path.join(dirpath, name) |
| 47 | print(f"Downloading {url} to {path}") |
| 48 | |
| 49 | def is_cached_file_valid() -> bool: |
| 50 | # Check if the file is new enough (see: FILE_CACHE_LIFESPAN_SECONDS). A real check |
| 51 | # could make a HEAD request and check/store the file's ETag |
| 52 | fname = pathlib.Path(path) |
| 53 | now = datetime.datetime.now() |
| 54 | mtime = datetime.datetime.fromtimestamp(fname.stat().st_mtime) |
| 55 | diff = now - mtime |
| 56 | return diff.total_seconds() < FILE_CACHE_LIFESPAN_SECONDS |
| 57 | |
| 58 | if os.path.exists(path) and is_cached_file_valid(): |
| 59 | # Another test process already download the file, so don't re-do it |
| 60 | with open(path) as f: |
| 61 | return cast(Dict[str, Any], json.load(f)) |
| 62 | |
| 63 | for _ in range(3): |
| 64 | try: |
| 65 | contents = urlopen(url, timeout=5).read().decode("utf-8") |
| 66 | processed_contents = process_fn(json.loads(contents)) |
| 67 | with open(path, "w") as f: |
| 68 | f.write(json.dumps(processed_contents)) |
| 69 | return processed_contents |
| 70 | except Exception as e: |
| 71 | print(f"Could not download {url} because: {e}.") |
| 72 | print(f"All retries exhausted, downloading {url} failed.") |
| 73 | return {} |
| 74 | |
| 75 | |
| 76 | def get_slow_tests( |
no test coverage detected
searching dependent graphs…