test_event_frequency.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797
  1. import time
  2. from copy import deepcopy
  3. from datetime import timedelta
  4. from unittest.mock import patch
  5. from uuid import uuid4
  6. import pytest
  7. from django.utils import timezone
  8. from sentry.issues.grouptype import PerformanceNPlusOneGroupType
  9. from sentry.models.group import Group
  10. from sentry.models.project import Project
  11. from sentry.models.rule import Rule
  12. from sentry.rules.conditions.event_frequency import (
  13. EventFrequencyCondition,
  14. EventFrequencyPercentCondition,
  15. EventUniqueUserFrequencyCondition,
  16. )
  17. from sentry.testutils.abstract import Abstract
  18. from sentry.testutils.cases import (
  19. BaseMetricsTestCase,
  20. PerformanceIssueTestCase,
  21. RuleTestCase,
  22. SnubaTestCase,
  23. )
  24. from sentry.testutils.helpers.datetime import before_now, freeze_time, iso_format
  25. from sentry.testutils.skips import requires_snuba
  26. from sentry.utils.samples import load_data
  27. pytestmark = [pytest.mark.sentry_metrics, requires_snuba]
  28. class BaseEventFrequencyPercentTest(BaseMetricsTestCase):
  29. def _make_sessions(
  30. self, num: int, environment_name: str | None = None, project: Project | None = None
  31. ):
  32. received = time.time()
  33. def make_session(i):
  34. return dict(
  35. distinct_id=uuid4().hex,
  36. session_id=uuid4().hex,
  37. org_id=project.organization_id if project else self.project.organization_id,
  38. project_id=project.id if project else self.project.id,
  39. status="ok",
  40. seq=0,
  41. release="foo@1.0.0",
  42. environment=environment_name if environment_name else "prod",
  43. retention_days=90,
  44. duration=None,
  45. errors=0,
  46. # The line below is crucial to spread sessions throughout the time period.
  47. started=received - i - 1,
  48. received=received,
  49. )
  50. self.bulk_store_sessions([make_session(i) for i in range(num)])
  51. class EventFrequencyQueryTestBase(SnubaTestCase, RuleTestCase, PerformanceIssueTestCase):
  52. def setUp(self):
  53. super().setUp()
  54. self.start = before_now(minutes=1)
  55. self.end = timezone.now()
  56. self.event = self.store_event(
  57. data={
  58. "event_id": "a" * 32,
  59. "environment": self.environment.name,
  60. "timestamp": iso_format(before_now(seconds=30)),
  61. "fingerprint": ["group-1"],
  62. "user": {"id": uuid4().hex},
  63. },
  64. project_id=self.project.id,
  65. )
  66. self.event2 = self.store_event(
  67. data={
  68. "event_id": "b" * 32,
  69. "environment": self.environment.name,
  70. "timestamp": iso_format(before_now(seconds=12)),
  71. "fingerprint": ["group-2"],
  72. "user": {"id": uuid4().hex},
  73. },
  74. project_id=self.project.id,
  75. )
  76. self.environment2 = self.create_environment(name="staging")
  77. self.event3 = self.store_event(
  78. data={
  79. "event_id": "c" * 32,
  80. "environment": self.environment2.name,
  81. "timestamp": iso_format(before_now(seconds=12)),
  82. "fingerprint": ["group-3"],
  83. "user": {"id": uuid4().hex},
  84. },
  85. project_id=self.project.id,
  86. )
  87. fingerprint = f"{PerformanceNPlusOneGroupType.type_id}-something_random"
  88. perf_event_data = load_data(
  89. "transaction-n-plus-one",
  90. timestamp=before_now(seconds=12),
  91. start_timestamp=before_now(seconds=13),
  92. fingerprint=[fingerprint],
  93. )
  94. perf_event_data["user"] = {"id": uuid4().hex}
  95. perf_event_data["environment"] = self.environment.name
  96. # Store a performance event
  97. self.perf_event = self.create_performance_issue(
  98. event_data=perf_event_data,
  99. project_id=self.project.id,
  100. fingerprint=fingerprint,
  101. )
  102. self.data = {"interval": "5m", "value": 30}
  103. self.condition_inst = self.get_rule(
  104. data=self.data,
  105. project=self.event.group.project,
  106. rule=Rule(environment_id=self.environment.id),
  107. )
  108. self.condition_inst2 = self.get_rule(
  109. data=self.data,
  110. project=self.event.group.project,
  111. rule=Rule(environment_id=self.environment2.id),
  112. )
  113. class EventFrequencyQueryTest(EventFrequencyQueryTestBase):
  114. rule_cls = EventFrequencyCondition
  115. def test_batch_query(self):
  116. batch_query = self.condition_inst.batch_query_hook(
  117. group_ids=[self.event.group_id, self.event2.group_id, self.perf_event.group_id],
  118. start=self.start,
  119. end=self.end,
  120. environment_id=self.environment.id,
  121. )
  122. assert batch_query == {
  123. self.event.group_id: 1,
  124. self.event2.group_id: 1,
  125. self.perf_event.group_id: 1,
  126. }
  127. batch_query = self.condition_inst2.batch_query_hook(
  128. group_ids=[self.event3.group_id],
  129. start=self.start,
  130. end=self.end,
  131. environment_id=self.environment2.id,
  132. )
  133. assert batch_query == {self.event3.group_id: 1}
  134. def test_get_error_and_generic_group_ids(self):
  135. groups = Group.objects.filter(
  136. id__in=[self.event.group_id, self.event2.group_id, self.perf_event.group_id]
  137. ).values("id", "type", "project__organization_id")
  138. error_issue_ids, generic_issue_ids = self.condition_inst.get_error_and_generic_group_ids(
  139. groups
  140. )
  141. assert self.event.group_id in error_issue_ids
  142. assert self.event2.group_id in error_issue_ids
  143. assert self.perf_event.group_id in generic_issue_ids
  144. class EventUniqueUserFrequencyQueryTest(EventFrequencyQueryTestBase):
  145. rule_cls = EventUniqueUserFrequencyCondition
  146. def test_batch_query_user(self):
  147. batch_query = self.condition_inst.batch_query_hook(
  148. group_ids=[self.event.group_id, self.event2.group_id, self.perf_event.group_id],
  149. start=self.start,
  150. end=self.end,
  151. environment_id=self.environment.id,
  152. )
  153. assert batch_query == {
  154. self.event.group_id: 1,
  155. self.event2.group_id: 1,
  156. self.perf_event.group_id: 1,
  157. }
  158. batch_query = self.condition_inst2.batch_query_hook(
  159. group_ids=[self.event3.group_id],
  160. start=self.start,
  161. end=self.end,
  162. environment_id=self.environment2.id,
  163. )
  164. assert batch_query == {self.event3.group_id: 1}
  165. class EventFrequencyPercentConditionQueryTest(
  166. EventFrequencyQueryTestBase, BaseEventFrequencyPercentTest
  167. ):
  168. rule_cls = EventFrequencyPercentCondition
  169. @patch("sentry.rules.conditions.event_frequency.MIN_SESSIONS_TO_FIRE", 1)
  170. def test_batch_query_percent(self):
  171. self._make_sessions(60, self.environment2.name)
  172. self._make_sessions(60, self.environment.name)
  173. batch_query = self.condition_inst.batch_query_hook(
  174. group_ids=[self.event.group_id, self.event2.group_id, self.perf_event.group_id],
  175. start=self.start,
  176. end=self.end,
  177. environment_id=self.environment.id,
  178. )
  179. percent_of_sessions = 20
  180. assert batch_query == {
  181. self.event.group_id: percent_of_sessions,
  182. self.event2.group_id: percent_of_sessions,
  183. }
  184. batch_query = self.condition_inst2.batch_query_hook(
  185. group_ids=[self.event3.group_id],
  186. start=self.start,
  187. end=self.end,
  188. environment_id=self.environment2.id,
  189. )
  190. assert batch_query == {self.event3.group_id: percent_of_sessions}
  191. @patch("sentry.rules.conditions.event_frequency.MIN_SESSIONS_TO_FIRE", 100)
  192. def test_batch_query_percent_no_avg_sessions_in_interval(self):
  193. self._make_sessions(60, self.environment2.name)
  194. self._make_sessions(60, self.environment.name)
  195. batch_query = self.condition_inst.batch_query_hook(
  196. group_ids=[self.event.group_id, self.event2.group_id, self.perf_event.group_id],
  197. start=self.start,
  198. end=self.end,
  199. environment_id=self.environment.id,
  200. )
  201. percent = 0
  202. assert batch_query == {
  203. self.event.group_id: percent,
  204. self.event2.group_id: percent,
  205. self.perf_event.group_id: percent,
  206. }
  207. batch_query = self.condition_inst2.batch_query_hook(
  208. group_ids=[self.event3.group_id],
  209. start=self.start,
  210. end=self.end,
  211. environment_id=self.environment2.id,
  212. )
  213. assert batch_query == {self.event3.group_id: percent}
  214. class ErrorEventMixin(SnubaTestCase):
  215. def add_event(self, data, project_id, timestamp):
  216. data["timestamp"] = iso_format(timestamp)
  217. # Store an error event
  218. event = self.store_event(
  219. data=data,
  220. project_id=project_id,
  221. )
  222. return event.for_group(event.group)
  223. class PerfIssuePlatformEventMixin(PerformanceIssueTestCase):
  224. def add_event(self, data, project_id, timestamp):
  225. fingerprint = data["fingerprint"][0]
  226. fingerprint = (
  227. fingerprint
  228. if "-" in fingerprint
  229. else f"{PerformanceNPlusOneGroupType.type_id}-{data['fingerprint'][0]}"
  230. )
  231. event_data = load_data(
  232. "transaction-n-plus-one",
  233. timestamp=timestamp,
  234. start_timestamp=timestamp,
  235. fingerprint=[fingerprint],
  236. )
  237. event_data["user"] = {"id": uuid4().hex}
  238. event_data["environment"] = data.get("environment")
  239. for tag in event_data["tags"]:
  240. if tag[0] == "environment":
  241. tag[1] = data.get("environment")
  242. break
  243. else:
  244. event_data["tags"].append(data.get("environment"))
  245. # Store a performance event
  246. event = self.create_performance_issue(
  247. event_data=event_data,
  248. project_id=project_id,
  249. fingerprint=fingerprint,
  250. )
  251. return event
  252. @pytest.mark.snuba_ci
  253. class StandardIntervalTestBase(SnubaTestCase, RuleTestCase, PerformanceIssueTestCase):
  254. __test__ = Abstract(__module__, __qualname__)
  255. def add_event(self, data, project_id, timestamp):
  256. raise NotImplementedError
  257. def increment(self, event, count, environment=None, timestamp=None):
  258. raise NotImplementedError
  259. def _run_test(self, minutes, data, passes, add_events=False):
  260. if not self.environment:
  261. self.environment = self.create_environment(name="prod")
  262. rule = self.get_rule(data=data, rule=Rule(environment_id=None))
  263. environment_rule = self.get_rule(data=data, rule=Rule(environment_id=self.environment.id))
  264. event = self.add_event(
  265. data={
  266. "fingerprint": ["something_random"],
  267. "user": {"id": uuid4().hex},
  268. },
  269. project_id=self.project.id,
  270. timestamp=before_now(minutes=minutes),
  271. )
  272. if add_events:
  273. self.increment(
  274. event,
  275. data["value"] + 1,
  276. environment=self.environment.name,
  277. timestamp=timezone.now() - timedelta(minutes=minutes),
  278. )
  279. self.increment(
  280. event,
  281. data["value"] + 1,
  282. timestamp=timezone.now() - timedelta(minutes=minutes),
  283. )
  284. if passes:
  285. self.assertPasses(rule, event, is_new=False)
  286. self.assertPasses(environment_rule, event, is_new=False)
  287. else:
  288. self.assertDoesNotPass(rule, event, is_new=False)
  289. self.assertDoesNotPass(environment_rule, event, is_new=False)
  290. def test_comparison_interval_empty_string(self):
  291. data = {
  292. "interval": "1m",
  293. "value": 16,
  294. "comparisonType": "count",
  295. "comparisonInterval": "",
  296. }
  297. self._run_test(data=data, minutes=1, passes=False)
  298. def test_one_minute_with_events(self):
  299. data = {"interval": "1m", "value": 6, "comparisonType": "count", "comparisonInterval": "5m"}
  300. self._run_test(data=data, minutes=1, passes=True, add_events=True)
  301. data = {
  302. "interval": "1m",
  303. "value": 16,
  304. "comparisonType": "count",
  305. "comparisonInterval": "5m",
  306. }
  307. self._run_test(data=data, minutes=1, passes=False)
  308. def test_one_hour_with_events(self):
  309. data = {"interval": "1h", "value": 6, "comparisonType": "count", "comparisonInterval": "5m"}
  310. self._run_test(data=data, minutes=60, passes=True, add_events=True)
  311. data = {
  312. "interval": "1h",
  313. "value": 16,
  314. "comparisonType": "count",
  315. "comparisonInterval": "5m",
  316. }
  317. self._run_test(data=data, minutes=60, passes=False)
  318. def test_one_day_with_events(self):
  319. data = {"interval": "1d", "value": 6, "comparisonType": "count", "comparisonInterval": "5m"}
  320. self._run_test(data=data, minutes=1440, passes=True, add_events=True)
  321. data = {
  322. "interval": "1d",
  323. "value": 16,
  324. "comparisonType": "count",
  325. "comparisonInterval": "5m",
  326. }
  327. self._run_test(data=data, minutes=1440, passes=False)
  328. def test_one_week_with_events(self):
  329. data = {"interval": "1w", "value": 6, "comparisonType": "count", "comparisonInterval": "5m"}
  330. self._run_test(data=data, minutes=10080, passes=True, add_events=True)
  331. data = {
  332. "interval": "1w",
  333. "value": 16,
  334. "comparisonType": "count",
  335. "comparisonInterval": "5m",
  336. }
  337. self._run_test(data=data, minutes=10080, passes=False)
  338. def test_one_minute_no_events(self):
  339. data = {"interval": "1m", "value": 6, "comparisonType": "count", "comparisonInterval": "5m"}
  340. self._run_test(data=data, minutes=1, passes=False)
  341. def test_one_hour_no_events(self):
  342. data = {"interval": "1h", "value": 6, "comparisonType": "count", "comparisonInterval": "5m"}
  343. self._run_test(data=data, minutes=60, passes=False)
  344. def test_one_day_no_events(self):
  345. data = {"interval": "1d", "value": 6, "comparisonType": "count", "comparisonInterval": "5m"}
  346. self._run_test(data=data, minutes=1440, passes=False)
  347. def test_one_week_no_events(self):
  348. data = {"interval": "1w", "value": 6, "comparisonType": "count", "comparisonInterval": "5m"}
  349. self._run_test(data=data, minutes=10080, passes=False)
  350. def test_comparison(self):
  351. # Test data is 4 events in the current period and 2 events in the comparison period, so
  352. # a 100% increase.
  353. event = self.add_event(
  354. data={
  355. "fingerprint": ["something_random"],
  356. "user": {"id": uuid4().hex},
  357. },
  358. project_id=self.project.id,
  359. timestamp=before_now(minutes=1),
  360. )
  361. self.increment(
  362. event,
  363. 3,
  364. timestamp=timezone.now() - timedelta(minutes=1),
  365. )
  366. self.increment(
  367. event,
  368. 2,
  369. timestamp=timezone.now() - timedelta(days=1, minutes=20),
  370. )
  371. data = {
  372. "interval": "1h",
  373. "value": 99,
  374. "comparisonType": "percent",
  375. "comparisonInterval": "1d",
  376. }
  377. rule = self.get_rule(data=data, rule=Rule(environment_id=None))
  378. self.assertPasses(rule, event, is_new=False)
  379. data = {
  380. "interval": "1h",
  381. "value": 101,
  382. "comparisonType": "percent",
  383. "comparisonInterval": "1d",
  384. }
  385. rule = self.get_rule(data=data, rule=Rule(environment_id=None))
  386. self.assertDoesNotPass(rule, event, is_new=False)
  387. def test_comparison_empty_comparison_period(self):
  388. # Test data is 1 event in the current period and 0 events in the comparison period. This
  389. # should always result in 0 and never fire.
  390. event = self.add_event(
  391. data={
  392. "fingerprint": ["something_random"],
  393. "user": {"id": uuid4().hex},
  394. },
  395. project_id=self.project.id,
  396. timestamp=before_now(minutes=1),
  397. )
  398. data = {
  399. "interval": "1h",
  400. "value": 0,
  401. "comparisonType": "percent",
  402. "comparisonInterval": "1d",
  403. }
  404. rule = self.get_rule(data=data, rule=Rule(environment_id=None))
  405. self.assertDoesNotPass(rule, event, is_new=False)
  406. data = {
  407. "interval": "1h",
  408. "value": 100,
  409. "comparisonType": "percent",
  410. "comparisonInterval": "1d",
  411. }
  412. rule = self.get_rule(data=data, rule=Rule(environment_id=None))
  413. self.assertDoesNotPass(rule, event, is_new=False)
  414. @patch("sentry.rules.conditions.event_frequency.BaseEventFrequencyCondition.get_rate")
  415. def test_is_new_issue_skips_snuba(self, mock_get_rate):
  416. # Looking for more than 1 event
  417. data = {"interval": "1m", "value": 6}
  418. minutes = 1
  419. rule = self.get_rule(data=data, rule=Rule(environment_id=None))
  420. environment_rule = self.get_rule(data=data, rule=Rule(environment_id=self.environment.id))
  421. event = self.add_event(
  422. data={
  423. "fingerprint": ["something_random"],
  424. "user": {"id": uuid4().hex},
  425. },
  426. project_id=self.project.id,
  427. timestamp=before_now(minutes=minutes),
  428. )
  429. # Issue is new and is the first event
  430. self.assertDoesNotPass(rule, event, is_new=True)
  431. self.assertDoesNotPass(environment_rule, event, is_new=True)
  432. assert mock_get_rate.call_count == 0
  433. class EventFrequencyConditionTestCase(StandardIntervalTestBase):
  434. __test__ = Abstract(__module__, __qualname__)
  435. rule_cls = EventFrequencyCondition
  436. def increment(self, event, count, environment=None, timestamp=None):
  437. timestamp = timestamp if timestamp else before_now(minutes=1)
  438. data = {"fingerprint": event.data["fingerprint"]}
  439. if environment:
  440. data["environment"] = environment
  441. for _ in range(count):
  442. self.add_event(
  443. data=data,
  444. project_id=self.project.id,
  445. timestamp=timestamp,
  446. )
  447. class EventUniqueUserFrequencyConditionTestCase(StandardIntervalTestBase):
  448. __test__ = Abstract(__module__, __qualname__)
  449. rule_cls = EventUniqueUserFrequencyCondition
  450. def increment(self, event, count, environment=None, timestamp=None):
  451. timestamp = timestamp if timestamp else before_now(minutes=1)
  452. data = {"fingerprint": event.data["fingerprint"]}
  453. if environment:
  454. data["environment"] = environment
  455. for _ in range(count):
  456. event_data = deepcopy(data)
  457. event_data["user"] = {"id": uuid4().hex}
  458. self.add_event(
  459. data=event_data,
  460. project_id=self.project.id,
  461. timestamp=timestamp,
  462. )
  463. class EventFrequencyPercentConditionTestCase(BaseEventFrequencyPercentTest, RuleTestCase):
  464. __test__ = Abstract(__module__, __qualname__)
  465. rule_cls = EventFrequencyPercentCondition
  466. def add_event(self, data, project_id, timestamp):
  467. raise NotImplementedError
  468. def _run_test(self, minutes, data, passes, add_events=False):
  469. if not self.environment or self.environment.name != "prod":
  470. self.environment = self.create_environment(name="prod")
  471. if not hasattr(self, "test_event"):
  472. self.test_event = self.add_event(
  473. data={
  474. "fingerprint": ["something_random"],
  475. "user": {"id": uuid4().hex},
  476. "environment": self.environment.name,
  477. },
  478. project_id=self.project.id,
  479. timestamp=before_now(minutes=minutes),
  480. )
  481. if add_events:
  482. self.increment(
  483. self.test_event,
  484. max(1, int(minutes / 2)) - 1,
  485. environment=self.environment.name,
  486. timestamp=timezone.now() - timedelta(minutes=minutes),
  487. )
  488. rule = self.get_rule(data=data, rule=Rule(environment_id=None))
  489. environment_rule = self.get_rule(data=data, rule=Rule(environment_id=self.environment.id))
  490. if passes:
  491. self.assertPasses(rule, self.test_event, is_new=False)
  492. self.assertPasses(environment_rule, self.test_event, is_new=False)
  493. else:
  494. self.assertDoesNotPass(rule, self.test_event)
  495. self.assertDoesNotPass(environment_rule, self.test_event)
  496. def increment(self, event, count, environment=None, timestamp=None):
  497. data = {
  498. "fingerprint": event.data["fingerprint"],
  499. }
  500. timestamp = timestamp if timestamp else before_now(minutes=1)
  501. if environment:
  502. data["environment"] = environment
  503. for _ in range(count):
  504. event_data = deepcopy(data)
  505. event_data["user"] = {"id": uuid4().hex}
  506. self.add_event(
  507. data=event_data,
  508. project_id=self.project.id,
  509. timestamp=timestamp,
  510. )
  511. @patch("sentry.rules.conditions.event_frequency.MIN_SESSIONS_TO_FIRE", 1)
  512. def test_five_minutes_with_events(self):
  513. self._make_sessions(60)
  514. data = {
  515. "interval": "5m",
  516. "value": 39,
  517. "comparisonType": "count",
  518. "comparisonInterval": "5m",
  519. }
  520. self._run_test(data=data, minutes=5, passes=True, add_events=True)
  521. data = {
  522. "interval": "5m",
  523. "value": 41,
  524. "comparisonType": "count",
  525. "comparisonInterval": "5m",
  526. }
  527. self._run_test(data=data, minutes=5, passes=False)
  528. @patch("sentry.rules.conditions.event_frequency.MIN_SESSIONS_TO_FIRE", 1)
  529. def test_ten_minutes_with_events(self):
  530. self._make_sessions(60)
  531. data = {
  532. "interval": "10m",
  533. "value": 49,
  534. "comparisonType": "count",
  535. "comparisonInterval": "5m",
  536. }
  537. self._run_test(data=data, minutes=10, passes=True, add_events=True)
  538. data = {
  539. "interval": "10m",
  540. "value": 51,
  541. "comparisonType": "count",
  542. "comparisonInterval": "5m",
  543. }
  544. self._run_test(data=data, minutes=10, passes=False)
  545. @patch("sentry.rules.conditions.event_frequency.MIN_SESSIONS_TO_FIRE", 1)
  546. def test_thirty_minutes_with_events(self):
  547. self._make_sessions(60)
  548. data = {
  549. "interval": "30m",
  550. "value": 49,
  551. "comparisonType": "count",
  552. "comparisonInterval": "5m",
  553. }
  554. self._run_test(data=data, minutes=30, passes=True, add_events=True)
  555. data = {
  556. "interval": "30m",
  557. "value": 51,
  558. "comparisonType": "count",
  559. "comparisonInterval": "5m",
  560. }
  561. self._run_test(data=data, minutes=30, passes=False)
  562. @patch("sentry.rules.conditions.event_frequency.MIN_SESSIONS_TO_FIRE", 1)
  563. def test_one_hour_with_events(self):
  564. self._make_sessions(60)
  565. data = {
  566. "interval": "1h",
  567. "value": 49,
  568. "comparisonType": "count",
  569. "comparisonInterval": "5m",
  570. }
  571. self._run_test(data=data, minutes=60, add_events=True, passes=True)
  572. data = {
  573. "interval": "1h",
  574. "value": 51,
  575. "comparisonType": "count",
  576. "comparisonInterval": "5m",
  577. }
  578. self._run_test(data=data, minutes=60, passes=False)
  579. @patch("sentry.rules.conditions.event_frequency.MIN_SESSIONS_TO_FIRE", 1)
  580. def test_five_minutes_no_events(self):
  581. self._make_sessions(60)
  582. data = {
  583. "interval": "5m",
  584. "value": 39,
  585. "comparisonType": "count",
  586. "comparisonInterval": "5m",
  587. }
  588. self._run_test(data=data, minutes=5, passes=True, add_events=True)
  589. @patch("sentry.rules.conditions.event_frequency.MIN_SESSIONS_TO_FIRE", 1)
  590. def test_ten_minutes_no_events(self):
  591. self._make_sessions(60)
  592. data = {
  593. "interval": "10m",
  594. "value": 49,
  595. "comparisonType": "count",
  596. "comparisonInterval": "5m",
  597. }
  598. self._run_test(data=data, minutes=10, passes=True, add_events=True)
  599. @patch("sentry.rules.conditions.event_frequency.MIN_SESSIONS_TO_FIRE", 1)
  600. def test_thirty_minutes_no_events(self):
  601. self._make_sessions(60)
  602. data = {
  603. "interval": "30m",
  604. "value": 49,
  605. "comparisonType": "count",
  606. "comparisonInterval": "5m",
  607. }
  608. self._run_test(data=data, minutes=30, passes=True, add_events=True)
  609. @patch("sentry.rules.conditions.event_frequency.MIN_SESSIONS_TO_FIRE", 1)
  610. def test_one_hour_no_events(self):
  611. self._make_sessions(60)
  612. data = {
  613. "interval": "1h",
  614. "value": 49,
  615. "comparisonType": "count",
  616. "comparisonInterval": "5m",
  617. }
  618. self._run_test(data=data, minutes=60, passes=False)
  619. @patch("sentry.rules.conditions.event_frequency.MIN_SESSIONS_TO_FIRE", 1)
  620. def test_comparison(self):
  621. self._make_sessions(10)
  622. # Create sessions for previous period
  623. self._make_sessions(10)
  624. # Test data is 2 events in the current period and 1 events in the comparison period.
  625. # Number of sessions is 20 in each period, so current period is 20% of sessions, prev
  626. # is 10%. Overall a 100% increase comparatively.
  627. event = self.add_event(
  628. data={"fingerprint": ["something_random"]},
  629. project_id=self.project.id,
  630. timestamp=before_now(minutes=1),
  631. )
  632. self.increment(
  633. event,
  634. 1,
  635. timestamp=timezone.now() - timedelta(minutes=1),
  636. )
  637. self.increment(
  638. event,
  639. 1,
  640. timestamp=timezone.now() - timedelta(days=1, minutes=20),
  641. )
  642. data = {
  643. "interval": "1h",
  644. "value": 99,
  645. "comparisonType": "percent",
  646. "comparisonInterval": "1d",
  647. }
  648. rule = self.get_rule(data=data, rule=Rule(environment_id=None))
  649. self.assertPasses(rule, event, is_new=False)
  650. data = {
  651. "interval": "1h",
  652. "value": 101,
  653. "comparisonType": "percent",
  654. "comparisonInterval": "1d",
  655. }
  656. rule = self.get_rule(data=data, rule=Rule(environment_id=None))
  657. self.assertDoesNotPass(rule, event, is_new=False)
  658. @freeze_time(
  659. (timezone.now() - timedelta(days=2)).replace(hour=12, minute=40, second=0, microsecond=0)
  660. )
  661. class ErrorIssueFrequencyConditionTestCase(ErrorEventMixin, EventFrequencyConditionTestCase):
  662. pass
  663. @freeze_time(
  664. (timezone.now() - timedelta(days=2)).replace(hour=12, minute=40, second=0, microsecond=0)
  665. )
  666. class PerfIssuePlatformIssueFrequencyConditionTestCase(
  667. PerfIssuePlatformEventMixin,
  668. EventFrequencyConditionTestCase,
  669. ):
  670. pass
  671. @freeze_time(
  672. (timezone.now() - timedelta(days=2)).replace(hour=12, minute=40, second=0, microsecond=0)
  673. )
  674. class ErrorIssueUniqueUserFrequencyConditionTestCase(
  675. ErrorEventMixin,
  676. EventUniqueUserFrequencyConditionTestCase,
  677. ):
  678. pass
  679. @freeze_time(
  680. (timezone.now() - timedelta(days=2)).replace(hour=12, minute=40, second=0, microsecond=0)
  681. )
  682. class PerfIssuePlatformIssueUniqueUserFrequencyConditionTestCase(
  683. PerfIssuePlatformEventMixin,
  684. EventUniqueUserFrequencyConditionTestCase,
  685. ):
  686. pass
  687. @freeze_time(
  688. (timezone.now() - timedelta(days=2)).replace(hour=12, minute=40, second=0, microsecond=0)
  689. )
  690. class ErrorIssueEventFrequencyPercentConditionTestCase(
  691. ErrorEventMixin, EventFrequencyPercentConditionTestCase
  692. ):
  693. pass
  694. @freeze_time(
  695. (timezone.now() - timedelta(days=2)).replace(hour=12, minute=40, second=0, microsecond=0)
  696. )
  697. class PerfIssuePlatformIssueEventFrequencyPercentConditionTestCase(
  698. PerfIssuePlatformEventMixin,
  699. EventFrequencyPercentConditionTestCase,
  700. ):
  701. pass