upstashvectordb.py 2.1 KB

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