test_organization_events_stats.py 102 KB

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