conftest.py
Language Python3.1 KB98 lines
"""Test setup: server.py reads its configuration at import time and exits whenBITRIX_WEBHOOK_URL is unset, so the environment is fixed here, before any testmodule imports it. Data (logs, schema snapshots) goes to a throwaway directory."""import osimport sysimport tempfilefrom pathlib import Pathimport pytestos.environ["BITRIX_WEBHOOK_URL"] = "https://example.invalid/rest/1/x"os.environ["BITRIX_DATA_DIR"] = tempfile.mkdtemp(prefix="bitrix-mcp-tests-")os.environ["BITRIX_LOCAL_TZ"] = "America/Chicago"os.environ["BITRIX_WRITES"] = "on"os.environ["BITRIX_WRITE_PARTIES"] = "on"os.environ["BITRIX_LOG_ARGS"] = "redact"sys.path.insert(0, str(Path(__file__).resolve().parent.parent))import server # noqa: E402# Per-process caches that must not leak between tests. Listed by name and# reset only if present, so the fixture does not depend on how the server# organises them internally._CACHES = ("_STATUS_CACHE", "_PIPELINES_CACHE", "_FIELDS_CACHE", "_USER_CACHE","_USER_NAMES", "_ALLOWED_CATS", "_FUNNEL_NAMES")@pytest.fixture(autouse=True)def _fresh_caches():def reset():for name in _CACHES:if not hasattr(server, name):continuevalue = getattr(server, name)if isinstance(value, dict):value.clear()else:setattr(server, name, None)reset()yieldreset()class FakeBitrix:"""Stands in for server.bitrix_call: records every (method, params) pairand answers from a script keyed by method name. A scripted value may be alist (consumed in order), an exception instance (raised), or a callabletaking params."""def __init__(self, script: dict | None = None):self.script = dict(script or {})self.calls: list[tuple[str, dict]] = []async def __call__(self, method, params=None, envelope=False):self.calls.append((method, params))if method not in self.script:raise AssertionError(f"unexpected Bitrix call: {method} {params!r}")answer = self.script[method]if isinstance(answer, list) and answer and isinstance(answer[0], _Seq):answer = answer.pop(0).valueif isinstance(answer, BaseException):raise answerif callable(answer):return answer(params)return answer@propertydef methods(self) -> list[str]:return [m for m, _ in self.calls]class _Seq:def __init__(self, value):self.value = valuedef seq(*values):"""Script helper: successive answers for repeated calls to one method."""return [_Seq(v) for v in values]@pytest.fixturedef fake_bitrix(monkeypatch):def install(script=None):fake = FakeBitrix(script)monkeypatch.setattr(server, "bitrix_call", fake)return fakereturn install@pytest.fixturedef logged(monkeypatch):"""Capture log_call records instead of writing calls.jsonl."""records: list[tuple[str, dict, str]] = []monkeypatch.setattr(server, "log_call", lambda tool, args, summary: records.append((tool, args, summary)))return records