test_organization_events_stats.py 122 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276
  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_eps_equation(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": ["equation|eps() * 2"],
  692. },
  693. )
  694. assert response.status_code == 200, response.content
  695. assert len(response.data["data"]) == 2
  696. assert pytest.approx(0.000556, abs=0.0001) == response.data["data"][0][1][0]["count"]
  697. assert pytest.approx(0.001112, abs=0.0001) == response.data["data"][1][1][0]["count"]
  698. def test_epm_equation(self):
  699. response = self.do_request(
  700. data={
  701. "start": self.day_ago,
  702. "end": self.day_ago + timedelta(hours=2),
  703. "interval": "1h",
  704. "yAxis": ["equation|epm() * 2"],
  705. },
  706. )
  707. assert response.status_code == 200, response.content
  708. assert len(response.data["data"]) == 2
  709. assert pytest.approx(0.03334, abs=0.01) == response.data["data"][0][1][0]["count"]
  710. assert pytest.approx(0.06667, abs=0.01) == response.data["data"][1][1][0]["count"]
  711. def test_equation_mixed_multi_yaxis(self):
  712. response = self.do_request(
  713. data={
  714. "start": self.day_ago,
  715. "end": self.day_ago + timedelta(hours=2),
  716. "interval": "1h",
  717. "yAxis": ["count()", "equation|count() * 100"],
  718. },
  719. )
  720. assert response.status_code == 200, response.content
  721. assert response.data["count()"]["order"] == 0
  722. assert [attrs for time, attrs in response.data["count()"]["data"]] == [
  723. [{"count": 1}],
  724. [{"count": 2}],
  725. ]
  726. assert response.data["equation|count() * 100"]["order"] == 1
  727. assert [attrs for time, attrs in response.data["equation|count() * 100"]["data"]] == [
  728. [{"count": 100}],
  729. [{"count": 200}],
  730. ]
  731. def test_equation_multi_yaxis(self):
  732. response = self.do_request(
  733. data={
  734. "start": self.day_ago,
  735. "end": self.day_ago + timedelta(hours=2),
  736. "interval": "1h",
  737. "yAxis": ["equation|count() / 100", "equation|count() * 100"],
  738. },
  739. )
  740. assert response.status_code == 200, response.content
  741. assert response.data["equation|count() / 100"]["order"] == 0
  742. assert [attrs for time, attrs in response.data["equation|count() / 100"]["data"]] == [
  743. [{"count": 0.01}],
  744. [{"count": 0.02}],
  745. ]
  746. assert response.data["equation|count() * 100"]["order"] == 1
  747. assert [attrs for time, attrs in response.data["equation|count() * 100"]["data"]] == [
  748. [{"count": 100}],
  749. [{"count": 200}],
  750. ]
  751. def test_large_interval_no_drop_values(self):
  752. self.store_event(
  753. data={
  754. "event_id": "d" * 32,
  755. "message": "not good",
  756. "timestamp": iso_format(self.day_ago - timedelta(minutes=10)),
  757. "fingerprint": ["group3"],
  758. },
  759. project_id=self.project.id,
  760. )
  761. response = self.do_request(
  762. data={
  763. "project": self.project.id,
  764. "end": self.day_ago,
  765. "start": self.day_ago - timedelta(hours=24),
  766. "query": 'message:"not good"',
  767. "interval": "1d",
  768. "yAxis": "count()",
  769. },
  770. )
  771. assert response.status_code == 200
  772. assert [attrs for time, attrs in response.data["data"]] == [[{"count": 0}], [{"count": 1}]]
  773. @mock.patch("sentry.snuba.discover.timeseries_query", return_value={})
  774. def test_multiple_yaxis_only_one_query(self, mock_query):
  775. self.do_request(
  776. data={
  777. "project": self.project.id,
  778. "start": self.day_ago,
  779. "end": self.day_ago + timedelta(hours=2),
  780. "interval": "1h",
  781. "yAxis": ["user_count", "event_count", "epm()", "eps()"],
  782. },
  783. )
  784. assert mock_query.call_count == 1
  785. @mock.patch("sentry.snuba.discover.bulk_snuba_queries", return_value=[{"data": []}])
  786. def test_invalid_interval(self, mock_query):
  787. self.do_request(
  788. data={
  789. "end": before_now(),
  790. "start": before_now(hours=24),
  791. "query": "",
  792. "interval": "1s",
  793. "yAxis": "count()",
  794. },
  795. )
  796. assert mock_query.call_count == 1
  797. # Should've reset to the default for 24h
  798. assert mock_query.mock_calls[0].args[0][0].query.granularity.granularity == 300
  799. self.do_request(
  800. data={
  801. "end": before_now(),
  802. "start": before_now(hours=24),
  803. "query": "",
  804. "interval": "0d",
  805. "yAxis": "count()",
  806. },
  807. )
  808. assert mock_query.call_count == 2
  809. # Should've reset to the default for 24h
  810. assert mock_query.mock_calls[1].args[0][0].query.granularity.granularity == 300
  811. def test_out_of_retention(self):
  812. with self.options({"system.event-retention-days": 10}):
  813. response = self.do_request(
  814. data={
  815. "start": before_now(days=20),
  816. "end": before_now(days=15),
  817. "query": "",
  818. "interval": "30m",
  819. "yAxis": "count()",
  820. },
  821. )
  822. assert response.status_code == 400
  823. @mock.patch("sentry.utils.snuba.quantize_time")
  824. def test_quantize_dates(self, mock_quantize):
  825. mock_quantize.return_value = before_now(days=1)
  826. # Don't quantize short time periods
  827. self.do_request(
  828. data={"statsPeriod": "1h", "query": "", "interval": "30m", "yAxis": "count()"},
  829. )
  830. # Don't quantize absolute date periods
  831. self.do_request(
  832. data={
  833. "start": before_now(days=20),
  834. "end": before_now(days=15),
  835. "query": "",
  836. "interval": "30m",
  837. "yAxis": "count()",
  838. },
  839. )
  840. assert len(mock_quantize.mock_calls) == 0
  841. # Quantize long date periods
  842. self.do_request(
  843. data={"statsPeriod": "90d", "query": "", "interval": "30m", "yAxis": "count()"},
  844. )
  845. assert len(mock_quantize.mock_calls) == 2
  846. def test_with_zerofill(self):
  847. response = self.do_request(
  848. data={
  849. "start": self.day_ago,
  850. "end": self.day_ago + timedelta(hours=2),
  851. "interval": "30m",
  852. },
  853. )
  854. assert response.status_code == 200, response.content
  855. assert [attrs for time, attrs in response.data["data"]] == [
  856. [{"count": 1}],
  857. [{"count": 0}],
  858. [{"count": 2}],
  859. [{"count": 0}],
  860. ]
  861. def test_without_zerofill(self):
  862. start = iso_format(self.day_ago)
  863. end = iso_format(self.day_ago + timedelta(hours=2))
  864. response = self.do_request(
  865. data={
  866. "start": start,
  867. "end": end,
  868. "interval": "30m",
  869. "withoutZerofill": "1",
  870. },
  871. features={
  872. "organizations:performance-chart-interpolation": True,
  873. "organizations:discover-basic": True,
  874. },
  875. )
  876. assert response.status_code == 200, response.content
  877. assert [attrs for time, attrs in response.data["data"]] == [
  878. [{"count": 1}],
  879. [{"count": 2}],
  880. ]
  881. assert response.data["start"] == parse_date(start).timestamp()
  882. assert response.data["end"] == parse_date(end).timestamp()
  883. def test_comparison_error_dataset(self):
  884. self.store_event(
  885. data={
  886. "timestamp": iso_format(self.day_ago + timedelta(days=-1, minutes=1)),
  887. },
  888. project_id=self.project.id,
  889. )
  890. self.store_event(
  891. data={
  892. "timestamp": iso_format(self.day_ago + timedelta(days=-1, minutes=2)),
  893. },
  894. project_id=self.project.id,
  895. )
  896. self.store_event(
  897. data={
  898. "timestamp": iso_format(self.day_ago + timedelta(days=-1, hours=1, minutes=1)),
  899. },
  900. project_id=self.project2.id,
  901. )
  902. response = self.do_request(
  903. data={
  904. "start": self.day_ago,
  905. "end": self.day_ago + timedelta(hours=2),
  906. "interval": "1h",
  907. "comparisonDelta": int(timedelta(days=1).total_seconds()),
  908. "dataset": "errors",
  909. }
  910. )
  911. assert response.status_code == 200, response.content
  912. assert [attrs for time, attrs in response.data["data"]] == [
  913. [{"count": 1, "comparisonCount": 2}],
  914. [{"count": 2, "comparisonCount": 1}],
  915. ]
  916. def test_comparison(self):
  917. self.store_event(
  918. data={
  919. "timestamp": iso_format(self.day_ago + timedelta(days=-1, minutes=1)),
  920. },
  921. project_id=self.project.id,
  922. )
  923. self.store_event(
  924. data={
  925. "timestamp": iso_format(self.day_ago + timedelta(days=-1, minutes=2)),
  926. },
  927. project_id=self.project.id,
  928. )
  929. self.store_event(
  930. data={
  931. "timestamp": iso_format(self.day_ago + timedelta(days=-1, hours=1, minutes=1)),
  932. },
  933. project_id=self.project2.id,
  934. )
  935. response = self.do_request(
  936. data={
  937. "start": self.day_ago,
  938. "end": self.day_ago + timedelta(hours=2),
  939. "interval": "1h",
  940. "comparisonDelta": int(timedelta(days=1).total_seconds()),
  941. }
  942. )
  943. assert response.status_code == 200, response.content
  944. assert [attrs for time, attrs in response.data["data"]] == [
  945. [{"count": 1, "comparisonCount": 2}],
  946. [{"count": 2, "comparisonCount": 1}],
  947. ]
  948. def test_comparison_invalid(self):
  949. response = self.do_request(
  950. data={
  951. "start": self.day_ago,
  952. "end": self.day_ago + timedelta(hours=2),
  953. "interval": "1h",
  954. "comparisonDelta": "17h",
  955. },
  956. )
  957. assert response.status_code == 400, response.content
  958. assert response.data["detail"] == "comparisonDelta must be an integer"
  959. start = before_now(days=85)
  960. end = start + timedelta(days=7)
  961. with self.options({"system.event-retention-days": 90}):
  962. response = self.do_request(
  963. data={
  964. "start": start,
  965. "end": end,
  966. "interval": "1h",
  967. "comparisonDelta": int(timedelta(days=7).total_seconds()),
  968. }
  969. )
  970. assert response.status_code == 400, response.content
  971. assert response.data["detail"] == "Comparison period is outside retention window"
  972. def test_equations_divide_by_zero(self):
  973. response = self.do_request(
  974. data={
  975. "start": self.day_ago,
  976. "end": self.day_ago + timedelta(hours=2),
  977. "interval": "1h",
  978. # force a 0 in the denominator by doing 1 - 1
  979. # since a 0 literal is illegal as the denominator
  980. "yAxis": ["equation|count() / (1-1)"],
  981. },
  982. )
  983. assert response.status_code == 200, response.content
  984. assert len(response.data["data"]) == 2
  985. assert [attrs for time, attrs in response.data["data"]] == [
  986. [{"count": None}],
  987. [{"count": None}],
  988. ]
  989. @mock.patch("sentry.search.events.builder.base.raw_snql_query")
  990. def test_profiles_dataset_simple(self, mock_snql_query):
  991. mock_snql_query.side_effect = [{"meta": {}, "data": []}]
  992. query = {
  993. "yAxis": [
  994. "count()",
  995. "p75()",
  996. "p95()",
  997. "p99()",
  998. "p75(profile.duration)",
  999. "p95(profile.duration)",
  1000. "p99(profile.duration)",
  1001. ],
  1002. "project": [self.project.id],
  1003. "dataset": "profiles",
  1004. }
  1005. response = self.do_request(query, features={"organizations:profiling": True})
  1006. assert response.status_code == 200, response.content
  1007. def test_tag_with_conflicting_function_alias_simple(self):
  1008. for _ in range(7):
  1009. self.store_event(
  1010. data={
  1011. "timestamp": iso_format(self.day_ago + timedelta(minutes=2)),
  1012. "tags": {"count": "9001"},
  1013. },
  1014. project_id=self.project2.id,
  1015. )
  1016. # Query for count and count()
  1017. data = {
  1018. "start": self.day_ago.isoformat(),
  1019. "end": (self.day_ago + timedelta(minutes=3)).isoformat(),
  1020. "interval": "1h",
  1021. "yAxis": "count()",
  1022. "orderby": ["-count()"],
  1023. "field": ["count()", "count"],
  1024. "partial": "1",
  1025. }
  1026. response = self.client.get(self.url, data, format="json")
  1027. assert response.status_code == 200
  1028. # Expect a count of 8 because one event from setUp
  1029. assert response.data["data"][0][1] == [{"count": 8}]
  1030. data["query"] = "count:9001"
  1031. response = self.client.get(self.url, data, format="json")
  1032. assert response.status_code == 200
  1033. assert response.data["data"][0][1] == [{"count": 7}]
  1034. data["query"] = "count:abc"
  1035. response = self.client.get(self.url, data, format="json")
  1036. assert response.status_code == 200
  1037. assert all([interval[1][0]["count"] == 0 for interval in response.data["data"]])
  1038. def test_group_id_tag_simple(self):
  1039. event_data: _EventDataDict = {
  1040. "data": {
  1041. "message": "poof",
  1042. "timestamp": iso_format(self.day_ago + timedelta(minutes=2)),
  1043. "user": {"email": self.user.email},
  1044. "tags": {"group_id": "testing"},
  1045. "fingerprint": ["group1"],
  1046. },
  1047. "project": self.project2,
  1048. "count": 7,
  1049. }
  1050. for i in range(event_data["count"]):
  1051. event_data["data"]["event_id"] = f"a{i}" * 16
  1052. self.store_event(event_data["data"], project_id=event_data["project"].id)
  1053. data = {
  1054. "start": self.day_ago.isoformat(),
  1055. "end": (self.day_ago + timedelta(hours=2)).isoformat(),
  1056. "interval": "1h",
  1057. "yAxis": "count()",
  1058. "orderby": ["-count()"],
  1059. "field": ["count()", "group_id"],
  1060. "partial": "1",
  1061. }
  1062. response = self.client.get(self.url, data, format="json")
  1063. assert response.status_code == 200
  1064. assert response.data["data"][0][1] == [{"count": 8}]
  1065. data["query"] = "group_id:testing"
  1066. response = self.client.get(self.url, data, format="json")
  1067. assert response.status_code == 200
  1068. assert response.data["data"][0][1] == [{"count": 7}]
  1069. data["query"] = "group_id:abc"
  1070. response = self.client.get(self.url, data, format="json")
  1071. assert response.status_code == 200
  1072. assert all([interval[1][0]["count"] == 0 for interval in response.data["data"]])
  1073. class OrganizationEventsStatsTopNEvents(APITestCase, SnubaTestCase):
  1074. def setUp(self):
  1075. super().setUp()
  1076. self.login_as(user=self.user)
  1077. self.day_ago = before_now(days=1).replace(hour=10, minute=0, second=0, microsecond=0)
  1078. self.project = self.create_project()
  1079. self.project2 = self.create_project()
  1080. self.user2 = self.create_user()
  1081. transaction_data = load_data("transaction")
  1082. transaction_data["start_timestamp"] = iso_format(self.day_ago + timedelta(minutes=2))
  1083. transaction_data["timestamp"] = iso_format(self.day_ago + timedelta(minutes=4))
  1084. transaction_data["tags"] = {"shared-tag": "yup"}
  1085. self.event_data: list[_EventDataDict] = [
  1086. {
  1087. "data": {
  1088. "message": "poof",
  1089. "timestamp": iso_format(self.day_ago + timedelta(minutes=2)),
  1090. "user": {"email": self.user.email},
  1091. "tags": {"shared-tag": "yup"},
  1092. "fingerprint": ["group1"],
  1093. },
  1094. "project": self.project2,
  1095. "count": 7,
  1096. },
  1097. {
  1098. "data": {
  1099. "message": "voof",
  1100. "timestamp": iso_format(self.day_ago + timedelta(hours=1, minutes=2)),
  1101. "fingerprint": ["group2"],
  1102. "user": {"email": self.user2.email},
  1103. "tags": {"shared-tag": "yup"},
  1104. },
  1105. "project": self.project2,
  1106. "count": 6,
  1107. },
  1108. {
  1109. "data": {
  1110. "message": "very bad",
  1111. "timestamp": iso_format(self.day_ago + timedelta(minutes=2)),
  1112. "fingerprint": ["group3"],
  1113. "user": {"email": "foo@example.com"},
  1114. "tags": {"shared-tag": "yup"},
  1115. },
  1116. "project": self.project,
  1117. "count": 5,
  1118. },
  1119. {
  1120. "data": {
  1121. "message": "oh no",
  1122. "timestamp": iso_format(self.day_ago + timedelta(minutes=2)),
  1123. "fingerprint": ["group4"],
  1124. "user": {"email": "bar@example.com"},
  1125. "tags": {"shared-tag": "yup"},
  1126. },
  1127. "project": self.project,
  1128. "count": 4,
  1129. },
  1130. {"data": transaction_data, "project": self.project, "count": 3},
  1131. # Not in the top 5
  1132. {
  1133. "data": {
  1134. "message": "sorta bad",
  1135. "timestamp": iso_format(self.day_ago + timedelta(minutes=2)),
  1136. "fingerprint": ["group5"],
  1137. "user": {"email": "bar@example.com"},
  1138. "tags": {"shared-tag": "yup"},
  1139. },
  1140. "project": self.project,
  1141. "count": 2,
  1142. },
  1143. {
  1144. "data": {
  1145. "message": "not so bad",
  1146. "timestamp": iso_format(self.day_ago + timedelta(minutes=2)),
  1147. "fingerprint": ["group6"],
  1148. "user": {"email": "bar@example.com"},
  1149. "tags": {"shared-tag": "yup"},
  1150. },
  1151. "project": self.project,
  1152. "count": 1,
  1153. },
  1154. ]
  1155. self.events = []
  1156. for index, event_data in enumerate(self.event_data):
  1157. data = event_data["data"].copy()
  1158. for i in range(event_data["count"]):
  1159. data["event_id"] = f"{index}{i}" * 16
  1160. event = self.store_event(data, project_id=event_data["project"].id)
  1161. self.events.append(event)
  1162. self.transaction = self.events[4]
  1163. self.enabled_features = {
  1164. "organizations:discover-basic": True,
  1165. }
  1166. self.url = reverse(
  1167. "sentry-api-0-organization-events-stats",
  1168. kwargs={"organization_id_or_slug": self.project.organization.slug},
  1169. )
  1170. def test_no_top_events_with_project_field(self):
  1171. project = self.create_project()
  1172. with self.feature(self.enabled_features):
  1173. response = self.client.get(
  1174. self.url,
  1175. data={
  1176. # make sure to query the project with 0 events
  1177. "project": str(project.id),
  1178. "start": self.day_ago.isoformat(),
  1179. "end": (self.day_ago + timedelta(hours=2)).isoformat(),
  1180. "interval": "1h",
  1181. "yAxis": "count()",
  1182. "orderby": ["-count()"],
  1183. "field": ["count()", "project"],
  1184. "topEvents": "5",
  1185. },
  1186. format="json",
  1187. )
  1188. assert response.status_code == 200, response.content
  1189. # When there are no top events, we do not return an empty dict.
  1190. # Instead, we return a single zero-filled series for an empty graph.
  1191. data = response.data["data"]
  1192. assert [attrs for time, attrs in data] == [[{"count": 0}], [{"count": 0}]]
  1193. def test_no_top_events(self):
  1194. project = self.create_project()
  1195. with self.feature(self.enabled_features):
  1196. response = self.client.get(
  1197. self.url,
  1198. data={
  1199. # make sure to query the project with 0 events
  1200. "project": str(project.id),
  1201. "start": self.day_ago.isoformat(),
  1202. "end": (self.day_ago + timedelta(hours=2)).isoformat(),
  1203. "interval": "1h",
  1204. "yAxis": "count()",
  1205. "orderby": ["-count()"],
  1206. "field": ["count()", "message", "user.email"],
  1207. "topEvents": "5",
  1208. },
  1209. format="json",
  1210. )
  1211. data = response.data["data"]
  1212. assert response.status_code == 200, response.content
  1213. # When there are no top events, we do not return an empty dict.
  1214. # Instead, we return a single zero-filled series for an empty graph.
  1215. assert [attrs for time, attrs in data] == [[{"count": 0}], [{"count": 0}]]
  1216. def test_no_top_events_with_multi_axis(self):
  1217. project = self.create_project()
  1218. with self.feature(self.enabled_features):
  1219. response = self.client.get(
  1220. self.url,
  1221. data={
  1222. # make sure to query the project with 0 events
  1223. "project": str(project.id),
  1224. "start": self.day_ago.isoformat(),
  1225. "end": (self.day_ago + timedelta(hours=2)).isoformat(),
  1226. "interval": "1h",
  1227. "yAxis": ["count()", "count_unique(user)"],
  1228. "orderby": ["-count()"],
  1229. "field": ["count()", "count_unique(user)", "message", "user.email"],
  1230. "topEvents": "5",
  1231. },
  1232. format="json",
  1233. )
  1234. assert response.status_code == 200
  1235. data = response.data[""]
  1236. assert [attrs for time, attrs in data["count()"]["data"]] == [
  1237. [{"count": 0}],
  1238. [{"count": 0}],
  1239. ]
  1240. assert [attrs for time, attrs in data["count_unique(user)"]["data"]] == [
  1241. [{"count": 0}],
  1242. [{"count": 0}],
  1243. ]
  1244. def test_simple_top_events(self):
  1245. with self.feature(self.enabled_features):
  1246. response = self.client.get(
  1247. self.url,
  1248. data={
  1249. "start": self.day_ago.isoformat(),
  1250. "end": (self.day_ago + timedelta(hours=2)).isoformat(),
  1251. "interval": "1h",
  1252. "yAxis": "count()",
  1253. "orderby": ["-count()"],
  1254. "field": ["count()", "message", "user.email"],
  1255. "topEvents": "5",
  1256. },
  1257. format="json",
  1258. )
  1259. data = response.data
  1260. assert response.status_code == 200, response.content
  1261. assert len(data) == 6
  1262. for index, event in enumerate(self.events[:5]):
  1263. message = event.message or event.transaction
  1264. results = data[
  1265. ",".join([message, self.event_data[index]["data"]["user"].get("email", "None")])
  1266. ]
  1267. assert results["order"] == index
  1268. assert [{"count": self.event_data[index]["count"]}] in [
  1269. attrs for _, attrs in results["data"]
  1270. ]
  1271. other = data["Other"]
  1272. assert other["order"] == 5
  1273. assert [{"count": 3}] in [attrs for _, attrs in other["data"]]
  1274. def test_top_events_with_projects_other(self):
  1275. with self.feature(self.enabled_features):
  1276. response = self.client.get(
  1277. self.url,
  1278. data={
  1279. "start": self.day_ago.isoformat(),
  1280. "end": (self.day_ago + timedelta(hours=2)).isoformat(),
  1281. "interval": "1h",
  1282. "yAxis": "count()",
  1283. "orderby": ["-count()"],
  1284. "field": ["count()", "project"],
  1285. "topEvents": "1",
  1286. },
  1287. format="json",
  1288. )
  1289. data = response.data
  1290. assert response.status_code == 200, response.content
  1291. assert set(data.keys()) == {"Other", self.project.slug}
  1292. assert data[self.project.slug]["order"] == 0
  1293. assert [attrs[0]["count"] for _, attrs in data[self.project.slug]["data"]] == [15, 0]
  1294. assert data["Other"]["order"] == 1
  1295. assert [attrs[0]["count"] for _, attrs in data["Other"]["data"]] == [7, 6]
  1296. def test_top_events_with_projects_fields(self):
  1297. # We need to handle the project name fields differently
  1298. for project_field in ["project", "project.name"]:
  1299. with self.feature(self.enabled_features):
  1300. response = self.client.get(
  1301. self.url,
  1302. data={
  1303. "start": self.day_ago.isoformat(),
  1304. "end": (self.day_ago + timedelta(hours=2)).isoformat(),
  1305. "interval": "1h",
  1306. "yAxis": "count()",
  1307. "orderby": ["-count()"],
  1308. "field": ["count()", project_field],
  1309. "topEvents": "5",
  1310. },
  1311. format="json",
  1312. )
  1313. data = response.data
  1314. assert response.status_code == 200, response.content
  1315. assert data[self.project.slug]["order"] == 0, project_field
  1316. assert [attrs[0]["count"] for _, attrs in data[self.project.slug]["data"]] == [
  1317. 15,
  1318. 0,
  1319. ], project_field
  1320. assert data[self.project2.slug]["order"] == 1, project_field
  1321. assert [attrs[0]["count"] for _, attrs in data[self.project2.slug]["data"]] == [
  1322. 7,
  1323. 6,
  1324. ], project_field
  1325. def test_tag_with_conflicting_function_alias_simple(self):
  1326. event_data: _EventDataDict = {
  1327. "data": {
  1328. "message": "poof",
  1329. "timestamp": iso_format(self.day_ago + timedelta(minutes=2)),
  1330. "user": {"email": self.user.email},
  1331. "tags": {"count": "9001"},
  1332. "fingerprint": ["group1"],
  1333. },
  1334. "project": self.project2,
  1335. "count": 7,
  1336. }
  1337. for i in range(event_data["count"]):
  1338. event_data["data"]["event_id"] = f"a{i}" * 16
  1339. self.store_event(event_data["data"], project_id=event_data["project"].id)
  1340. # Query for count and count()
  1341. data = {
  1342. "start": self.day_ago.isoformat(),
  1343. "end": (self.day_ago + timedelta(hours=2)).isoformat(),
  1344. "interval": "1h",
  1345. "yAxis": "count()",
  1346. "orderby": ["-count()"],
  1347. "field": ["count()", "count"],
  1348. "topEvents": "5",
  1349. "partial": "1",
  1350. }
  1351. with self.feature(self.enabled_features):
  1352. response = self.client.get(self.url, data, format="json")
  1353. assert response.status_code == 200
  1354. assert response.data["9001"]["data"][0][1] == [{"count": 7}]
  1355. data["query"] = "count:9001"
  1356. with self.feature(self.enabled_features):
  1357. response = self.client.get(self.url, data, format="json")
  1358. assert response.status_code == 200
  1359. assert response.data["9001"]["data"][0][1] == [{"count": 7}]
  1360. data["query"] = "count:abc"
  1361. with self.feature(self.enabled_features):
  1362. response = self.client.get(self.url, data, format="json")
  1363. assert response.status_code == 200
  1364. assert all([interval[1][0]["count"] == 0 for interval in response.data["data"]])
  1365. @pytest.mark.xfail(
  1366. reason="The response.data[Other] returns 15 locally and returns 16 or 15 remotely."
  1367. )
  1368. def test_tag_with_conflicting_function_alias_with_other_single_grouping(self):
  1369. event_data: list[_EventDataDict] = [
  1370. {
  1371. "data": {
  1372. "message": "poof",
  1373. "timestamp": self.day_ago + timedelta(minutes=2),
  1374. "user": {"email": self.user.email},
  1375. "tags": {"count": "9001"},
  1376. "fingerprint": ["group1"],
  1377. },
  1378. "project": self.project2,
  1379. "count": 7,
  1380. },
  1381. {
  1382. "data": {
  1383. "message": "poof2",
  1384. "timestamp": self.day_ago + timedelta(minutes=2),
  1385. "user": {"email": self.user.email},
  1386. "tags": {"count": "abc"},
  1387. "fingerprint": ["group1"],
  1388. },
  1389. "project": self.project2,
  1390. "count": 3,
  1391. },
  1392. ]
  1393. for index, event in enumerate(event_data):
  1394. for i in range(event["count"]):
  1395. event["data"]["event_id"] = f"{index}{i}" * 16
  1396. self.store_event(event["data"], project_id=event["project"].id)
  1397. # Query for count and count()
  1398. data = {
  1399. "start": self.day_ago.isoformat(),
  1400. "end": (self.day_ago + timedelta(hours=1)).isoformat(),
  1401. "interval": "1h",
  1402. "yAxis": "count()",
  1403. "orderby": ["-count"],
  1404. "field": ["count()", "count"],
  1405. "topEvents": "2",
  1406. "partial": "1",
  1407. }
  1408. with self.feature(self.enabled_features):
  1409. response = self.client.get(self.url, data, format="json")
  1410. assert response.status_code == 200
  1411. assert response.data["9001"]["data"][0][1] == [{"count": 7}]
  1412. assert response.data["abc"]["data"][0][1] == [{"count": 3}]
  1413. assert response.data["Other"]["data"][0][1] == [{"count": 16}]
  1414. def test_tag_with_conflicting_function_alias_with_other_multiple_groupings(self):
  1415. event_data: list[_EventDataDict] = [
  1416. {
  1417. "data": {
  1418. "message": "abc",
  1419. "timestamp": iso_format(self.day_ago + timedelta(minutes=2)),
  1420. "user": {"email": self.user.email},
  1421. "tags": {"count": "2"},
  1422. "fingerprint": ["group1"],
  1423. },
  1424. "project": self.project2,
  1425. "count": 3,
  1426. },
  1427. {
  1428. "data": {
  1429. "message": "def",
  1430. "timestamp": iso_format(self.day_ago + timedelta(minutes=2)),
  1431. "user": {"email": self.user.email},
  1432. "tags": {"count": "9001"},
  1433. "fingerprint": ["group1"],
  1434. },
  1435. "project": self.project2,
  1436. "count": 7,
  1437. },
  1438. ]
  1439. for index, event in enumerate(event_data):
  1440. for i in range(event["count"]):
  1441. event["data"]["event_id"] = f"{index}{i}" * 16
  1442. self.store_event(event["data"], project_id=event["project"].id)
  1443. # Query for count and count()
  1444. data = {
  1445. "start": self.day_ago.isoformat(),
  1446. "end": (self.day_ago + timedelta(hours=2)).isoformat(),
  1447. "interval": "2d",
  1448. "yAxis": "count()",
  1449. "orderby": ["-count"],
  1450. "field": ["count()", "count", "message"],
  1451. "topEvents": "2",
  1452. "partial": "1",
  1453. }
  1454. with self.feature(self.enabled_features):
  1455. response = self.client.get(self.url, data, format="json")
  1456. assert response.status_code == 200
  1457. assert response.data["abc,2"]["data"][0][1] == [{"count": 3}]
  1458. assert response.data["def,9001"]["data"][0][1] == [{"count": 7}]
  1459. assert response.data["Other"]["data"][0][1] == [{"count": 25}]
  1460. def test_group_id_tag_simple(self):
  1461. event_data: _EventDataDict = {
  1462. "data": {
  1463. "message": "poof",
  1464. "timestamp": iso_format(self.day_ago + timedelta(minutes=2)),
  1465. "user": {"email": self.user.email},
  1466. "tags": {"group_id": "the tag"},
  1467. "fingerprint": ["group1"],
  1468. },
  1469. "project": self.project2,
  1470. "count": 7,
  1471. }
  1472. for i in range(event_data["count"]):
  1473. event_data["data"]["event_id"] = f"a{i}" * 16
  1474. self.store_event(event_data["data"], project_id=event_data["project"].id)
  1475. data = {
  1476. "start": self.day_ago.isoformat(),
  1477. "end": (self.day_ago + timedelta(hours=2)).isoformat(),
  1478. "interval": "1h",
  1479. "yAxis": "count()",
  1480. "orderby": ["-count()"],
  1481. "field": ["count()", "group_id"],
  1482. "topEvents": "5",
  1483. "partial": "1",
  1484. }
  1485. with self.feature(self.enabled_features):
  1486. response = self.client.get(self.url, data, format="json")
  1487. assert response.status_code == 200, response.content
  1488. assert response.data["the tag"]["data"][0][1] == [{"count": 7}]
  1489. data["query"] = 'group_id:"the tag"'
  1490. with self.feature(self.enabled_features):
  1491. response = self.client.get(self.url, data, format="json")
  1492. assert response.status_code == 200
  1493. assert response.data["the tag"]["data"][0][1] == [{"count": 7}]
  1494. data["query"] = "group_id:abc"
  1495. with self.feature(self.enabled_features):
  1496. response = self.client.get(self.url, data, format="json")
  1497. assert response.status_code == 200
  1498. assert all([interval[1][0]["count"] == 0 for interval in response.data["data"]])
  1499. def test_top_events_limits(self):
  1500. data = {
  1501. "start": self.day_ago.isoformat(),
  1502. "end": (self.day_ago + timedelta(hours=2)).isoformat(),
  1503. "interval": "1h",
  1504. "yAxis": "count()",
  1505. "orderby": ["-count()"],
  1506. "field": ["count()", "message", "user.email"],
  1507. }
  1508. with self.feature(self.enabled_features):
  1509. data["topEvents"] = str(MAX_TOP_EVENTS + 1)
  1510. response = self.client.get(self.url, data, format="json")
  1511. assert response.status_code == 400
  1512. data["topEvents"] = "0"
  1513. response = self.client.get(self.url, data, format="json")
  1514. assert response.status_code == 400
  1515. data["topEvents"] = "a"
  1516. response = self.client.get(self.url, data, format="json")
  1517. assert response.status_code == 400
  1518. @pytest.mark.xfail(
  1519. reason="The response is wrong whenever we have a top events timeseries on project + any other field + aggregation"
  1520. )
  1521. def test_top_events_with_projects(self):
  1522. with self.feature(self.enabled_features):
  1523. response = self.client.get(
  1524. self.url,
  1525. data={
  1526. "start": self.day_ago.isoformat(),
  1527. "end": (self.day_ago + timedelta(hours=2)).isoformat(),
  1528. "interval": "1h",
  1529. "yAxis": "count()",
  1530. "orderby": ["-count()"],
  1531. "field": ["count()", "message", "project"],
  1532. "topEvents": "5",
  1533. },
  1534. format="json",
  1535. )
  1536. data = response.data
  1537. assert response.status_code == 200, response.content
  1538. assert len(data) == 6
  1539. for index, event in enumerate(self.events[:5]):
  1540. message = event.message or event.transaction
  1541. results = data[",".join([message, event.project.slug])]
  1542. assert results["order"] == index
  1543. assert [{"count": self.event_data[index]["count"]}] in [
  1544. attrs for time, attrs in results["data"]
  1545. ]
  1546. other = data["Other"]
  1547. assert other["order"] == 5
  1548. assert [{"count": 3}] in [attrs for _, attrs in other["data"]]
  1549. def test_top_events_with_issue(self):
  1550. # delete a group to make sure if this happens the value becomes unknown
  1551. event_group = self.events[0].group
  1552. event_group.delete()
  1553. with self.feature(self.enabled_features):
  1554. response = self.client.get(
  1555. self.url,
  1556. data={
  1557. "start": self.day_ago.isoformat(),
  1558. "end": (self.day_ago + timedelta(hours=2)).isoformat(),
  1559. "interval": "1h",
  1560. "yAxis": "count()",
  1561. "orderby": ["-count()"],
  1562. "field": ["count()", "message", "issue"],
  1563. "topEvents": "5",
  1564. "query": "!event.type:transaction",
  1565. },
  1566. format="json",
  1567. )
  1568. data = response.data
  1569. assert response.status_code == 200, response.content
  1570. assert len(data) == 6
  1571. for index, event in enumerate(self.events[:4]):
  1572. message = event.message
  1573. # Because we deleted the group for event 0
  1574. if index == 0 or event.group is None:
  1575. issue = "unknown"
  1576. else:
  1577. issue = event.group.qualified_short_id
  1578. results = data[",".join([issue, message])]
  1579. assert results["order"] == index
  1580. assert [{"count": self.event_data[index]["count"]}] in [
  1581. attrs for time, attrs in results["data"]
  1582. ]
  1583. other = data["Other"]
  1584. assert other["order"] == 5
  1585. assert [{"count": 1}] in [attrs for _, attrs in other["data"]]
  1586. def test_top_events_with_transaction_status(self):
  1587. with self.feature(self.enabled_features):
  1588. response = self.client.get(
  1589. self.url,
  1590. data={
  1591. "start": self.day_ago.isoformat(),
  1592. "end": (self.day_ago + timedelta(hours=2)).isoformat(),
  1593. "interval": "1h",
  1594. "yAxis": "count()",
  1595. "orderby": ["-count()"],
  1596. "field": ["count()", "transaction.status"],
  1597. "topEvents": "5",
  1598. },
  1599. format="json",
  1600. )
  1601. data = response.data
  1602. assert response.status_code == 200, response.content
  1603. assert len(data) == 1
  1604. assert "ok" in data
  1605. @mock.patch("sentry.models.GroupManager.get_issues_mapping")
  1606. def test_top_events_with_unknown_issue(self, mock_issues_mapping):
  1607. event = self.events[0]
  1608. event_data = self.event_data[0]
  1609. # ensure that the issue mapping returns None for the issue
  1610. mock_issues_mapping.return_value = {event.group.id: None}
  1611. with self.feature(self.enabled_features):
  1612. response = self.client.get(
  1613. self.url,
  1614. data={
  1615. "start": self.day_ago.isoformat(),
  1616. "end": (self.day_ago + timedelta(hours=2)).isoformat(),
  1617. "interval": "1h",
  1618. "yAxis": "count()",
  1619. "orderby": ["-count()"],
  1620. "field": ["count()", "issue"],
  1621. "topEvents": "5",
  1622. # narrow the search to just one issue
  1623. "query": f"issue.id:{event.group.id}",
  1624. },
  1625. format="json",
  1626. )
  1627. assert response.status_code == 200, response.content
  1628. data = response.data
  1629. assert len(data) == 1
  1630. results = data["unknown"]
  1631. assert results["order"] == 0
  1632. assert [{"count": event_data["count"]}] in [attrs for time, attrs in results["data"]]
  1633. @mock.patch(
  1634. "sentry.search.events.builder.base.raw_snql_query",
  1635. side_effect=[{"data": [{"issue.id": 1}], "meta": []}, {"data": [], "meta": []}],
  1636. )
  1637. def test_top_events_with_issue_check_query_conditions(self, mock_query):
  1638. """ "Intentionally separate from test_top_events_with_issue
  1639. This is to test against a bug where the condition for issues wasn't included and we'd be missing data for
  1640. the interval since we'd cap out the max rows. This was not caught by the previous test since the results
  1641. would still be correct given the smaller interval & lack of data
  1642. """
  1643. with self.feature(self.enabled_features):
  1644. self.client.get(
  1645. self.url,
  1646. data={
  1647. "start": self.day_ago.isoformat(),
  1648. "end": (self.day_ago + timedelta(hours=2)).isoformat(),
  1649. "interval": "1h",
  1650. "yAxis": "count()",
  1651. "orderby": ["-count()"],
  1652. "field": ["count()", "message", "issue"],
  1653. "topEvents": "5",
  1654. "query": "!event.type:transaction",
  1655. },
  1656. format="json",
  1657. )
  1658. assert (
  1659. Condition(Function("coalesce", [Column("group_id"), 0], "issue.id"), Op.IN, [1])
  1660. in mock_query.mock_calls[1].args[0].query.where
  1661. )
  1662. def test_top_events_with_functions(self):
  1663. for dataset in ["transactions", "discover"]:
  1664. with self.feature(self.enabled_features):
  1665. response = self.client.get(
  1666. self.url,
  1667. data={
  1668. "start": self.day_ago.isoformat(),
  1669. "end": (self.day_ago + timedelta(hours=2)).isoformat(),
  1670. "interval": "1h",
  1671. "yAxis": "count()",
  1672. "orderby": ["-p99()"],
  1673. "field": ["transaction", "avg(transaction.duration)", "p99()"],
  1674. "topEvents": "5",
  1675. "dataset": dataset,
  1676. },
  1677. format="json",
  1678. )
  1679. data = response.data
  1680. assert response.status_code == 200, response.content
  1681. assert len(data) == 1
  1682. results = data[self.transaction.transaction]
  1683. assert results["order"] == 0
  1684. assert [attrs for time, attrs in results["data"]] == [[{"count": 3}], [{"count": 0}]]
  1685. def test_top_events_with_functions_on_different_transactions(self):
  1686. """Transaction2 has less events, but takes longer so order should be self.transaction then transaction2"""
  1687. transaction_data = load_data("transaction")
  1688. transaction_data["start_timestamp"] = iso_format(self.day_ago + timedelta(minutes=2))
  1689. transaction_data["timestamp"] = iso_format(self.day_ago + timedelta(minutes=6))
  1690. transaction_data["transaction"] = "/foo_bar/"
  1691. transaction2 = self.store_event(transaction_data, project_id=self.project.id)
  1692. with self.feature(self.enabled_features):
  1693. response = self.client.get(
  1694. self.url,
  1695. data={
  1696. "start": self.day_ago.isoformat(),
  1697. "end": (self.day_ago + timedelta(hours=2)).isoformat(),
  1698. "interval": "1h",
  1699. "yAxis": "count()",
  1700. "orderby": ["-p90()"],
  1701. "field": ["transaction", "avg(transaction.duration)", "p90()"],
  1702. "topEvents": "5",
  1703. },
  1704. format="json",
  1705. )
  1706. data = response.data
  1707. assert response.status_code == 200, response.content
  1708. assert len(data) == 2
  1709. results = data[self.transaction.transaction]
  1710. assert results["order"] == 1
  1711. assert [attrs for time, attrs in results["data"]] == [[{"count": 3}], [{"count": 0}]]
  1712. results = data[transaction2.transaction]
  1713. assert results["order"] == 0
  1714. assert [attrs for time, attrs in results["data"]] == [[{"count": 1}], [{"count": 0}]]
  1715. def test_top_events_with_query(self):
  1716. transaction_data = load_data("transaction")
  1717. transaction_data["start_timestamp"] = iso_format(self.day_ago + timedelta(minutes=2))
  1718. transaction_data["timestamp"] = iso_format(self.day_ago + timedelta(minutes=6))
  1719. transaction_data["transaction"] = "/foo_bar/"
  1720. self.store_event(transaction_data, project_id=self.project.id)
  1721. with self.feature(self.enabled_features):
  1722. response = self.client.get(
  1723. self.url,
  1724. data={
  1725. "start": self.day_ago.isoformat(),
  1726. "end": (self.day_ago + timedelta(hours=2)).isoformat(),
  1727. "interval": "1h",
  1728. "yAxis": "count()",
  1729. "orderby": ["-p99()"],
  1730. "query": "transaction:/foo_bar/",
  1731. "field": ["transaction", "avg(transaction.duration)", "p99()"],
  1732. "topEvents": "5",
  1733. },
  1734. format="json",
  1735. )
  1736. data = response.data
  1737. assert response.status_code == 200, response.content
  1738. assert len(data) == 1
  1739. transaction2_data = data["/foo_bar/"]
  1740. assert transaction2_data["order"] == 0
  1741. assert [attrs for time, attrs in transaction2_data["data"]] == [
  1742. [{"count": 1}],
  1743. [{"count": 0}],
  1744. ]
  1745. def test_top_events_with_negated_condition(self):
  1746. with self.feature(self.enabled_features):
  1747. response = self.client.get(
  1748. self.url,
  1749. data={
  1750. "start": self.day_ago.isoformat(),
  1751. "end": (self.day_ago + timedelta(hours=2)).isoformat(),
  1752. "interval": "1h",
  1753. "yAxis": "count()",
  1754. "orderby": ["-count()"],
  1755. "query": f"!message:{self.events[0].message}",
  1756. "field": ["message", "count()"],
  1757. "topEvents": "5",
  1758. },
  1759. format="json",
  1760. )
  1761. data = response.data
  1762. assert response.status_code == 200, response.content
  1763. assert len(data) == 6
  1764. for index, event in enumerate(self.events[1:5]):
  1765. message = event.message or event.transaction
  1766. results = data[message]
  1767. assert results["order"] == index
  1768. assert [{"count": self.event_data[index + 1]["count"]}] in [
  1769. attrs for _, attrs in results["data"]
  1770. ]
  1771. other = data["Other"]
  1772. assert other["order"] == 5
  1773. assert [{"count": 1}] in [attrs for _, attrs in other["data"]]
  1774. def test_top_events_with_epm(self):
  1775. with self.feature(self.enabled_features):
  1776. response = self.client.get(
  1777. self.url,
  1778. data={
  1779. "start": self.day_ago.isoformat(),
  1780. "end": (self.day_ago + timedelta(hours=2)).isoformat(),
  1781. "interval": "1h",
  1782. "yAxis": "epm()",
  1783. "orderby": ["-count()"],
  1784. "field": ["message", "user.email", "count()"],
  1785. "topEvents": "5",
  1786. },
  1787. format="json",
  1788. )
  1789. data = response.data
  1790. assert response.status_code == 200, response.content
  1791. assert len(data) == 6
  1792. for index, event in enumerate(self.events[:5]):
  1793. message = event.message or event.transaction
  1794. results = data[
  1795. ",".join([message, self.event_data[index]["data"]["user"].get("email", "None")])
  1796. ]
  1797. assert results["order"] == index
  1798. assert [{"count": self.event_data[index]["count"] / (3600.0 / 60.0)}] in [
  1799. attrs for time, attrs in results["data"]
  1800. ]
  1801. other = data["Other"]
  1802. assert other["order"] == 5
  1803. assert [{"count": 0.05}] in [attrs for _, attrs in other["data"]]
  1804. def test_top_events_with_multiple_yaxis(self):
  1805. with self.feature(self.enabled_features):
  1806. response = self.client.get(
  1807. self.url,
  1808. data={
  1809. "start": self.day_ago.isoformat(),
  1810. "end": (self.day_ago + timedelta(hours=2)).isoformat(),
  1811. "interval": "1h",
  1812. "yAxis": ["epm()", "count()"],
  1813. "orderby": ["-count()"],
  1814. "field": ["message", "user.email", "count()"],
  1815. "topEvents": "5",
  1816. },
  1817. format="json",
  1818. )
  1819. data = response.data
  1820. assert response.status_code == 200, response.content
  1821. assert len(data) == 6
  1822. for index, event in enumerate(self.events[:5]):
  1823. message = event.message or event.transaction
  1824. results = data[
  1825. ",".join([message, self.event_data[index]["data"]["user"].get("email", "None")])
  1826. ]
  1827. assert results["order"] == index
  1828. assert results["epm()"]["order"] == 0
  1829. assert results["count()"]["order"] == 1
  1830. assert [{"count": self.event_data[index]["count"] / (3600.0 / 60.0)}] in [
  1831. attrs for time, attrs in results["epm()"]["data"]
  1832. ]
  1833. assert [{"count": self.event_data[index]["count"]}] in [
  1834. attrs for time, attrs in results["count()"]["data"]
  1835. ]
  1836. other = data["Other"]
  1837. assert other["order"] == 5
  1838. assert other["epm()"]["order"] == 0
  1839. assert other["count()"]["order"] == 1
  1840. assert [{"count": 0.05}] in [attrs for _, attrs in other["epm()"]["data"]]
  1841. assert [{"count": 3}] in [attrs for _, attrs in other["count()"]["data"]]
  1842. def test_top_events_with_boolean(self):
  1843. with self.feature(self.enabled_features):
  1844. response = self.client.get(
  1845. self.url,
  1846. data={
  1847. "start": self.day_ago.isoformat(),
  1848. "end": (self.day_ago + timedelta(hours=2)).isoformat(),
  1849. "interval": "1h",
  1850. "yAxis": "count()",
  1851. "orderby": ["-count()"],
  1852. "field": ["count()", "message", "device.charging"],
  1853. "topEvents": "5",
  1854. },
  1855. format="json",
  1856. )
  1857. data = response.data
  1858. assert response.status_code == 200, response.content
  1859. assert len(data) == 6
  1860. for index, event in enumerate(self.events[:5]):
  1861. message = event.message or event.transaction
  1862. results = data[",".join(["False", message])]
  1863. assert results["order"] == index
  1864. assert [{"count": self.event_data[index]["count"]}] in [
  1865. attrs for time, attrs in results["data"]
  1866. ]
  1867. other = data["Other"]
  1868. assert other["order"] == 5
  1869. assert [{"count": 3}] in [attrs for _, attrs in other["data"]]
  1870. def test_top_events_with_error_unhandled(self):
  1871. self.login_as(user=self.user)
  1872. project = self.create_project()
  1873. prototype = load_data("android-ndk")
  1874. prototype["event_id"] = "f" * 32
  1875. prototype["logentry"] = {"formatted": "not handled"}
  1876. prototype["exception"]["values"][0]["value"] = "not handled"
  1877. prototype["exception"]["values"][0]["mechanism"]["handled"] = False
  1878. prototype["timestamp"] = iso_format(self.day_ago + timedelta(minutes=2))
  1879. self.store_event(data=prototype, project_id=project.id)
  1880. with self.feature(self.enabled_features):
  1881. response = self.client.get(
  1882. self.url,
  1883. data={
  1884. "start": self.day_ago.isoformat(),
  1885. "end": (self.day_ago + timedelta(hours=2)).isoformat(),
  1886. "interval": "1h",
  1887. "yAxis": "count()",
  1888. "orderby": ["-count()"],
  1889. "field": ["count()", "error.unhandled"],
  1890. "topEvents": "5",
  1891. },
  1892. format="json",
  1893. )
  1894. data = response.data
  1895. assert response.status_code == 200, response.content
  1896. assert len(data) == 2
  1897. def test_top_events_with_timestamp(self):
  1898. with self.feature(self.enabled_features):
  1899. response = self.client.get(
  1900. self.url,
  1901. data={
  1902. "start": self.day_ago.isoformat(),
  1903. "end": (self.day_ago + timedelta(hours=2)).isoformat(),
  1904. "interval": "1h",
  1905. "yAxis": "count()",
  1906. "orderby": ["-count()"],
  1907. "query": "event.type:default",
  1908. "field": ["count()", "message", "timestamp"],
  1909. "topEvents": "5",
  1910. },
  1911. format="json",
  1912. )
  1913. data = response.data
  1914. assert response.status_code == 200, response.content
  1915. assert len(data) == 6
  1916. # Transactions won't be in the results because of the query
  1917. del self.events[4]
  1918. del self.event_data[4]
  1919. for index, event in enumerate(self.events[:5]):
  1920. results = data[",".join([event.message, event.timestamp])]
  1921. assert results["order"] == index
  1922. assert [{"count": self.event_data[index]["count"]}] in [
  1923. attrs for time, attrs in results["data"]
  1924. ]
  1925. other = data["Other"]
  1926. assert other["order"] == 5
  1927. assert [{"count": 1}] in [attrs for _, attrs in other["data"]]
  1928. def test_top_events_with_int(self):
  1929. with self.feature(self.enabled_features):
  1930. response = self.client.get(
  1931. self.url,
  1932. data={
  1933. "start": self.day_ago.isoformat(),
  1934. "end": (self.day_ago + timedelta(hours=2)).isoformat(),
  1935. "interval": "1h",
  1936. "yAxis": "count()",
  1937. "orderby": ["-count()"],
  1938. "field": ["count()", "message", "transaction.duration"],
  1939. "topEvents": "5",
  1940. },
  1941. format="json",
  1942. )
  1943. data = response.data
  1944. assert response.status_code == 200, response.content
  1945. assert len(data) == 1
  1946. results = data[",".join([self.transaction.transaction, "120000"])]
  1947. assert results["order"] == 0
  1948. assert [attrs for time, attrs in results["data"]] == [[{"count": 3}], [{"count": 0}]]
  1949. def test_top_events_with_user(self):
  1950. with self.feature(self.enabled_features):
  1951. response = self.client.get(
  1952. self.url,
  1953. data={
  1954. "start": self.day_ago.isoformat(),
  1955. "end": (self.day_ago + timedelta(hours=2)).isoformat(),
  1956. "interval": "1h",
  1957. "yAxis": "count()",
  1958. "orderby": ["-count()", "user"],
  1959. "field": ["user", "count()"],
  1960. "topEvents": "5",
  1961. },
  1962. format="json",
  1963. )
  1964. data = response.data
  1965. assert response.status_code == 200, response.content
  1966. assert len(data) == 5
  1967. assert data["email:bar@example.com"]["order"] == 1
  1968. assert [attrs for time, attrs in data["email:bar@example.com"]["data"]] == [
  1969. [{"count": 7}],
  1970. [{"count": 0}],
  1971. ]
  1972. assert [attrs for time, attrs in data["ip:127.0.0.1"]["data"]] == [
  1973. [{"count": 3}],
  1974. [{"count": 0}],
  1975. ]
  1976. def test_top_events_with_user_and_email(self):
  1977. with self.feature(self.enabled_features):
  1978. response = self.client.get(
  1979. self.url,
  1980. data={
  1981. "start": self.day_ago.isoformat(),
  1982. "end": (self.day_ago + timedelta(hours=2)).isoformat(),
  1983. "interval": "1h",
  1984. "yAxis": "count()",
  1985. "orderby": ["-count()", "user"],
  1986. "field": ["user", "user.email", "count()"],
  1987. "topEvents": "5",
  1988. },
  1989. format="json",
  1990. )
  1991. data = response.data
  1992. assert response.status_code == 200, response.content
  1993. assert len(data) == 5
  1994. assert data["email:bar@example.com,bar@example.com"]["order"] == 1
  1995. assert [attrs for time, attrs in data["email:bar@example.com,bar@example.com"]["data"]] == [
  1996. [{"count": 7}],
  1997. [{"count": 0}],
  1998. ]
  1999. assert [attrs for time, attrs in data["ip:127.0.0.1,None"]["data"]] == [
  2000. [{"count": 3}],
  2001. [{"count": 0}],
  2002. ]
  2003. def test_top_events_with_user_display(self):
  2004. with self.feature(self.enabled_features):
  2005. response = self.client.get(
  2006. self.url,
  2007. data={
  2008. "start": self.day_ago.isoformat(),
  2009. "end": (self.day_ago + timedelta(hours=2)).isoformat(),
  2010. "interval": "1h",
  2011. "yAxis": "count()",
  2012. "orderby": ["-count()"],
  2013. "field": ["message", "user.display", "count()"],
  2014. "topEvents": "5",
  2015. },
  2016. format="json",
  2017. )
  2018. data = response.data
  2019. assert response.status_code == 200, response.content
  2020. assert len(data) == 6
  2021. for index, event in enumerate(self.events[:5]):
  2022. message = event.message or event.transaction
  2023. user = self.event_data[index]["data"]["user"]
  2024. results = data[
  2025. ",".join([message, user.get("email", None) or user.get("ip_address", "None")])
  2026. ]
  2027. assert results["order"] == index
  2028. assert [{"count": self.event_data[index]["count"]}] in [
  2029. attrs for _, attrs in results["data"]
  2030. ]
  2031. other = data["Other"]
  2032. assert other["order"] == 5
  2033. assert [{"count": 3}] in [attrs for _, attrs in other["data"]]
  2034. @pytest.mark.skip(reason="A query with group_id will not return transactions")
  2035. def test_top_events_none_filter(self):
  2036. """When a field is None in one of the top events, make sure we filter by it
  2037. In this case event[4] is a transaction and has no issue
  2038. """
  2039. with self.feature(self.enabled_features):
  2040. response = self.client.get(
  2041. self.url,
  2042. data={
  2043. "start": self.day_ago.isoformat(),
  2044. "end": (self.day_ago + timedelta(hours=2)).isoformat(),
  2045. "interval": "1h",
  2046. "yAxis": "count()",
  2047. "orderby": ["-count()"],
  2048. "field": ["count()", "issue"],
  2049. "topEvents": "5",
  2050. },
  2051. format="json",
  2052. )
  2053. data = response.data
  2054. assert response.status_code == 200, response.content
  2055. assert len(data) == 5
  2056. for index, event in enumerate(self.events[:5]):
  2057. if event.group is None:
  2058. issue = "unknown"
  2059. else:
  2060. issue = event.group.qualified_short_id
  2061. results = data[issue]
  2062. assert results["order"] == index
  2063. assert [{"count": self.event_data[index]["count"]}] in [
  2064. attrs for time, attrs in results["data"]
  2065. ]
  2066. @pytest.mark.skip(reason="Invalid query - transaction events don't have group_id field")
  2067. def test_top_events_one_field_with_none(self):
  2068. with self.feature(self.enabled_features):
  2069. response = self.client.get(
  2070. self.url,
  2071. data={
  2072. "start": self.day_ago.isoformat(),
  2073. "end": (self.day_ago + timedelta(hours=2)).isoformat(),
  2074. "interval": "1h",
  2075. "yAxis": "count()",
  2076. "orderby": ["-count()"],
  2077. "query": "event.type:transaction",
  2078. "field": ["count()", "issue"],
  2079. "topEvents": "5",
  2080. },
  2081. format="json",
  2082. )
  2083. data = response.data
  2084. assert response.status_code == 200, response.content
  2085. assert len(data) == 1
  2086. results = data["unknown"]
  2087. assert [attrs for time, attrs in results["data"]] == [[{"count": 3}], [{"count": 0}]]
  2088. assert results["order"] == 0
  2089. def test_top_events_with_error_handled(self):
  2090. data = self.event_data[0]
  2091. data["data"]["level"] = "error"
  2092. data["data"]["exception"] = {
  2093. "values": [
  2094. {
  2095. "type": "ValidationError",
  2096. "value": "Bad request",
  2097. "mechanism": {"handled": True, "type": "generic"},
  2098. }
  2099. ]
  2100. }
  2101. self.store_event(data["data"], project_id=data["project"].id)
  2102. data["data"]["exception"] = {
  2103. "values": [
  2104. {
  2105. "type": "ValidationError",
  2106. "value": "Bad request",
  2107. "mechanism": {"handled": False, "type": "generic"},
  2108. }
  2109. ]
  2110. }
  2111. self.store_event(data["data"], project_id=data["project"].id)
  2112. with self.feature(self.enabled_features):
  2113. response = self.client.get(
  2114. self.url,
  2115. data={
  2116. "start": self.day_ago.isoformat(),
  2117. "end": (self.day_ago + timedelta(hours=2)).isoformat(),
  2118. "interval": "1h",
  2119. "yAxis": "count()",
  2120. "orderby": ["-count()"],
  2121. "field": ["count()", "error.handled"],
  2122. "topEvents": "5",
  2123. "query": "!event.type:transaction",
  2124. },
  2125. format="json",
  2126. )
  2127. assert response.status_code == 200, response.content
  2128. res_data = response.data
  2129. assert len(res_data) == 2
  2130. results = res_data["1"]
  2131. assert [attrs for time, attrs in results["data"]] == [[{"count": 20}], [{"count": 6}]]
  2132. results = res_data["0"]
  2133. assert [attrs for time, attrs in results["data"]] == [[{"count": 1}], [{"count": 0}]]
  2134. def test_top_events_with_aggregate_condition(self):
  2135. with self.feature(self.enabled_features):
  2136. response = self.client.get(
  2137. self.url,
  2138. data={
  2139. "start": self.day_ago.isoformat(),
  2140. "end": (self.day_ago + timedelta(hours=2)).isoformat(),
  2141. "interval": "1h",
  2142. "yAxis": "count()",
  2143. "orderby": ["-count()"],
  2144. "field": ["message", "count()"],
  2145. "query": "count():>4",
  2146. "topEvents": "5",
  2147. },
  2148. format="json",
  2149. )
  2150. assert response.status_code == 200, response.content
  2151. data = response.data
  2152. assert len(data) == 3
  2153. for index, event in enumerate(self.events[:3]):
  2154. message = event.message or event.transaction
  2155. results = data[message]
  2156. assert results["order"] == index
  2157. assert [{"count": self.event_data[index]["count"]}] in [
  2158. attrs for time, attrs in results["data"]
  2159. ]
  2160. @pytest.mark.xfail(reason="There's only 2 rows total, which mean there shouldn't be other")
  2161. def test_top_events_with_to_other(self):
  2162. version = "version -@'\" 1.2,3+(4)"
  2163. version_escaped = "version -@'\\\" 1.2,3+(4)"
  2164. # every symbol is replaced with a underscore to make the alias
  2165. version_alias = "version_______1_2_3__4_"
  2166. # add an event in the current release
  2167. event = self.event_data[0]
  2168. event_data = event["data"].copy()
  2169. event_data["event_id"] = uuid4().hex
  2170. event_data["release"] = version
  2171. self.store_event(event_data, project_id=event["project"].id)
  2172. with self.feature(self.enabled_features):
  2173. response = self.client.get(
  2174. self.url,
  2175. data={
  2176. "start": self.day_ago.isoformat(),
  2177. "end": (self.day_ago + timedelta(hours=2)).isoformat(),
  2178. "interval": "1h",
  2179. "yAxis": "count()",
  2180. # the double underscores around the version alias is because of a comma and quote
  2181. "orderby": [f"-to_other_release__{version_alias}__others_current"],
  2182. "field": [
  2183. "count()",
  2184. f'to_other(release,"{version_escaped}",others,current)',
  2185. ],
  2186. "topEvents": "2",
  2187. },
  2188. format="json",
  2189. )
  2190. assert response.status_code == 200, response.content
  2191. data = response.data
  2192. assert len(data) == 2
  2193. current = data["current"]
  2194. assert current["order"] == 1
  2195. assert sum(attrs[0]["count"] for _, attrs in current["data"]) == 1
  2196. others = data["others"]
  2197. assert others["order"] == 0
  2198. assert sum(attrs[0]["count"] for _, attrs in others["data"]) == sum(
  2199. event_data["count"] for event_data in self.event_data
  2200. )
  2201. def test_top_events_with_equations(self):
  2202. with self.feature(self.enabled_features):
  2203. response = self.client.get(
  2204. self.url,
  2205. data={
  2206. "start": self.day_ago.isoformat(),
  2207. "end": (self.day_ago + timedelta(hours=2)).isoformat(),
  2208. "interval": "1h",
  2209. "yAxis": "equation|count() / 100",
  2210. "orderby": ["-count()"],
  2211. "field": ["count()", "message", "user.email", "equation|count() / 100"],
  2212. "topEvents": "5",
  2213. },
  2214. format="json",
  2215. )
  2216. data = response.data
  2217. assert response.status_code == 200, response.content
  2218. assert len(data) == 6
  2219. for index, event in enumerate(self.events[:5]):
  2220. message = event.message or event.transaction
  2221. results = data[
  2222. ",".join([message, self.event_data[index]["data"]["user"].get("email", "None")])
  2223. ]
  2224. assert results["order"] == index
  2225. assert [{"count": self.event_data[index]["count"] / 100}] in [
  2226. attrs for time, attrs in results["data"]
  2227. ]
  2228. other = data["Other"]
  2229. assert other["order"] == 5
  2230. assert [{"count": 0.03}] in [attrs for _, attrs in other["data"]]
  2231. @mock.patch("sentry.snuba.discover.bulk_snuba_queries", return_value=[{"data": [], "meta": []}])
  2232. @mock.patch(
  2233. "sentry.search.events.builder.base.raw_snql_query",
  2234. return_value={"data": [], "meta": []},
  2235. )
  2236. def test_invalid_interval(self, mock_raw_query, mock_bulk_query):
  2237. with self.feature(self.enabled_features):
  2238. response = self.client.get(
  2239. self.url,
  2240. format="json",
  2241. data={
  2242. "end": before_now().isoformat(),
  2243. # 7,200 points for each event
  2244. "start": before_now(seconds=7200).isoformat(),
  2245. "field": ["count()", "issue"],
  2246. "query": "",
  2247. "interval": "1s",
  2248. "yAxis": "count()",
  2249. },
  2250. )
  2251. assert response.status_code == 200
  2252. assert mock_bulk_query.call_count == 1
  2253. with self.feature(self.enabled_features):
  2254. response = self.client.get(
  2255. self.url,
  2256. format="json",
  2257. data={
  2258. "end": before_now().isoformat(),
  2259. "start": before_now(seconds=7200).isoformat(),
  2260. "field": ["count()", "issue"],
  2261. "query": "",
  2262. "interval": "1s",
  2263. "yAxis": "count()",
  2264. # 7,200 points for each event * 2, should error
  2265. "topEvents": "2",
  2266. },
  2267. )
  2268. assert response.status_code == 200
  2269. assert mock_raw_query.call_count == 2
  2270. # Should've reset to the default for between 1 and 24h
  2271. assert mock_raw_query.mock_calls[1].args[0].query.granularity.granularity == 300
  2272. with self.feature(self.enabled_features):
  2273. response = self.client.get(
  2274. self.url,
  2275. format="json",
  2276. data={
  2277. "end": before_now().isoformat(),
  2278. # 1999 points * 5 events should just be enough to not error
  2279. "start": before_now(seconds=1999).isoformat(),
  2280. "field": ["count()", "issue"],
  2281. "query": "",
  2282. "interval": "1s",
  2283. "yAxis": "count()",
  2284. "topEvents": "5",
  2285. },
  2286. )
  2287. assert response.status_code == 200
  2288. assert mock_raw_query.call_count == 4
  2289. # Should've left the interval alone since we're just below the limit
  2290. assert mock_raw_query.mock_calls[3].args[0].query.granularity.granularity == 1
  2291. with self.feature(self.enabled_features):
  2292. response = self.client.get(
  2293. self.url,
  2294. format="json",
  2295. data={
  2296. "end": before_now().isoformat(),
  2297. "start": before_now(hours=24).isoformat(),
  2298. "field": ["count()", "issue"],
  2299. "query": "",
  2300. "interval": "0d",
  2301. "yAxis": "count()",
  2302. "topEvents": "5",
  2303. },
  2304. )
  2305. assert response.status_code == 200
  2306. assert mock_raw_query.call_count == 6
  2307. # Should've default to 24h's default of 5m
  2308. assert mock_raw_query.mock_calls[5].args[0].query.granularity.granularity == 300
  2309. def test_top_events_timestamp_fields(self):
  2310. with self.feature(self.enabled_features):
  2311. response = self.client.get(
  2312. self.url,
  2313. format="json",
  2314. data={
  2315. "start": self.day_ago.isoformat(),
  2316. "end": (self.day_ago + timedelta(hours=2)).isoformat(),
  2317. "interval": "1h",
  2318. "yAxis": "count()",
  2319. "orderby": ["-count()"],
  2320. "field": ["count()", "timestamp", "timestamp.to_hour", "timestamp.to_day"],
  2321. "topEvents": "5",
  2322. },
  2323. )
  2324. assert response.status_code == 200
  2325. data = response.data
  2326. assert len(data) == 3
  2327. # these are the timestamps corresponding to the events stored
  2328. timestamps = [
  2329. self.day_ago + timedelta(minutes=2),
  2330. self.day_ago + timedelta(hours=1, minutes=2),
  2331. self.day_ago + timedelta(minutes=4),
  2332. ]
  2333. timestamp_hours = [timestamp.replace(minute=0, second=0) for timestamp in timestamps]
  2334. timestamp_days = [timestamp.replace(hour=0, minute=0, second=0) for timestamp in timestamps]
  2335. for ts, ts_hr, ts_day in zip(timestamps, timestamp_hours, timestamp_days):
  2336. key = f"{iso_format(ts)}+00:00,{iso_format(ts_day)}+00:00,{iso_format(ts_hr)}+00:00"
  2337. count = sum(e["count"] for e in self.event_data if e["data"]["timestamp"] == ts)
  2338. results = data[key]
  2339. assert [{"count": count}] in [attrs for time, attrs in results["data"]]
  2340. def test_top_events_other_with_matching_columns(self):
  2341. with self.feature(self.enabled_features):
  2342. response = self.client.get(
  2343. self.url,
  2344. data={
  2345. "start": self.day_ago.isoformat(),
  2346. "end": (self.day_ago + timedelta(hours=2)).isoformat(),
  2347. "interval": "1h",
  2348. "yAxis": "count()",
  2349. "orderby": ["-count()"],
  2350. "field": ["count()", "tags[shared-tag]", "message"],
  2351. "topEvents": "5",
  2352. },
  2353. format="json",
  2354. )
  2355. data = response.data
  2356. assert response.status_code == 200, response.content
  2357. assert len(data) == 6
  2358. for index, event in enumerate(self.events[:5]):
  2359. message = event.message or event.transaction
  2360. results = data[",".join([message, "yup"])]
  2361. assert results["order"] == index
  2362. assert [{"count": self.event_data[index]["count"]}] in [
  2363. attrs for _, attrs in results["data"]
  2364. ]
  2365. other = data["Other"]
  2366. assert other["order"] == 5
  2367. assert [{"count": 3}] in [attrs for _, attrs in other["data"]]
  2368. def test_top_events_with_field_overlapping_other_key(self):
  2369. transaction_data = load_data("transaction")
  2370. transaction_data["start_timestamp"] = iso_format(self.day_ago + timedelta(minutes=2))
  2371. transaction_data["timestamp"] = iso_format(self.day_ago + timedelta(minutes=6))
  2372. transaction_data["transaction"] = OTHER_KEY
  2373. for i in range(5):
  2374. data = transaction_data.copy()
  2375. data["event_id"] = "ab" + f"{i}" * 30
  2376. data["contexts"]["trace"]["span_id"] = "ab" + f"{i}" * 14
  2377. self.store_event(data, project_id=self.project.id)
  2378. with self.feature(self.enabled_features):
  2379. response = self.client.get(
  2380. self.url,
  2381. data={
  2382. "start": self.day_ago.isoformat(),
  2383. "end": (self.day_ago + timedelta(hours=2)).isoformat(),
  2384. "interval": "1h",
  2385. "yAxis": "count()",
  2386. "orderby": ["-count()"],
  2387. "field": ["count()", "message"],
  2388. "topEvents": "5",
  2389. },
  2390. format="json",
  2391. )
  2392. data = response.data
  2393. assert response.status_code == 200, response.content
  2394. assert len(data) == 6
  2395. assert f"{OTHER_KEY} (message)" in data
  2396. results = data[f"{OTHER_KEY} (message)"]
  2397. assert [{"count": 5}] in [attrs for _, attrs in results["data"]]
  2398. other = data["Other"]
  2399. assert other["order"] == 5
  2400. assert [{"count": 4}] in [attrs for _, attrs in other["data"]]
  2401. def test_top_events_can_exclude_other_series(self):
  2402. with self.feature(self.enabled_features):
  2403. response = self.client.get(
  2404. self.url,
  2405. data={
  2406. "start": self.day_ago.isoformat(),
  2407. "end": (self.day_ago + timedelta(hours=2)).isoformat(),
  2408. "interval": "1h",
  2409. "yAxis": "count()",
  2410. "orderby": ["count()"],
  2411. "field": ["count()", "message"],
  2412. "topEvents": "5",
  2413. "excludeOther": "1",
  2414. },
  2415. format="json",
  2416. )
  2417. data = response.data
  2418. assert response.status_code == 200, response.content
  2419. assert len(data) == 5
  2420. assert "Other" not in response.data
  2421. @pytest.mark.xfail(reason="Started failing on ClickHouse 21.8")
  2422. def test_top_events_with_equation_including_unselected_fields_passes_field_validation(self):
  2423. with self.feature(self.enabled_features):
  2424. response = self.client.get(
  2425. self.url,
  2426. data={
  2427. "start": self.day_ago.isoformat(),
  2428. "end": (self.day_ago + timedelta(hours=2)).isoformat(),
  2429. "interval": "1h",
  2430. "yAxis": "count()",
  2431. "orderby": ["-equation[0]"],
  2432. "field": ["count()", "message", "equation|count_unique(user) * 2"],
  2433. "topEvents": "5",
  2434. },
  2435. format="json",
  2436. )
  2437. data = response.data
  2438. assert response.status_code == 200, response.content
  2439. assert len(data) == 6
  2440. other = data["Other"]
  2441. assert other["order"] == 5
  2442. assert [{"count": 4}] in [attrs for _, attrs in other["data"]]
  2443. def test_top_events_boolean_condition_and_project_field(self):
  2444. with self.feature(self.enabled_features):
  2445. response = self.client.get(
  2446. self.url,
  2447. data={
  2448. "start": self.day_ago.isoformat(),
  2449. "end": (self.day_ago + timedelta(hours=2)).isoformat(),
  2450. "interval": "1h",
  2451. "yAxis": "count()",
  2452. "orderby": ["-count()"],
  2453. "field": ["project", "count()"],
  2454. "topEvents": "5",
  2455. "query": "event.type:transaction (transaction:*a OR transaction:b*)",
  2456. },
  2457. format="json",
  2458. )
  2459. assert response.status_code == 200
  2460. class OrganizationEventsStatsProfileFunctionDatasetEndpointTest(
  2461. APITestCase, ProfilesSnubaTestCase, SearchIssueTestMixin
  2462. ):
  2463. endpoint = "sentry-api-0-organization-events-stats"
  2464. def setUp(self):
  2465. super().setUp()
  2466. self.login_as(user=self.user)
  2467. self.one_day_ago = before_now(days=1).replace(hour=10, minute=0, second=0, microsecond=0)
  2468. self.two_days_ago = before_now(days=2).replace(hour=10, minute=0, second=0, microsecond=0)
  2469. self.three_days_ago = before_now(days=3).replace(hour=10, minute=0, second=0, microsecond=0)
  2470. self.project = self.create_project()
  2471. self.url = reverse(
  2472. "sentry-api-0-organization-events-stats",
  2473. kwargs={"organization_id_or_slug": self.project.organization.slug},
  2474. )
  2475. def test_functions_dataset_simple(self):
  2476. transaction_function = self.store_functions(
  2477. [
  2478. {
  2479. "self_times_ns": [100_000_000 for _ in range(100)],
  2480. "package": "foo",
  2481. "function": "bar",
  2482. "in_app": True,
  2483. },
  2484. ],
  2485. project=self.project,
  2486. timestamp=self.two_days_ago - timedelta(hours=12),
  2487. )
  2488. continuous_timestamp = self.two_days_ago + timedelta(hours=12)
  2489. continuous_function = self.store_functions_chunk(
  2490. [
  2491. {
  2492. "self_times_ns": [200_000_000 for _ in range(100)],
  2493. "package": "bar",
  2494. "function": "bar",
  2495. "thread_id": "1",
  2496. "in_app": True,
  2497. },
  2498. ],
  2499. project=self.project,
  2500. timestamp=continuous_timestamp,
  2501. )
  2502. y_axes = [
  2503. "cpm()",
  2504. "p95(function.duration)",
  2505. "all_examples()",
  2506. ]
  2507. data = {
  2508. "dataset": "profileFunctions",
  2509. "start": self.three_days_ago.isoformat(),
  2510. "end": self.one_day_ago.isoformat(),
  2511. "interval": "1d",
  2512. "yAxis": y_axes,
  2513. }
  2514. response = self.client.get(self.url, data=data, format="json")
  2515. assert response.status_code == 200, response.content
  2516. assert sum(row[1][0]["count"] for row in response.data["cpm()"]["data"]) == pytest.approx(
  2517. 200 / ((self.one_day_ago - self.three_days_ago).total_seconds() / 60), rel=1e-3
  2518. )
  2519. assert any(
  2520. row[1][0]["count"] > 0 for row in response.data["p95(function.duration)"]["data"]
  2521. )
  2522. examples = [row[1][0]["count"] for row in response.data["all_examples()"]["data"]]
  2523. assert examples == [
  2524. [
  2525. {
  2526. "profile_id": transaction_function["transaction"]["contexts"]["profile"][
  2527. "profile_id"
  2528. ],
  2529. },
  2530. ],
  2531. [
  2532. {
  2533. "profiler_id": continuous_function["profiler_id"],
  2534. "thread_id": "1",
  2535. "start": continuous_timestamp.timestamp(),
  2536. "end": (continuous_timestamp + timedelta(microseconds=200_000)).timestamp(),
  2537. },
  2538. ],
  2539. ]
  2540. for y_axis in y_axes:
  2541. assert response.data[y_axis]["meta"]["fields"] == {
  2542. "time": "date",
  2543. "cpm": "number",
  2544. "p95_function_duration": "duration",
  2545. "all_examples": "string",
  2546. }
  2547. assert response.data[y_axis]["meta"]["units"] == {
  2548. "time": None,
  2549. "cpm": None,
  2550. "p95_function_duration": "nanosecond",
  2551. "all_examples": None,
  2552. }
  2553. class OrganizationEventsStatsTopNEventsProfileFunctionDatasetEndpointTest(
  2554. APITestCase, ProfilesSnubaTestCase, SearchIssueTestMixin
  2555. ):
  2556. endpoint = "sentry-api-0-organization-events-stats"
  2557. def setUp(self):
  2558. super().setUp()
  2559. self.login_as(user=self.user)
  2560. self.one_day_ago = before_now(days=1).replace(hour=10, minute=0, second=0, microsecond=0)
  2561. self.two_days_ago = before_now(days=2).replace(hour=10, minute=0, second=0, microsecond=0)
  2562. self.three_days_ago = before_now(days=3).replace(hour=10, minute=0, second=0, microsecond=0)
  2563. self.project = self.create_project()
  2564. self.url = reverse(
  2565. "sentry-api-0-organization-events-stats",
  2566. kwargs={"organization_id_or_slug": self.project.organization.slug},
  2567. )
  2568. def test_functions_dataset_simple(self):
  2569. self.store_functions(
  2570. [
  2571. {
  2572. "self_times_ns": [100 for _ in range(100)],
  2573. "package": "pkg",
  2574. "function": "foo",
  2575. "in_app": True,
  2576. },
  2577. {
  2578. "self_times_ns": [100 for _ in range(10)],
  2579. "package": "pkg",
  2580. "function": "bar",
  2581. "in_app": True,
  2582. },
  2583. ],
  2584. project=self.project,
  2585. timestamp=self.two_days_ago,
  2586. )
  2587. data = {
  2588. "dataset": "profileFunctions",
  2589. "field": ["function", "count()"],
  2590. "start": self.three_days_ago.isoformat(),
  2591. "end": self.one_day_ago.isoformat(),
  2592. "yAxis": ["cpm()", "p95(function.duration)"],
  2593. "interval": "1d",
  2594. "topEvents": "2",
  2595. "excludeOther": "1",
  2596. }
  2597. response = self.client.get(self.url, data=data, format="json")
  2598. assert response.status_code == 200, response.content
  2599. assert sum(
  2600. row[1][0]["count"] for row in response.data["foo"]["cpm()"]["data"]
  2601. ) == pytest.approx(
  2602. 100 / ((self.one_day_ago - self.three_days_ago).total_seconds() / 60), rel=1e-3
  2603. )
  2604. assert sum(
  2605. row[1][0]["count"] for row in response.data["bar"]["cpm()"]["data"]
  2606. ) == pytest.approx(
  2607. 10 / ((self.one_day_ago - self.three_days_ago).total_seconds() / 60), rel=1e-3
  2608. )
  2609. assert any(
  2610. row[1][0]["count"] > 0 for row in response.data["foo"]["p95(function.duration)"]["data"]
  2611. )
  2612. assert any(
  2613. row[1][0]["count"] > 0 for row in response.data["bar"]["p95(function.duration)"]["data"]
  2614. )
  2615. class OrganizationEventsStatsTopNEventsErrors(APITestCase, SnubaTestCase):
  2616. def setUp(self):
  2617. super().setUp()
  2618. self.login_as(user=self.user)
  2619. self.day_ago = before_now(days=1).replace(hour=10, minute=0, second=0, microsecond=0)
  2620. self.project = self.create_project()
  2621. self.project2 = self.create_project()
  2622. self.user2 = self.create_user()
  2623. self.event_data: list[_EventDataDict] = [
  2624. {
  2625. "data": {
  2626. "message": "poof",
  2627. "timestamp": iso_format(self.day_ago + timedelta(minutes=2)),
  2628. "user": {"email": self.user.email},
  2629. "tags": {"shared-tag": "yup"},
  2630. "fingerprint": ["group1"],
  2631. },
  2632. "project": self.project2,
  2633. "count": 7,
  2634. },
  2635. {
  2636. "data": {
  2637. "message": "voof",
  2638. "timestamp": iso_format(self.day_ago + timedelta(hours=1, minutes=2)),
  2639. "fingerprint": ["group2"],
  2640. "user": {"email": self.user2.email},
  2641. "tags": {"shared-tag": "yup"},
  2642. },
  2643. "project": self.project2,
  2644. "count": 6,
  2645. },
  2646. {
  2647. "data": {
  2648. "message": "very bad",
  2649. "timestamp": iso_format(self.day_ago + timedelta(minutes=2)),
  2650. "fingerprint": ["group3"],
  2651. "user": {"email": "foo@example.com"},
  2652. "tags": {"shared-tag": "yup"},
  2653. },
  2654. "project": self.project,
  2655. "count": 5,
  2656. },
  2657. {
  2658. "data": {
  2659. "message": "oh no",
  2660. "timestamp": iso_format(self.day_ago + timedelta(minutes=2)),
  2661. "fingerprint": ["group4"],
  2662. "user": {"email": "bar@example.com"},
  2663. "tags": {"shared-tag": "yup"},
  2664. },
  2665. "project": self.project,
  2666. "count": 4,
  2667. },
  2668. {
  2669. "data": {
  2670. "message": "kinda bad",
  2671. "timestamp": iso_format(self.day_ago + timedelta(minutes=2)),
  2672. "user": {"email": self.user.email},
  2673. "tags": {"shared-tag": "yup"},
  2674. "fingerprint": ["group7"],
  2675. },
  2676. "project": self.project,
  2677. "count": 3,
  2678. },
  2679. # Not in the top 5
  2680. {
  2681. "data": {
  2682. "message": "sorta bad",
  2683. "timestamp": iso_format(self.day_ago + timedelta(minutes=2)),
  2684. "fingerprint": ["group5"],
  2685. "user": {"email": "bar@example.com"},
  2686. "tags": {"shared-tag": "yup"},
  2687. },
  2688. "project": self.project,
  2689. "count": 2,
  2690. },
  2691. {
  2692. "data": {
  2693. "message": "not so bad",
  2694. "timestamp": iso_format(self.day_ago + timedelta(minutes=2)),
  2695. "fingerprint": ["group6"],
  2696. "user": {"email": "bar@example.com"},
  2697. "tags": {"shared-tag": "yup"},
  2698. },
  2699. "project": self.project,
  2700. "count": 1,
  2701. },
  2702. ]
  2703. self.events = []
  2704. for index, event_data in enumerate(self.event_data):
  2705. data = event_data["data"].copy()
  2706. for i in range(event_data["count"]):
  2707. data["event_id"] = f"{index}{i}" * 16
  2708. event = self.store_event(data, project_id=event_data["project"].id)
  2709. self.events.append(event)
  2710. self.enabled_features = {
  2711. "organizations:discover-basic": True,
  2712. }
  2713. self.url = reverse(
  2714. "sentry-api-0-organization-events-stats",
  2715. kwargs={"organization_id_or_slug": self.project.organization.slug},
  2716. )
  2717. def test_simple_top_events(self):
  2718. with self.feature(self.enabled_features):
  2719. response = self.client.get(
  2720. self.url,
  2721. data={
  2722. "start": self.day_ago.isoformat(),
  2723. "end": (self.day_ago + timedelta(hours=2)).isoformat(),
  2724. "interval": "1h",
  2725. "yAxis": "count()",
  2726. "orderby": ["-count()"],
  2727. "field": ["count()", "message", "user.email"],
  2728. "dataset": "errors",
  2729. "topEvents": "5",
  2730. },
  2731. format="json",
  2732. )
  2733. data = response.data
  2734. assert response.status_code == 200, response.content
  2735. assert len(data) == 6
  2736. for index, event in enumerate(self.events[:5]):
  2737. message = event.message or event.transaction
  2738. results = data[
  2739. ",".join([message, self.event_data[index]["data"]["user"].get("email", "None")])
  2740. ]
  2741. assert results["order"] == index
  2742. assert [{"count": self.event_data[index]["count"]}] in [
  2743. attrs for _, attrs in results["data"]
  2744. ]
  2745. other = data["Other"]
  2746. assert other["order"] == 5
  2747. assert [{"count": 3}] in [attrs for _, attrs in other["data"]]
  2748. def test_top_events_with_projects_other(self):
  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()", "project"],
  2759. "dataset": "errors",
  2760. "topEvents": "1",
  2761. },
  2762. format="json",
  2763. )
  2764. data = response.data
  2765. assert response.status_code == 200, response.content
  2766. assert set(data.keys()) == {"Other", self.project.slug}
  2767. assert data[self.project.slug]["order"] == 0
  2768. assert [attrs[0]["count"] for _, attrs in data[self.project.slug]["data"]] == [15, 0]
  2769. assert data["Other"]["order"] == 1
  2770. assert [attrs[0]["count"] for _, attrs in data["Other"]["data"]] == [7, 6]
  2771. def test_top_events_with_issue(self):
  2772. # delete a group to make sure if this happens the value becomes unknown
  2773. event_group = self.events[0].group
  2774. event_group.delete()
  2775. with self.feature(self.enabled_features):
  2776. response = self.client.get(
  2777. self.url,
  2778. data={
  2779. "start": self.day_ago.isoformat(),
  2780. "end": (self.day_ago + timedelta(hours=2)).isoformat(),
  2781. "interval": "1h",
  2782. "yAxis": "count()",
  2783. "orderby": ["-count()"],
  2784. "field": ["count()", "message", "issue"],
  2785. "topEvents": "5",
  2786. "query": "",
  2787. "dataset": "errors",
  2788. },
  2789. format="json",
  2790. )
  2791. data = response.data
  2792. assert response.status_code == 200, response.content
  2793. assert len(data) == 6
  2794. for index, event in enumerate(self.events[:4]):
  2795. message = event.message
  2796. # Because we deleted the group for event 0
  2797. if index == 0 or event.group is None:
  2798. issue = "unknown"
  2799. else:
  2800. issue = event.group.qualified_short_id
  2801. results = data[",".join([issue, message])]
  2802. assert results["order"] == index
  2803. assert [{"count": self.event_data[index]["count"]}] in [
  2804. attrs for time, attrs in results["data"]
  2805. ]
  2806. other = data["Other"]
  2807. assert other["order"] == 5
  2808. assert [attrs[0]["count"] for _, attrs in data["Other"]["data"]] == [3, 0]
  2809. @mock.patch("sentry.models.GroupManager.get_issues_mapping")
  2810. def test_top_events_with_unknown_issue(self, mock_issues_mapping):
  2811. event = self.events[0]
  2812. event_data = self.event_data[0]
  2813. # ensure that the issue mapping returns None for the issue
  2814. mock_issues_mapping.return_value = {event.group.id: None}
  2815. with self.feature(self.enabled_features):
  2816. response = self.client.get(
  2817. self.url,
  2818. data={
  2819. "start": self.day_ago.isoformat(),
  2820. "end": (self.day_ago + timedelta(hours=2)).isoformat(),
  2821. "interval": "1h",
  2822. "yAxis": "count()",
  2823. "orderby": ["-count()"],
  2824. "field": ["count()", "issue"],
  2825. "topEvents": "5",
  2826. # narrow the search to just one issue
  2827. "query": f"issue.id:{event.group.id}",
  2828. "dataset": "errors",
  2829. },
  2830. format="json",
  2831. )
  2832. assert response.status_code == 200, response.content
  2833. data = response.data
  2834. assert len(data) == 1
  2835. results = data["unknown"]
  2836. assert results["order"] == 0
  2837. assert [{"count": event_data["count"]}] in [attrs for time, attrs in results["data"]]
  2838. @mock.patch(
  2839. "sentry.search.events.builder.base.raw_snql_query",
  2840. side_effect=[{"data": [{"issue.id": 1}], "meta": []}, {"data": [], "meta": []}],
  2841. )
  2842. def test_top_events_with_issue_check_query_conditions(self, mock_query):
  2843. """ "Intentionally separate from test_top_events_with_issue
  2844. This is to test against a bug where the condition for issues wasn't included and we'd be missing data for
  2845. the interval since we'd cap out the max rows. This was not caught by the previous test since the results
  2846. would still be correct given the smaller interval & lack of data
  2847. """
  2848. with self.feature(self.enabled_features):
  2849. self.client.get(
  2850. self.url,
  2851. data={
  2852. "start": self.day_ago.isoformat(),
  2853. "end": (self.day_ago + timedelta(hours=2)).isoformat(),
  2854. "interval": "1h",
  2855. "yAxis": "count()",
  2856. "orderby": ["-count()"],
  2857. "field": ["count()", "message", "issue"],
  2858. "topEvents": "5",
  2859. "query": "!event.type:transaction",
  2860. "dataset": "errors",
  2861. },
  2862. format="json",
  2863. )
  2864. assert (
  2865. Condition(
  2866. Function(
  2867. "coalesce",
  2868. [Column("group_id", entity=Entity("events", alias="events")), 0],
  2869. "issue.id",
  2870. ),
  2871. Op.IN,
  2872. [1],
  2873. )
  2874. in mock_query.mock_calls[1].args[0].query.where
  2875. )
  2876. def test_group_id_tag_simple(self):
  2877. event_data: _EventDataDict = {
  2878. "data": {
  2879. "message": "poof",
  2880. "timestamp": iso_format(self.day_ago + timedelta(minutes=2)),
  2881. "user": {"email": self.user.email},
  2882. "tags": {"group_id": "the tag"},
  2883. "fingerprint": ["group1"],
  2884. },
  2885. "project": self.project2,
  2886. "count": 7,
  2887. }
  2888. for i in range(event_data["count"]):
  2889. event_data["data"]["event_id"] = f"a{i}" * 16
  2890. self.store_event(event_data["data"], project_id=event_data["project"].id)
  2891. data = {
  2892. "start": self.day_ago.isoformat(),
  2893. "end": (self.day_ago + timedelta(hours=2)).isoformat(),
  2894. "interval": "1h",
  2895. "yAxis": "count()",
  2896. "orderby": ["-count()"],
  2897. "field": ["count()", "group_id"],
  2898. "topEvents": "5",
  2899. "partial": "1",
  2900. }
  2901. with self.feature(self.enabled_features):
  2902. response = self.client.get(self.url, data, format="json")
  2903. assert response.status_code == 200, response.content
  2904. assert response.data["the tag"]["data"][0][1] == [{"count": 7}]
  2905. data["query"] = 'group_id:"the tag"'
  2906. with self.feature(self.enabled_features):
  2907. response = self.client.get(self.url, data, format="json")
  2908. assert response.status_code == 200
  2909. assert response.data["the tag"]["data"][0][1] == [{"count": 7}]
  2910. data["query"] = "group_id:abc"
  2911. with self.feature(self.enabled_features):
  2912. response = self.client.get(self.url, data, format="json")
  2913. assert response.status_code == 200
  2914. assert all([interval[1][0]["count"] == 0 for interval in response.data["data"]])
  2915. def test_top_events_with_error_unhandled(self):
  2916. self.login_as(user=self.user)
  2917. project = self.create_project()
  2918. prototype = load_data("android-ndk")
  2919. prototype["event_id"] = "f" * 32
  2920. prototype["logentry"] = {"formatted": "not handled"}
  2921. prototype["exception"]["values"][0]["value"] = "not handled"
  2922. prototype["exception"]["values"][0]["mechanism"]["handled"] = False
  2923. prototype["timestamp"] = iso_format(self.day_ago + timedelta(minutes=2))
  2924. self.store_event(data=prototype, project_id=project.id)
  2925. with self.feature(self.enabled_features):
  2926. response = self.client.get(
  2927. self.url,
  2928. data={
  2929. "start": self.day_ago.isoformat(),
  2930. "end": (self.day_ago + timedelta(hours=2)).isoformat(),
  2931. "interval": "1h",
  2932. "yAxis": "count()",
  2933. "orderby": ["-count()"],
  2934. "field": ["count()", "error.unhandled"],
  2935. "topEvents": "5",
  2936. },
  2937. format="json",
  2938. )
  2939. data = response.data
  2940. assert response.status_code == 200, response.content
  2941. assert len(data) == 2