|
| 1 | +import json |
| 2 | +import socket |
| 3 | +from pathlib import Path |
| 4 | +from unittest.mock import MagicMock |
| 5 | + |
| 6 | +import pytest |
| 7 | +from curl_cffi.curl import Curl |
| 8 | + |
| 9 | +FIXTURES_DIR = Path(__file__).parent.parent / "fixtures" / "extract" |
| 10 | + |
| 11 | + |
| 12 | +@pytest.fixture(autouse=True) |
| 13 | +def _no_outbound_network(monkeypatch): |
| 14 | + """Fail fast if a mis-targeted Session patch would let a test reach libcurl or a raw socket.""" |
| 15 | + |
| 16 | + def _blocked(*args, **kwargs): |
| 17 | + raise AssertionError("outbound network attempted in tests/extract") |
| 18 | + |
| 19 | + monkeypatch.setattr(Curl, "perform", _blocked) |
| 20 | + monkeypatch.setattr(socket.socket, "connect", _blocked) |
| 21 | + |
| 22 | + |
| 23 | +@pytest.fixture |
| 24 | +def load_fixture(): |
| 25 | + def _load(name: str): |
| 26 | + text = (FIXTURES_DIR / name).read_text(encoding="utf-8") |
| 27 | + return json.loads(text) if name.endswith(".json") else text |
| 28 | + |
| 29 | + return _load |
| 30 | + |
| 31 | + |
| 32 | +def _fake_response(body): |
| 33 | + resp = MagicMock(status_code=200, **{"raise_for_status.return_value": None}) |
| 34 | + if isinstance(body, str): |
| 35 | + resp.text = body |
| 36 | + else: |
| 37 | + resp.json.return_value = body |
| 38 | + return resp |
| 39 | + |
| 40 | + |
| 41 | +@pytest.fixture |
| 42 | +def fake_session(monkeypatch): |
| 43 | + """Serve bodies in call order: ``str`` as ``.text``, anything else as ``.json()``.""" |
| 44 | + |
| 45 | + def _install(module, *, get=(), post=()): |
| 46 | + session = MagicMock() |
| 47 | + session.get.side_effect = [_fake_response(b) for b in get] |
| 48 | + session.post.side_effect = [_fake_response(b) for b in post] |
| 49 | + session.__enter__.return_value = session |
| 50 | + session.__exit__.return_value = False |
| 51 | + monkeypatch.setattr(module.cffi_requests, "Session", MagicMock(return_value=session)) |
| 52 | + return session |
| 53 | + |
| 54 | + return _install |
0 commit comments