test_organization_events_stats.py 125 KB

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