test_organization_events_stats.py 93 KB

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