test_organization_events_stats.py 83 KB

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