"""Fixture loading utilities for SQLSpec.
Provides functions for writing, loading and parsing JSON fixture files
used in testing and development. Supports both sync and async operations.
"""
import gzip
import zipfile
from pathlib import Path
from typing import TYPE_CHECKING, Any
from sqlspec.storage import storage_registry
from sqlspec.utils.serializers import from_json as decode_json
from sqlspec.utils.serializers import schema_dump
from sqlspec.utils.serializers import to_json as encode_json
from sqlspec.utils.sync_tools import async_
if TYPE_CHECKING:
from sqlspec.typing import SupportedSchemaModel
__all__ = ("open_fixture_async", "open_fixture_sync", "write_fixture_async", "write_fixture_sync")
def open_fixture_sync(fixtures_path: Any, fixture_name: str) -> Any:
"""Load and parse a JSON fixture file with compression support.
Supports reading from:
- Regular JSON files (.json)
- Gzipped JSON files (.json.gz)
- Zipped JSON files (.json.zip)
Args:
fixtures_path: The path to look for fixtures (pathlib.Path)
fixture_name: The fixture name to load.
Returns:
The parsed JSON data
"""
fixture_path = _find_fixture_file(fixtures_path, fixture_name)
if fixture_path.suffix in {".gz", ".zip"}:
f_data = _read_compressed_file(fixture_path)
else:
with fixture_path.open(mode="r", encoding="utf-8") as f:
f_data = f.read()
return decode_json(f_data)