upstashvectordb.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import os
  2. from typing import Optional
  3. import pytest
  4. from _pytest.monkeypatch import MonkeyPatch
  5. from upstash_vector import Index
  6. # Mocking the Index class from upstash_vector
  7. class MockIndex:
  8. def __init__(self, url="", token=""):
  9. self.url = url
  10. self.token = token
  11. self.vectors = []
  12. def upsert(self, vectors):
  13. for vector in vectors:
  14. vector.score = 0.5
  15. self.vectors.append(vector)
  16. return {"code": 0, "msg": "operation success", "affectedCount": len(vectors)}
  17. def fetch(self, ids):
  18. return [vector for vector in self.vectors if vector.id in ids]
  19. def delete(self, ids):
  20. self.vectors = [vector for vector in self.vectors if vector.id not in ids]
  21. return {"code": 0, "msg": "Success"}
  22. def query(
  23. self,
  24. vector: None,
  25. top_k: int = 10,
  26. include_vectors: bool = False,
  27. include_metadata: bool = False,
  28. filter: str = "",
  29. data: Optional[str] = None,
  30. namespace: str = "",
  31. include_data: bool = False,
  32. ):
  33. # Simple mock query, in real scenario you would calculate similarity
  34. mock_result = []
  35. for vector_data in self.vectors:
  36. mock_result.append(vector_data)
  37. return mock_result[:top_k]
  38. def reset(self):
  39. self.vectors = []
  40. def info(self):
  41. return AttrDict({"dimension": 1024})
  42. class AttrDict(dict):
  43. def __getattr__(self, item):
  44. return self.get(item)
  45. MOCK = os.getenv("MOCK_SWITCH", "false").lower() == "true"
  46. @pytest.fixture
  47. def setup_upstashvector_mock(request, monkeypatch: MonkeyPatch):
  48. if MOCK:
  49. monkeypatch.setattr(Index, "__init__", MockIndex.__init__)
  50. monkeypatch.setattr(Index, "upsert", MockIndex.upsert)
  51. monkeypatch.setattr(Index, "fetch", MockIndex.fetch)
  52. monkeypatch.setattr(Index, "delete", MockIndex.delete)
  53. monkeypatch.setattr(Index, "query", MockIndex.query)
  54. monkeypatch.setattr(Index, "reset", MockIndex.reset)
  55. monkeypatch.setattr(Index, "info", MockIndex.info)
  56. yield
  57. if MOCK:
  58. monkeypatch.undo()