Download backend/common/testing.py from isold23/MeloonTop: direct link, hf CLI and curl.
- Browser
- Download file 6 kB
-
https://huggingface.co/spaces/isold23/MeloonTop/resolve/main/backend/common/testing.py
- Command line
-
hf download hf://spaces/isold23/MeloonTop/backend/common/testing.py
-
curl -L -o testing.py https://huggingface.co/spaces/isold23/MeloonTop/resolve/main/backend/common/testing.py
6 kB
| """Shared test helpers for every product's unittest suite. | |
| Lives in ``common/`` (not in a ``unittest/`` directory) so that the | |
| MeloonTop / MeloonExam / MeloonChatBI suites can all import it without | |
| duplicating code or relying on sys.path tricks. Import as:: | |
| from common.testing import make_mock_db, auth_headers | |
| """ | |
| import os | |
| import sys | |
| import uuid | |
| from unittest.mock import MagicMock | |
| # Ensure project root is on sys.path | |
| PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) | |
| if PROJECT_ROOT not in sys.path: | |
| sys.path.insert(0, PROJECT_ROOT) | |
| def make_mock_db( | |
| *, | |
| select_data=None, | |
| insert_data=None, | |
| update_data=None, | |
| delete_data=None, | |
| upsert_data=None, | |
| ): | |
| """Build a fluent Supabase-client mock that returns specific data per operation.""" | |
| mock = MagicMock() | |
| current_op = {"op": "select"} | |
| def _execute(): | |
| op = current_op["op"] | |
| data = select_data if select_data is not None else [] | |
| if op == "insert" and insert_data is not None: | |
| data = insert_data | |
| elif op == "update" and update_data is not None: | |
| data = update_data | |
| elif op == "delete" and delete_data is not None: | |
| data = delete_data | |
| elif op == "upsert" and upsert_data is not None: | |
| data = upsert_data | |
| m = MagicMock() | |
| m.data = data | |
| m.count = len(data) if isinstance(data, list) else 0 | |
| return m | |
| chain = MagicMock() | |
| def _make_op(op_name): | |
| def _op(*args, **kwargs): | |
| current_op["op"] = op_name | |
| return chain | |
| return _op | |
| chain.select = _make_op("select") | |
| chain.insert = _make_op("insert") | |
| chain.update = _make_op("update") | |
| chain.delete = _make_op("delete") | |
| chain.upsert = _make_op("upsert") | |
| for attr in ( | |
| "eq", | |
| "neq", | |
| "or_", | |
| "ilike", | |
| "order", | |
| "limit", | |
| "offset", | |
| "range", | |
| "single", | |
| "in_", | |
| "contains", | |
| "count", | |
| ): | |
| getattr(chain, attr).return_value = chain | |
| chain.execute.side_effect = _execute | |
| mock.table.return_value = chain | |
| mock._chain = chain | |
| def _set_select(data): | |
| nonlocal select_data | |
| select_data = data | |
| mock._set_select = _set_select | |
| return mock | |
| def make_recording_db(*, insert_data=None): | |
| """Build a Supabase stub that records every (table, op, payload) call. | |
| Unlike :func:`make_mock_db` this returns a *fresh* query object per | |
| ``table()`` call, so a test can assert exactly which tables a service | |
| touched -- e.g. that MeloonChatBI writes ``chatbi_profile`` and not | |
| ``exam_profile``. | |
| """ | |
| calls = [] | |
| created_row = insert_data or [ | |
| {"id": "00000000-0000-0000-0000-000000000001"} | |
| ] | |
| class _Query: | |
| def __init__(self, table): | |
| self._table = table | |
| self._op = "select" | |
| self._payload = None | |
| def select(self, *args, **kwargs): | |
| self._op = "select" | |
| return self | |
| def insert(self, payload, *args, **kwargs): | |
| self._op, self._payload = "insert", payload | |
| return self | |
| def upsert(self, payload, *args, **kwargs): | |
| self._op, self._payload = "upsert", payload | |
| return self | |
| def update(self, payload, *args, **kwargs): | |
| self._op, self._payload = "update", payload | |
| return self | |
| def delete(self, *args, **kwargs): | |
| self._op = "delete" | |
| return self | |
| def execute(self): | |
| calls.append((self._table, self._op, self._payload)) | |
| if self._op == "insert" and self._table == "users": | |
| data = created_row | |
| elif self._op in ("insert", "upsert", "update"): | |
| data = [dict(self._payload or {})] | |
| else: | |
| data = [] | |
| result = MagicMock() | |
| result.data = data | |
| result.count = len(data) | |
| return result | |
| for attr in ( | |
| "eq", | |
| "neq", | |
| "or_", | |
| "ilike", | |
| "order", | |
| "limit", | |
| "offset", | |
| "range", | |
| "single", | |
| "in_", | |
| "contains", | |
| ): | |
| setattr(_Query, attr, lambda self, *a, **k: self) | |
| mock = MagicMock() | |
| mock.table.side_effect = lambda name: _Query(name) | |
| mock.calls = calls | |
| return mock | |
| def written_tables(mock): | |
| """Return the (table, op) pairs a recording stub saw for writes.""" | |
| return [ | |
| (table, op) | |
| for (table, op, _payload) in getattr(mock, "calls", []) | |
| if op in ("insert", "upsert") | |
| ] | |
| def written_payload(mock, table): | |
| """Return the payload of the last write recorded for ``table``.""" | |
| payload = None | |
| for (name, op, data) in getattr(mock, "calls", []): | |
| if name == table and op in ("insert", "upsert", "update"): | |
| payload = data | |
| return payload | |
| def make_jwt_token(user_id: str, secret: str = None) -> str: | |
| """Generate a real JWT token using common.security.""" | |
| from common.security import SECRET_KEY, create_access_token | |
| token = create_access_token({"sub": user_id}) | |
| return token | |
| def auth_headers(user_id: str) -> dict: | |
| """Return Authorization headers with a valid JWT.""" | |
| token = make_jwt_token(user_id) | |
| return {"Authorization": f"Bearer {token}"} | |
| def uid() -> str: | |
| return f"user-{uuid.uuid4().hex[:8]}" | |
| #: 测试进程的兜底身份(见 backend/conftest.py 与 common/security.py)。 | |
| #: 放在这里是为了让「需要构造出属主数据」的用例能引用同一个常量。 | |
| TEST_USER_ID = "11111111-1111-4111-8111-111111111111" | |
| TEST_ADMIN_ID = "22222222-2222-4222-8222-222222222222" | |
| def payloads_for(mock, table, op): | |
| """Return every payload a recording stub saw for ``(table, op)``.""" | |
| return [ | |
| data | |
| for (name, recorded_op, data) in getattr(mock, "calls", []) | |
| if name == table and recorded_op == op | |
| ] | |