import os
import secrets
from typing import Any, Literal
import base58
import ipfshttpclient
import pytest
class _FakeIPFSClient:
def __init__(self, store: dict[str, Any]) -> None:
self._store = store
def __enter__(self) -> "_FakeIPFSClient":
return self
def __exit__(self, exc_type: object, exc: object, tb: object) -> Literal[False]:
return False
@staticmethod
def _new_cid_v0() -> str:
multihash = bytes([18, 32]) + secrets.token_bytes(32)
return base58.b58encode(multihash).decode("ascii")
def add_json(self, data: Any) -> str:
cid = self._new_cid_v0()
self._store[cid] = data
return cid
def get_json(self, cid: str) -> Any:
return self._store[cid]
@pytest.fixture(autouse=True)
def _mock_ipfs(monkeypatch: pytest.MonkeyPatch) -> None:
if os.environ.get("USE_REAL_IPFS") == "1":
return
store: dict[str, Any] = {}
def _connect(*_args: object, **_kwargs: object) -> _FakeIPFSClient:
return _FakeIPFSClient(store)
monkeypatch.setattr(ipfshttpclient, "connect", _connect, raising=True)