test_event_frequency.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  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. from django.utils.timezone import now
  7. from freezegun import freeze_time
  8. from sentry.models import Rule
  9. from sentry.rules.conditions.event_frequency import (
  10. EventFrequencyCondition,
  11. EventFrequencyPercentCondition,
  12. EventUniqueUserFrequencyCondition,
  13. )
  14. from sentry.testutils.cases import RuleTestCase, SnubaTestCase
  15. from sentry.testutils.helpers.datetime import before_now, iso_format
  16. class FrequencyConditionMixin:
  17. def increment(self, event, count, environment=None, timestamp=None):
  18. raise NotImplementedError
  19. def _run_test(self, minutes, data, passes, add_events=False):
  20. if not self.environment:
  21. self.environment = self.create_environment(name="prod")
  22. rule = self.get_rule(data=data, rule=Rule(environment_id=None))
  23. environment_rule = self.get_rule(data=data, rule=Rule(environment_id=self.environment.id))
  24. event = self.store_event(
  25. data={
  26. "fingerprint": ["something_random"],
  27. "timestamp": iso_format(before_now(minutes=minutes)),
  28. "user": {"id": uuid4().hex},
  29. },
  30. project_id=self.project.id,
  31. )
  32. if add_events:
  33. self.increment(
  34. event,
  35. data["value"] + 1,
  36. environment=self.environment.name,
  37. timestamp=now() - timedelta(minutes=minutes),
  38. )
  39. self.increment(
  40. event,
  41. data["value"] + 1,
  42. timestamp=now() - timedelta(minutes=minutes),
  43. )
  44. if passes:
  45. self.assertPasses(rule, event)
  46. self.assertPasses(environment_rule, event)
  47. else:
  48. self.assertDoesNotPass(rule, event)
  49. self.assertDoesNotPass(environment_rule, event)
  50. class StandardIntervalMixin:
  51. def test_one_minute_with_events(self):
  52. data = {"interval": "1m", "value": 6}
  53. self._run_test(data=data, minutes=1, passes=True, add_events=True)
  54. data = {"interval": "1m", "value": 16}
  55. self._run_test(data=data, minutes=1, passes=False)
  56. def test_one_hour_with_events(self):
  57. data = {"interval": "1h", "value": 6}
  58. self._run_test(data=data, minutes=60, passes=True, add_events=True)
  59. data = {"interval": "1h", "value": 16}
  60. self._run_test(data=data, minutes=60, passes=False)
  61. def test_one_day_with_events(self):
  62. data = {"interval": "1d", "value": 6}
  63. self._run_test(data=data, minutes=1440, passes=True, add_events=True)
  64. data = {"interval": "1d", "value": 16}
  65. self._run_test(data=data, minutes=1440, passes=False)
  66. def test_one_week_with_events(self):
  67. data = {"interval": "1w", "value": 6}
  68. self._run_test(data=data, minutes=10080, passes=True, add_events=True)
  69. data = {"interval": "1w", "value": 16}
  70. self._run_test(data=data, minutes=10080, passes=False)
  71. def test_one_minute_no_events(self):
  72. data = {"interval": "1m", "value": 6}
  73. self._run_test(data=data, minutes=1, passes=False)
  74. def test_one_hour_no_events(self):
  75. data = {"interval": "1h", "value": 6}
  76. self._run_test(data=data, minutes=60, passes=False)
  77. def test_one_day_no_events(self):
  78. data = {"interval": "1d", "value": 6}
  79. self._run_test(data=data, minutes=1440, passes=False)
  80. def test_one_week_no_events(self):
  81. data = {"interval": "1w", "value": 6}
  82. self._run_test(data=data, minutes=10080, passes=False)
  83. def test_comparison(self):
  84. # Test data is 4 events in the current period and 2 events in the comparison period, so
  85. # a 100% increase.
  86. event = self.store_event(
  87. data={
  88. "fingerprint": ["something_random"],
  89. "timestamp": iso_format(before_now(minutes=1)),
  90. "user": {"id": uuid4().hex},
  91. },
  92. project_id=self.project.id,
  93. )
  94. self.increment(
  95. event,
  96. 3,
  97. timestamp=now() - timedelta(minutes=1),
  98. )
  99. self.increment(
  100. event,
  101. 2,
  102. timestamp=now() - timedelta(days=1, minutes=20),
  103. )
  104. data = {
  105. "interval": "1h",
  106. "value": 99,
  107. "comparisonType": "percent",
  108. "comparisonInterval": "1d",
  109. }
  110. rule = self.get_rule(data=data, rule=Rule(environment_id=None))
  111. self.assertPasses(rule, event)
  112. data = {
  113. "interval": "1h",
  114. "value": 101,
  115. "comparisonType": "percent",
  116. "comparisonInterval": "1d",
  117. }
  118. rule = self.get_rule(data=data, rule=Rule(environment_id=None))
  119. self.assertDoesNotPass(rule, event)
  120. def test_comparison_empty_comparison_period(self):
  121. # Test data is 1 event in the current period and 0 events in the comparison period. This
  122. # should always result in 0 and never fire.
  123. event = self.store_event(
  124. data={
  125. "fingerprint": ["something_random"],
  126. "timestamp": iso_format(before_now(minutes=1)),
  127. "user": {"id": uuid4().hex},
  128. },
  129. project_id=self.project.id,
  130. )
  131. data = {
  132. "interval": "1h",
  133. "value": 0,
  134. "comparisonType": "percent",
  135. "comparisonInterval": "1d",
  136. }
  137. rule = self.get_rule(data=data, rule=Rule(environment_id=None))
  138. self.assertDoesNotPass(rule, event)
  139. data = {
  140. "interval": "1h",
  141. "value": 100,
  142. "comparisonType": "percent",
  143. "comparisonInterval": "1d",
  144. }
  145. rule = self.get_rule(data=data, rule=Rule(environment_id=None))
  146. self.assertDoesNotPass(rule, event)
  147. @freeze_time((now() - timedelta(days=2)).replace(hour=12, minute=40, second=0, microsecond=0))
  148. class EventFrequencyConditionTestCase(
  149. FrequencyConditionMixin, StandardIntervalMixin, RuleTestCase, SnubaTestCase
  150. ):
  151. rule_cls = EventFrequencyCondition
  152. def increment(self, event, count, environment=None, timestamp=None):
  153. data = {
  154. "fingerprint": event.data["fingerprint"],
  155. "timestamp": iso_format(timestamp) if timestamp else iso_format(before_now(minutes=1)),
  156. }
  157. if environment:
  158. data["environment"] = environment
  159. for _ in range(count):
  160. self.store_event(
  161. data=data,
  162. project_id=self.project.id,
  163. )
  164. @freeze_time((now() - timedelta(days=2)).replace(hour=12, minute=40, second=0, microsecond=0))
  165. class EventUniqueUserFrequencyConditionTestCase(
  166. FrequencyConditionMixin,
  167. StandardIntervalMixin,
  168. RuleTestCase,
  169. SnubaTestCase,
  170. ):
  171. rule_cls = EventUniqueUserFrequencyCondition
  172. def increment(self, event, count, environment=None, timestamp=None):
  173. data = {
  174. "fingerprint": event.data["fingerprint"],
  175. "timestamp": iso_format(timestamp) if timestamp else iso_format(before_now(minutes=1)),
  176. }
  177. if environment:
  178. data["environment"] = environment
  179. for _ in range(count):
  180. event_data = deepcopy(data)
  181. event_data["user"] = {"id": uuid4().hex}
  182. self.store_event(
  183. data=event_data,
  184. project_id=self.project.id,
  185. )
  186. @freeze_time((now() - timedelta(days=2)).replace(hour=12, minute=40, second=0, microsecond=0))
  187. class EventFrequencyPercentConditionTestCase(
  188. RuleTestCase,
  189. SnubaTestCase,
  190. ):
  191. rule_cls = EventFrequencyPercentCondition
  192. def _make_sessions(self, num):
  193. received = time.time()
  194. def make_session(i):
  195. return dict(
  196. distinct_id=uuid4().hex,
  197. session_id=uuid4().hex,
  198. org_id=self.project.organization_id,
  199. project_id=self.project.id,
  200. status="ok",
  201. seq=0,
  202. release="foo@1.0.0",
  203. environment="prod",
  204. retention_days=90,
  205. duration=None,
  206. errors=0,
  207. # The line below is crucial to spread sessions throughout the time period.
  208. started=received - i,
  209. received=received,
  210. )
  211. self.bulk_store_sessions([make_session(i) for i in range(num)])
  212. def _run_test(self, minutes, data, passes, add_events=False):
  213. if not self.environment or self.environment.name != "prod":
  214. self.environment = self.create_environment(name="prod")
  215. if not hasattr(self, "test_event"):
  216. self.test_event = self.store_event(
  217. data={
  218. "fingerprint": ["something_random"],
  219. "timestamp": iso_format(before_now(minutes=minutes)),
  220. "user": {"id": uuid4().hex},
  221. "environment": self.environment.name,
  222. },
  223. project_id=self.project.id,
  224. )
  225. if add_events:
  226. self.increment(
  227. self.test_event,
  228. max(1, int(minutes / 2)) - 1,
  229. environment=self.environment.name,
  230. timestamp=now() - timedelta(minutes=minutes),
  231. )
  232. rule = self.get_rule(data=data, rule=Rule(environment_id=None))
  233. environment_rule = self.get_rule(data=data, rule=Rule(environment_id=self.environment.id))
  234. if passes:
  235. self.assertPasses(rule, self.test_event)
  236. self.assertPasses(environment_rule, self.test_event)
  237. else:
  238. self.assertDoesNotPass(rule, self.test_event)
  239. self.assertDoesNotPass(environment_rule, self.test_event)
  240. def increment(self, event, count, environment=None, timestamp=None):
  241. data = {
  242. "fingerprint": event.data["fingerprint"],
  243. "timestamp": iso_format(timestamp) if timestamp else iso_format(before_now(minutes=1)),
  244. }
  245. if environment:
  246. data["environment"] = environment
  247. for _ in range(count):
  248. event_data = deepcopy(data)
  249. event_data["user"] = {"id": uuid4().hex}
  250. self.store_event(
  251. data=event_data,
  252. project_id=self.project.id,
  253. )
  254. @patch("sentry.rules.conditions.event_frequency.MIN_SESSIONS_TO_FIRE", 1)
  255. def test_five_minutes_with_events(self):
  256. self._make_sessions(60)
  257. data = {"interval": "5m", "value": 39}
  258. self._run_test(data=data, minutes=5, passes=True, add_events=True)
  259. data = {"interval": "5m", "value": 41}
  260. self._run_test(data=data, minutes=5, passes=False)
  261. @patch("sentry.rules.conditions.event_frequency.MIN_SESSIONS_TO_FIRE", 1)
  262. def test_ten_minutes_with_events(self):
  263. self._make_sessions(60)
  264. data = {"interval": "10m", "value": 49}
  265. self._run_test(data=data, minutes=10, passes=True, add_events=True)
  266. data = {"interval": "10m", "value": 51}
  267. self._run_test(data=data, minutes=10, passes=False)
  268. @patch("sentry.rules.conditions.event_frequency.MIN_SESSIONS_TO_FIRE", 1)
  269. def test_thirty_minutes_with_events(self):
  270. self._make_sessions(60)
  271. data = {"interval": "30m", "value": 49}
  272. self._run_test(data=data, minutes=30, passes=True, add_events=True)
  273. data = {"interval": "30m", "value": 51}
  274. self._run_test(data=data, minutes=30, passes=False)
  275. @patch("sentry.rules.conditions.event_frequency.MIN_SESSIONS_TO_FIRE", 1)
  276. def test_one_hour_with_events(self):
  277. self._make_sessions(60)
  278. data = {"interval": "1h", "value": 49}
  279. self._run_test(data=data, minutes=60, add_events=True, passes=True)
  280. data = {"interval": "1h", "value": 51}
  281. self._run_test(data=data, minutes=60, passes=False)
  282. @patch("sentry.rules.conditions.event_frequency.MIN_SESSIONS_TO_FIRE", 1)
  283. def test_five_minutes_no_events(self):
  284. self._make_sessions(60)
  285. data = {"interval": "5m", "value": 39}
  286. self._run_test(data=data, minutes=5, passes=True, add_events=True)
  287. @patch("sentry.rules.conditions.event_frequency.MIN_SESSIONS_TO_FIRE", 1)
  288. def test_ten_minutes_no_events(self):
  289. self._make_sessions(60)
  290. data = {"interval": "10m", "value": 49}
  291. self._run_test(data=data, minutes=10, passes=True, add_events=True)
  292. @patch("sentry.rules.conditions.event_frequency.MIN_SESSIONS_TO_FIRE", 1)
  293. def test_thirty_minutes_no_events(self):
  294. self._make_sessions(60)
  295. data = {"interval": "30m", "value": 49}
  296. self._run_test(data=data, minutes=30, passes=True, add_events=True)
  297. @patch("sentry.rules.conditions.event_frequency.MIN_SESSIONS_TO_FIRE", 1)
  298. def test_one_hour_no_events(self):
  299. self._make_sessions(60)
  300. data = {"interval": "1h", "value": 49}
  301. self._run_test(data=data, minutes=60, passes=False)
  302. @patch("sentry.rules.conditions.event_frequency.MIN_SESSIONS_TO_FIRE", 1)
  303. def test_comparison(self):
  304. self._make_sessions(10)
  305. # Create sessions for previous period
  306. self._make_sessions(10)
  307. # Test data is 2 events in the current period and 1 events in the comparison period.
  308. # Number of sessions is 20 in each period, so current period is 20% of sessions, prev
  309. # is 10%. Overall a 100% increase comparitively.
  310. event = self.store_event(
  311. data={
  312. "fingerprint": ["something_random"],
  313. "timestamp": iso_format(before_now(minutes=1)),
  314. },
  315. project_id=self.project.id,
  316. )
  317. self.increment(
  318. event,
  319. 1,
  320. timestamp=now() - timedelta(minutes=1),
  321. )
  322. self.increment(
  323. event,
  324. 1,
  325. timestamp=now() - timedelta(days=1, minutes=20),
  326. )
  327. data = {
  328. "interval": "1h",
  329. "value": 99,
  330. "comparisonType": "percent",
  331. "comparisonInterval": "1d",
  332. }
  333. rule = self.get_rule(data=data, rule=Rule(environment_id=None))
  334. self.assertPasses(rule, event)
  335. data = {
  336. "interval": "1h",
  337. "value": 101,
  338. "comparisonType": "percent",
  339. "comparisonInterval": "1d",
  340. }
  341. rule = self.get_rule(data=data, rule=Rule(environment_id=None))
  342. self.assertDoesNotPass(rule, event)