test_snql_snuba.py 2.7 KB

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