test_organization_events_stats.py 121 KB

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