test_organization_events_stats.py 104 KB

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