test_organization_events_stats.py 105 KB

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