test_event_frequency.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798
  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. self.perf_event.group_id: 0,
  184. }
  185. batch_query = self.condition_inst2.batch_query_hook(
  186. group_ids=[self.event3.group_id],
  187. start=self.start,
  188. end=self.end,
  189. environment_id=self.environment2.id,
  190. )
  191. assert batch_query == {self.event3.group_id: percent_of_sessions}
  192. @patch("sentry.rules.conditions.event_frequency.MIN_SESSIONS_TO_FIRE", 100)
  193. def test_batch_query_percent_no_avg_sessions_in_interval(self):
  194. self._make_sessions(60, self.environment2.name)
  195. self._make_sessions(60, self.environment.name)
  196. batch_query = self.condition_inst.batch_query_hook(
  197. group_ids=[self.event.group_id, self.event2.group_id, self.perf_event.group_id],
  198. start=self.start,
  199. end=self.end,
  200. environment_id=self.environment.id,
  201. )
  202. percent = 0
  203. assert batch_query == {
  204. self.event.group_id: percent,
  205. self.event2.group_id: percent,
  206. self.perf_event.group_id: percent,
  207. }
  208. batch_query = self.condition_inst2.batch_query_hook(
  209. group_ids=[self.event3.group_id],
  210. start=self.start,
  211. end=self.end,
  212. environment_id=self.environment2.id,
  213. )
  214. assert batch_query == {self.event3.group_id: percent}
  215. class ErrorEventMixin(SnubaTestCase):
  216. def add_event(self, data, project_id, timestamp):
  217. data["timestamp"] = iso_format(timestamp)
  218. # Store an error event
  219. event = self.store_event(
  220. data=data,
  221. project_id=project_id,
  222. )
  223. return event.for_group(event.group)
  224. class PerfIssuePlatformEventMixin(PerformanceIssueTestCase):
  225. def add_event(self, data, project_id, timestamp):
  226. fingerprint = data["fingerprint"][0]
  227. fingerprint = (
  228. fingerprint
  229. if "-" in fingerprint
  230. else f"{PerformanceNPlusOneGroupType.type_id}-{data['fingerprint'][0]}"
  231. )
  232. event_data = load_data(
  233. "transaction-n-plus-one",
  234. timestamp=timestamp,
  235. start_timestamp=timestamp,
  236. fingerprint=[fingerprint],
  237. )
  238. event_data["user"] = {"id": uuid4().hex}
  239. event_data["environment"] = data.get("environment")
  240. for tag in event_data["tags"]:
  241. if tag[0] == "environment":
  242. tag[1] = data.get("environment")
  243. break
  244. else:
  245. event_data["tags"].append(data.get("environment"))
  246. # Store a performance event
  247. event = self.create_performance_issue(
  248. event_data=event_data,
  249. project_id=project_id,
  250. fingerprint=fingerprint,
  251. )
  252. return event
  253. @pytest.mark.snuba_ci
  254. class StandardIntervalTestBase(SnubaTestCase, RuleTestCase, PerformanceIssueTestCase):
  255. __test__ = Abstract(__module__, __qualname__)
  256. def add_event(self, data, project_id, timestamp):
  257. raise NotImplementedError
  258. def increment(self, event, count, environment=None, timestamp=None):
  259. raise NotImplementedError
  260. def _run_test(self, minutes, data, passes, add_events=False):
  261. if not self.environment:
  262. self.environment = self.create_environment(name="prod")
  263. rule = self.get_rule(data=data, rule=Rule(environment_id=None))
  264. environment_rule = self.get_rule(data=data, rule=Rule(environment_id=self.environment.id))
  265. event = self.add_event(
  266. data={
  267. "fingerprint": ["something_random"],
  268. "user": {"id": uuid4().hex},
  269. },
  270. project_id=self.project.id,
  271. timestamp=before_now(minutes=minutes),
  272. )
  273. if add_events:
  274. self.increment(
  275. event,
  276. data["value"] + 1,
  277. environment=self.environment.name,
  278. timestamp=timezone.now() - timedelta(minutes=minutes),
  279. )
  280. self.increment(
  281. event,
  282. data["value"] + 1,
  283. timestamp=timezone.now() - timedelta(minutes=minutes),
  284. )
  285. if passes:
  286. self.assertPasses(rule, event, is_new=False)
  287. self.assertPasses(environment_rule, event, is_new=False)
  288. else:
  289. self.assertDoesNotPass(rule, event, is_new=False)
  290. self.assertDoesNotPass(environment_rule, event, is_new=False)
  291. def test_comparison_interval_empty_string(self):
  292. data = {
  293. "interval": "1m",
  294. "value": 16,
  295. "comparisonType": "count",
  296. "comparisonInterval": "",
  297. }
  298. self._run_test(data=data, minutes=1, passes=False)
  299. def test_one_minute_with_events(self):
  300. data = {"interval": "1m", "value": 6, "comparisonType": "count", "comparisonInterval": "5m"}
  301. self._run_test(data=data, minutes=1, passes=True, add_events=True)
  302. data = {
  303. "interval": "1m",
  304. "value": 16,
  305. "comparisonType": "count",
  306. "comparisonInterval": "5m",
  307. }
  308. self._run_test(data=data, minutes=1, passes=False)
  309. def test_one_hour_with_events(self):
  310. data = {"interval": "1h", "value": 6, "comparisonType": "count", "comparisonInterval": "5m"}
  311. self._run_test(data=data, minutes=60, passes=True, add_events=True)
  312. data = {
  313. "interval": "1h",
  314. "value": 16,
  315. "comparisonType": "count",
  316. "comparisonInterval": "5m",
  317. }
  318. self._run_test(data=data, minutes=60, passes=False)
  319. def test_one_day_with_events(self):
  320. data = {"interval": "1d", "value": 6, "comparisonType": "count", "comparisonInterval": "5m"}
  321. self._run_test(data=data, minutes=1440, passes=True, add_events=True)
  322. data = {
  323. "interval": "1d",
  324. "value": 16,
  325. "comparisonType": "count",
  326. "comparisonInterval": "5m",
  327. }
  328. self._run_test(data=data, minutes=1440, passes=False)
  329. def test_one_week_with_events(self):
  330. data = {"interval": "1w", "value": 6, "comparisonType": "count", "comparisonInterval": "5m"}
  331. self._run_test(data=data, minutes=10080, passes=True, add_events=True)
  332. data = {
  333. "interval": "1w",
  334. "value": 16,
  335. "comparisonType": "count",
  336. "comparisonInterval": "5m",
  337. }
  338. self._run_test(data=data, minutes=10080, passes=False)
  339. def test_one_minute_no_events(self):
  340. data = {"interval": "1m", "value": 6, "comparisonType": "count", "comparisonInterval": "5m"}
  341. self._run_test(data=data, minutes=1, passes=False)
  342. def test_one_hour_no_events(self):
  343. data = {"interval": "1h", "value": 6, "comparisonType": "count", "comparisonInterval": "5m"}
  344. self._run_test(data=data, minutes=60, passes=False)
  345. def test_one_day_no_events(self):
  346. data = {"interval": "1d", "value": 6, "comparisonType": "count", "comparisonInterval": "5m"}
  347. self._run_test(data=data, minutes=1440, passes=False)
  348. def test_one_week_no_events(self):
  349. data = {"interval": "1w", "value": 6, "comparisonType": "count", "comparisonInterval": "5m"}
  350. self._run_test(data=data, minutes=10080, passes=False)
  351. def test_comparison(self):
  352. # Test data is 4 events in the current period and 2 events in the comparison period, so
  353. # a 100% increase.
  354. event = self.add_event(
  355. data={
  356. "fingerprint": ["something_random"],
  357. "user": {"id": uuid4().hex},
  358. },
  359. project_id=self.project.id,
  360. timestamp=before_now(minutes=1),
  361. )
  362. self.increment(
  363. event,
  364. 3,
  365. timestamp=timezone.now() - timedelta(minutes=1),
  366. )
  367. self.increment(
  368. event,
  369. 2,
  370. timestamp=timezone.now() - timedelta(days=1, minutes=20),
  371. )
  372. data = {
  373. "interval": "1h",
  374. "value": 99,
  375. "comparisonType": "percent",
  376. "comparisonInterval": "1d",
  377. }
  378. rule = self.get_rule(data=data, rule=Rule(environment_id=None))
  379. self.assertPasses(rule, event, is_new=False)
  380. data = {
  381. "interval": "1h",
  382. "value": 101,
  383. "comparisonType": "percent",
  384. "comparisonInterval": "1d",
  385. }
  386. rule = self.get_rule(data=data, rule=Rule(environment_id=None))
  387. self.assertDoesNotPass(rule, event, is_new=False)
  388. def test_comparison_empty_comparison_period(self):
  389. # Test data is 1 event in the current period and 0 events in the comparison period. This
  390. # should always result in 0 and never fire.
  391. event = self.add_event(
  392. data={
  393. "fingerprint": ["something_random"],
  394. "user": {"id": uuid4().hex},
  395. },
  396. project_id=self.project.id,
  397. timestamp=before_now(minutes=1),
  398. )
  399. data = {
  400. "interval": "1h",
  401. "value": 0,
  402. "comparisonType": "percent",
  403. "comparisonInterval": "1d",
  404. }
  405. rule = self.get_rule(data=data, rule=Rule(environment_id=None))
  406. self.assertDoesNotPass(rule, event, is_new=False)
  407. data = {
  408. "interval": "1h",
  409. "value": 100,
  410. "comparisonType": "percent",
  411. "comparisonInterval": "1d",
  412. }
  413. rule = self.get_rule(data=data, rule=Rule(environment_id=None))
  414. self.assertDoesNotPass(rule, event, is_new=False)
  415. @patch("sentry.rules.conditions.event_frequency.BaseEventFrequencyCondition.get_rate")
  416. def test_is_new_issue_skips_snuba(self, mock_get_rate):
  417. # Looking for more than 1 event
  418. data = {"interval": "1m", "value": 6}
  419. minutes = 1
  420. rule = self.get_rule(data=data, rule=Rule(environment_id=None))
  421. environment_rule = self.get_rule(data=data, rule=Rule(environment_id=self.environment.id))
  422. event = self.add_event(
  423. data={
  424. "fingerprint": ["something_random"],
  425. "user": {"id": uuid4().hex},
  426. },
  427. project_id=self.project.id,
  428. timestamp=before_now(minutes=minutes),
  429. )
  430. # Issue is new and is the first event
  431. self.assertDoesNotPass(rule, event, is_new=True)
  432. self.assertDoesNotPass(environment_rule, event, is_new=True)
  433. assert mock_get_rate.call_count == 0
  434. class EventFrequencyConditionTestCase(StandardIntervalTestBase):
  435. __test__ = Abstract(__module__, __qualname__)
  436. rule_cls = EventFrequencyCondition
  437. def increment(self, event, count, environment=None, timestamp=None):
  438. timestamp = timestamp if timestamp else before_now(minutes=1)
  439. data = {"fingerprint": event.data["fingerprint"]}
  440. if environment:
  441. data["environment"] = environment
  442. for _ in range(count):
  443. self.add_event(
  444. data=data,
  445. project_id=self.project.id,
  446. timestamp=timestamp,
  447. )
  448. class EventUniqueUserFrequencyConditionTestCase(StandardIntervalTestBase):
  449. __test__ = Abstract(__module__, __qualname__)
  450. rule_cls = EventUniqueUserFrequencyCondition
  451. def increment(self, event, count, environment=None, timestamp=None):
  452. timestamp = timestamp if timestamp else before_now(minutes=1)
  453. data = {"fingerprint": event.data["fingerprint"]}
  454. if environment:
  455. data["environment"] = environment
  456. for _ in range(count):
  457. event_data = deepcopy(data)
  458. event_data["user"] = {"id": uuid4().hex}
  459. self.add_event(
  460. data=event_data,
  461. project_id=self.project.id,
  462. timestamp=timestamp,
  463. )
  464. class EventFrequencyPercentConditionTestCase(BaseEventFrequencyPercentTest, RuleTestCase):
  465. __test__ = Abstract(__module__, __qualname__)
  466. rule_cls = EventFrequencyPercentCondition
  467. def add_event(self, data, project_id, timestamp):
  468. raise NotImplementedError
  469. def _run_test(self, minutes, data, passes, add_events=False):
  470. if not self.environment or self.environment.name != "prod":
  471. self.environment = self.create_environment(name="prod")
  472. if not hasattr(self, "test_event"):
  473. self.test_event = self.add_event(
  474. data={
  475. "fingerprint": ["something_random"],
  476. "user": {"id": uuid4().hex},
  477. "environment": self.environment.name,
  478. },
  479. project_id=self.project.id,
  480. timestamp=before_now(minutes=minutes),
  481. )
  482. if add_events:
  483. self.increment(
  484. self.test_event,
  485. max(1, int(minutes / 2)) - 1,
  486. environment=self.environment.name,
  487. timestamp=timezone.now() - timedelta(minutes=minutes),
  488. )
  489. rule = self.get_rule(data=data, rule=Rule(environment_id=None))
  490. environment_rule = self.get_rule(data=data, rule=Rule(environment_id=self.environment.id))
  491. if passes:
  492. self.assertPasses(rule, self.test_event, is_new=False)
  493. self.assertPasses(environment_rule, self.test_event, is_new=False)
  494. else:
  495. self.assertDoesNotPass(rule, self.test_event)
  496. self.assertDoesNotPass(environment_rule, self.test_event)
  497. def increment(self, event, count, environment=None, timestamp=None):
  498. data = {
  499. "fingerprint": event.data["fingerprint"],
  500. }
  501. timestamp = timestamp if timestamp else before_now(minutes=1)
  502. if environment:
  503. data["environment"] = environment
  504. for _ in range(count):
  505. event_data = deepcopy(data)
  506. event_data["user"] = {"id": uuid4().hex}
  507. self.add_event(
  508. data=event_data,
  509. project_id=self.project.id,
  510. timestamp=timestamp,
  511. )
  512. @patch("sentry.rules.conditions.event_frequency.MIN_SESSIONS_TO_FIRE", 1)
  513. def test_five_minutes_with_events(self):
  514. self._make_sessions(60)
  515. data = {
  516. "interval": "5m",
  517. "value": 39,
  518. "comparisonType": "count",
  519. "comparisonInterval": "5m",
  520. }
  521. self._run_test(data=data, minutes=5, passes=True, add_events=True)
  522. data = {
  523. "interval": "5m",
  524. "value": 41,
  525. "comparisonType": "count",
  526. "comparisonInterval": "5m",
  527. }
  528. self._run_test(data=data, minutes=5, passes=False)
  529. @patch("sentry.rules.conditions.event_frequency.MIN_SESSIONS_TO_FIRE", 1)
  530. def test_ten_minutes_with_events(self):
  531. self._make_sessions(60)
  532. data = {
  533. "interval": "10m",
  534. "value": 49,
  535. "comparisonType": "count",
  536. "comparisonInterval": "5m",
  537. }
  538. self._run_test(data=data, minutes=10, passes=True, add_events=True)
  539. data = {
  540. "interval": "10m",
  541. "value": 51,
  542. "comparisonType": "count",
  543. "comparisonInterval": "5m",
  544. }
  545. self._run_test(data=data, minutes=10, passes=False)
  546. @patch("sentry.rules.conditions.event_frequency.MIN_SESSIONS_TO_FIRE", 1)
  547. def test_thirty_minutes_with_events(self):
  548. self._make_sessions(60)
  549. data = {
  550. "interval": "30m",
  551. "value": 49,
  552. "comparisonType": "count",
  553. "comparisonInterval": "5m",
  554. }
  555. self._run_test(data=data, minutes=30, passes=True, add_events=True)
  556. data = {
  557. "interval": "30m",
  558. "value": 51,
  559. "comparisonType": "count",
  560. "comparisonInterval": "5m",
  561. }
  562. self._run_test(data=data, minutes=30, passes=False)
  563. @patch("sentry.rules.conditions.event_frequency.MIN_SESSIONS_TO_FIRE", 1)
  564. def test_one_hour_with_events(self):
  565. self._make_sessions(60)
  566. data = {
  567. "interval": "1h",
  568. "value": 49,
  569. "comparisonType": "count",
  570. "comparisonInterval": "5m",
  571. }
  572. self._run_test(data=data, minutes=60, add_events=True, passes=True)
  573. data = {
  574. "interval": "1h",
  575. "value": 51,
  576. "comparisonType": "count",
  577. "comparisonInterval": "5m",
  578. }
  579. self._run_test(data=data, minutes=60, passes=False)
  580. @patch("sentry.rules.conditions.event_frequency.MIN_SESSIONS_TO_FIRE", 1)
  581. def test_five_minutes_no_events(self):
  582. self._make_sessions(60)
  583. data = {
  584. "interval": "5m",
  585. "value": 39,
  586. "comparisonType": "count",
  587. "comparisonInterval": "5m",
  588. }
  589. self._run_test(data=data, minutes=5, passes=True, add_events=True)
  590. @patch("sentry.rules.conditions.event_frequency.MIN_SESSIONS_TO_FIRE", 1)
  591. def test_ten_minutes_no_events(self):
  592. self._make_sessions(60)
  593. data = {
  594. "interval": "10m",
  595. "value": 49,
  596. "comparisonType": "count",
  597. "comparisonInterval": "5m",
  598. }
  599. self._run_test(data=data, minutes=10, passes=True, add_events=True)
  600. @patch("sentry.rules.conditions.event_frequency.MIN_SESSIONS_TO_FIRE", 1)
  601. def test_thirty_minutes_no_events(self):
  602. self._make_sessions(60)
  603. data = {
  604. "interval": "30m",
  605. "value": 49,
  606. "comparisonType": "count",
  607. "comparisonInterval": "5m",
  608. }
  609. self._run_test(data=data, minutes=30, passes=True, add_events=True)
  610. @patch("sentry.rules.conditions.event_frequency.MIN_SESSIONS_TO_FIRE", 1)
  611. def test_one_hour_no_events(self):
  612. self._make_sessions(60)
  613. data = {
  614. "interval": "1h",
  615. "value": 49,
  616. "comparisonType": "count",
  617. "comparisonInterval": "5m",
  618. }
  619. self._run_test(data=data, minutes=60, passes=False)
  620. @patch("sentry.rules.conditions.event_frequency.MIN_SESSIONS_TO_FIRE", 1)
  621. def test_comparison(self):
  622. self._make_sessions(10)
  623. # Create sessions for previous period
  624. self._make_sessions(10)
  625. # Test data is 2 events in the current period and 1 events in the comparison period.
  626. # Number of sessions is 20 in each period, so current period is 20% of sessions, prev
  627. # is 10%. Overall a 100% increase comparatively.
  628. event = self.add_event(
  629. data={"fingerprint": ["something_random"]},
  630. project_id=self.project.id,
  631. timestamp=before_now(minutes=1),
  632. )
  633. self.increment(
  634. event,
  635. 1,
  636. timestamp=timezone.now() - timedelta(minutes=1),
  637. )
  638. self.increment(
  639. event,
  640. 1,
  641. timestamp=timezone.now() - timedelta(days=1, minutes=20),
  642. )
  643. data = {
  644. "interval": "1h",
  645. "value": 99,
  646. "comparisonType": "percent",
  647. "comparisonInterval": "1d",
  648. }
  649. rule = self.get_rule(data=data, rule=Rule(environment_id=None))
  650. self.assertPasses(rule, event, is_new=False)
  651. data = {
  652. "interval": "1h",
  653. "value": 101,
  654. "comparisonType": "percent",
  655. "comparisonInterval": "1d",
  656. }
  657. rule = self.get_rule(data=data, rule=Rule(environment_id=None))
  658. self.assertDoesNotPass(rule, event, is_new=False)
  659. @freeze_time(
  660. (timezone.now() - timedelta(days=2)).replace(hour=12, minute=40, second=0, microsecond=0)
  661. )
  662. class ErrorIssueFrequencyConditionTestCase(ErrorEventMixin, EventFrequencyConditionTestCase):
  663. pass
  664. @freeze_time(
  665. (timezone.now() - timedelta(days=2)).replace(hour=12, minute=40, second=0, microsecond=0)
  666. )
  667. class PerfIssuePlatformIssueFrequencyConditionTestCase(
  668. PerfIssuePlatformEventMixin,
  669. EventFrequencyConditionTestCase,
  670. ):
  671. pass
  672. @freeze_time(
  673. (timezone.now() - timedelta(days=2)).replace(hour=12, minute=40, second=0, microsecond=0)
  674. )
  675. class ErrorIssueUniqueUserFrequencyConditionTestCase(
  676. ErrorEventMixin,
  677. EventUniqueUserFrequencyConditionTestCase,
  678. ):
  679. pass
  680. @freeze_time(
  681. (timezone.now() - timedelta(days=2)).replace(hour=12, minute=40, second=0, microsecond=0)
  682. )
  683. class PerfIssuePlatformIssueUniqueUserFrequencyConditionTestCase(
  684. PerfIssuePlatformEventMixin,
  685. EventUniqueUserFrequencyConditionTestCase,
  686. ):
  687. pass
  688. @freeze_time(
  689. (timezone.now() - timedelta(days=2)).replace(hour=12, minute=40, second=0, microsecond=0)
  690. )
  691. class ErrorIssueEventFrequencyPercentConditionTestCase(
  692. ErrorEventMixin, EventFrequencyPercentConditionTestCase
  693. ):
  694. pass
  695. @freeze_time(
  696. (timezone.now() - timedelta(days=2)).replace(hour=12, minute=40, second=0, microsecond=0)
  697. )
  698. class PerfIssuePlatformIssueEventFrequencyPercentConditionTestCase(
  699. PerfIssuePlatformEventMixin,
  700. EventFrequencyPercentConditionTestCase,
  701. ):
  702. pass