fakes.py 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. """不连数据库的连接替身。"""
  2. class FakeCursor:
  3. """记录语句,并按连接上的标志返回只读探针结果。"""
  4. def __init__(self, connection: "FakeConnection") -> None:
  5. self._connection = connection
  6. async def __aenter__(self) -> "FakeCursor":
  7. return self
  8. async def __aexit__(self, exc_type: object, exc: object, tb: object) -> bool:
  9. return False
  10. async def execute(self, query: str, args: object = None) -> None:
  11. self._connection.statements.append(query)
  12. async def fetchall(self) -> list[tuple[object, ...]]:
  13. return [(self._connection.readonly_flag,)]
  14. @property
  15. def description(self) -> tuple[tuple[str], ...]:
  16. return (("value",),)
  17. class FakeConnection:
  18. """业务连接或自有库连接的替身。"""
  19. def __init__(self, readonly_flag: object = 1) -> None:
  20. self.readonly_flag = readonly_flag
  21. self.statements: list[str] = []
  22. self.cursor_calls = 0
  23. self.closed = False
  24. def cursor(self) -> FakeCursor:
  25. self.cursor_calls += 1
  26. return FakeCursor(self)
  27. async def ensure_closed(self) -> None:
  28. self.closed = True
  29. class RejectingConnection:
  30. """游标一旦创建就失败,用来证明语句没有发给驱动。"""
  31. def __init__(self) -> None:
  32. self.cursor_calls = 0
  33. def cursor(self) -> FakeCursor:
  34. self.cursor_calls += 1
  35. raise AssertionError("不应向数据库发送语句")