|
| 1 | +import gzip |
| 2 | +import zipfile |
| 3 | +from functools import partial |
1 | 4 | from typing import TYPE_CHECKING, Any, Union
|
2 | 5 |
|
3 | 6 | from advanced_alchemy._serialization import decode_json
|
|
12 | 15 |
|
13 | 16 |
|
14 | 17 | def open_fixture(fixtures_path: "Union[Path, AsyncPath]", fixture_name: str) -> Any:
|
15 |
| - """Loads JSON file with the specified fixture name |
| 18 | + """Loads JSON file with the specified fixture name. |
| 19 | +
|
| 20 | + Supports plain JSON files, gzipped JSON files (.json.gz), and zipped JSON files (.json.zip). |
| 21 | + The function automatically detects the file format based on file extension and handles |
| 22 | + decompression transparently. Supports both lowercase and uppercase variations for better |
| 23 | + compatibility with database exports. |
16 | 24 |
|
17 | 25 | Args:
|
18 |
| - fixtures_path: :class:`pathlib.Path` | :class:`anyio.Path` The path to look for fixtures |
19 |
| - fixture_name (str): The fixture name to load. |
| 26 | + fixtures_path: The path to look for fixtures. Can be a :class:`pathlib.Path` or |
| 27 | + :class:`anyio.Path` instance. |
| 28 | + fixture_name: The fixture name to load (without file extension). |
20 | 29 |
|
21 | 30 | Raises:
|
22 |
| - :class:`FileNotFoundError`: Fixtures not found. |
| 31 | + FileNotFoundError: If no fixture file is found with any supported extension. |
| 32 | + OSError: If there's an error reading or decompressing the file. |
| 33 | + ValueError: If the JSON content is invalid. |
| 34 | + zipfile.BadZipFile: If the zip file is corrupted. |
| 35 | + gzip.BadGzipFile: If the gzip file is corrupted. |
23 | 36 |
|
24 | 37 | Returns:
|
25 |
| - Any: The parsed JSON data |
| 38 | + Any: The parsed JSON data from the fixture file. |
| 39 | +
|
| 40 | + Examples: |
| 41 | + >>> from pathlib import Path |
| 42 | + >>> fixtures_path = Path("./fixtures") |
| 43 | + >>> data = open_fixture( |
| 44 | + ... fixtures_path, "users" |
| 45 | + ... ) # loads users.json, users.json.gz, or users.json.zip |
| 46 | + >>> print(data) |
| 47 | + [{"id": 1, "name": "Alice"}, {"id": 2, "name": "Bob"}] |
26 | 48 | """
|
27 | 49 | from pathlib import Path
|
28 | 50 |
|
29 |
| - fixture = Path(fixtures_path / f"{fixture_name}.json") |
30 |
| - if fixture.exists(): |
31 |
| - with fixture.open(mode="r", encoding="utf-8") as f: |
32 |
| - f_data = f.read() |
33 |
| - return decode_json(f_data) |
34 |
| - msg = f"Could not find the {fixture_name} fixture" |
| 51 | + base_path = Path(fixtures_path) |
| 52 | + |
| 53 | + # Try different file extensions in order of preference |
| 54 | + # Include both case variations for better compatibility with database exports |
| 55 | + file_variants = [ |
| 56 | + (base_path / f"{fixture_name}.json", "plain"), |
| 57 | + (base_path / f"{fixture_name.upper()}.json.gz", "gzip"), # Uppercase first (common for exports) |
| 58 | + (base_path / f"{fixture_name}.json.gz", "gzip"), |
| 59 | + (base_path / f"{fixture_name.upper()}.json.zip", "zip"), |
| 60 | + (base_path / f"{fixture_name}.json.zip", "zip"), |
| 61 | + ] |
| 62 | + |
| 63 | + for fixture_path, file_type in file_variants: |
| 64 | + if fixture_path.exists(): |
| 65 | + try: |
| 66 | + f_data: str |
| 67 | + if file_type == "plain": |
| 68 | + with fixture_path.open(mode="r", encoding="utf-8") as f: |
| 69 | + f_data = f.read() |
| 70 | + elif file_type == "gzip": |
| 71 | + with fixture_path.open(mode="rb") as f: |
| 72 | + compressed_data = f.read() |
| 73 | + f_data = gzip.decompress(compressed_data).decode("utf-8") |
| 74 | + elif file_type == "zip": |
| 75 | + with zipfile.ZipFile(fixture_path, mode="r") as zf: |
| 76 | + # Look for JSON file inside zip |
| 77 | + json_files = [name for name in zf.namelist() if name.endswith(".json")] |
| 78 | + if not json_files: |
| 79 | + msg = f"No JSON files found in zip archive: {fixture_path}" |
| 80 | + raise ValueError(msg) |
| 81 | + |
| 82 | + # Use the first JSON file found, or prefer one matching the fixture name |
| 83 | + json_file = next((name for name in json_files if name == f"{fixture_name}.json"), json_files[0]) |
| 84 | + |
| 85 | + with zf.open(json_file, mode="r") as f: |
| 86 | + f_data = f.read().decode("utf-8") |
| 87 | + else: |
| 88 | + continue # Skip unknown file types |
| 89 | + |
| 90 | + return decode_json(f_data) |
| 91 | + except (OSError, zipfile.BadZipFile, gzip.BadGzipFile) as exc: |
| 92 | + msg = f"Error reading fixture file {fixture_path}: {exc}" |
| 93 | + raise OSError(msg) from exc |
| 94 | + |
| 95 | + # No valid fixture file found |
| 96 | + msg = f"Could not find the {fixture_name} fixture (tried .json, .json.gz, .json.zip with case variations)" |
35 | 97 | raise FileNotFoundError(msg)
|
36 | 98 |
|
37 | 99 |
|
38 | 100 | async def open_fixture_async(fixtures_path: "Union[Path, AsyncPath]", fixture_name: str) -> Any:
|
39 |
| - """Loads JSON file with the specified fixture name |
| 101 | + """Loads JSON file with the specified fixture name asynchronously. |
| 102 | +
|
| 103 | + Supports plain JSON files, gzipped JSON files (.json.gz), and zipped JSON files (.json.zip). |
| 104 | + The function automatically detects the file format based on file extension and handles |
| 105 | + decompression transparently. Supports both lowercase and uppercase variations for better |
| 106 | + compatibility with database exports. For compressed files, decompression is performed |
| 107 | + synchronously in a thread pool to avoid blocking the event loop. |
40 | 108 |
|
41 | 109 | Args:
|
42 |
| - fixtures_path: :class:`pathlib.Path` | :class:`anyio.Path` The path to look for fixtures |
43 |
| - fixture_name (str): The fixture name to load. |
| 110 | + fixtures_path: The path to look for fixtures. Can be a :class:`pathlib.Path` or |
| 111 | + :class:`anyio.Path` instance. |
| 112 | + fixture_name: The fixture name to load (without file extension). |
44 | 113 |
|
45 | 114 | Raises:
|
46 |
| - :class:`~advanced_alchemy.exceptions.MissingDependencyError`: The `anyio` library is required to use this function. |
47 |
| - :class:`FileNotFoundError`: Fixtures not found. |
| 115 | + MissingDependencyError: If the `anyio` library is not installed. |
| 116 | + FileNotFoundError: If no fixture file is found with any supported extension. |
| 117 | + OSError: If there's an error reading or decompressing the file. |
| 118 | + ValueError: If the JSON content is invalid. |
| 119 | + zipfile.BadZipFile: If the zip file is corrupted. |
| 120 | + gzip.BadGzipFile: If the gzip file is corrupted. |
48 | 121 |
|
49 | 122 | Returns:
|
50 |
| - Any: The parsed JSON data |
| 123 | + Any: The parsed JSON data from the fixture file. |
| 124 | +
|
| 125 | + Examples: |
| 126 | + >>> from anyio import Path as AsyncPath |
| 127 | + >>> fixtures_path = AsyncPath("./fixtures") |
| 128 | + >>> data = await open_fixture_async( |
| 129 | + ... fixtures_path, "users" |
| 130 | + ... ) # loads users.json, users.json.gz, or users.json.zip |
| 131 | + >>> print(data) |
| 132 | + [{"id": 1, "name": "Alice"}, {"id": 2, "name": "Bob"}] |
51 | 133 | """
|
52 | 134 | try:
|
53 | 135 | from anyio import Path as AsyncPath
|
54 | 136 | except ImportError as exc:
|
55 | 137 | msg = "The `anyio` library is required to use this function. Please install it with `pip install anyio`."
|
56 | 138 | raise MissingDependencyError(msg) from exc
|
57 | 139 |
|
58 |
| - fixture = AsyncPath(fixtures_path / f"{fixture_name}.json") |
59 |
| - if await fixture.exists(): |
60 |
| - async with await fixture.open(mode="r", encoding="utf-8") as f: |
61 |
| - f_data = await f.read() |
62 |
| - return decode_json(f_data) |
63 |
| - msg = f"Could not find the {fixture_name} fixture" |
| 140 | + from advanced_alchemy.utils.sync_tools import async_ |
| 141 | + |
| 142 | + def _read_zip_file(path: "AsyncPath", name: str) -> str: |
| 143 | + """Helper function to read zip files.""" |
| 144 | + with zipfile.ZipFile(str(path), mode="r") as zf: |
| 145 | + # Look for JSON file inside zip |
| 146 | + json_files = [file for file in zf.namelist() if file.endswith(".json")] |
| 147 | + if not json_files: |
| 148 | + error_msg = f"No JSON files found in zip archive: {path}" |
| 149 | + raise ValueError(error_msg) |
| 150 | + |
| 151 | + # Use the first JSON file found, or prefer one matching the fixture name |
| 152 | + json_file = next((file for file in json_files if file == f"{name}.json"), json_files[0]) |
| 153 | + |
| 154 | + with zf.open(json_file, mode="r") as f: |
| 155 | + return f.read().decode("utf-8") |
| 156 | + |
| 157 | + base_path = AsyncPath(fixtures_path) |
| 158 | + |
| 159 | + # Try different file extensions in order of preference |
| 160 | + # Include both case variations for better compatibility with database exports |
| 161 | + file_variants = [ |
| 162 | + (base_path / f"{fixture_name}.json", "plain"), |
| 163 | + (base_path / f"{fixture_name.upper()}.json.gz", "gzip"), # Uppercase first (common for exports) |
| 164 | + (base_path / f"{fixture_name}.json.gz", "gzip"), |
| 165 | + (base_path / f"{fixture_name.upper()}.json.zip", "zip"), |
| 166 | + (base_path / f"{fixture_name}.json.zip", "zip"), |
| 167 | + ] |
| 168 | + |
| 169 | + for fixture_path, file_type in file_variants: |
| 170 | + if await fixture_path.exists(): |
| 171 | + try: |
| 172 | + f_data: str |
| 173 | + if file_type == "plain": |
| 174 | + async with await fixture_path.open(mode="r", encoding="utf-8") as f: |
| 175 | + f_data = await f.read() |
| 176 | + elif file_type == "gzip": |
| 177 | + # Read gzipped files using binary pattern |
| 178 | + async with await fixture_path.open(mode="rb") as f: # type: ignore[assignment] |
| 179 | + compressed_data: bytes = await f.read() # type: ignore[assignment] |
| 180 | + |
| 181 | + # Decompress in thread pool to avoid blocking |
| 182 | + def _decompress_gzip(data: bytes) -> str: |
| 183 | + return gzip.decompress(data).decode("utf-8") |
| 184 | + |
| 185 | + f_data = await async_(partial(_decompress_gzip, compressed_data))() |
| 186 | + elif file_type == "zip": |
| 187 | + # Read zipped files in thread pool to avoid blocking |
| 188 | + f_data = await async_(partial(_read_zip_file, fixture_path, fixture_name))() |
| 189 | + else: |
| 190 | + continue # Skip unknown file types |
| 191 | + |
| 192 | + return decode_json(f_data) |
| 193 | + except (OSError, zipfile.BadZipFile, gzip.BadGzipFile) as exc: |
| 194 | + msg = f"Error reading fixture file {fixture_path}: {exc}" |
| 195 | + raise OSError(msg) from exc |
| 196 | + |
| 197 | + # No valid fixture file found |
| 198 | + msg = f"Could not find the {fixture_name} fixture (tried .json, .json.gz, .json.zip with case variations)" |
64 | 199 | raise FileNotFoundError(msg)
|
0 commit comments