test_organization_events_stats.py 93 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485
  1. import uuid
  2. from datetime import timedelta
  3. from unittest import mock
  4. from uuid import uuid4
  5. import pytest
  6. from dateutil.parser import parse as parse_date
  7. from django.urls import reverse
  8. from pytz import utc
  9. from snuba_sdk.column import Column
  10. from snuba_sdk.conditions import Condition, Op
  11. from snuba_sdk.function import Function
  12. from sentry.constants import MAX_TOP_EVENTS
  13. from sentry.models.transaction_threshold import ProjectTransactionThreshold, TransactionMetric
  14. from sentry.snuba.discover import OTHER_KEY
  15. from sentry.testutils import APITestCase, SnubaTestCase
  16. from sentry.testutils.helpers.datetime import before_now, iso_format
  17. from sentry.testutils.silo import region_silo_test
  18. from sentry.types.issues import GroupType
  19. from sentry.utils.samples import load_data
  20. from tests.sentry.issues.test_utils import SearchIssueTestMixin
  21. pytestmark = pytest.mark.sentry_metrics
  22. @region_silo_test
  23. class OrganizationEventsStatsEndpointTest(APITestCase, SnubaTestCase, SearchIssueTestMixin):
  24. endpoint = "sentry-api-0-organization-events-stats"
  25. def setUp(self):
  26. super().setUp()
  27. self.login_as(user=self.user)
  28. self.authed_user = self.user
  29. self.day_ago = before_now(days=1).replace(hour=10, minute=0, second=0, microsecond=0)
  30. self.project = self.create_project()
  31. self.project2 = self.create_project()
  32. self.user = self.create_user()
  33. self.user2 = self.create_user()
  34. self.store_event(
  35. data={
  36. "event_id": "a" * 32,
  37. "message": "very bad",
  38. "timestamp": iso_format(self.day_ago + timedelta(minutes=1)),
  39. "fingerprint": ["group1"],
  40. "tags": {"sentry:user": self.user.email},
  41. },
  42. project_id=self.project.id,
  43. )
  44. self.store_event(
  45. data={
  46. "event_id": "b" * 32,
  47. "message": "oh my",
  48. "timestamp": iso_format(self.day_ago + timedelta(hours=1, minutes=1)),
  49. "fingerprint": ["group2"],
  50. "tags": {"sentry:user": self.user2.email},
  51. },
  52. project_id=self.project2.id,
  53. )
  54. self.store_event(
  55. data={
  56. "event_id": "c" * 32,
  57. "message": "very bad",
  58. "timestamp": iso_format(self.day_ago + timedelta(hours=1, minutes=2)),
  59. "fingerprint": ["group2"],
  60. "tags": {"sentry:user": self.user2.email},
  61. },
  62. project_id=self.project2.id,
  63. )
  64. self.url = reverse(
  65. "sentry-api-0-organization-events-stats",
  66. kwargs={"organization_slug": self.project.organization.slug},
  67. )
  68. self.features = {}
  69. def do_request(self, data, url=None, features=None):
  70. if features is None:
  71. features = {"organizations:discover-basic": True}
  72. features.update(self.features)
  73. with self.feature(features):
  74. return self.client.get(self.url if url is None else url, data=data, format="json")
  75. def test_simple(self):
  76. response = self.do_request(
  77. {
  78. "start": iso_format(self.day_ago),
  79. "end": iso_format(self.day_ago + timedelta(hours=2)),
  80. "interval": "1h",
  81. },
  82. )
  83. assert response.status_code == 200, response.content
  84. assert [attrs for time, attrs in response.data["data"]] == [[{"count": 1}], [{"count": 2}]]
  85. def test_generic_issue(self):
  86. _, _, group_info = self.store_search_issue(
  87. self.project.id,
  88. self.user.id,
  89. [f"{GroupType.PROFILE_BLOCKED_THREAD.value}-group1"],
  90. "prod",
  91. self.day_ago.replace(tzinfo=utc),
  92. )
  93. self.store_search_issue(
  94. self.project.id,
  95. self.user.id,
  96. [f"{GroupType.PROFILE_BLOCKED_THREAD.value}-group1"],
  97. "prod",
  98. self.day_ago.replace(tzinfo=utc) + timedelta(hours=1, minutes=1),
  99. )
  100. self.store_search_issue(
  101. self.project.id,
  102. self.user.id,
  103. [f"{GroupType.PROFILE_BLOCKED_THREAD.value}-group1"],
  104. "prod",
  105. self.day_ago.replace(tzinfo=utc) + timedelta(hours=1, minutes=2),
  106. )
  107. with self.feature(
  108. [
  109. "organizations:profiling",
  110. ]
  111. ):
  112. response = self.do_request(
  113. {
  114. "start": iso_format(self.day_ago),
  115. "end": iso_format(self.day_ago + timedelta(hours=2)),
  116. "interval": "1h",
  117. "query": f"issue:{group_info.group.qualified_short_id}",
  118. "dataset": "issuePlatform",
  119. },
  120. )
  121. assert response.status_code == 200, response.content
  122. assert [attrs for time, attrs in response.data["data"]] == [[{"count": 1}], [{"count": 2}]]
  123. def test_generic_issue_calculated_interval(self):
  124. """Test that a 4h interval returns the correct generic event stats.
  125. This follows a different code path than 1h or 1d as the IssuePlatformTimeSeriesQueryBuilder
  126. does some calculation to create the time column."""
  127. _, _, group_info = self.store_search_issue(
  128. self.project.id,
  129. self.user.id,
  130. [f"{GroupType.PROFILE_BLOCKED_THREAD.value}-group1"],
  131. "prod",
  132. self.day_ago.replace(tzinfo=utc) + timedelta(minutes=1),
  133. )
  134. self.store_search_issue(
  135. self.project.id,
  136. self.user.id,
  137. [f"{GroupType.PROFILE_BLOCKED_THREAD.value}-group1"],
  138. "prod",
  139. self.day_ago.replace(tzinfo=utc) + timedelta(minutes=1),
  140. )
  141. self.store_search_issue(
  142. self.project.id,
  143. self.user.id,
  144. [f"{GroupType.PROFILE_BLOCKED_THREAD.value}-group1"],
  145. "prod",
  146. self.day_ago.replace(tzinfo=utc) + timedelta(minutes=2),
  147. )
  148. with self.feature(
  149. [
  150. "organizations:profiling",
  151. ]
  152. ):
  153. response = self.do_request(
  154. {
  155. "start": iso_format(self.day_ago),
  156. "end": iso_format(self.day_ago + timedelta(hours=4)),
  157. "interval": "4h",
  158. "query": f"issue:{group_info.group.qualified_short_id}",
  159. "dataset": "issuePlatform",
  160. },
  161. )
  162. assert response.status_code == 200, response.content
  163. assert [attrs for time, attrs in response.data["data"]] == [[{"count": 3}], [{"count": 0}]]
  164. def test_misaligned_last_bucket(self):
  165. response = self.do_request(
  166. data={
  167. "start": iso_format(self.day_ago - timedelta(minutes=30)),
  168. "end": iso_format(self.day_ago + timedelta(hours=1, minutes=30)),
  169. "interval": "1h",
  170. "partial": "1",
  171. },
  172. )
  173. assert response.status_code == 200, response.content
  174. assert [attrs for time, attrs in response.data["data"]] == [
  175. [{"count": 0}],
  176. [{"count": 1}],
  177. [{"count": 2}],
  178. ]
  179. def test_no_projects(self):
  180. org = self.create_organization(owner=self.user)
  181. self.login_as(user=self.user)
  182. url = reverse(
  183. "sentry-api-0-organization-events-stats", kwargs={"organization_slug": org.slug}
  184. )
  185. response = self.do_request({}, url)
  186. assert response.status_code == 200, response.content
  187. assert len(response.data["data"]) == 0
  188. def test_user_count(self):
  189. self.store_event(
  190. data={
  191. "event_id": "d" * 32,
  192. "message": "something",
  193. "timestamp": iso_format(self.day_ago + timedelta(minutes=2)),
  194. "tags": {"sentry:user": self.user2.email},
  195. "fingerprint": ["group2"],
  196. },
  197. project_id=self.project2.id,
  198. )
  199. response = self.do_request(
  200. data={
  201. "start": iso_format(self.day_ago),
  202. "end": iso_format(self.day_ago + timedelta(hours=2)),
  203. "interval": "1h",
  204. "yAxis": "user_count",
  205. },
  206. )
  207. assert response.status_code == 200, response.content
  208. assert [attrs for time, attrs in response.data["data"]] == [[{"count": 2}], [{"count": 1}]]
  209. def test_discover2_backwards_compatibility(self):
  210. response = self.do_request(
  211. data={
  212. "project": self.project.id,
  213. "start": iso_format(self.day_ago),
  214. "end": iso_format(self.day_ago + timedelta(hours=2)),
  215. "interval": "1h",
  216. "yAxis": "user_count",
  217. },
  218. )
  219. assert response.status_code == 200, response.content
  220. assert len(response.data["data"]) > 0
  221. response = self.do_request(
  222. data={
  223. "project": self.project.id,
  224. "start": iso_format(self.day_ago),
  225. "end": iso_format(self.day_ago + timedelta(hours=2)),
  226. "interval": "1h",
  227. "yAxis": "event_count",
  228. },
  229. )
  230. assert response.status_code == 200, response.content
  231. assert len(response.data["data"]) > 0
  232. def test_with_event_count_flag(self):
  233. response = self.do_request(
  234. data={
  235. "start": iso_format(self.day_ago),
  236. "end": iso_format(self.day_ago + timedelta(hours=2)),
  237. "interval": "1h",
  238. "yAxis": "event_count",
  239. },
  240. )
  241. assert response.status_code == 200, response.content
  242. assert [attrs for time, attrs in response.data["data"]] == [[{"count": 1}], [{"count": 2}]]
  243. def test_performance_view_feature(self):
  244. response = self.do_request(
  245. data={
  246. "end": iso_format(before_now()),
  247. "start": iso_format(before_now(hours=2)),
  248. "query": "project_id:1",
  249. "interval": "30m",
  250. "yAxis": "count()",
  251. },
  252. features={
  253. "organizations:performance-view": True,
  254. "organizations:discover-basic": False,
  255. },
  256. )
  257. assert response.status_code == 200, response.content
  258. def test_apdex_divide_by_zero(self):
  259. ProjectTransactionThreshold.objects.create(
  260. project=self.project,
  261. organization=self.project.organization,
  262. threshold=600,
  263. metric=TransactionMetric.LCP.value,
  264. )
  265. # Shouldn't count towards apdex
  266. data = load_data(
  267. "transaction",
  268. start_timestamp=self.day_ago + timedelta(minutes=(1)),
  269. timestamp=self.day_ago + timedelta(minutes=(3)),
  270. )
  271. data["transaction"] = "/apdex/new/"
  272. data["user"] = {"email": "1@example.com"}
  273. data["measurements"] = {}
  274. self.store_event(data, project_id=self.project.id)
  275. response = self.do_request(
  276. data={
  277. "start": iso_format(self.day_ago),
  278. "end": iso_format(self.day_ago + timedelta(hours=2)),
  279. "interval": "1h",
  280. "yAxis": "apdex()",
  281. "project": [self.project.id],
  282. },
  283. )
  284. assert response.status_code == 200, response.content
  285. assert len(response.data["data"]) == 2
  286. data = response.data["data"]
  287. # 0 transactions with LCP 0/0
  288. assert [attrs for time, attrs in response.data["data"]] == [
  289. [{"count": 0}],
  290. [{"count": 0}],
  291. ]
  292. def test_aggregate_function_apdex(self):
  293. project1 = self.create_project()
  294. project2 = self.create_project()
  295. events = [
  296. ("one", 400, project1.id),
  297. ("one", 400, project1.id),
  298. ("two", 3000, project2.id),
  299. ("two", 1000, project2.id),
  300. ("three", 3000, project2.id),
  301. ]
  302. for idx, event in enumerate(events):
  303. data = load_data(
  304. "transaction",
  305. start_timestamp=self.day_ago + timedelta(minutes=(1 + idx)),
  306. timestamp=self.day_ago + timedelta(minutes=(1 + idx), milliseconds=event[1]),
  307. )
  308. data["event_id"] = f"{idx}" * 32
  309. data["transaction"] = f"/apdex/new/{event[0]}"
  310. data["user"] = {"email": f"{idx}@example.com"}
  311. self.store_event(data, project_id=event[2])
  312. response = self.do_request(
  313. data={
  314. "start": iso_format(self.day_ago),
  315. "end": iso_format(self.day_ago + timedelta(hours=2)),
  316. "interval": "1h",
  317. "yAxis": "apdex()",
  318. },
  319. )
  320. assert response.status_code == 200, response.content
  321. assert [attrs for time, attrs in response.data["data"]] == [
  322. [{"count": 0.3}],
  323. [{"count": 0}],
  324. ]
  325. ProjectTransactionThreshold.objects.create(
  326. project=project1,
  327. organization=project1.organization,
  328. threshold=100,
  329. metric=TransactionMetric.DURATION.value,
  330. )
  331. ProjectTransactionThreshold.objects.create(
  332. project=project2,
  333. organization=project1.organization,
  334. threshold=100,
  335. metric=TransactionMetric.DURATION.value,
  336. )
  337. response = self.do_request(
  338. data={
  339. "start": iso_format(self.day_ago),
  340. "end": iso_format(self.day_ago + timedelta(hours=2)),
  341. "interval": "1h",
  342. "yAxis": "apdex()",
  343. },
  344. )
  345. assert response.status_code == 200, response.content
  346. assert [attrs for time, attrs in response.data["data"]] == [
  347. [{"count": 0.2}],
  348. [{"count": 0}],
  349. ]
  350. response = self.do_request(
  351. data={
  352. "start": iso_format(self.day_ago),
  353. "end": iso_format(self.day_ago + timedelta(hours=2)),
  354. "interval": "1h",
  355. "yAxis": ["user_count", "apdex()"],
  356. },
  357. )
  358. assert response.status_code == 200, response.content
  359. assert response.data["user_count"]["order"] == 0
  360. assert [attrs for time, attrs in response.data["user_count"]["data"]] == [
  361. [{"count": 5}],
  362. [{"count": 0}],
  363. ]
  364. assert response.data["apdex()"]["order"] == 1
  365. assert [attrs for time, attrs in response.data["apdex()"]["data"]] == [
  366. [{"count": 0.2}],
  367. [{"count": 0}],
  368. ]
  369. def test_aggregate_function_count(self):
  370. response = self.do_request(
  371. data={
  372. "start": iso_format(self.day_ago),
  373. "end": iso_format(self.day_ago + timedelta(hours=2)),
  374. "interval": "1h",
  375. "yAxis": "count()",
  376. },
  377. )
  378. assert response.status_code == 200, response.content
  379. assert [attrs for time, attrs in response.data["data"]] == [[{"count": 1}], [{"count": 2}]]
  380. def test_invalid_aggregate(self):
  381. response = self.do_request(
  382. data={
  383. "start": iso_format(self.day_ago),
  384. "end": iso_format(self.day_ago + timedelta(hours=2)),
  385. "interval": "1h",
  386. "yAxis": "rubbish",
  387. },
  388. )
  389. assert response.status_code == 400, response.content
  390. def test_aggregate_function_user_count(self):
  391. response = self.do_request(
  392. data={
  393. "start": iso_format(self.day_ago),
  394. "end": iso_format(self.day_ago + timedelta(hours=2)),
  395. "interval": "1h",
  396. "yAxis": "count_unique(user)",
  397. },
  398. )
  399. assert response.status_code == 200, response.content
  400. assert [attrs for time, attrs in response.data["data"]] == [[{"count": 1}], [{"count": 1}]]
  401. def test_aggregate_invalid(self):
  402. response = self.do_request(
  403. data={
  404. "start": iso_format(self.day_ago),
  405. "end": iso_format(self.day_ago + timedelta(hours=2)),
  406. "interval": "1h",
  407. "yAxis": "nope(lol)",
  408. },
  409. )
  410. assert response.status_code == 400, response.content
  411. def test_throughput_epm_hour_rollup(self):
  412. project = self.create_project()
  413. # Each of these denotes how many events to create in each hour
  414. event_counts = [6, 0, 6, 3, 0, 3]
  415. for hour, count in enumerate(event_counts):
  416. for minute in range(count):
  417. self.store_event(
  418. data={
  419. "event_id": str(uuid.uuid1()),
  420. "message": "very bad",
  421. "timestamp": iso_format(
  422. self.day_ago + timedelta(hours=hour, minutes=minute)
  423. ),
  424. "fingerprint": ["group1"],
  425. "tags": {"sentry:user": self.user.email},
  426. },
  427. project_id=project.id,
  428. )
  429. for axis in ["epm()", "tpm()"]:
  430. response = self.do_request(
  431. data={
  432. "start": iso_format(self.day_ago),
  433. "end": iso_format(self.day_ago + timedelta(hours=6)),
  434. "interval": "1h",
  435. "yAxis": axis,
  436. "project": project.id,
  437. },
  438. )
  439. assert response.status_code == 200, response.content
  440. data = response.data["data"]
  441. assert len(data) == 6
  442. rows = data[0:6]
  443. for test in zip(event_counts, rows):
  444. assert test[1][1][0]["count"] == test[0] / (3600.0 / 60.0)
  445. def test_throughput_epm_day_rollup(self):
  446. project = self.create_project()
  447. # Each of these denotes how many events to create in each minute
  448. event_counts = [6, 0, 6, 3, 0, 3]
  449. for hour, count in enumerate(event_counts):
  450. for minute in range(count):
  451. self.store_event(
  452. data={
  453. "event_id": str(uuid.uuid1()),
  454. "message": "very bad",
  455. "timestamp": iso_format(
  456. self.day_ago + timedelta(hours=hour, minutes=minute)
  457. ),
  458. "fingerprint": ["group1"],
  459. "tags": {"sentry:user": self.user.email},
  460. },
  461. project_id=project.id,
  462. )
  463. for axis in ["epm()", "tpm()"]:
  464. response = self.do_request(
  465. data={
  466. "start": iso_format(self.day_ago),
  467. "end": iso_format(self.day_ago + timedelta(hours=24)),
  468. "interval": "24h",
  469. "yAxis": axis,
  470. "project": project.id,
  471. },
  472. )
  473. assert response.status_code == 200, response.content
  474. data = response.data["data"]
  475. assert len(data) == 2
  476. assert data[0][1][0]["count"] == sum(event_counts) / (86400.0 / 60.0)
  477. def test_throughput_eps_minute_rollup(self):
  478. project = self.create_project()
  479. # Each of these denotes how many events to create in each minute
  480. event_counts = [6, 0, 6, 3, 0, 3]
  481. for minute, count in enumerate(event_counts):
  482. for second in range(count):
  483. self.store_event(
  484. data={
  485. "event_id": str(uuid.uuid1()),
  486. "message": "very bad",
  487. "timestamp": iso_format(
  488. self.day_ago + timedelta(minutes=minute, seconds=second)
  489. ),
  490. "fingerprint": ["group1"],
  491. "tags": {"sentry:user": self.user.email},
  492. },
  493. project_id=project.id,
  494. )
  495. for axis in ["eps()", "tps()"]:
  496. response = self.do_request(
  497. data={
  498. "start": iso_format(self.day_ago),
  499. "end": iso_format(self.day_ago + timedelta(minutes=6)),
  500. "interval": "1m",
  501. "yAxis": axis,
  502. "project": project.id,
  503. },
  504. )
  505. assert response.status_code == 200, response.content
  506. data = response.data["data"]
  507. assert len(data) == 6
  508. rows = data[0:6]
  509. for test in zip(event_counts, rows):
  510. assert test[1][1][0]["count"] == test[0] / 60.0
  511. def test_throughput_eps_no_rollup(self):
  512. project = self.create_project()
  513. # Each of these denotes how many events to create in each minute
  514. event_counts = [6, 0, 6, 3, 0, 3]
  515. for minute, count in enumerate(event_counts):
  516. for second in range(count):
  517. self.store_event(
  518. data={
  519. "event_id": str(uuid.uuid1()),
  520. "message": "very bad",
  521. "timestamp": iso_format(
  522. self.day_ago + timedelta(minutes=minute, seconds=second)
  523. ),
  524. "fingerprint": ["group1"],
  525. "tags": {"sentry:user": self.user.email},
  526. },
  527. project_id=project.id,
  528. )
  529. response = self.do_request(
  530. data={
  531. "start": iso_format(self.day_ago),
  532. "end": iso_format(self.day_ago + timedelta(minutes=1)),
  533. "interval": "1s",
  534. "yAxis": "eps()",
  535. "project": project.id,
  536. },
  537. )
  538. assert response.status_code == 200, response.content
  539. data = response.data["data"]
  540. # expect 60 data points between time span of 0 and 60 seconds
  541. assert len(data) == 60
  542. rows = data[0:6]
  543. for row in rows:
  544. assert row[1][0]["count"] == 1
  545. def test_transaction_events(self):
  546. prototype = {
  547. "type": "transaction",
  548. "transaction": "api.issue.delete",
  549. "spans": [],
  550. "contexts": {"trace": {"op": "foobar", "trace_id": "a" * 32, "span_id": "a" * 16}},
  551. "tags": {"important": "yes"},
  552. }
  553. fixtures = (
  554. ("d" * 32, before_now(minutes=32)),
  555. ("e" * 32, before_now(hours=1, minutes=2)),
  556. ("f" * 32, before_now(hours=1, minutes=35)),
  557. )
  558. for fixture in fixtures:
  559. data = prototype.copy()
  560. data["event_id"] = fixture[0]
  561. data["timestamp"] = iso_format(fixture[1])
  562. data["start_timestamp"] = iso_format(fixture[1] - timedelta(seconds=1))
  563. self.store_event(data=data, project_id=self.project.id)
  564. response = self.do_request(
  565. data={
  566. "project": self.project.id,
  567. "end": iso_format(before_now()),
  568. "start": iso_format(before_now(hours=2)),
  569. "query": "event.type:transaction",
  570. "interval": "30m",
  571. "yAxis": "count()",
  572. },
  573. )
  574. assert response.status_code == 200, response.content
  575. items = [item for time, item in response.data["data"] if item]
  576. # We could get more results depending on where the 30 min
  577. # windows land.
  578. assert len(items) >= 3
  579. def test_project_id_query_filter(self):
  580. response = self.do_request(
  581. data={
  582. "end": iso_format(before_now()),
  583. "start": iso_format(before_now(hours=2)),
  584. "query": "project_id:1",
  585. "interval": "30m",
  586. "yAxis": "count()",
  587. },
  588. )
  589. assert response.status_code == 200
  590. def test_latest_release_query_filter(self):
  591. response = self.do_request(
  592. data={
  593. "project": self.project.id,
  594. "end": iso_format(before_now()),
  595. "start": iso_format(before_now(hours=2)),
  596. "query": "release:latest",
  597. "interval": "30m",
  598. "yAxis": "count()",
  599. },
  600. )
  601. assert response.status_code == 200
  602. def test_conditional_filter(self):
  603. response = self.do_request(
  604. data={
  605. "start": iso_format(self.day_ago),
  606. "end": iso_format(self.day_ago + timedelta(hours=2)),
  607. "query": "id:{} OR id:{}".format("a" * 32, "b" * 32),
  608. "interval": "30m",
  609. "yAxis": "count()",
  610. },
  611. )
  612. assert response.status_code == 200, response.content
  613. data = response.data["data"]
  614. assert len(data) == 4
  615. assert data[0][1][0]["count"] == 1
  616. assert data[2][1][0]["count"] == 1
  617. def test_simple_multiple_yaxis(self):
  618. response = self.do_request(
  619. data={
  620. "start": iso_format(self.day_ago),
  621. "end": iso_format(self.day_ago + timedelta(hours=2)),
  622. "interval": "1h",
  623. "yAxis": ["user_count", "event_count"],
  624. },
  625. )
  626. assert response.status_code == 200, response.content
  627. assert response.data["user_count"]["order"] == 0
  628. assert [attrs for time, attrs in response.data["user_count"]["data"]] == [
  629. [{"count": 1}],
  630. [{"count": 1}],
  631. ]
  632. assert response.data["event_count"]["order"] == 1
  633. assert [attrs for time, attrs in response.data["event_count"]["data"]] == [
  634. [{"count": 1}],
  635. [{"count": 2}],
  636. ]
  637. def test_equation_yaxis(self):
  638. response = self.do_request(
  639. data={
  640. "start": iso_format(self.day_ago),
  641. "end": iso_format(self.day_ago + timedelta(hours=2)),
  642. "interval": "1h",
  643. "yAxis": ["equation|count() / 100"],
  644. },
  645. )
  646. assert response.status_code == 200, response.content
  647. assert len(response.data["data"]) == 2
  648. assert [attrs for time, attrs in response.data["data"]] == [
  649. [{"count": 0.01}],
  650. [{"count": 0.02}],
  651. ]
  652. def test_equation_mixed_multi_yaxis(self):
  653. response = self.do_request(
  654. data={
  655. "start": iso_format(self.day_ago),
  656. "end": iso_format(self.day_ago + timedelta(hours=2)),
  657. "interval": "1h",
  658. "yAxis": ["count()", "equation|count() * 100"],
  659. },
  660. )
  661. assert response.status_code == 200, response.content
  662. assert response.data["count()"]["order"] == 0
  663. assert [attrs for time, attrs in response.data["count()"]["data"]] == [
  664. [{"count": 1}],
  665. [{"count": 2}],
  666. ]
  667. assert response.data["equation|count() * 100"]["order"] == 1
  668. assert [attrs for time, attrs in response.data["equation|count() * 100"]["data"]] == [
  669. [{"count": 100}],
  670. [{"count": 200}],
  671. ]
  672. def test_equation_multi_yaxis(self):
  673. response = self.do_request(
  674. data={
  675. "start": iso_format(self.day_ago),
  676. "end": iso_format(self.day_ago + timedelta(hours=2)),
  677. "interval": "1h",
  678. "yAxis": ["equation|count() / 100", "equation|count() * 100"],
  679. },
  680. )
  681. assert response.status_code == 200, response.content
  682. assert response.data["equation|count() / 100"]["order"] == 0
  683. assert [attrs for time, attrs in response.data["equation|count() / 100"]["data"]] == [
  684. [{"count": 0.01}],
  685. [{"count": 0.02}],
  686. ]
  687. assert response.data["equation|count() * 100"]["order"] == 1
  688. assert [attrs for time, attrs in response.data["equation|count() * 100"]["data"]] == [
  689. [{"count": 100}],
  690. [{"count": 200}],
  691. ]
  692. def test_large_interval_no_drop_values(self):
  693. self.store_event(
  694. data={
  695. "event_id": "d" * 32,
  696. "message": "not good",
  697. "timestamp": iso_format(self.day_ago - timedelta(minutes=10)),
  698. "fingerprint": ["group3"],
  699. },
  700. project_id=self.project.id,
  701. )
  702. response = self.do_request(
  703. data={
  704. "project": self.project.id,
  705. "end": iso_format(self.day_ago),
  706. "start": iso_format(self.day_ago - timedelta(hours=24)),
  707. "query": 'message:"not good"',
  708. "interval": "1d",
  709. "yAxis": "count()",
  710. },
  711. )
  712. assert response.status_code == 200
  713. assert [attrs for time, attrs in response.data["data"]] == [[{"count": 0}], [{"count": 1}]]
  714. @mock.patch("sentry.snuba.discover.timeseries_query", return_value={})
  715. def test_multiple_yaxis_only_one_query(self, mock_query):
  716. self.do_request(
  717. data={
  718. "project": self.project.id,
  719. "start": iso_format(self.day_ago),
  720. "end": iso_format(self.day_ago + timedelta(hours=2)),
  721. "interval": "1h",
  722. "yAxis": ["user_count", "event_count", "epm()", "eps()"],
  723. },
  724. )
  725. assert mock_query.call_count == 1
  726. @mock.patch("sentry.snuba.discover.bulk_snql_query", return_value=[{"data": []}])
  727. def test_invalid_interval(self, mock_query):
  728. self.do_request(
  729. data={
  730. "end": iso_format(before_now()),
  731. "start": iso_format(before_now(hours=24)),
  732. "query": "",
  733. "interval": "1s",
  734. "yAxis": "count()",
  735. },
  736. )
  737. assert mock_query.call_count == 1
  738. # Should've reset to the default for 24h
  739. assert mock_query.mock_calls[0].args[0][0].query.granularity.granularity == 300
  740. self.do_request(
  741. data={
  742. "end": iso_format(before_now()),
  743. "start": iso_format(before_now(hours=24)),
  744. "query": "",
  745. "interval": "0d",
  746. "yAxis": "count()",
  747. },
  748. )
  749. assert mock_query.call_count == 2
  750. # Should've reset to the default for 24h
  751. assert mock_query.mock_calls[1].args[0][0].query.granularity.granularity == 300
  752. def test_out_of_retention(self):
  753. with self.options({"system.event-retention-days": 10}):
  754. response = self.do_request(
  755. data={
  756. "start": iso_format(before_now(days=20)),
  757. "end": iso_format(before_now(days=15)),
  758. "query": "",
  759. "interval": "30m",
  760. "yAxis": "count()",
  761. },
  762. )
  763. assert response.status_code == 400
  764. @mock.patch("sentry.utils.snuba.quantize_time")
  765. def test_quantize_dates(self, mock_quantize):
  766. mock_quantize.return_value = before_now(days=1).replace(tzinfo=utc)
  767. # Don't quantize short time periods
  768. self.do_request(
  769. data={"statsPeriod": "1h", "query": "", "interval": "30m", "yAxis": "count()"},
  770. )
  771. # Don't quantize absolute date periods
  772. self.do_request(
  773. data={
  774. "start": iso_format(before_now(days=20)),
  775. "end": iso_format(before_now(days=15)),
  776. "query": "",
  777. "interval": "30m",
  778. "yAxis": "count()",
  779. },
  780. )
  781. assert len(mock_quantize.mock_calls) == 0
  782. # Quantize long date periods
  783. self.do_request(
  784. data={"statsPeriod": "90d", "query": "", "interval": "30m", "yAxis": "count()"},
  785. )
  786. assert len(mock_quantize.mock_calls) == 2
  787. def test_with_zerofill(self):
  788. response = self.do_request(
  789. data={
  790. "start": iso_format(self.day_ago),
  791. "end": iso_format(self.day_ago + timedelta(hours=2)),
  792. "interval": "30m",
  793. },
  794. )
  795. assert response.status_code == 200, response.content
  796. assert [attrs for time, attrs in response.data["data"]] == [
  797. [{"count": 1}],
  798. [{"count": 0}],
  799. [{"count": 2}],
  800. [{"count": 0}],
  801. ]
  802. def test_without_zerofill(self):
  803. start = iso_format(self.day_ago)
  804. end = iso_format(self.day_ago + timedelta(hours=2))
  805. response = self.do_request(
  806. data={
  807. "start": start,
  808. "end": end,
  809. "interval": "30m",
  810. "withoutZerofill": "1",
  811. },
  812. features={
  813. "organizations:performance-chart-interpolation": True,
  814. "organizations:discover-basic": True,
  815. },
  816. )
  817. assert response.status_code == 200, response.content
  818. assert [attrs for time, attrs in response.data["data"]] == [
  819. [{"count": 1}],
  820. [{"count": 2}],
  821. ]
  822. assert response.data["start"] == parse_date(start).timestamp()
  823. assert response.data["end"] == parse_date(end).timestamp()
  824. def test_comparison(self):
  825. self.store_event(
  826. data={
  827. "timestamp": iso_format(self.day_ago + timedelta(days=-1, minutes=1)),
  828. },
  829. project_id=self.project.id,
  830. )
  831. self.store_event(
  832. data={
  833. "timestamp": iso_format(self.day_ago + timedelta(days=-1, minutes=2)),
  834. },
  835. project_id=self.project.id,
  836. )
  837. self.store_event(
  838. data={
  839. "timestamp": iso_format(self.day_ago + timedelta(days=-1, hours=1, minutes=1)),
  840. },
  841. project_id=self.project2.id,
  842. )
  843. response = self.do_request(
  844. data={
  845. "start": iso_format(self.day_ago),
  846. "end": iso_format(self.day_ago + timedelta(hours=2)),
  847. "interval": "1h",
  848. "comparisonDelta": int(timedelta(days=1).total_seconds()),
  849. }
  850. )
  851. assert response.status_code == 200, response.content
  852. assert [attrs for time, attrs in response.data["data"]] == [
  853. [{"count": 1, "comparisonCount": 2}],
  854. [{"count": 2, "comparisonCount": 1}],
  855. ]
  856. def test_comparison_invalid(self):
  857. response = self.do_request(
  858. data={
  859. "start": iso_format(self.day_ago),
  860. "end": iso_format(self.day_ago + timedelta(hours=2)),
  861. "interval": "1h",
  862. "comparisonDelta": "17h",
  863. },
  864. )
  865. assert response.status_code == 400, response.content
  866. assert response.data["detail"] == "comparisonDelta must be an integer"
  867. start = before_now(days=85)
  868. end = start + timedelta(days=7)
  869. with self.options({"system.event-retention-days": 90}):
  870. response = self.do_request(
  871. data={
  872. "start": iso_format(start),
  873. "end": iso_format(end),
  874. "interval": "1h",
  875. "comparisonDelta": int(timedelta(days=7).total_seconds()),
  876. }
  877. )
  878. assert response.status_code == 400, response.content
  879. assert response.data["detail"] == "Comparison period is outside retention window"
  880. def test_equations_divide_by_zero(self):
  881. response = self.do_request(
  882. data={
  883. "start": iso_format(self.day_ago),
  884. "end": iso_format(self.day_ago + timedelta(hours=2)),
  885. "interval": "1h",
  886. # force a 0 in the denominator by doing 1 - 1
  887. # since a 0 literal is illegal as the denominator
  888. "yAxis": ["equation|count() / (1-1)"],
  889. },
  890. )
  891. assert response.status_code == 200, response.content
  892. assert len(response.data["data"]) == 2
  893. assert [attrs for time, attrs in response.data["data"]] == [
  894. [{"count": None}],
  895. [{"count": None}],
  896. ]
  897. @mock.patch("sentry.search.events.builder.discover.raw_snql_query")
  898. def test_profiles_dataset_simple(self, mock_snql_query):
  899. mock_snql_query.side_effect = [{"meta": {}, "data": []}]
  900. query = {
  901. "yAxis": [
  902. "count()",
  903. "p75()",
  904. "p95()",
  905. "p99()",
  906. "p75(profile.duration)",
  907. "p95(profile.duration)",
  908. "p99(profile.duration)",
  909. ],
  910. "project": [self.project.id],
  911. "dataset": "profiles",
  912. }
  913. response = self.do_request(query, features={"organizations:profiling": True})
  914. assert response.status_code == 200, response.content
  915. def test_tag_with_conflicting_function_alias_simple(self):
  916. for _ in range(7):
  917. self.store_event(
  918. data={
  919. "timestamp": iso_format(self.day_ago + timedelta(minutes=2)),
  920. "tags": {"count": "9001"},
  921. },
  922. project_id=self.project2.id,
  923. )
  924. # Query for count and count()
  925. data = {
  926. "start": iso_format(self.day_ago),
  927. "end": iso_format(self.day_ago + timedelta(minutes=3)),
  928. "interval": "1h",
  929. "yAxis": "count()",
  930. "orderby": ["-count()"],
  931. "field": ["count()", "count"],
  932. "partial": 1,
  933. }
  934. response = self.client.get(self.url, data, format="json")
  935. assert response.status_code == 200
  936. # Expect a count of 8 because one event from setUp
  937. assert response.data["data"][0][1] == [{"count": 8}]
  938. data["query"] = "count:9001"
  939. response = self.client.get(self.url, data, format="json")
  940. assert response.status_code == 200
  941. assert response.data["data"][0][1] == [{"count": 7}]
  942. data["query"] = "count:abc"
  943. response = self.client.get(self.url, data, format="json")
  944. assert response.status_code == 200
  945. assert all([interval[1][0]["count"] == 0 for interval in response.data["data"]])
  946. @region_silo_test
  947. class OrganizationEventsStatsTopNEvents(APITestCase, SnubaTestCase):
  948. def setUp(self):
  949. super().setUp()
  950. self.login_as(user=self.user)
  951. self.day_ago = before_now(days=1).replace(hour=10, minute=0, second=0, microsecond=0)
  952. self.project = self.create_project()
  953. self.project2 = self.create_project()
  954. self.user2 = self.create_user()
  955. transaction_data = load_data("transaction")
  956. transaction_data["start_timestamp"] = iso_format(self.day_ago + timedelta(minutes=2))
  957. transaction_data["timestamp"] = iso_format(self.day_ago + timedelta(minutes=4))
  958. transaction_data["tags"] = {"shared-tag": "yup"}
  959. self.event_data = [
  960. {
  961. "data": {
  962. "message": "poof",
  963. "timestamp": iso_format(self.day_ago + timedelta(minutes=2)),
  964. "user": {"email": self.user.email},
  965. "tags": {"shared-tag": "yup"},
  966. "fingerprint": ["group1"],
  967. },
  968. "project": self.project2,
  969. "count": 7,
  970. },
  971. {
  972. "data": {
  973. "message": "voof",
  974. "timestamp": iso_format(self.day_ago + timedelta(hours=1, minutes=2)),
  975. "fingerprint": ["group2"],
  976. "user": {"email": self.user2.email},
  977. "tags": {"shared-tag": "yup"},
  978. },
  979. "project": self.project2,
  980. "count": 6,
  981. },
  982. {
  983. "data": {
  984. "message": "very bad",
  985. "timestamp": iso_format(self.day_ago + timedelta(minutes=2)),
  986. "fingerprint": ["group3"],
  987. "user": {"email": "foo@example.com"},
  988. "tags": {"shared-tag": "yup"},
  989. },
  990. "project": self.project,
  991. "count": 5,
  992. },
  993. {
  994. "data": {
  995. "message": "oh no",
  996. "timestamp": iso_format(self.day_ago + timedelta(minutes=2)),
  997. "fingerprint": ["group4"],
  998. "user": {"email": "bar@example.com"},
  999. "tags": {"shared-tag": "yup"},
  1000. },
  1001. "project": self.project,
  1002. "count": 4,
  1003. },
  1004. {"data": transaction_data, "project": self.project, "count": 3},
  1005. # Not in the top 5
  1006. {
  1007. "data": {
  1008. "message": "sorta bad",
  1009. "timestamp": iso_format(self.day_ago + timedelta(minutes=2)),
  1010. "fingerprint": ["group5"],
  1011. "user": {"email": "bar@example.com"},
  1012. "tags": {"shared-tag": "yup"},
  1013. },
  1014. "project": self.project,
  1015. "count": 2,
  1016. },
  1017. {
  1018. "data": {
  1019. "message": "not so bad",
  1020. "timestamp": iso_format(self.day_ago + timedelta(minutes=2)),
  1021. "fingerprint": ["group6"],
  1022. "user": {"email": "bar@example.com"},
  1023. "tags": {"shared-tag": "yup"},
  1024. },
  1025. "project": self.project,
  1026. "count": 1,
  1027. },
  1028. ]
  1029. self.events = []
  1030. for index, event_data in enumerate(self.event_data):
  1031. data = event_data["data"].copy()
  1032. event = {}
  1033. for i in range(event_data["count"]):
  1034. data["event_id"] = f"{index}{i}" * 16
  1035. event = self.store_event(data, project_id=event_data["project"].id)
  1036. self.events.append(event)
  1037. self.transaction = self.events[4]
  1038. self.enabled_features = {
  1039. "organizations:discover-basic": True,
  1040. }
  1041. self.url = reverse(
  1042. "sentry-api-0-organization-events-stats",
  1043. kwargs={"organization_slug": self.project.organization.slug},
  1044. )
  1045. def test_no_top_events_with_project_field(self):
  1046. project = self.create_project()
  1047. with self.feature(self.enabled_features):
  1048. response = self.client.get(
  1049. self.url,
  1050. data={
  1051. # make sure to query the project with 0 events
  1052. "project": project.id,
  1053. "start": iso_format(self.day_ago),
  1054. "end": iso_format(self.day_ago + timedelta(hours=2)),
  1055. "interval": "1h",
  1056. "yAxis": "count()",
  1057. "orderby": ["-count()"],
  1058. "field": ["count()", "project"],
  1059. "topEvents": 5,
  1060. },
  1061. format="json",
  1062. )
  1063. assert response.status_code == 200, response.content
  1064. # When there are no top events, we do not return an empty dict.
  1065. # Instead, we return a single zero-filled series for an empty graph.
  1066. data = response.data["data"]
  1067. assert [attrs for time, attrs in data] == [[{"count": 0}], [{"count": 0}]]
  1068. def test_no_top_events(self):
  1069. project = self.create_project()
  1070. with self.feature(self.enabled_features):
  1071. response = self.client.get(
  1072. self.url,
  1073. data={
  1074. # make sure to query the project with 0 events
  1075. "project": project.id,
  1076. "start": iso_format(self.day_ago),
  1077. "end": iso_format(self.day_ago + timedelta(hours=2)),
  1078. "interval": "1h",
  1079. "yAxis": "count()",
  1080. "orderby": ["-count()"],
  1081. "field": ["count()", "message", "user.email"],
  1082. "topEvents": 5,
  1083. },
  1084. format="json",
  1085. )
  1086. data = response.data["data"]
  1087. assert response.status_code == 200, response.content
  1088. # When there are no top events, we do not return an empty dict.
  1089. # Instead, we return a single zero-filled series for an empty graph.
  1090. assert [attrs for time, attrs in data] == [[{"count": 0}], [{"count": 0}]]
  1091. def test_no_top_events_with_multi_axis(self):
  1092. project = self.create_project()
  1093. with self.feature(self.enabled_features):
  1094. response = self.client.get(
  1095. self.url,
  1096. data={
  1097. # make sure to query the project with 0 events
  1098. "project": project.id,
  1099. "start": iso_format(self.day_ago),
  1100. "end": iso_format(self.day_ago + timedelta(hours=2)),
  1101. "interval": "1h",
  1102. "yAxis": ["count()", "count_unique(user)"],
  1103. "orderby": ["-count()"],
  1104. "field": ["count()", "count_unique(user)", "message", "user.email"],
  1105. "topEvents": 5,
  1106. },
  1107. format="json",
  1108. )
  1109. assert response.status_code == 200
  1110. data = response.data[""]
  1111. assert [attrs for time, attrs in data["count()"]["data"]] == [
  1112. [{"count": 0}],
  1113. [{"count": 0}],
  1114. ]
  1115. assert [attrs for time, attrs in data["count_unique(user)"]["data"]] == [
  1116. [{"count": 0}],
  1117. [{"count": 0}],
  1118. ]
  1119. def test_simple_top_events(self):
  1120. with self.feature(self.enabled_features):
  1121. response = self.client.get(
  1122. self.url,
  1123. data={
  1124. "start": iso_format(self.day_ago),
  1125. "end": iso_format(self.day_ago + timedelta(hours=2)),
  1126. "interval": "1h",
  1127. "yAxis": "count()",
  1128. "orderby": ["-count()"],
  1129. "field": ["count()", "message", "user.email"],
  1130. "topEvents": 5,
  1131. },
  1132. format="json",
  1133. )
  1134. data = response.data
  1135. assert response.status_code == 200, response.content
  1136. assert len(data) == 6
  1137. for index, event in enumerate(self.events[:5]):
  1138. message = event.message or event.transaction
  1139. results = data[
  1140. ",".join([message, self.event_data[index]["data"]["user"].get("email", "None")])
  1141. ]
  1142. assert results["order"] == index
  1143. assert [{"count": self.event_data[index]["count"]}] in [
  1144. attrs for _, attrs in results["data"]
  1145. ]
  1146. other = data["Other"]
  1147. assert other["order"] == 5
  1148. assert [{"count": 3}] in [attrs for _, attrs in other["data"]]
  1149. def test_tag_with_conflicting_function_alias_simple(self):
  1150. event_data = {
  1151. "data": {
  1152. "message": "poof",
  1153. "timestamp": iso_format(self.day_ago + timedelta(minutes=2)),
  1154. "user": {"email": self.user.email},
  1155. "tags": {"count": "9001"},
  1156. "fingerprint": ["group1"],
  1157. },
  1158. "project": self.project2,
  1159. "count": 7,
  1160. }
  1161. for i in range(event_data["count"]):
  1162. event_data["data"]["event_id"] = f"a{i}" * 16
  1163. self.store_event(event_data["data"], project_id=event_data["project"].id)
  1164. # Query for count and count()
  1165. data = {
  1166. "start": iso_format(self.day_ago),
  1167. "end": iso_format(self.day_ago + timedelta(hours=2)),
  1168. "interval": "1h",
  1169. "yAxis": "count()",
  1170. "orderby": ["-count()"],
  1171. "field": ["count()", "count"],
  1172. "topEvents": 5,
  1173. "partial": 1,
  1174. }
  1175. with self.feature(self.enabled_features):
  1176. response = self.client.get(self.url, data, format="json")
  1177. assert response.status_code == 200
  1178. assert response.data["9001"]["data"][0][1] == [{"count": 7}]
  1179. data["query"] = "count:9001"
  1180. with self.feature(self.enabled_features):
  1181. response = self.client.get(self.url, data, format="json")
  1182. assert response.status_code == 200
  1183. assert response.data["9001"]["data"][0][1] == [{"count": 7}]
  1184. data["query"] = "count:abc"
  1185. with self.feature(self.enabled_features):
  1186. response = self.client.get(self.url, data, format="json")
  1187. assert response.status_code == 200
  1188. assert all([interval[1][0]["count"] == 0 for interval in response.data["data"]])
  1189. def test_tag_with_conflicting_function_alias_with_other_single_grouping(self):
  1190. event_data = [
  1191. {
  1192. "data": {
  1193. "message": "poof",
  1194. "timestamp": iso_format(self.day_ago + timedelta(minutes=2)),
  1195. "user": {"email": self.user.email},
  1196. "tags": {"count": "9001"},
  1197. "fingerprint": ["group1"],
  1198. },
  1199. "project": self.project2,
  1200. "count": 7,
  1201. },
  1202. {
  1203. "data": {
  1204. "message": "poof2",
  1205. "timestamp": iso_format(self.day_ago + timedelta(minutes=2)),
  1206. "user": {"email": self.user.email},
  1207. "tags": {"count": "abc"},
  1208. "fingerprint": ["group1"],
  1209. },
  1210. "project": self.project2,
  1211. "count": 3,
  1212. },
  1213. ]
  1214. for index, event in enumerate(event_data):
  1215. for i in range(event["count"]):
  1216. event["data"]["event_id"] = f"{index}{i}" * 16
  1217. self.store_event(event["data"], project_id=event["project"].id)
  1218. # Query for count and count()
  1219. data = {
  1220. "start": iso_format(self.day_ago),
  1221. "end": iso_format(self.day_ago + timedelta(hours=1)),
  1222. "interval": "1h",
  1223. "yAxis": "count()",
  1224. "orderby": ["-count"],
  1225. "field": ["count()", "count"],
  1226. "topEvents": 2,
  1227. "partial": 1,
  1228. }
  1229. with self.feature(self.enabled_features):
  1230. response = self.client.get(self.url, data, format="json")
  1231. assert response.status_code == 200
  1232. assert response.data["9001"]["data"][0][1] == [{"count": 7}]
  1233. assert response.data["abc"]["data"][0][1] == [{"count": 3}]
  1234. assert response.data["Other"]["data"][0][1] == [{"count": 16}]
  1235. def test_tag_with_conflicting_function_alias_with_other_multiple_groupings(self):
  1236. event_data = [
  1237. {
  1238. "data": {
  1239. "message": "abc",
  1240. "timestamp": iso_format(self.day_ago + timedelta(minutes=2)),
  1241. "user": {"email": self.user.email},
  1242. "tags": {"count": "2"},
  1243. "fingerprint": ["group1"],
  1244. },
  1245. "project": self.project2,
  1246. "count": 3,
  1247. },
  1248. {
  1249. "data": {
  1250. "message": "def",
  1251. "timestamp": iso_format(self.day_ago + timedelta(minutes=2)),
  1252. "user": {"email": self.user.email},
  1253. "tags": {"count": "9001"},
  1254. "fingerprint": ["group1"],
  1255. },
  1256. "project": self.project2,
  1257. "count": 7,
  1258. },
  1259. ]
  1260. for index, event in enumerate(event_data):
  1261. for i in range(event["count"]):
  1262. event["data"]["event_id"] = f"{index}{i}" * 16
  1263. self.store_event(event["data"], project_id=event["project"].id)
  1264. # Query for count and count()
  1265. data = {
  1266. "start": iso_format(self.day_ago),
  1267. "end": iso_format(self.day_ago + timedelta(hours=2)),
  1268. "interval": "2d",
  1269. "yAxis": "count()",
  1270. "orderby": ["-count"],
  1271. "field": ["count()", "count", "message"],
  1272. "topEvents": 2,
  1273. "partial": 1,
  1274. }
  1275. with self.feature(self.enabled_features):
  1276. response = self.client.get(self.url, data, format="json")
  1277. assert response.status_code == 200
  1278. assert response.data["abc,2"]["data"][0][1] == [{"count": 3}]
  1279. assert response.data["def,9001"]["data"][0][1] == [{"count": 7}]
  1280. assert response.data["Other"]["data"][0][1] == [{"count": 25}]
  1281. def test_top_events_limits(self):
  1282. data = {
  1283. "start": iso_format(self.day_ago),
  1284. "end": iso_format(self.day_ago + timedelta(hours=2)),
  1285. "interval": "1h",
  1286. "yAxis": "count()",
  1287. "orderby": ["-count()"],
  1288. "field": ["count()", "message", "user.email"],
  1289. }
  1290. with self.feature(self.enabled_features):
  1291. data["topEvents"] = MAX_TOP_EVENTS + 1
  1292. response = self.client.get(self.url, data, format="json")
  1293. assert response.status_code == 400
  1294. data["topEvents"] = 0
  1295. response = self.client.get(self.url, data, format="json")
  1296. assert response.status_code == 400
  1297. data["topEvents"] = "a"
  1298. response = self.client.get(self.url, data, format="json")
  1299. assert response.status_code == 400
  1300. def test_top_events_with_projects(self):
  1301. with self.feature(self.enabled_features):
  1302. response = self.client.get(
  1303. self.url,
  1304. data={
  1305. "start": iso_format(self.day_ago),
  1306. "end": iso_format(self.day_ago + timedelta(hours=2)),
  1307. "interval": "1h",
  1308. "yAxis": "count()",
  1309. "orderby": ["-count()"],
  1310. "field": ["count()", "message", "project"],
  1311. "topEvents": 5,
  1312. },
  1313. format="json",
  1314. )
  1315. data = response.data
  1316. assert response.status_code == 200, response.content
  1317. assert len(data) == 6
  1318. for index, event in enumerate(self.events[:5]):
  1319. message = event.message or event.transaction
  1320. results = data[",".join([message, event.project.slug])]
  1321. assert results["order"] == index
  1322. assert [{"count": self.event_data[index]["count"]}] in [
  1323. attrs for time, attrs in results["data"]
  1324. ]
  1325. other = data["Other"]
  1326. assert other["order"] == 5
  1327. assert [{"count": 3}] in [attrs for _, attrs in other["data"]]
  1328. def test_top_events_with_issue(self):
  1329. # delete a group to make sure if this happens the value becomes unknown
  1330. event_group = self.events[0].group
  1331. event_group.delete()
  1332. with self.feature(self.enabled_features):
  1333. response = self.client.get(
  1334. self.url,
  1335. data={
  1336. "start": iso_format(self.day_ago),
  1337. "end": iso_format(self.day_ago + timedelta(hours=2)),
  1338. "interval": "1h",
  1339. "yAxis": "count()",
  1340. "orderby": ["-count()"],
  1341. "field": ["count()", "message", "issue"],
  1342. "topEvents": 5,
  1343. "query": "!event.type:transaction",
  1344. },
  1345. format="json",
  1346. )
  1347. data = response.data
  1348. assert response.status_code == 200, response.content
  1349. assert len(data) == 6
  1350. for index, event in enumerate(self.events[:4]):
  1351. message = event.message
  1352. # Because we deleted the group for event 0
  1353. if index == 0 or event.group is None:
  1354. issue = "unknown"
  1355. else:
  1356. issue = event.group.qualified_short_id
  1357. results = data[",".join([issue, message])]
  1358. assert results["order"] == index
  1359. assert [{"count": self.event_data[index]["count"]}] in [
  1360. attrs for time, attrs in results["data"]
  1361. ]
  1362. other = data["Other"]
  1363. assert other["order"] == 5
  1364. assert [{"count": 1}] in [attrs for _, attrs in other["data"]]
  1365. def test_top_events_with_transaction_status(self):
  1366. with self.feature(self.enabled_features):
  1367. response = self.client.get(
  1368. self.url,
  1369. data={
  1370. "start": iso_format(self.day_ago),
  1371. "end": iso_format(self.day_ago + timedelta(hours=2)),
  1372. "interval": "1h",
  1373. "yAxis": "count()",
  1374. "orderby": ["-count()"],
  1375. "field": ["count()", "transaction.status"],
  1376. "topEvents": 5,
  1377. },
  1378. format="json",
  1379. )
  1380. data = response.data
  1381. assert response.status_code == 200, response.content
  1382. assert len(data) == 1
  1383. assert "ok" in data
  1384. @mock.patch("sentry.models.GroupManager.get_issues_mapping")
  1385. def test_top_events_with_unknown_issue(self, mock_issues_mapping):
  1386. event = self.events[0]
  1387. event_data = self.event_data[0]
  1388. # ensure that the issue mapping returns None for the issue
  1389. mock_issues_mapping.return_value = {event.group.id: None}
  1390. with self.feature(self.enabled_features):
  1391. response = self.client.get(
  1392. self.url,
  1393. data={
  1394. "start": iso_format(self.day_ago),
  1395. "end": iso_format(self.day_ago + timedelta(hours=2)),
  1396. "interval": "1h",
  1397. "yAxis": "count()",
  1398. "orderby": ["-count()"],
  1399. "field": ["count()", "issue"],
  1400. "topEvents": 5,
  1401. # narrow the search to just one issue
  1402. "query": f"issue.id:{event.group.id}",
  1403. },
  1404. format="json",
  1405. )
  1406. assert response.status_code == 200, response.content
  1407. data = response.data
  1408. assert len(data) == 1
  1409. results = data["unknown"]
  1410. assert results["order"] == 0
  1411. assert [{"count": event_data["count"]}] in [attrs for time, attrs in results["data"]]
  1412. @mock.patch(
  1413. "sentry.search.events.builder.discover.raw_snql_query",
  1414. side_effect=[{"data": [{"issue.id": 1}], "meta": []}, {"data": [], "meta": []}],
  1415. )
  1416. def test_top_events_with_issue_check_query_conditions(self, mock_query):
  1417. """ "Intentionally separate from test_top_events_with_issue
  1418. This is to test against a bug where the condition for issues wasn't included and we'd be missing data for
  1419. the interval since we'd cap out the max rows. This was not caught by the previous test since the results
  1420. would still be correct given the smaller interval & lack of data
  1421. """
  1422. with self.feature(self.enabled_features):
  1423. self.client.get(
  1424. self.url,
  1425. data={
  1426. "start": iso_format(self.day_ago),
  1427. "end": iso_format(self.day_ago + timedelta(hours=2)),
  1428. "interval": "1h",
  1429. "yAxis": "count()",
  1430. "orderby": ["-count()"],
  1431. "field": ["count()", "message", "issue"],
  1432. "topEvents": 5,
  1433. "query": "!event.type:transaction",
  1434. },
  1435. format="json",
  1436. )
  1437. assert (
  1438. Condition(Function("coalesce", [Column("group_id"), 0], "issue.id"), Op.IN, [1])
  1439. in mock_query.mock_calls[1].args[0].query.where
  1440. )
  1441. def test_top_events_with_functions(self):
  1442. with self.feature(self.enabled_features):
  1443. response = self.client.get(
  1444. self.url,
  1445. data={
  1446. "start": iso_format(self.day_ago),
  1447. "end": iso_format(self.day_ago + timedelta(hours=2)),
  1448. "interval": "1h",
  1449. "yAxis": "count()",
  1450. "orderby": ["-p99()"],
  1451. "field": ["transaction", "avg(transaction.duration)", "p99()"],
  1452. "topEvents": 5,
  1453. },
  1454. format="json",
  1455. )
  1456. data = response.data
  1457. assert response.status_code == 200, response.content
  1458. assert len(data) == 1
  1459. results = data[self.transaction.transaction]
  1460. assert results["order"] == 0
  1461. assert [attrs for time, attrs in results["data"]] == [[{"count": 3}], [{"count": 0}]]
  1462. def test_top_events_with_functions_on_different_transactions(self):
  1463. """Transaction2 has less events, but takes longer so order should be self.transaction then transaction2"""
  1464. transaction_data = load_data("transaction")
  1465. transaction_data["start_timestamp"] = iso_format(self.day_ago + timedelta(minutes=2))
  1466. transaction_data["timestamp"] = iso_format(self.day_ago + timedelta(minutes=6))
  1467. transaction_data["transaction"] = "/foo_bar/"
  1468. transaction2 = self.store_event(transaction_data, project_id=self.project.id)
  1469. with self.feature(self.enabled_features):
  1470. response = self.client.get(
  1471. self.url,
  1472. data={
  1473. "start": iso_format(self.day_ago),
  1474. "end": iso_format(self.day_ago + timedelta(hours=2)),
  1475. "interval": "1h",
  1476. "yAxis": "count()",
  1477. "orderby": ["-p99()"],
  1478. "field": ["transaction", "avg(transaction.duration)", "p99()"],
  1479. "topEvents": 5,
  1480. },
  1481. format="json",
  1482. )
  1483. data = response.data
  1484. assert response.status_code == 200, response.content
  1485. assert len(data) == 2
  1486. results = data[self.transaction.transaction]
  1487. assert results["order"] == 1
  1488. assert [attrs for time, attrs in results["data"]] == [[{"count": 3}], [{"count": 0}]]
  1489. results = data[transaction2.transaction]
  1490. assert results["order"] == 0
  1491. assert [attrs for time, attrs in results["data"]] == [[{"count": 1}], [{"count": 0}]]
  1492. def test_top_events_with_query(self):
  1493. transaction_data = load_data("transaction")
  1494. transaction_data["start_timestamp"] = iso_format(self.day_ago + timedelta(minutes=2))
  1495. transaction_data["timestamp"] = iso_format(self.day_ago + timedelta(minutes=6))
  1496. transaction_data["transaction"] = "/foo_bar/"
  1497. self.store_event(transaction_data, project_id=self.project.id)
  1498. with self.feature(self.enabled_features):
  1499. response = self.client.get(
  1500. self.url,
  1501. data={
  1502. "start": iso_format(self.day_ago),
  1503. "end": iso_format(self.day_ago + timedelta(hours=2)),
  1504. "interval": "1h",
  1505. "yAxis": "count()",
  1506. "orderby": ["-p99()"],
  1507. "query": "transaction:/foo_bar/",
  1508. "field": ["transaction", "avg(transaction.duration)", "p99()"],
  1509. "topEvents": 5,
  1510. },
  1511. format="json",
  1512. )
  1513. data = response.data
  1514. assert response.status_code == 200, response.content
  1515. assert len(data) == 1
  1516. transaction2_data = data["/foo_bar/"]
  1517. assert transaction2_data["order"] == 0
  1518. assert [attrs for time, attrs in transaction2_data["data"]] == [
  1519. [{"count": 1}],
  1520. [{"count": 0}],
  1521. ]
  1522. def test_top_events_with_negated_condition(self):
  1523. with self.feature(self.enabled_features):
  1524. response = self.client.get(
  1525. self.url,
  1526. data={
  1527. "start": iso_format(self.day_ago),
  1528. "end": iso_format(self.day_ago + timedelta(hours=2)),
  1529. "interval": "1h",
  1530. "yAxis": "count()",
  1531. "orderby": ["-count()"],
  1532. "query": f"!message:{self.events[0].message}",
  1533. "field": ["message", "count()"],
  1534. "topEvents": 5,
  1535. },
  1536. format="json",
  1537. )
  1538. data = response.data
  1539. assert response.status_code == 200, response.content
  1540. assert len(data) == 6
  1541. for index, event in enumerate(self.events[1:5]):
  1542. message = event.message or event.transaction
  1543. results = data[message]
  1544. assert results["order"] == index
  1545. assert [{"count": self.event_data[index + 1]["count"]}] in [
  1546. attrs for _, attrs in results["data"]
  1547. ]
  1548. other = data["Other"]
  1549. assert other["order"] == 5
  1550. assert [{"count": 1}] in [attrs for _, attrs in other["data"]]
  1551. def test_top_events_with_epm(self):
  1552. with self.feature(self.enabled_features):
  1553. response = self.client.get(
  1554. self.url,
  1555. data={
  1556. "start": iso_format(self.day_ago),
  1557. "end": iso_format(self.day_ago + timedelta(hours=2)),
  1558. "interval": "1h",
  1559. "yAxis": "epm()",
  1560. "orderby": ["-count()"],
  1561. "field": ["message", "user.email", "count()"],
  1562. "topEvents": 5,
  1563. },
  1564. format="json",
  1565. )
  1566. data = response.data
  1567. assert response.status_code == 200, response.content
  1568. assert len(data) == 6
  1569. for index, event in enumerate(self.events[:5]):
  1570. message = event.message or event.transaction
  1571. results = data[
  1572. ",".join([message, self.event_data[index]["data"]["user"].get("email", "None")])
  1573. ]
  1574. assert results["order"] == index
  1575. assert [{"count": self.event_data[index]["count"] / (3600.0 / 60.0)}] in [
  1576. attrs for time, attrs in results["data"]
  1577. ]
  1578. other = data["Other"]
  1579. assert other["order"] == 5
  1580. assert [{"count": 0.05}] in [attrs for _, attrs in other["data"]]
  1581. def test_top_events_with_multiple_yaxis(self):
  1582. with self.feature(self.enabled_features):
  1583. response = self.client.get(
  1584. self.url,
  1585. data={
  1586. "start": iso_format(self.day_ago),
  1587. "end": iso_format(self.day_ago + timedelta(hours=2)),
  1588. "interval": "1h",
  1589. "yAxis": ["epm()", "count()"],
  1590. "orderby": ["-count()"],
  1591. "field": ["message", "user.email", "count()"],
  1592. "topEvents": 5,
  1593. },
  1594. format="json",
  1595. )
  1596. data = response.data
  1597. assert response.status_code == 200, response.content
  1598. assert len(data) == 6
  1599. for index, event in enumerate(self.events[:5]):
  1600. message = event.message or event.transaction
  1601. results = data[
  1602. ",".join([message, self.event_data[index]["data"]["user"].get("email", "None")])
  1603. ]
  1604. assert results["order"] == index
  1605. assert results["epm()"]["order"] == 0
  1606. assert results["count()"]["order"] == 1
  1607. assert [{"count": self.event_data[index]["count"] / (3600.0 / 60.0)}] in [
  1608. attrs for time, attrs in results["epm()"]["data"]
  1609. ]
  1610. assert [{"count": self.event_data[index]["count"]}] in [
  1611. attrs for time, attrs in results["count()"]["data"]
  1612. ]
  1613. other = data["Other"]
  1614. assert other["order"] == 5
  1615. assert other["epm()"]["order"] == 0
  1616. assert other["count()"]["order"] == 1
  1617. assert [{"count": 0.05}] in [attrs for _, attrs in other["epm()"]["data"]]
  1618. assert [{"count": 3}] in [attrs for _, attrs in other["count()"]["data"]]
  1619. def test_top_events_with_boolean(self):
  1620. with self.feature(self.enabled_features):
  1621. response = self.client.get(
  1622. self.url,
  1623. data={
  1624. "start": iso_format(self.day_ago),
  1625. "end": iso_format(self.day_ago + timedelta(hours=2)),
  1626. "interval": "1h",
  1627. "yAxis": "count()",
  1628. "orderby": ["-count()"],
  1629. "field": ["count()", "message", "device.charging"],
  1630. "topEvents": 5,
  1631. },
  1632. format="json",
  1633. )
  1634. data = response.data
  1635. assert response.status_code == 200, response.content
  1636. assert len(data) == 6
  1637. for index, event in enumerate(self.events[:5]):
  1638. message = event.message or event.transaction
  1639. results = data[",".join(["False", message])]
  1640. assert results["order"] == index
  1641. assert [{"count": self.event_data[index]["count"]}] in [
  1642. attrs for time, attrs in results["data"]
  1643. ]
  1644. other = data["Other"]
  1645. assert other["order"] == 5
  1646. assert [{"count": 3}] in [attrs for _, attrs in other["data"]]
  1647. def test_top_events_with_error_unhandled(self):
  1648. self.login_as(user=self.user)
  1649. project = self.create_project()
  1650. prototype = load_data("android-ndk")
  1651. prototype["event_id"] = "f" * 32
  1652. prototype["message"] = "not handled"
  1653. prototype["exception"]["values"][0]["value"] = "not handled"
  1654. prototype["exception"]["values"][0]["mechanism"]["handled"] = False
  1655. prototype["timestamp"] = iso_format(self.day_ago + timedelta(minutes=2))
  1656. self.store_event(data=prototype, project_id=project.id)
  1657. with self.feature(self.enabled_features):
  1658. response = self.client.get(
  1659. self.url,
  1660. data={
  1661. "start": iso_format(self.day_ago),
  1662. "end": iso_format(self.day_ago + timedelta(hours=2)),
  1663. "interval": "1h",
  1664. "yAxis": "count()",
  1665. "orderby": ["-count()"],
  1666. "field": ["count()", "error.unhandled"],
  1667. "topEvents": 5,
  1668. },
  1669. format="json",
  1670. )
  1671. data = response.data
  1672. assert response.status_code == 200, response.content
  1673. assert len(data) == 2
  1674. def test_top_events_with_timestamp(self):
  1675. with self.feature(self.enabled_features):
  1676. response = self.client.get(
  1677. self.url,
  1678. data={
  1679. "start": iso_format(self.day_ago),
  1680. "end": iso_format(self.day_ago + timedelta(hours=2)),
  1681. "interval": "1h",
  1682. "yAxis": "count()",
  1683. "orderby": ["-count()"],
  1684. "query": "event.type:default",
  1685. "field": ["count()", "message", "timestamp"],
  1686. "topEvents": 5,
  1687. },
  1688. format="json",
  1689. )
  1690. data = response.data
  1691. assert response.status_code == 200, response.content
  1692. assert len(data) == 6
  1693. # Transactions won't be in the results because of the query
  1694. del self.events[4]
  1695. del self.event_data[4]
  1696. for index, event in enumerate(self.events[:5]):
  1697. results = data[",".join([event.message, event.timestamp])]
  1698. assert results["order"] == index
  1699. assert [{"count": self.event_data[index]["count"]}] in [
  1700. attrs for time, attrs in results["data"]
  1701. ]
  1702. other = data["Other"]
  1703. assert other["order"] == 5
  1704. assert [{"count": 1}] in [attrs for _, attrs in other["data"]]
  1705. def test_top_events_with_int(self):
  1706. with self.feature(self.enabled_features):
  1707. response = self.client.get(
  1708. self.url,
  1709. data={
  1710. "start": iso_format(self.day_ago),
  1711. "end": iso_format(self.day_ago + timedelta(hours=2)),
  1712. "interval": "1h",
  1713. "yAxis": "count()",
  1714. "orderby": ["-count()"],
  1715. "field": ["count()", "message", "transaction.duration"],
  1716. "topEvents": 5,
  1717. },
  1718. format="json",
  1719. )
  1720. data = response.data
  1721. assert response.status_code == 200, response.content
  1722. assert len(data) == 1
  1723. results = data[",".join([self.transaction.transaction, "120000"])]
  1724. assert results["order"] == 0
  1725. assert [attrs for time, attrs in results["data"]] == [[{"count": 3}], [{"count": 0}]]
  1726. def test_top_events_with_user(self):
  1727. with self.feature(self.enabled_features):
  1728. response = self.client.get(
  1729. self.url,
  1730. data={
  1731. "start": iso_format(self.day_ago),
  1732. "end": iso_format(self.day_ago + timedelta(hours=2)),
  1733. "interval": "1h",
  1734. "yAxis": "count()",
  1735. "orderby": ["-count()", "user"],
  1736. "field": ["user", "count()"],
  1737. "topEvents": 5,
  1738. },
  1739. format="json",
  1740. )
  1741. data = response.data
  1742. assert response.status_code == 200, response.content
  1743. assert len(data) == 5
  1744. assert data["email:bar@example.com"]["order"] == 1
  1745. assert [attrs for time, attrs in data["email:bar@example.com"]["data"]] == [
  1746. [{"count": 7}],
  1747. [{"count": 0}],
  1748. ]
  1749. assert [attrs for time, attrs in data["ip:127.0.0.1"]["data"]] == [
  1750. [{"count": 3}],
  1751. [{"count": 0}],
  1752. ]
  1753. def test_top_events_with_user_and_email(self):
  1754. with self.feature(self.enabled_features):
  1755. response = self.client.get(
  1756. self.url,
  1757. data={
  1758. "start": iso_format(self.day_ago),
  1759. "end": iso_format(self.day_ago + timedelta(hours=2)),
  1760. "interval": "1h",
  1761. "yAxis": "count()",
  1762. "orderby": ["-count()", "user"],
  1763. "field": ["user", "user.email", "count()"],
  1764. "topEvents": 5,
  1765. },
  1766. format="json",
  1767. )
  1768. data = response.data
  1769. assert response.status_code == 200, response.content
  1770. assert len(data) == 5
  1771. assert data["email:bar@example.com,bar@example.com"]["order"] == 1
  1772. assert [attrs for time, attrs in data["email:bar@example.com,bar@example.com"]["data"]] == [
  1773. [{"count": 7}],
  1774. [{"count": 0}],
  1775. ]
  1776. assert [attrs for time, attrs in data["ip:127.0.0.1,None"]["data"]] == [
  1777. [{"count": 3}],
  1778. [{"count": 0}],
  1779. ]
  1780. def test_top_events_with_user_display(self):
  1781. with self.feature(self.enabled_features):
  1782. response = self.client.get(
  1783. self.url,
  1784. data={
  1785. "start": iso_format(self.day_ago),
  1786. "end": iso_format(self.day_ago + timedelta(hours=2)),
  1787. "interval": "1h",
  1788. "yAxis": "count()",
  1789. "orderby": ["-count()"],
  1790. "field": ["message", "user.display", "count()"],
  1791. "topEvents": 5,
  1792. },
  1793. format="json",
  1794. )
  1795. data = response.data
  1796. assert response.status_code == 200, response.content
  1797. assert len(data) == 6
  1798. for index, event in enumerate(self.events[:5]):
  1799. message = event.message or event.transaction
  1800. user = self.event_data[index]["data"]["user"]
  1801. results = data[
  1802. ",".join([message, user.get("email", None) or user.get("ip_address", "None")])
  1803. ]
  1804. assert results["order"] == index
  1805. assert [{"count": self.event_data[index]["count"]}] in [
  1806. attrs for _, attrs in results["data"]
  1807. ]
  1808. other = data["Other"]
  1809. assert other["order"] == 5
  1810. assert [{"count": 3}] in [attrs for _, attrs in other["data"]]
  1811. @pytest.mark.skip(reason="A query with group_id will not return transactions")
  1812. def test_top_events_none_filter(self):
  1813. """When a field is None in one of the top events, make sure we filter by it
  1814. In this case event[4] is a transaction and has no issue
  1815. """
  1816. with self.feature(self.enabled_features):
  1817. response = self.client.get(
  1818. self.url,
  1819. data={
  1820. "start": iso_format(self.day_ago),
  1821. "end": iso_format(self.day_ago + timedelta(hours=2)),
  1822. "interval": "1h",
  1823. "yAxis": "count()",
  1824. "orderby": ["-count()"],
  1825. "field": ["count()", "issue"],
  1826. "topEvents": 5,
  1827. },
  1828. format="json",
  1829. )
  1830. data = response.data
  1831. assert response.status_code == 200, response.content
  1832. assert len(data) == 5
  1833. for index, event in enumerate(self.events[:5]):
  1834. if event.group is None:
  1835. issue = "unknown"
  1836. else:
  1837. issue = event.group.qualified_short_id
  1838. results = data[issue]
  1839. assert results["order"] == index
  1840. assert [{"count": self.event_data[index]["count"]}] in [
  1841. attrs for time, attrs in results["data"]
  1842. ]
  1843. @pytest.mark.skip(reason="Invalid query - transaction events don't have group_id field")
  1844. def test_top_events_one_field_with_none(self):
  1845. with self.feature(self.enabled_features):
  1846. response = self.client.get(
  1847. self.url,
  1848. data={
  1849. "start": iso_format(self.day_ago),
  1850. "end": iso_format(self.day_ago + timedelta(hours=2)),
  1851. "interval": "1h",
  1852. "yAxis": "count()",
  1853. "orderby": ["-count()"],
  1854. "query": "event.type:transaction",
  1855. "field": ["count()", "issue"],
  1856. "topEvents": 5,
  1857. },
  1858. format="json",
  1859. )
  1860. data = response.data
  1861. assert response.status_code == 200, response.content
  1862. assert len(data) == 1
  1863. results = data["unknown"]
  1864. assert [attrs for time, attrs in results["data"]] == [[{"count": 3}], [{"count": 0}]]
  1865. assert results["order"] == 0
  1866. def test_top_events_with_error_handled(self):
  1867. data = self.event_data[0]
  1868. data["data"]["level"] = "error"
  1869. data["data"]["exception"] = {
  1870. "values": [
  1871. {
  1872. "type": "ValidationError",
  1873. "value": "Bad request",
  1874. "mechanism": {"handled": True, "type": "generic"},
  1875. }
  1876. ]
  1877. }
  1878. self.store_event(data["data"], project_id=data["project"].id)
  1879. data["data"]["exception"] = {
  1880. "values": [
  1881. {
  1882. "type": "ValidationError",
  1883. "value": "Bad request",
  1884. "mechanism": {"handled": False, "type": "generic"},
  1885. }
  1886. ]
  1887. }
  1888. self.store_event(data["data"], project_id=data["project"].id)
  1889. with self.feature(self.enabled_features):
  1890. response = self.client.get(
  1891. self.url,
  1892. data={
  1893. "start": iso_format(self.day_ago),
  1894. "end": iso_format(self.day_ago + timedelta(hours=2)),
  1895. "interval": "1h",
  1896. "yAxis": "count()",
  1897. "orderby": ["-count()"],
  1898. "field": ["count()", "error.handled"],
  1899. "topEvents": 5,
  1900. "query": "!event.type:transaction",
  1901. },
  1902. format="json",
  1903. )
  1904. assert response.status_code == 200, response.content
  1905. data = response.data
  1906. assert len(data) == 2
  1907. results = data["1"]
  1908. assert [attrs for time, attrs in results["data"]] == [[{"count": 20}], [{"count": 6}]]
  1909. results = data["0"]
  1910. assert [attrs for time, attrs in results["data"]] == [[{"count": 1}], [{"count": 0}]]
  1911. def test_top_events_with_aggregate_condition(self):
  1912. with self.feature(self.enabled_features):
  1913. response = self.client.get(
  1914. self.url,
  1915. data={
  1916. "start": iso_format(self.day_ago),
  1917. "end": iso_format(self.day_ago + timedelta(hours=2)),
  1918. "interval": "1h",
  1919. "yAxis": "count()",
  1920. "orderby": ["-count()"],
  1921. "field": ["message", "count()"],
  1922. "query": "count():>4",
  1923. "topEvents": 5,
  1924. },
  1925. format="json",
  1926. )
  1927. assert response.status_code == 200, response.content
  1928. data = response.data
  1929. assert len(data) == 3
  1930. for index, event in enumerate(self.events[:3]):
  1931. message = event.message or event.transaction
  1932. results = data[message]
  1933. assert results["order"] == index
  1934. assert [{"count": self.event_data[index]["count"]}] in [
  1935. attrs for time, attrs in results["data"]
  1936. ]
  1937. @pytest.mark.xfail(reason="There's only 2 rows total, which mean there shouldn't be other")
  1938. def test_top_events_with_to_other(self):
  1939. version = "version -@'\" 1.2,3+(4)"
  1940. version_escaped = "version -@'\\\" 1.2,3+(4)"
  1941. # every symbol is replaced with a underscore to make the alias
  1942. version_alias = "version_______1_2_3__4_"
  1943. # add an event in the current release
  1944. event = self.event_data[0]
  1945. event_data = event["data"].copy()
  1946. event_data["event_id"] = uuid4().hex
  1947. event_data["release"] = version
  1948. self.store_event(event_data, project_id=event["project"].id)
  1949. with self.feature(self.enabled_features):
  1950. response = self.client.get(
  1951. self.url,
  1952. data={
  1953. "start": iso_format(self.day_ago),
  1954. "end": iso_format(self.day_ago + timedelta(hours=2)),
  1955. "interval": "1h",
  1956. "yAxis": "count()",
  1957. # the double underscores around the version alias is because of a comma and quote
  1958. "orderby": [f"-to_other_release__{version_alias}__others_current"],
  1959. "field": [
  1960. "count()",
  1961. f'to_other(release,"{version_escaped}",others,current)',
  1962. ],
  1963. "topEvents": 2,
  1964. },
  1965. format="json",
  1966. )
  1967. assert response.status_code == 200, response.content
  1968. data = response.data
  1969. assert len(data) == 2
  1970. current = data["current"]
  1971. assert current["order"] == 1
  1972. assert sum(attrs[0]["count"] for _, attrs in current["data"]) == 1
  1973. others = data["others"]
  1974. assert others["order"] == 0
  1975. assert sum(attrs[0]["count"] for _, attrs in others["data"]) == sum(
  1976. event_data["count"] for event_data in self.event_data
  1977. )
  1978. def test_top_events_with_equations(self):
  1979. with self.feature(self.enabled_features):
  1980. response = self.client.get(
  1981. self.url,
  1982. data={
  1983. "start": iso_format(self.day_ago),
  1984. "end": iso_format(self.day_ago + timedelta(hours=2)),
  1985. "interval": "1h",
  1986. "yAxis": "equation|count() / 100",
  1987. "orderby": ["-count()"],
  1988. "field": ["count()", "message", "user.email", "equation|count() / 100"],
  1989. "topEvents": 5,
  1990. },
  1991. format="json",
  1992. )
  1993. data = response.data
  1994. assert response.status_code == 200, response.content
  1995. assert len(data) == 6
  1996. for index, event in enumerate(self.events[:5]):
  1997. message = event.message or event.transaction
  1998. results = data[
  1999. ",".join([message, self.event_data[index]["data"]["user"].get("email", "None")])
  2000. ]
  2001. assert results["order"] == index
  2002. assert [{"count": self.event_data[index]["count"] / 100}] in [
  2003. attrs for time, attrs in results["data"]
  2004. ]
  2005. other = data["Other"]
  2006. assert other["order"] == 5
  2007. assert [{"count": 0.03}] in [attrs for _, attrs in other["data"]]
  2008. @mock.patch("sentry.snuba.discover.bulk_snql_query", return_value=[{"data": [], "meta": []}])
  2009. @mock.patch(
  2010. "sentry.search.events.builder.discover.raw_snql_query",
  2011. return_value={"data": [], "meta": []},
  2012. )
  2013. def test_invalid_interval(self, mock_raw_query, mock_bulk_query):
  2014. with self.feature(self.enabled_features):
  2015. response = self.client.get(
  2016. self.url,
  2017. format="json",
  2018. data={
  2019. "end": iso_format(before_now()),
  2020. # 7,200 points for each event
  2021. "start": iso_format(before_now(seconds=7200)),
  2022. "field": ["count()", "issue"],
  2023. "query": "",
  2024. "interval": "1s",
  2025. "yAxis": "count()",
  2026. },
  2027. )
  2028. assert response.status_code == 200
  2029. assert mock_bulk_query.call_count == 1
  2030. with self.feature(self.enabled_features):
  2031. response = self.client.get(
  2032. self.url,
  2033. format="json",
  2034. data={
  2035. "end": iso_format(before_now()),
  2036. "start": iso_format(before_now(seconds=7200)),
  2037. "field": ["count()", "issue"],
  2038. "query": "",
  2039. "interval": "1s",
  2040. "yAxis": "count()",
  2041. # 7,200 points for each event * 2, should error
  2042. "topEvents": 2,
  2043. },
  2044. )
  2045. assert response.status_code == 200
  2046. assert mock_raw_query.call_count == 2
  2047. # Should've reset to the default for between 1 and 24h
  2048. assert mock_raw_query.mock_calls[1].args[0].query.granularity.granularity == 300
  2049. with self.feature(self.enabled_features):
  2050. response = self.client.get(
  2051. self.url,
  2052. format="json",
  2053. data={
  2054. "end": iso_format(before_now()),
  2055. # 1999 points * 5 events should just be enough to not error
  2056. "start": iso_format(before_now(seconds=1999)),
  2057. "field": ["count()", "issue"],
  2058. "query": "",
  2059. "interval": "1s",
  2060. "yAxis": "count()",
  2061. "topEvents": 5,
  2062. },
  2063. )
  2064. assert response.status_code == 200
  2065. assert mock_raw_query.call_count == 4
  2066. # Should've left the interval alone since we're just below the limit
  2067. assert mock_raw_query.mock_calls[3].args[0].query.granularity.granularity == 1
  2068. with self.feature(self.enabled_features):
  2069. response = self.client.get(
  2070. self.url,
  2071. format="json",
  2072. data={
  2073. "end": iso_format(before_now()),
  2074. "start": iso_format(before_now(hours=24)),
  2075. "field": ["count()", "issue"],
  2076. "query": "",
  2077. "interval": "0d",
  2078. "yAxis": "count()",
  2079. "topEvents": 5,
  2080. },
  2081. )
  2082. assert response.status_code == 200
  2083. assert mock_raw_query.call_count == 6
  2084. # Should've default to 24h's default of 5m
  2085. assert mock_raw_query.mock_calls[5].args[0].query.granularity.granularity == 300
  2086. def test_top_events_timestamp_fields(self):
  2087. with self.feature(self.enabled_features):
  2088. response = self.client.get(
  2089. self.url,
  2090. format="json",
  2091. data={
  2092. "start": iso_format(self.day_ago),
  2093. "end": iso_format(self.day_ago + timedelta(hours=2)),
  2094. "interval": "1h",
  2095. "yAxis": "count()",
  2096. "orderby": ["-count()"],
  2097. "field": ["count()", "timestamp", "timestamp.to_hour", "timestamp.to_day"],
  2098. "topEvents": 5,
  2099. },
  2100. )
  2101. assert response.status_code == 200
  2102. data = response.data
  2103. assert len(data) == 3
  2104. # these are the timestamps corresponding to the events stored
  2105. timestamps = [
  2106. self.day_ago + timedelta(minutes=2),
  2107. self.day_ago + timedelta(hours=1, minutes=2),
  2108. self.day_ago + timedelta(minutes=4),
  2109. ]
  2110. timestamp_hours = [timestamp.replace(minute=0, second=0) for timestamp in timestamps]
  2111. timestamp_days = [timestamp.replace(hour=0, minute=0, second=0) for timestamp in timestamps]
  2112. for ts, ts_hr, ts_day in zip(timestamps, timestamp_hours, timestamp_days):
  2113. key = f"{iso_format(ts)}+00:00,{iso_format(ts_day)}+00:00,{iso_format(ts_hr)}+00:00"
  2114. count = sum(
  2115. e["count"] for e in self.event_data if e["data"]["timestamp"] == iso_format(ts)
  2116. )
  2117. results = data[key]
  2118. assert [{"count": count}] in [attrs for time, attrs in results["data"]]
  2119. def test_top_events_other_with_matching_columns(self):
  2120. with self.feature(self.enabled_features):
  2121. response = self.client.get(
  2122. self.url,
  2123. data={
  2124. "start": iso_format(self.day_ago),
  2125. "end": iso_format(self.day_ago + timedelta(hours=2)),
  2126. "interval": "1h",
  2127. "yAxis": "count()",
  2128. "orderby": ["-count()"],
  2129. "field": ["count()", "tags[shared-tag]", "message"],
  2130. "topEvents": 5,
  2131. },
  2132. format="json",
  2133. )
  2134. data = response.data
  2135. assert response.status_code == 200, response.content
  2136. assert len(data) == 6
  2137. for index, event in enumerate(self.events[:5]):
  2138. message = event.message or event.transaction
  2139. results = data[",".join([message, "yup"])]
  2140. assert results["order"] == index
  2141. assert [{"count": self.event_data[index]["count"]}] in [
  2142. attrs for _, attrs in results["data"]
  2143. ]
  2144. other = data["Other"]
  2145. assert other["order"] == 5
  2146. assert [{"count": 3}] in [attrs for _, attrs in other["data"]]
  2147. def test_top_events_with_field_overlapping_other_key(self):
  2148. transaction_data = load_data("transaction")
  2149. transaction_data["start_timestamp"] = iso_format(self.day_ago + timedelta(minutes=2))
  2150. transaction_data["timestamp"] = iso_format(self.day_ago + timedelta(minutes=6))
  2151. transaction_data["transaction"] = OTHER_KEY
  2152. for i in range(5):
  2153. data = transaction_data.copy()
  2154. data["event_id"] = "ab" + f"{i}" * 30
  2155. data["contexts"]["trace"]["span_id"] = "ab" + f"{i}" * 14
  2156. self.store_event(data, project_id=self.project.id)
  2157. with self.feature(self.enabled_features):
  2158. response = self.client.get(
  2159. self.url,
  2160. data={
  2161. "start": iso_format(self.day_ago),
  2162. "end": iso_format(self.day_ago + timedelta(hours=2)),
  2163. "interval": "1h",
  2164. "yAxis": "count()",
  2165. "orderby": ["-count()"],
  2166. "field": ["count()", "message"],
  2167. "topEvents": 5,
  2168. },
  2169. format="json",
  2170. )
  2171. data = response.data
  2172. assert response.status_code == 200, response.content
  2173. assert len(data) == 6
  2174. assert f"{OTHER_KEY} (message)" in data
  2175. results = data[f"{OTHER_KEY} (message)"]
  2176. assert [{"count": 5}] in [attrs for _, attrs in results["data"]]
  2177. other = data["Other"]
  2178. assert other["order"] == 5
  2179. assert [{"count": 4}] in [attrs for _, attrs in other["data"]]
  2180. def test_top_events_can_exclude_other_series(self):
  2181. with self.feature(self.enabled_features):
  2182. response = self.client.get(
  2183. self.url,
  2184. data={
  2185. "start": iso_format(self.day_ago),
  2186. "end": iso_format(self.day_ago + timedelta(hours=2)),
  2187. "interval": "1h",
  2188. "yAxis": "count()",
  2189. "orderby": ["count()"],
  2190. "field": ["count()", "message"],
  2191. "topEvents": 5,
  2192. "excludeOther": "1",
  2193. },
  2194. format="json",
  2195. )
  2196. data = response.data
  2197. assert response.status_code == 200, response.content
  2198. assert len(data) == 5
  2199. assert "Other" not in response.data
  2200. def test_top_events_with_equation_including_unselected_fields_passes_field_validation(self):
  2201. with self.feature(self.enabled_features):
  2202. response = self.client.get(
  2203. self.url,
  2204. data={
  2205. "start": iso_format(self.day_ago),
  2206. "end": iso_format(self.day_ago + timedelta(hours=2)),
  2207. "interval": "1h",
  2208. "yAxis": "count()",
  2209. "orderby": ["-equation[0]"],
  2210. "field": ["count()", "message", "equation|count_unique(user) * 2"],
  2211. "topEvents": 5,
  2212. },
  2213. format="json",
  2214. )
  2215. data = response.data
  2216. assert response.status_code == 200, response.content
  2217. assert len(data) == 6
  2218. other = data["Other"]
  2219. assert other["order"] == 5
  2220. assert [{"count": 4}] in [attrs for _, attrs in other["data"]]
  2221. def test_top_events_boolean_condition_and_project_field(self):
  2222. with self.feature(self.enabled_features):
  2223. response = self.client.get(
  2224. self.url,
  2225. data={
  2226. "start": iso_format(self.day_ago),
  2227. "end": iso_format(self.day_ago + timedelta(hours=2)),
  2228. "interval": "1h",
  2229. "yAxis": "count()",
  2230. "orderby": ["-count()"],
  2231. "field": ["project", "count()"],
  2232. "topEvents": 5,
  2233. "query": "event.type:transaction (transaction:*a OR transaction:b*)",
  2234. },
  2235. format="json",
  2236. )
  2237. assert response.status_code == 200