test_group.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563
  1. from datetime import timedelta, timezone
  2. from unittest import mock
  3. from django.utils import timezone as django_timezone
  4. from sentry.api.event_search import SearchFilter, SearchKey, SearchValue
  5. from sentry.api.serializers import serialize
  6. from sentry.api.serializers.models.group import GroupSerializerSnuba
  7. from sentry.issues.grouptype import PerformanceNPlusOneGroupType, ProfileFileIOGroupType
  8. from sentry.models.group import Group, GroupStatus
  9. from sentry.models.groupenvironment import GroupEnvironment
  10. from sentry.models.grouplink import GroupLink
  11. from sentry.models.groupresolution import GroupResolution
  12. from sentry.models.groupsnooze import GroupSnooze
  13. from sentry.models.groupsubscription import GroupSubscription
  14. from sentry.models.notificationsetting import NotificationSetting
  15. from sentry.models.notificationsettingoption import NotificationSettingOption
  16. from sentry.models.options.user_option import UserOption
  17. from sentry.notifications.types import (
  18. NotificationSettingOptionValues,
  19. NotificationSettingsOptionEnum,
  20. NotificationSettingTypes,
  21. )
  22. from sentry.silo import SiloMode
  23. from sentry.testutils.cases import APITestCase, PerformanceIssueTestCase, SnubaTestCase
  24. from sentry.testutils.helpers.datetime import before_now, iso_format
  25. from sentry.testutils.performance_issues.store_transaction import PerfIssueTransactionTestMixin
  26. from sentry.testutils.silo import assume_test_silo_mode, region_silo_test
  27. from sentry.types.integrations import ExternalProviders
  28. from sentry.utils.samples import load_data
  29. from tests.sentry.issues.test_utils import SearchIssueTestMixin
  30. @region_silo_test(stable=True)
  31. class GroupSerializerSnubaTest(APITestCase, SnubaTestCase):
  32. def setUp(self):
  33. super().setUp()
  34. self.min_ago = before_now(minutes=1)
  35. self.day_ago = before_now(days=1)
  36. self.week_ago = before_now(days=7)
  37. def test_permalink(self):
  38. group = self.create_group()
  39. result = serialize(group, self.user, serializer=GroupSerializerSnuba())
  40. assert "http://" in result["permalink"]
  41. assert f"{group.organization.slug}/issues/{group.id}" in result["permalink"]
  42. def test_permalink_outside_org(self):
  43. outside_user = self.create_user()
  44. group = self.create_group()
  45. result = serialize(group, outside_user, serializer=GroupSerializerSnuba())
  46. assert result["permalink"] is None
  47. def test_is_ignored_with_expired_snooze(self):
  48. now = django_timezone.now()
  49. user = self.create_user()
  50. group = self.create_group(status=GroupStatus.IGNORED)
  51. GroupSnooze.objects.create(group=group, until=now - timedelta(minutes=1))
  52. result = serialize(group, user, serializer=GroupSerializerSnuba())
  53. assert result["status"] == "unresolved"
  54. assert result["statusDetails"] == {}
  55. def test_is_ignored_with_valid_snooze(self):
  56. now = django_timezone.now()
  57. user = self.create_user()
  58. group = self.create_group(status=GroupStatus.IGNORED)
  59. snooze = GroupSnooze.objects.create(group=group, until=now + timedelta(minutes=1))
  60. result = serialize(group, user, serializer=GroupSerializerSnuba())
  61. assert result["status"] == "ignored"
  62. assert result["statusDetails"]["ignoreCount"] == snooze.count
  63. assert result["statusDetails"]["ignoreWindow"] == snooze.window
  64. assert result["statusDetails"]["ignoreUserCount"] == snooze.user_count
  65. assert result["statusDetails"]["ignoreUserWindow"] == snooze.user_window
  66. assert result["statusDetails"]["ignoreUntil"] == snooze.until
  67. assert result["statusDetails"]["actor"] is None
  68. def test_is_ignored_with_valid_snooze_and_actor(self):
  69. now = django_timezone.now()
  70. user = self.create_user()
  71. group = self.create_group(status=GroupStatus.IGNORED)
  72. GroupSnooze.objects.create(group=group, until=now + timedelta(minutes=1), actor_id=user.id)
  73. result = serialize(group, user, serializer=GroupSerializerSnuba())
  74. assert result["status"] == "ignored"
  75. assert result["statusDetails"]["actor"]["id"] == str(user.id)
  76. def test_resolved_in_next_release(self):
  77. release = self.create_release(project=self.project, version="a")
  78. user = self.create_user()
  79. group = self.create_group(status=GroupStatus.RESOLVED)
  80. GroupResolution.objects.create(
  81. group=group, release=release, type=GroupResolution.Type.in_next_release
  82. )
  83. result = serialize(group, user, serializer=GroupSerializerSnuba())
  84. assert result["status"] == "resolved"
  85. assert result["statusDetails"] == {"inNextRelease": True, "actor": None}
  86. def test_resolved_in_release(self):
  87. release = self.create_release(project=self.project, version="a")
  88. user = self.create_user()
  89. group = self.create_group(status=GroupStatus.RESOLVED)
  90. GroupResolution.objects.create(
  91. group=group, release=release, type=GroupResolution.Type.in_release
  92. )
  93. result = serialize(group, user, serializer=GroupSerializerSnuba())
  94. assert result["status"] == "resolved"
  95. assert result["statusDetails"] == {"inRelease": "a", "actor": None}
  96. def test_resolved_with_actor(self):
  97. release = self.create_release(project=self.project, version="a")
  98. user = self.create_user()
  99. group = self.create_group(status=GroupStatus.RESOLVED)
  100. GroupResolution.objects.create(
  101. group=group, release=release, type=GroupResolution.Type.in_release, actor_id=user.id
  102. )
  103. result = serialize(group, user, serializer=GroupSerializerSnuba())
  104. assert result["status"] == "resolved"
  105. assert result["statusDetails"]["actor"]["id"] == str(user.id)
  106. def test_resolved_in_commit(self):
  107. repo = self.create_repo(project=self.project)
  108. commit = self.create_commit(repo=repo)
  109. user = self.create_user()
  110. group = self.create_group(status=GroupStatus.RESOLVED)
  111. GroupLink.objects.create(
  112. group_id=group.id,
  113. project_id=group.project_id,
  114. linked_id=commit.id,
  115. linked_type=GroupLink.LinkedType.commit,
  116. relationship=GroupLink.Relationship.resolves,
  117. )
  118. result = serialize(group, user, serializer=GroupSerializerSnuba())
  119. assert result["status"] == "resolved"
  120. assert result["statusDetails"]["inCommit"]["id"] == commit.key
  121. @mock.patch("sentry.models.Group.is_over_resolve_age")
  122. def test_auto_resolved(self, mock_is_over_resolve_age):
  123. mock_is_over_resolve_age.return_value = True
  124. user = self.create_user()
  125. group = self.create_group(status=GroupStatus.UNRESOLVED)
  126. result = serialize(group, user, serializer=GroupSerializerSnuba())
  127. assert result["status"] == "resolved"
  128. assert result["statusDetails"] == {"autoResolved": True}
  129. def test_subscribed(self):
  130. user = self.create_user()
  131. group = self.create_group()
  132. GroupSubscription.objects.create(
  133. user_id=user.id, group=group, project=group.project, is_active=True
  134. )
  135. result = serialize(group, user, serializer=GroupSerializerSnuba())
  136. assert result["isSubscribed"]
  137. assert result["subscriptionDetails"] == {"reason": "unknown"}
  138. def test_explicit_unsubscribed(self):
  139. user = self.create_user()
  140. group = self.create_group()
  141. GroupSubscription.objects.create(
  142. user_id=user.id, group=group, project=group.project, is_active=False
  143. )
  144. result = serialize(group, user, serializer=GroupSerializerSnuba())
  145. assert not result["isSubscribed"]
  146. assert not result["subscriptionDetails"]
  147. def test_implicit_subscribed(self):
  148. user = self.create_user()
  149. group = self.create_group()
  150. combinations = (
  151. # (default, project, subscribed, has_details)
  152. (
  153. NotificationSettingsOptionEnum.ALWAYS,
  154. NotificationSettingsOptionEnum.DEFAULT,
  155. True,
  156. False,
  157. ),
  158. (
  159. NotificationSettingsOptionEnum.ALWAYS,
  160. NotificationSettingsOptionEnum.ALWAYS,
  161. True,
  162. False,
  163. ),
  164. (
  165. NotificationSettingsOptionEnum.ALWAYS,
  166. NotificationSettingsOptionEnum.SUBSCRIBE_ONLY,
  167. False,
  168. False,
  169. ),
  170. (
  171. NotificationSettingsOptionEnum.ALWAYS,
  172. NotificationSettingsOptionEnum.NEVER,
  173. False,
  174. True,
  175. ),
  176. (
  177. NotificationSettingsOptionEnum.DEFAULT,
  178. NotificationSettingsOptionEnum.DEFAULT,
  179. False,
  180. False,
  181. ),
  182. (
  183. NotificationSettingsOptionEnum.SUBSCRIBE_ONLY,
  184. NotificationSettingsOptionEnum.DEFAULT,
  185. False,
  186. False,
  187. ),
  188. (
  189. NotificationSettingsOptionEnum.SUBSCRIBE_ONLY,
  190. NotificationSettingsOptionEnum.ALWAYS,
  191. True,
  192. False,
  193. ),
  194. (
  195. NotificationSettingsOptionEnum.SUBSCRIBE_ONLY,
  196. NotificationSettingsOptionEnum.SUBSCRIBE_ONLY,
  197. False,
  198. False,
  199. ),
  200. (
  201. NotificationSettingsOptionEnum.SUBSCRIBE_ONLY,
  202. NotificationSettingsOptionEnum.NEVER,
  203. False,
  204. True,
  205. ),
  206. (
  207. NotificationSettingsOptionEnum.NEVER,
  208. NotificationSettingsOptionEnum.DEFAULT,
  209. False,
  210. True,
  211. ),
  212. (
  213. NotificationSettingsOptionEnum.NEVER,
  214. NotificationSettingsOptionEnum.ALWAYS,
  215. True,
  216. False,
  217. ),
  218. (
  219. NotificationSettingsOptionEnum.NEVER,
  220. NotificationSettingsOptionEnum.SUBSCRIBE_ONLY,
  221. False,
  222. False,
  223. ),
  224. (
  225. NotificationSettingsOptionEnum.NEVER,
  226. NotificationSettingsOptionEnum.NEVER,
  227. False,
  228. True,
  229. ),
  230. )
  231. for default_value, project_value, is_subscribed, has_details in combinations:
  232. with assume_test_silo_mode(SiloMode.CONTROL):
  233. UserOption.objects.clear_local_cache()
  234. NotificationSettingOption.objects.all().delete()
  235. if default_value != NotificationSettingsOptionEnum.DEFAULT:
  236. NotificationSettingOption.objects.create(
  237. user_id=user.id,
  238. scope_type="user",
  239. scope_identifier=user.id,
  240. value=default_value.value,
  241. type="workflow",
  242. )
  243. if project_value != NotificationSettingsOptionEnum.DEFAULT:
  244. NotificationSettingOption.objects.create(
  245. user_id=user.id,
  246. scope_type="project",
  247. scope_identifier=group.project.id,
  248. value=project_value.value,
  249. type="workflow",
  250. )
  251. result = serialize(group, user, serializer=GroupSerializerSnuba())
  252. subscription_details = result.get("subscriptionDetails")
  253. assert result["isSubscribed"] is is_subscribed
  254. assert (
  255. subscription_details == {"disabled": True}
  256. if has_details
  257. else subscription_details is None
  258. )
  259. def test_global_no_conversations_overrides_group_subscription(self):
  260. user = self.create_user()
  261. group = self.create_group()
  262. GroupSubscription.objects.create(
  263. user_id=user.id, group=group, project=group.project, is_active=True
  264. )
  265. with assume_test_silo_mode(SiloMode.CONTROL):
  266. for provider in [ExternalProviders.EMAIL, ExternalProviders.SLACK]:
  267. NotificationSetting.objects.update_settings(
  268. provider,
  269. NotificationSettingTypes.WORKFLOW,
  270. NotificationSettingOptionValues.NEVER,
  271. user_id=user.id,
  272. )
  273. result = serialize(group, user, serializer=GroupSerializerSnuba())
  274. assert not result["isSubscribed"]
  275. assert result["subscriptionDetails"] == {"disabled": True}
  276. def test_project_no_conversations_overrides_group_subscription(self):
  277. user = self.create_user()
  278. group = self.create_group()
  279. GroupSubscription.objects.create(
  280. user_id=user.id, group=group, project=group.project, is_active=True
  281. )
  282. for provider in [ExternalProviders.EMAIL, ExternalProviders.SLACK]:
  283. with assume_test_silo_mode(SiloMode.CONTROL):
  284. NotificationSetting.objects.update_settings(
  285. provider,
  286. NotificationSettingTypes.WORKFLOW,
  287. NotificationSettingOptionValues.NEVER,
  288. user_id=user.id,
  289. project=group.project.id,
  290. )
  291. result = serialize(group, user, serializer=GroupSerializerSnuba())
  292. assert not result["isSubscribed"]
  293. assert result["subscriptionDetails"] == {"disabled": True}
  294. def test_no_user_unsubscribed(self):
  295. group = self.create_group()
  296. result = serialize(group, serializer=GroupSerializerSnuba())
  297. assert not result["isSubscribed"]
  298. def test_seen_stats(self):
  299. environment = self.create_environment(project=self.project)
  300. environment2 = self.create_environment(project=self.project)
  301. events = []
  302. for event_id, env, user_id, timestamp in [
  303. ("a" * 32, environment, 1, iso_format(self.min_ago)),
  304. ("b" * 32, environment, 2, iso_format(self.min_ago)),
  305. ("c" * 32, environment2, 3, iso_format(self.week_ago)),
  306. ]:
  307. events.append(
  308. self.store_event(
  309. data={
  310. "event_id": event_id,
  311. "fingerprint": ["put-me-in-group1"],
  312. "timestamp": timestamp,
  313. "environment": env.name,
  314. "user": {"id": user_id},
  315. },
  316. project_id=self.project.id,
  317. )
  318. )
  319. # Assert all events are in the same group
  320. (group_id,) = {e.group.id for e in events}
  321. group = Group.objects.get(id=group_id)
  322. group.times_seen = 3
  323. group.first_seen = self.week_ago - timedelta(days=5)
  324. group.last_seen = self.week_ago
  325. group.save()
  326. # should use group columns when no environments arg passed
  327. result = serialize(group, serializer=GroupSerializerSnuba(environment_ids=[]))
  328. assert result["count"] == "3"
  329. assert iso_format(result["lastSeen"]) == iso_format(self.min_ago)
  330. assert result["firstSeen"] == group.first_seen
  331. # update this to something different to make sure it's being used
  332. group_env = GroupEnvironment.objects.get(group_id=group_id, environment_id=environment.id)
  333. group_env.first_seen = self.day_ago - timedelta(days=3)
  334. group_env.save()
  335. group_env2 = GroupEnvironment.objects.get(group_id=group_id, environment_id=environment2.id)
  336. result = serialize(
  337. group,
  338. serializer=GroupSerializerSnuba(environment_ids=[environment.id, environment2.id]),
  339. )
  340. assert result["count"] == "3"
  341. # result is rounded down to nearest second
  342. assert iso_format(result["lastSeen"]) == iso_format(self.min_ago)
  343. assert iso_format(result["firstSeen"]) == iso_format(group_env.first_seen)
  344. assert iso_format(group_env2.first_seen) > iso_format(group_env.first_seen)
  345. assert result["userCount"] == 3
  346. result = serialize(
  347. group,
  348. serializer=GroupSerializerSnuba(
  349. environment_ids=[environment.id, environment2.id],
  350. start=self.week_ago - timedelta(hours=1),
  351. end=self.week_ago + timedelta(hours=1),
  352. ),
  353. )
  354. assert result["userCount"] == 1
  355. assert iso_format(result["lastSeen"]) == iso_format(self.week_ago)
  356. assert iso_format(result["firstSeen"]) == iso_format(self.week_ago)
  357. assert result["count"] == "1"
  358. def test_get_start_from_seen_stats(self):
  359. for days, expected in [(None, 30), (0, 14), (1000, 90)]:
  360. last_seen = None if days is None else before_now(days=days).replace(tzinfo=timezone.utc)
  361. start = GroupSerializerSnuba._get_start_from_seen_stats(
  362. {
  363. mock.sentinel.group: {
  364. "last_seen": last_seen,
  365. "first_seen": None,
  366. "times_seen": 0,
  367. "user_count": 0,
  368. }
  369. }
  370. )
  371. assert iso_format(start) == iso_format(before_now(days=expected))
  372. def test_skipped_date_timestamp_filters(self):
  373. group = self.create_group()
  374. serializer = GroupSerializerSnuba(
  375. search_filters=[
  376. SearchFilter(
  377. SearchKey("timestamp"),
  378. ">",
  379. SearchValue(before_now(hours=1).replace(tzinfo=timezone.utc)),
  380. ),
  381. SearchFilter(
  382. SearchKey("timestamp"),
  383. "<",
  384. SearchValue(before_now(seconds=1).replace(tzinfo=timezone.utc)),
  385. ),
  386. SearchFilter(
  387. SearchKey("date"),
  388. ">",
  389. SearchValue(before_now(hours=1).replace(tzinfo=timezone.utc)),
  390. ),
  391. SearchFilter(
  392. SearchKey("date"),
  393. "<",
  394. SearchValue(before_now(seconds=1).replace(tzinfo=timezone.utc)),
  395. ),
  396. ]
  397. )
  398. assert not serializer.conditions
  399. result = serialize(group, self.user, serializer=serializer)
  400. assert result["id"] == str(group.id)
  401. @region_silo_test
  402. class PerformanceGroupSerializerSnubaTest(
  403. APITestCase,
  404. SnubaTestCase,
  405. PerfIssueTransactionTestMixin,
  406. PerformanceIssueTestCase,
  407. ):
  408. def test_perf_seen_stats(self):
  409. proj = self.create_project()
  410. first_group_fingerprint = f"{PerformanceNPlusOneGroupType.type_id}-group1"
  411. timestamp = django_timezone.now() - timedelta(days=5)
  412. times = 5
  413. for _ in range(0, times):
  414. event_data = load_data(
  415. "transaction-n-plus-one",
  416. timestamp=timestamp + timedelta(minutes=1),
  417. start_timestamp=timestamp + timedelta(minutes=1),
  418. )
  419. event_data["user"] = {"email": "test1@example.com"}
  420. self.create_performance_issue(
  421. event_data=event_data, fingerprint=first_group_fingerprint, project_id=proj.id
  422. )
  423. event_data = load_data(
  424. "transaction-n-plus-one",
  425. timestamp=timestamp + timedelta(minutes=2),
  426. start_timestamp=timestamp + timedelta(minutes=2),
  427. )
  428. event_data["user"] = {"email": "test2@example.com"}
  429. event = self.create_performance_issue(
  430. event_data=event_data, fingerprint=first_group_fingerprint, project_id=proj.id
  431. )
  432. first_group = event.group
  433. result = serialize(
  434. first_group,
  435. serializer=GroupSerializerSnuba(
  436. start=django_timezone.now() - timedelta(days=60),
  437. end=django_timezone.now() + timedelta(days=10),
  438. ),
  439. )
  440. assert result["userCount"] == 2
  441. assert iso_format(result["lastSeen"]) == iso_format(timestamp + timedelta(minutes=2))
  442. assert iso_format(result["firstSeen"]) == iso_format(timestamp + timedelta(minutes=1))
  443. assert result["count"] == str(times + 1)
  444. @region_silo_test
  445. class ProfilingGroupSerializerSnubaTest(
  446. APITestCase,
  447. SnubaTestCase,
  448. SearchIssueTestMixin,
  449. ):
  450. def test_profiling_seen_stats(self):
  451. proj = self.create_project()
  452. environment = self.create_environment(project=proj)
  453. first_group_fingerprint = f"{ProfileFileIOGroupType.type_id}-group1"
  454. timestamp = (django_timezone.now() - timedelta(days=5)).replace(hour=0, minute=0, second=0)
  455. times = 5
  456. for incr in range(0, times):
  457. # for user_0 - user_4, first_group
  458. self.store_search_issue(
  459. proj.id,
  460. incr,
  461. [first_group_fingerprint],
  462. environment.name,
  463. timestamp + timedelta(minutes=incr),
  464. )
  465. # user_5, another_group
  466. event, issue_occurrence, group_info = self.store_search_issue(
  467. proj.id,
  468. 5,
  469. [first_group_fingerprint],
  470. environment.name,
  471. timestamp + timedelta(minutes=5),
  472. )
  473. assert group_info is not None
  474. first_group = group_info.group
  475. result = serialize(
  476. first_group,
  477. serializer=GroupSerializerSnuba(
  478. environment_ids=[environment.id],
  479. start=timestamp - timedelta(days=1),
  480. end=timestamp + timedelta(days=1),
  481. ),
  482. )
  483. assert result["userCount"] == 6
  484. assert iso_format(result["lastSeen"]) == iso_format(timestamp + timedelta(minutes=5))
  485. assert iso_format(result["firstSeen"]) == iso_format(timestamp)
  486. assert result["count"] == str(times + 1)