test_organization_events_stats.py 93 KB

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