test_snql_snuba.py 2.9 KB

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