test_organization_events_stats.py 120 KB

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