test_snql_snuba.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import time
  2. import uuid
  3. from datetime import datetime, timedelta
  4. from typing import Optional
  5. from snuba_sdk.column import Column
  6. from snuba_sdk.conditions import Condition, Op
  7. from snuba_sdk.entity import Entity
  8. from snuba_sdk.function import Function
  9. from snuba_sdk.query import Query
  10. from sentry.testutils import SnubaTestCase, TestCase
  11. from sentry.utils import snuba
  12. class SnQLTest(TestCase, SnubaTestCase):
  13. def _insert_event_for_time(
  14. self, ts: datetime, group_hash: str = "a" * 32, group_id: Optional[int] = None
  15. ) -> str:
  16. event_id = uuid.uuid4().hex
  17. self.snuba_insert(
  18. (
  19. 2,
  20. "insert",
  21. {
  22. "event_id": event_id,
  23. "primary_hash": group_hash,
  24. "group_id": group_id if group_id else int(group_hash[:16], 16),
  25. "project_id": self.project.id,
  26. "message": "message",
  27. "platform": "python",
  28. "datetime": ts.strftime("%Y-%m-%dT%H:%M:%S.%fZ"),
  29. "data": {"received": time.mktime(ts.timetuple())},
  30. },
  31. )
  32. )
  33. return event_id
  34. def test_basic(self) -> None:
  35. now = datetime.now()
  36. self._insert_event_for_time(now)
  37. query = (
  38. Query(dataset="events", match=Entity("events"))
  39. .set_select([Function("count", [], "count")])
  40. .set_groupby([Column("project_id")])
  41. .set_where(
  42. [
  43. Condition(Column("project_id"), Op.EQ, self.project.id),
  44. Condition(Column("timestamp"), Op.GTE, now - timedelta(days=1)),
  45. Condition(Column("timestamp"), Op.LT, now + timedelta(days=1)),
  46. ]
  47. )
  48. )
  49. result = snuba.raw_snql_query(query)
  50. assert len(result["data"]) == 1
  51. assert result["data"][0] == {"count": 1, "project_id": self.project.id}