test_organization_events_stats.py 104 KB

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