test_organization_sessions.py 76 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064
  1. import datetime
  2. from unittest.mock import patch
  3. from uuid import uuid4
  4. import pytest
  5. from django.urls import reverse
  6. from freezegun import freeze_time
  7. from sentry.release_health.duplex import DuplexReleaseHealthBackend
  8. from sentry.release_health.metrics import MetricsReleaseHealthBackend
  9. from sentry.testutils import APITestCase, SnubaTestCase
  10. from sentry.testutils.cases import SessionMetricsReleaseHealthTestCase, SessionMetricsTestCase
  11. from sentry.testutils.helpers.features import Feature
  12. from sentry.testutils.helpers.link_header import parse_link_header
  13. from sentry.utils.cursors import Cursor
  14. from sentry.utils.dates import to_timestamp
  15. def result_sorted(result):
  16. """sort the groups of the results array by the `by` object, ensuring a stable order"""
  17. def stable_dict(d):
  18. return tuple(sorted(d.items(), key=lambda t: t[0]))
  19. result["groups"].sort(key=lambda group: stable_dict(group["by"]))
  20. return result
  21. ONE_DAY_AGO = datetime.datetime.now(tz=datetime.timezone.utc) - datetime.timedelta(days=1)
  22. TWO_DAYS_AGO = datetime.datetime.now(tz=datetime.timezone.utc) - datetime.timedelta(days=2)
  23. MOCK_DATETIME = ONE_DAY_AGO.replace(hour=12, minute=27, second=28, microsecond=303000)
  24. MOCK_DATETIME_PLUS_TEN_MINUTES = MOCK_DATETIME + datetime.timedelta(minutes=10)
  25. SNUBA_TIME_FORMAT = "%Y-%m-%dT%H:%M:%SZ"
  26. MOCK_DATETIME_START_OF_DAY = MOCK_DATETIME.replace(hour=0, minute=0, second=0)
  27. TIMESTAMP = to_timestamp(MOCK_DATETIME)
  28. RECEIVED = TIMESTAMP
  29. SESSION_STARTED = TIMESTAMP // 3600 * 3600 # round to the hour
  30. TEMPLATE = {
  31. "distinct_id": "00000000-0000-0000-0000-000000000000",
  32. "status": "exited",
  33. "seq": 0,
  34. "release": "foo@1.0.0",
  35. "environment": "production",
  36. "retention_days": 90,
  37. "duration": 123.4,
  38. "errors": 0,
  39. "started": SESSION_STARTED,
  40. "received": RECEIVED,
  41. }
  42. def make_duration(kwargs):
  43. """Randomish but deterministic duration"""
  44. return float(len(str(kwargs)))
  45. def make_session(project, **kwargs):
  46. return dict(
  47. dict(
  48. TEMPLATE,
  49. session_id=uuid4().hex,
  50. org_id=project.organization_id,
  51. project_id=project.id,
  52. duration=make_duration(kwargs),
  53. ),
  54. **kwargs,
  55. )
  56. class OrganizationSessionsEndpointTest(APITestCase, SnubaTestCase):
  57. def setUp(self):
  58. super().setUp()
  59. self.setup_fixture()
  60. def setup_fixture(self):
  61. self.organization1 = self.organization
  62. self.organization2 = self.create_organization()
  63. self.organization3 = self.create_organization()
  64. self.project1 = self.project
  65. self.project2 = self.create_project()
  66. self.project3 = self.create_project()
  67. self.project4 = self.create_project(organization=self.organization2)
  68. self.user2 = self.create_user(is_superuser=False)
  69. self.create_member(
  70. user=self.user2, organization=self.organization1, role="member", teams=[]
  71. )
  72. self.create_member(user=self.user, organization=self.organization3, role="admin", teams=[])
  73. self.create_environment(self.project2, name="development")
  74. self.store_session(make_session(self.project1, started=SESSION_STARTED + 12 * 60))
  75. self.store_session(
  76. make_session(self.project1, started=SESSION_STARTED + 24 * 60, release="foo@1.1.0")
  77. )
  78. self.store_session(make_session(self.project1, started=SESSION_STARTED - 60 * 60))
  79. self.store_session(make_session(self.project1, started=SESSION_STARTED - 12 * 60 * 60))
  80. self.store_session(make_session(self.project2, status="crashed"))
  81. self.store_session(make_session(self.project2, environment="development"))
  82. self.store_session(make_session(self.project3, errors=1, release="foo@1.2.0"))
  83. self.store_session(
  84. make_session(
  85. self.project3,
  86. distinct_id="39887d89-13b2-4c84-8c23-5d13d2102664",
  87. started=SESSION_STARTED - 60 * 60,
  88. )
  89. )
  90. self.store_session(
  91. make_session(
  92. self.project3, distinct_id="39887d89-13b2-4c84-8c23-5d13d2102664", errors=1
  93. )
  94. )
  95. self.store_session(make_session(self.project4))
  96. def do_request(self, query, user=None, org=None):
  97. self.login_as(user=user or self.user)
  98. url = reverse(
  99. "sentry-api-0-organization-sessions",
  100. kwargs={"organization_slug": (org or self.organization).slug},
  101. )
  102. return self.client.get(url, query, format="json")
  103. def test_empty_request(self):
  104. response = self.do_request({})
  105. assert response.status_code == 400, response.content
  106. assert response.data == {"detail": 'Request is missing a "field"'}
  107. def test_inaccessible_project(self):
  108. response = self.do_request({"project": [self.project4.id]})
  109. assert response.status_code == 403, response.content
  110. assert response.data == {"detail": "You do not have permission to perform this action."}
  111. def test_unknown_field(self):
  112. response = self.do_request({"field": ["summ(session)"]})
  113. assert response.status_code == 400, response.content
  114. assert response.data == {"detail": 'Invalid field: "summ(session)"'}
  115. def test_unknown_groupby(self):
  116. response = self.do_request({"field": ["sum(session)"], "groupBy": ["environment_"]})
  117. assert response.status_code == 400, response.content
  118. assert response.data == {"detail": 'Invalid groupBy: "environment_"'}
  119. def test_illegal_groupby(self):
  120. response = self.do_request({"field": ["sum(session)"], "groupBy": ["issue.id"]})
  121. assert response.status_code == 400, response.content
  122. assert response.data == {"detail": 'Invalid groupBy: "issue.id"'}
  123. def test_invalid_query(self):
  124. response = self.do_request(
  125. {"statsPeriod": "1d", "field": ["sum(session)"], "query": ["foo:bar"]}
  126. )
  127. assert response.status_code == 400, response.content
  128. assert response.data == {"detail": 'Invalid query field: "foo"'}
  129. response = self.do_request(
  130. {
  131. "statsPeriod": "1d",
  132. "field": ["sum(session)"],
  133. "query": ["release:foo-bar@1.2.3 (123)"],
  134. }
  135. )
  136. assert response.status_code == 400, response.content
  137. # TODO: it would be good to provide a better error here,
  138. # since its not obvious where `message` comes from.
  139. assert response.data == {"detail": 'Invalid query field: "message"'}
  140. def test_illegal_query(self):
  141. response = self.do_request(
  142. {"statsPeriod": "1d", "field": ["sum(session)"], "query": ["issue.id:123"]}
  143. )
  144. assert response.status_code == 400, response.content
  145. assert response.data == {"detail": 'Invalid query field: "group_id"'}
  146. def test_too_many_points(self):
  147. # default statsPeriod is 90d
  148. response = self.do_request({"field": ["sum(session)"], "interval": "1h"})
  149. assert response.status_code == 400, response.content
  150. assert response.data == {
  151. "detail": "Your interval and date range would create too many results. "
  152. "Use a larger interval, or a smaller date range."
  153. }
  154. @freeze_time(MOCK_DATETIME)
  155. def test_future_request(self):
  156. start = MOCK_DATETIME + datetime.timedelta(days=1)
  157. end = MOCK_DATETIME + datetime.timedelta(days=2)
  158. response = self.do_request(
  159. {
  160. "project": [-1],
  161. "interval": "1h",
  162. "field": ["sum(session)"],
  163. "start": start.strftime(SNUBA_TIME_FORMAT),
  164. "end": end.strftime(SNUBA_TIME_FORMAT),
  165. }
  166. )
  167. assert response.status_code == 200, response.content
  168. @freeze_time(MOCK_DATETIME)
  169. def test_timeseries_interval(self):
  170. response = self.do_request(
  171. {"project": [-1], "statsPeriod": "1d", "interval": "1d", "field": ["sum(session)"]}
  172. )
  173. start_of_day_snuba_format = MOCK_DATETIME_START_OF_DAY.strftime(SNUBA_TIME_FORMAT)
  174. assert response.status_code == 200, response.content
  175. assert result_sorted(response.data) == {
  176. "start": start_of_day_snuba_format,
  177. "end": MOCK_DATETIME.replace(minute=28, second=0).strftime(SNUBA_TIME_FORMAT),
  178. "query": "",
  179. "intervals": [start_of_day_snuba_format],
  180. "groups": [{"by": {}, "series": {"sum(session)": [9]}, "totals": {"sum(session)": 9}}],
  181. }
  182. response = self.do_request(
  183. {"project": [-1], "statsPeriod": "1d", "interval": "6h", "field": ["sum(session)"]}
  184. )
  185. assert response.status_code == 200, response.content
  186. assert result_sorted(response.data) == {
  187. "start": TWO_DAYS_AGO.replace(hour=18, minute=0, second=0).strftime(SNUBA_TIME_FORMAT),
  188. "end": MOCK_DATETIME.replace(minute=28, second=0).strftime(SNUBA_TIME_FORMAT),
  189. "query": "",
  190. "intervals": [
  191. TWO_DAYS_AGO.replace(hour=18, minute=0, second=0).strftime(SNUBA_TIME_FORMAT),
  192. MOCK_DATETIME.replace(hour=0, minute=0, second=0).strftime(SNUBA_TIME_FORMAT),
  193. MOCK_DATETIME.replace(hour=6, minute=0, second=0).strftime(SNUBA_TIME_FORMAT),
  194. MOCK_DATETIME.replace(hour=12, minute=0, second=0).strftime(SNUBA_TIME_FORMAT),
  195. ],
  196. "groups": [
  197. {"by": {}, "series": {"sum(session)": [0, 1, 2, 6]}, "totals": {"sum(session)": 9}}
  198. ],
  199. }
  200. @freeze_time(MOCK_DATETIME)
  201. def test_user_all_accessible(self):
  202. response = self.do_request(
  203. {"project": [-1], "statsPeriod": "1d", "interval": "1d", "field": ["sum(session)"]},
  204. user=self.user2,
  205. )
  206. start_of_day_snuba_format = MOCK_DATETIME_START_OF_DAY.strftime(SNUBA_TIME_FORMAT)
  207. assert response.status_code == 200, response.content
  208. assert result_sorted(response.data) == {
  209. "start": start_of_day_snuba_format,
  210. "end": MOCK_DATETIME.replace(hour=12, minute=28, second=0).strftime(SNUBA_TIME_FORMAT),
  211. "query": "",
  212. "intervals": [start_of_day_snuba_format],
  213. "groups": [{"by": {}, "series": {"sum(session)": [9]}, "totals": {"sum(session)": 9}}],
  214. }
  215. def test_no_projects(self):
  216. response = self.do_request(
  217. {"project": [-1], "statsPeriod": "1d", "interval": "1d", "field": ["sum(session)"]},
  218. org=self.organization3,
  219. )
  220. assert response.status_code == 400, response.content
  221. assert response.data == {"detail": "No projects available"}
  222. @freeze_time(MOCK_DATETIME_PLUS_TEN_MINUTES)
  223. def test_minute_resolution(self):
  224. with self.feature("organizations:minute-resolution-sessions"):
  225. response = self.do_request(
  226. {
  227. "project": [self.project1.id, self.project2.id],
  228. "statsPeriod": "30m",
  229. "interval": "10m",
  230. "field": ["sum(session)"],
  231. }
  232. )
  233. assert response.status_code == 200, response.content
  234. assert result_sorted(response.data) == {
  235. "start": MOCK_DATETIME.replace(hour=12, minute=0, second=0).strftime(
  236. SNUBA_TIME_FORMAT
  237. ),
  238. "end": MOCK_DATETIME.replace(hour=12, minute=38, second=0).strftime(
  239. SNUBA_TIME_FORMAT
  240. ),
  241. "query": "",
  242. "intervals": [
  243. *[
  244. MOCK_DATETIME.replace(hour=12, minute=min, second=0).strftime(
  245. SNUBA_TIME_FORMAT
  246. )
  247. for min in [0, 10, 20, 30]
  248. ],
  249. ],
  250. "groups": [
  251. {
  252. "by": {},
  253. "series": {"sum(session)": [2, 1, 1, 0]},
  254. "totals": {"sum(session)": 4},
  255. }
  256. ],
  257. }
  258. @freeze_time(MOCK_DATETIME_PLUS_TEN_MINUTES)
  259. def test_10s_resolution(self):
  260. with self.feature("organizations:minute-resolution-sessions"):
  261. response = self.do_request(
  262. {
  263. "project": [self.project1.id],
  264. "statsPeriod": "1m",
  265. "interval": "10s",
  266. "field": ["sum(session)"],
  267. }
  268. )
  269. assert response.status_code == 200, response.content
  270. from sentry.api.endpoints.organization_sessions import release_health
  271. if release_health.is_metrics_based():
  272. # With the metrics backend, we should get exactly what we asked for,
  273. # 6 intervals with 10 second length. However, because of rounding,
  274. # we get it rounded to the next minute (see https://github.com/getsentry/sentry/blob/d6c59c32307eee7162301c76b74af419055b9b39/src/sentry/snuba/sessions_v2.py#L388-L392)
  275. assert len(response.data["intervals"]) == 9
  276. else:
  277. # With the sessions backend, the entire period will be aligned
  278. # to one hour, and the resolution will still be one minute:
  279. assert len(response.data["intervals"]) == 38
  280. @freeze_time(MOCK_DATETIME)
  281. def test_filter_projects(self):
  282. response = self.do_request(
  283. {
  284. "statsPeriod": "1d",
  285. "interval": "1d",
  286. "field": ["sum(session)"],
  287. "project": [self.project2.id, self.project3.id],
  288. }
  289. )
  290. assert response.status_code == 200, response.content
  291. assert result_sorted(response.data)["groups"] == [
  292. {"by": {}, "series": {"sum(session)": [5]}, "totals": {"sum(session)": 5}}
  293. ]
  294. @freeze_time(MOCK_DATETIME)
  295. def test_filter_environment(self):
  296. response = self.do_request(
  297. {
  298. "project": [-1],
  299. "statsPeriod": "1d",
  300. "interval": "1d",
  301. "field": ["sum(session)"],
  302. "query": "environment:development",
  303. }
  304. )
  305. assert response.status_code == 200, response.content
  306. assert result_sorted(response.data)["groups"] == [
  307. {"by": {}, "series": {"sum(session)": [1]}, "totals": {"sum(session)": 1}}
  308. ]
  309. response = self.do_request(
  310. {
  311. "project": [-1],
  312. "statsPeriod": "1d",
  313. "interval": "1d",
  314. "field": ["sum(session)"],
  315. "environment": ["development"],
  316. }
  317. )
  318. assert response.status_code == 200, response.content
  319. assert result_sorted(response.data)["groups"] == [
  320. {"by": {}, "series": {"sum(session)": [1]}, "totals": {"sum(session)": 1}}
  321. ]
  322. @freeze_time(MOCK_DATETIME)
  323. def test_filter_release(self):
  324. response = self.do_request(
  325. {
  326. "project": [-1],
  327. "statsPeriod": "1d",
  328. "interval": "1d",
  329. "field": ["sum(session)"],
  330. "query": "release:foo@1.1.0",
  331. }
  332. )
  333. assert response.status_code == 200, response.content
  334. assert result_sorted(response.data)["groups"] == [
  335. {"by": {}, "series": {"sum(session)": [1]}, "totals": {"sum(session)": 1}}
  336. ]
  337. response = self.do_request(
  338. {
  339. "project": [-1],
  340. "statsPeriod": "1d",
  341. "interval": "1d",
  342. "field": ["sum(session)"],
  343. "query": 'release:"foo@1.1.0" or release:"foo@1.2.0"',
  344. }
  345. )
  346. assert response.status_code == 200, response.content
  347. assert result_sorted(response.data)["groups"] == [
  348. {"by": {}, "series": {"sum(session)": [2]}, "totals": {"sum(session)": 2}}
  349. ]
  350. response = self.do_request(
  351. {
  352. "project": [-1],
  353. "statsPeriod": "1d",
  354. "interval": "1d",
  355. "field": ["sum(session)"],
  356. "query": 'release:"foo@1.1.0" or release:["foo@1.2.0", release:"foo@1.3.0"]',
  357. "groupBy": ["release"],
  358. }
  359. )
  360. assert response.status_code == 200, response.content
  361. assert result_sorted(response.data)["groups"] == [
  362. {
  363. "by": {"release": "foo@1.1.0"},
  364. "series": {"sum(session)": [1]},
  365. "totals": {"sum(session)": 1},
  366. },
  367. {
  368. "by": {"release": "foo@1.2.0"},
  369. "series": {"sum(session)": [1]},
  370. "totals": {"sum(session)": 1},
  371. },
  372. ]
  373. @freeze_time(MOCK_DATETIME)
  374. def test_filter_unknown_release(self):
  375. response = self.do_request(
  376. {
  377. "project": [-1],
  378. "statsPeriod": "1d",
  379. "interval": "1h",
  380. "field": ["sum(session)"],
  381. "query": "release:foo@6.6.6",
  382. "groupBy": "session.status",
  383. }
  384. )
  385. assert response.status_code == 200, response.content
  386. @freeze_time(MOCK_DATETIME)
  387. def test_filter_unknown_release_in(self):
  388. response = self.do_request(
  389. {
  390. "project": [-1],
  391. "statsPeriod": "1d",
  392. "interval": "1d",
  393. "field": ["sum(session)"],
  394. "query": "release:[foo@6.6.6]",
  395. "groupBy": "session.status",
  396. }
  397. )
  398. assert response.status_code == 200, response.content
  399. assert result_sorted(response.data)["groups"] == [
  400. {
  401. "by": {"session.status": status},
  402. "series": {"sum(session)": [0]},
  403. "totals": {"sum(session)": 0},
  404. }
  405. for status in ("abnormal", "crashed", "errored", "healthy")
  406. ]
  407. @freeze_time(MOCK_DATETIME)
  408. def test_groupby_project(self):
  409. response = self.do_request(
  410. {
  411. "project": [-1],
  412. "statsPeriod": "1d",
  413. "interval": "1d",
  414. "field": ["sum(session)"],
  415. "groupBy": ["project"],
  416. }
  417. )
  418. assert response.status_code == 200, response.content
  419. assert result_sorted(response.data)["groups"] == [
  420. {
  421. "by": {"project": self.project1.id},
  422. "series": {"sum(session)": [4]},
  423. "totals": {"sum(session)": 4},
  424. },
  425. {
  426. "by": {"project": self.project2.id},
  427. "series": {"sum(session)": [2]},
  428. "totals": {"sum(session)": 2},
  429. },
  430. {
  431. "by": {"project": self.project3.id},
  432. "series": {"sum(session)": [3]},
  433. "totals": {"sum(session)": 3},
  434. },
  435. ]
  436. @freeze_time(MOCK_DATETIME)
  437. def test_groupby_environment(self):
  438. response = self.do_request(
  439. {
  440. "project": [-1],
  441. "statsPeriod": "1d",
  442. "interval": "1d",
  443. "field": ["sum(session)"],
  444. "groupBy": ["environment"],
  445. }
  446. )
  447. assert response.status_code == 200, response.content
  448. assert result_sorted(response.data)["groups"] == [
  449. {
  450. "by": {"environment": "development"},
  451. "series": {"sum(session)": [1]},
  452. "totals": {"sum(session)": 1},
  453. },
  454. {
  455. "by": {"environment": "production"},
  456. "series": {"sum(session)": [8]},
  457. "totals": {"sum(session)": 8},
  458. },
  459. ]
  460. @freeze_time(MOCK_DATETIME)
  461. def test_groupby_release(self):
  462. response = self.do_request(
  463. {
  464. "project": [-1],
  465. "statsPeriod": "1d",
  466. "interval": "1d",
  467. "field": ["sum(session)"],
  468. "groupBy": ["release"],
  469. }
  470. )
  471. assert response.status_code == 200, response.content
  472. assert result_sorted(response.data)["groups"] == [
  473. {
  474. "by": {"release": "foo@1.0.0"},
  475. "series": {"sum(session)": [7]},
  476. "totals": {"sum(session)": 7},
  477. },
  478. {
  479. "by": {"release": "foo@1.1.0"},
  480. "series": {"sum(session)": [1]},
  481. "totals": {"sum(session)": 1},
  482. },
  483. {
  484. "by": {"release": "foo@1.2.0"},
  485. "series": {"sum(session)": [1]},
  486. "totals": {"sum(session)": 1},
  487. },
  488. ]
  489. @freeze_time(MOCK_DATETIME)
  490. def test_groupby_status(self):
  491. response = self.do_request(
  492. {
  493. "project": [-1],
  494. "statsPeriod": "1d",
  495. "interval": "1d",
  496. "field": ["sum(session)"],
  497. "groupBy": ["session.status"],
  498. }
  499. )
  500. assert response.status_code == 200, response.content
  501. assert result_sorted(response.data)["groups"] == [
  502. {
  503. "by": {"session.status": "abnormal"},
  504. "series": {"sum(session)": [0]},
  505. "totals": {"sum(session)": 0},
  506. },
  507. {
  508. "by": {"session.status": "crashed"},
  509. "series": {"sum(session)": [1]},
  510. "totals": {"sum(session)": 1},
  511. },
  512. {
  513. "by": {"session.status": "errored"},
  514. "series": {"sum(session)": [2]},
  515. "totals": {"sum(session)": 2},
  516. },
  517. {
  518. "by": {"session.status": "healthy"},
  519. "series": {"sum(session)": [6]},
  520. "totals": {"sum(session)": 6},
  521. },
  522. ]
  523. @freeze_time(MOCK_DATETIME)
  524. def test_groupby_cross(self):
  525. response = self.do_request(
  526. {
  527. "project": [-1],
  528. "statsPeriod": "1d",
  529. "interval": "1d",
  530. "field": ["sum(session)"],
  531. "groupBy": ["release", "environment"],
  532. }
  533. )
  534. assert response.status_code == 200, response.content
  535. assert result_sorted(response.data)["groups"] == [
  536. {
  537. "by": {"environment": "development", "release": "foo@1.0.0"},
  538. "series": {"sum(session)": [1]},
  539. "totals": {"sum(session)": 1},
  540. },
  541. {
  542. "by": {"environment": "production", "release": "foo@1.0.0"},
  543. "series": {"sum(session)": [6]},
  544. "totals": {"sum(session)": 6},
  545. },
  546. {
  547. "by": {"environment": "production", "release": "foo@1.1.0"},
  548. "series": {"sum(session)": [1]},
  549. "totals": {"sum(session)": 1},
  550. },
  551. {
  552. "by": {"environment": "production", "release": "foo@1.2.0"},
  553. "series": {"sum(session)": [1]},
  554. "totals": {"sum(session)": 1},
  555. },
  556. ]
  557. @freeze_time(MOCK_DATETIME)
  558. def test_users_groupby(self):
  559. response = self.do_request(
  560. {
  561. "project": [-1],
  562. "statsPeriod": "1d",
  563. "interval": "1d",
  564. "field": ["count_unique(user)"],
  565. }
  566. )
  567. assert response.status_code == 200, response.content
  568. assert result_sorted(response.data)["groups"] == [
  569. {"by": {}, "series": {"count_unique(user)": [1]}, "totals": {"count_unique(user)": 1}}
  570. ]
  571. response = self.do_request(
  572. {
  573. "project": [-1],
  574. "statsPeriod": "1d",
  575. "interval": "1d",
  576. "field": ["count_unique(user)"],
  577. "groupBy": ["session.status"],
  578. }
  579. )
  580. assert response.status_code == 200, response.content
  581. assert result_sorted(response.data)["groups"] == [
  582. {
  583. "by": {"session.status": "abnormal"},
  584. "series": {"count_unique(user)": [0]},
  585. "totals": {"count_unique(user)": 0},
  586. },
  587. {
  588. "by": {"session.status": "crashed"},
  589. "series": {"count_unique(user)": [0]},
  590. "totals": {"count_unique(user)": 0},
  591. },
  592. {
  593. "by": {"session.status": "errored"},
  594. "series": {"count_unique(user)": [1]},
  595. "totals": {"count_unique(user)": 1},
  596. },
  597. {
  598. "by": {"session.status": "healthy"},
  599. "series": {"count_unique(user)": [0]},
  600. "totals": {"count_unique(user)": 0},
  601. },
  602. ]
  603. expected_duration_values = {
  604. "avg(session.duration)": 42375.0,
  605. "max(session.duration)": 80000.0,
  606. "p50(session.duration)": 33500.0,
  607. "p75(session.duration)": 53750.0,
  608. "p90(session.duration)": 71600.0,
  609. "p95(session.duration)": 75800.0,
  610. "p99(session.duration)": 79159.99999999999,
  611. }
  612. @freeze_time(MOCK_DATETIME)
  613. def test_users_groupby_status_advanced(self):
  614. project = self.create_project()
  615. user1 = uuid4().hex
  616. session1 = uuid4().hex
  617. user2 = uuid4().hex
  618. session2a = uuid4().hex
  619. session2b = uuid4().hex
  620. user3 = uuid4().hex
  621. session3 = uuid4().hex
  622. self.store_session(
  623. make_session(project, session_id=session1, distinct_id=user1, status="ok")
  624. )
  625. self.store_session(
  626. make_session(
  627. project, session_id=session1, distinct_id=user1, seq=1, errors=1, status="errored"
  628. )
  629. )
  630. self.store_session(
  631. make_session(project, session_id=session1, distinct_id=user1, seq=2, status="crashed")
  632. )
  633. self.store_session(
  634. make_session(project, session_id=session2a, distinct_id=user2, status="ok")
  635. )
  636. self.store_session(
  637. make_session(project, session_id=session2b, distinct_id=user2, status="ok")
  638. )
  639. self.store_session(
  640. make_session(project, session_id=session2b, distinct_id=user2, status="abnormal")
  641. )
  642. self.store_session(
  643. make_session(
  644. project, session_id=session3, distinct_id=user3, errors=123, status="errored"
  645. )
  646. )
  647. # Add some extra healthy users:
  648. for _ in range(3):
  649. user = uuid4().hex
  650. self.store_session(make_session(project, distinct_id=user))
  651. # First, check if totals make sense:
  652. response = self.do_request(
  653. {
  654. "project": [project.id],
  655. "statsPeriod": "1d",
  656. "interval": "1d",
  657. "field": ["count_unique(user)"],
  658. }
  659. )
  660. assert response.status_code == 200, response.content
  661. assert result_sorted(response.data)["groups"] == [
  662. {
  663. "by": {},
  664. "series": {"count_unique(user)": [6]},
  665. "totals": {"count_unique(user)": 6},
  666. },
  667. ]
  668. # Then check if grouping makes sense:
  669. response = self.do_request(
  670. {
  671. "project": [project.id],
  672. "statsPeriod": "1d",
  673. "interval": "1d",
  674. "field": ["count_unique(user)"],
  675. "groupBy": ["session.status"],
  676. }
  677. )
  678. assert response.status_code == 200, response.content
  679. assert result_sorted(response.data)["groups"] == [
  680. {
  681. "by": {"session.status": "abnormal"},
  682. "series": {"count_unique(user)": [1]},
  683. "totals": {"count_unique(user)": 1},
  684. },
  685. {
  686. "by": {"session.status": "crashed"},
  687. "series": {"count_unique(user)": [1]},
  688. "totals": {"count_unique(user)": 1},
  689. },
  690. {
  691. "by": {"session.status": "errored"},
  692. "series": {"count_unique(user)": [1]},
  693. "totals": {"count_unique(user)": 1},
  694. },
  695. {
  696. # user
  697. "by": {"session.status": "healthy"},
  698. "series": {"count_unique(user)": [3]},
  699. "totals": {"count_unique(user)": 3},
  700. },
  701. ]
  702. @freeze_time(MOCK_DATETIME)
  703. def test_duration_percentiles(self):
  704. response = self.do_request(
  705. {
  706. "project": [-1],
  707. "statsPeriod": "1d",
  708. "interval": "1d",
  709. "field": [
  710. "avg(session.duration)",
  711. "p50(session.duration)",
  712. "p75(session.duration)",
  713. "p90(session.duration)",
  714. "p95(session.duration)",
  715. "p99(session.duration)",
  716. "max(session.duration)",
  717. ],
  718. }
  719. )
  720. assert response.status_code == 200, response.content
  721. expected = self.expected_duration_values
  722. groups = result_sorted(response.data)["groups"]
  723. assert len(groups) == 1, groups
  724. group = groups[0]
  725. assert group["by"] == {}
  726. assert group["totals"] == pytest.approx(expected)
  727. for key, series in group["series"].items():
  728. assert series == pytest.approx([expected[key]])
  729. @freeze_time(MOCK_DATETIME)
  730. def test_duration_percentiles_groupby(self):
  731. response = self.do_request(
  732. {
  733. "project": [-1],
  734. "statsPeriod": "1d",
  735. "interval": "1d",
  736. "field": [
  737. "avg(session.duration)",
  738. "p50(session.duration)",
  739. "p75(session.duration)",
  740. "p90(session.duration)",
  741. "p95(session.duration)",
  742. "p99(session.duration)",
  743. "max(session.duration)",
  744. ],
  745. "groupBy": "session.status",
  746. }
  747. )
  748. assert response.status_code == 200, response.content
  749. expected = self.expected_duration_values
  750. seen = set() # Make sure all session statuses are listed
  751. for group in result_sorted(response.data)["groups"]:
  752. seen.add(group["by"].get("session.status"))
  753. if group["by"] == {"session.status": "healthy"}:
  754. assert group["totals"] == pytest.approx(expected)
  755. for key, series in group["series"].items():
  756. assert series == pytest.approx([expected[key]])
  757. else:
  758. # Everything's none:
  759. assert group["totals"] == {key: None for key in expected}, group["by"]
  760. assert group["series"] == {key: [None] for key in expected}
  761. assert seen == {"abnormal", "crashed", "errored", "healthy"}
  762. @freeze_time(MOCK_DATETIME)
  763. def test_snuba_limit_exceeded(self):
  764. # 2 * 3 => only show two groups
  765. with patch("sentry.snuba.sessions_v2.SNUBA_LIMIT", 6), patch(
  766. "sentry.snuba.metrics.query.MAX_POINTS", 6
  767. ):
  768. response = self.do_request(
  769. {
  770. "project": [-1],
  771. "statsPeriod": "3d",
  772. "interval": "1d",
  773. # "user" is the first field, but "session" always wins:
  774. "field": ["count_unique(user)", "sum(session)"],
  775. "groupBy": ["project", "release", "environment"],
  776. }
  777. )
  778. assert response.status_code == 200, response.content
  779. assert result_sorted(response.data)["groups"] == [
  780. {
  781. "by": {
  782. "release": "foo@1.0.0",
  783. "environment": "production",
  784. "project": self.project1.id,
  785. },
  786. "totals": {"sum(session)": 3, "count_unique(user)": 0},
  787. "series": {"sum(session)": [0, 0, 3], "count_unique(user)": [0, 0, 0]},
  788. },
  789. {
  790. "by": {
  791. "release": "foo@1.0.0",
  792. "environment": "production",
  793. "project": self.project3.id,
  794. },
  795. "totals": {"sum(session)": 2, "count_unique(user)": 1},
  796. "series": {"sum(session)": [0, 0, 2], "count_unique(user)": [0, 0, 1]},
  797. },
  798. ]
  799. @freeze_time(MOCK_DATETIME)
  800. def test_snuba_limit_exceeded_groupby_status(self):
  801. """Get consistent result when grouping by status"""
  802. # 2 * 3 => only show two groups
  803. with patch("sentry.snuba.sessions_v2.SNUBA_LIMIT", 6), patch(
  804. "sentry.snuba.metrics.query.MAX_POINTS", 6
  805. ):
  806. response = self.do_request(
  807. {
  808. "project": [-1],
  809. "statsPeriod": "3d",
  810. "interval": "1d",
  811. "field": ["sum(session)", "count_unique(user)"],
  812. "groupBy": ["project", "release", "environment", "session.status"],
  813. }
  814. )
  815. assert response.status_code == 200, response.content
  816. assert result_sorted(response.data)["groups"] == [
  817. {
  818. "by": {
  819. "project": self.project1.id,
  820. "release": "foo@1.0.0",
  821. "session.status": "abnormal",
  822. "environment": "production",
  823. },
  824. "totals": {"sum(session)": 0, "count_unique(user)": 0},
  825. "series": {"sum(session)": [0, 0, 0], "count_unique(user)": [0, 0, 0]},
  826. },
  827. {
  828. "by": {
  829. "project": self.project1.id,
  830. "release": "foo@1.0.0",
  831. "session.status": "crashed",
  832. "environment": "production",
  833. },
  834. "totals": {"sum(session)": 0, "count_unique(user)": 0},
  835. "series": {"sum(session)": [0, 0, 0], "count_unique(user)": [0, 0, 0]},
  836. },
  837. {
  838. "by": {
  839. "project": self.project1.id,
  840. "release": "foo@1.0.0",
  841. "environment": "production",
  842. "session.status": "errored",
  843. },
  844. "totals": {"sum(session)": 0, "count_unique(user)": 0},
  845. "series": {"sum(session)": [0, 0, 0], "count_unique(user)": [0, 0, 0]},
  846. },
  847. {
  848. "by": {
  849. "project": self.project1.id,
  850. "session.status": "healthy",
  851. "release": "foo@1.0.0",
  852. "environment": "production",
  853. },
  854. "totals": {"sum(session)": 3, "count_unique(user)": 0},
  855. "series": {"sum(session)": [0, 0, 3], "count_unique(user)": [0, 0, 0]},
  856. },
  857. {
  858. "by": {
  859. "session.status": "abnormal",
  860. "release": "foo@1.0.0",
  861. "project": self.project3.id,
  862. "environment": "production",
  863. },
  864. "totals": {"sum(session)": 0, "count_unique(user)": 0},
  865. "series": {"sum(session)": [0, 0, 0], "count_unique(user)": [0, 0, 0]},
  866. },
  867. {
  868. "by": {
  869. "release": "foo@1.0.0",
  870. "project": self.project3.id,
  871. "session.status": "crashed",
  872. "environment": "production",
  873. },
  874. "totals": {"sum(session)": 0, "count_unique(user)": 0},
  875. "series": {"sum(session)": [0, 0, 0], "count_unique(user)": [0, 0, 0]},
  876. },
  877. {
  878. "by": {
  879. "release": "foo@1.0.0",
  880. "project": self.project3.id,
  881. "environment": "production",
  882. "session.status": "errored",
  883. },
  884. "totals": {"sum(session)": 1, "count_unique(user)": 1},
  885. "series": {"sum(session)": [0, 0, 1], "count_unique(user)": [0, 0, 1]},
  886. },
  887. {
  888. "by": {
  889. "session.status": "healthy",
  890. "release": "foo@1.0.0",
  891. "project": self.project3.id,
  892. "environment": "production",
  893. },
  894. "totals": {"sum(session)": 1, "count_unique(user)": 0},
  895. "series": {"sum(session)": [0, 0, 1], "count_unique(user)": [0, 0, 0]},
  896. },
  897. ]
  898. @freeze_time(MOCK_DATETIME)
  899. def test_environment_filter_not_present_in_query(self):
  900. self.create_environment(name="abc")
  901. response = self.do_request(
  902. {
  903. "project": [-1],
  904. "statsPeriod": "1d",
  905. "interval": "1d",
  906. "field": ["sum(session)"],
  907. "environment": ["development", "abc"],
  908. }
  909. )
  910. assert response.status_code == 200, response.content
  911. assert result_sorted(response.data)["groups"] == [
  912. {"by": {}, "series": {"sum(session)": [1]}, "totals": {"sum(session)": 1}}
  913. ]
  914. @freeze_time(MOCK_DATETIME)
  915. def test_sessions_without_users(self):
  916. # The first field defines by which groups additional queries are filtered
  917. # But if the first field is the user count, the series should still
  918. # contain the session counts even if the project does not track users
  919. response = self.do_request(
  920. {
  921. "project": self.project.id, # project without users
  922. "statsPeriod": "1d",
  923. "interval": "1d",
  924. "field": ["count_unique(user)", "sum(session)"],
  925. "groupBy": "release",
  926. }
  927. )
  928. assert response.status_code == 200, response.content
  929. assert result_sorted(response.data)["groups"] == [
  930. {
  931. "by": {"release": "foo@1.0.0"},
  932. "series": {"count_unique(user)": [0], "sum(session)": [3]},
  933. "totals": {"count_unique(user)": 0, "sum(session)": 3},
  934. },
  935. {
  936. "by": {"release": "foo@1.1.0"},
  937. "series": {"count_unique(user)": [0], "sum(session)": [1]},
  938. "totals": {"count_unique(user)": 0, "sum(session)": 1},
  939. },
  940. ]
  941. @freeze_time(MOCK_DATETIME + datetime.timedelta(days=2))
  942. def test_groupby_no_data(self):
  943. # Empty results for everything
  944. response = self.do_request(
  945. {
  946. "project": self.project.id, # project without users
  947. "statsPeriod": "1d",
  948. "interval": "1d",
  949. "field": ["count_unique(user)", "sum(session)"],
  950. "groupBy": "release",
  951. }
  952. )
  953. assert response.status_code == 200, response.content
  954. assert result_sorted(response.data)["groups"] == []
  955. @freeze_time(MOCK_DATETIME)
  956. def test_mix_known_and_unknown_strings(self):
  957. for query_string in ("environment:[production,foo]",):
  958. response = self.do_request(
  959. {
  960. "project": self.project.id, # project without users
  961. "statsPeriod": "1d",
  962. "interval": "1d",
  963. "field": ["count_unique(user)", "sum(session)"],
  964. "query": query_string,
  965. }
  966. )
  967. assert response.status_code == 200, response.data
  968. @patch("sentry.api.endpoints.organization_sessions.release_health", MetricsReleaseHealthBackend())
  969. class OrganizationSessionsEndpointMetricsTest(
  970. SessionMetricsReleaseHealthTestCase, OrganizationSessionsEndpointTest
  971. ):
  972. """Repeat all tests with metrics backend"""
  973. @freeze_time(MOCK_DATETIME)
  974. def test_orderby(self):
  975. response = self.do_request(
  976. {
  977. "project": [-1],
  978. "statsPeriod": "2d",
  979. "interval": "1d",
  980. "field": ["sum(session)"],
  981. "orderBy": "foobar",
  982. }
  983. )
  984. assert response.status_code == 400
  985. assert response.data == {"detail": "'orderBy' must be one of the provided 'fields'"}
  986. response = self.do_request(
  987. {
  988. "project": [-1],
  989. "statsPeriod": "2d",
  990. "interval": "1d",
  991. "field": ["sum(session)"],
  992. "orderBy": "count_unique(user)", # wrong field
  993. }
  994. )
  995. assert response.status_code == 400
  996. assert response.data == {"detail": "'orderBy' must be one of the provided 'fields'"}
  997. # Cannot sort by more than one field
  998. response = self.do_request(
  999. {
  1000. "project": [-1],
  1001. "statsPeriod": "2d",
  1002. "interval": "1d",
  1003. "field": ["sum(session)", "count_unique(user)"],
  1004. "orderBy": ["sum(session)", "count_unique(user)"],
  1005. }
  1006. )
  1007. assert response.status_code == 400
  1008. assert response.data == {"detail": "Cannot order by multiple fields"}
  1009. response = self.do_request(
  1010. {
  1011. "project": [-1],
  1012. "statsPeriod": "2d",
  1013. "interval": "1d",
  1014. "field": ["sum(session)"],
  1015. "orderBy": "sum(session)", # misses group by, but why not
  1016. }
  1017. )
  1018. assert response.status_code == 200
  1019. response = self.do_request(
  1020. {
  1021. "project": [-1],
  1022. "statsPeriod": "2d",
  1023. "interval": "1d",
  1024. "field": ["sum(session)"],
  1025. "orderBy": "sum(session)",
  1026. "groupBy": ["session.status"],
  1027. }
  1028. )
  1029. assert response.status_code == 400
  1030. assert response.data == {"detail": "Cannot use 'orderBy' when grouping by sessions.status"}
  1031. response = self.do_request(
  1032. {
  1033. "project": [self.project.id, self.project3.id],
  1034. "statsPeriod": "2d",
  1035. "interval": "1d",
  1036. "field": ["sum(session)", "p95(session.duration)"],
  1037. "orderBy": "p95(session.duration)",
  1038. "groupBy": ["project", "release", "environment"],
  1039. }
  1040. )
  1041. expected_groups = [
  1042. {
  1043. "by": {
  1044. "project": self.project.id,
  1045. "release": "foo@1.0.0",
  1046. "environment": "production",
  1047. },
  1048. "totals": {"sum(session)": 3, "p95(session.duration)": 25000.0},
  1049. "series": {"sum(session)": [0, 3], "p95(session.duration)": [None, 25000.0]},
  1050. },
  1051. {
  1052. "by": {
  1053. "project": self.project3.id,
  1054. "release": "foo@1.2.0",
  1055. "environment": "production",
  1056. },
  1057. "totals": {"sum(session)": 1, "p95(session.duration)": 37000.0},
  1058. "series": {"sum(session)": [0, 1], "p95(session.duration)": [None, 37000.0]},
  1059. },
  1060. {
  1061. "by": {
  1062. "project": self.project.id,
  1063. "release": "foo@1.1.0",
  1064. "environment": "production",
  1065. },
  1066. "totals": {"sum(session)": 1, "p95(session.duration)": 49000.0},
  1067. "series": {"sum(session)": [0, 1], "p95(session.duration)": [None, 49000.0]},
  1068. },
  1069. {
  1070. "by": {
  1071. "project": self.project3.id,
  1072. "release": "foo@1.0.0",
  1073. "environment": "production",
  1074. },
  1075. "totals": {"sum(session)": 2, "p95(session.duration)": 79400.0},
  1076. "series": {"sum(session)": [0, 2], "p95(session.duration)": [None, 79400.0]},
  1077. },
  1078. ]
  1079. # Not using `result_sorted` here, because we want to verify the order
  1080. assert response.status_code == 200, response.data
  1081. assert response.data["groups"] == expected_groups
  1082. # Sort descending
  1083. response = self.do_request(
  1084. {
  1085. "project": [self.project.id, self.project3.id],
  1086. "statsPeriod": "2d",
  1087. "interval": "1d",
  1088. "field": ["sum(session)", "p95(session.duration)"],
  1089. "orderBy": "-p95(session.duration)",
  1090. "groupBy": ["project", "release", "environment"],
  1091. }
  1092. )
  1093. assert response.status_code == 200
  1094. assert response.data["groups"] == list(reversed(expected_groups))
  1095. # Add some more code coverage
  1096. all_fields = [
  1097. "sum(session)",
  1098. "count_unique(user)",
  1099. "avg(session.duration)",
  1100. ]
  1101. for field in all_fields:
  1102. assert (
  1103. self.do_request(
  1104. {
  1105. "project": [self.project.id, self.project3.id],
  1106. "statsPeriod": "2d",
  1107. "interval": "1d",
  1108. "field": all_fields,
  1109. "orderBy": field,
  1110. "groupBy": ["project", "release", "environment"],
  1111. }
  1112. ).status_code
  1113. == 200
  1114. )
  1115. @freeze_time(MOCK_DATETIME)
  1116. def test_filter_by_session_status(self):
  1117. default_request = {
  1118. "project": [-1],
  1119. "statsPeriod": "1d",
  1120. "interval": "1d",
  1121. }
  1122. def req(**kwargs):
  1123. return self.do_request(dict(default_request, **kwargs))
  1124. response = req(field=["sum(session)"], query="session.status:bogus")
  1125. assert response.status_code == 200, response.content
  1126. assert result_sorted(response.data)["groups"] == []
  1127. response = req(field=["sum(session)"], query="!session.status:healthy")
  1128. assert response.status_code == 200, response.content
  1129. assert result_sorted(response.data)["groups"] == [
  1130. {"by": {}, "series": {"sum(session)": [3]}, "totals": {"sum(session)": 3}}
  1131. ]
  1132. # sum(session) filtered by multiple statuses adds them
  1133. response = req(field=["sum(session)"], query="session.status:[healthy, errored]")
  1134. assert response.status_code == 200, response.content
  1135. assert result_sorted(response.data)["groups"] == [
  1136. {"by": {}, "series": {"sum(session)": [8]}, "totals": {"sum(session)": 8}}
  1137. ]
  1138. response = req(
  1139. field=["sum(session)"],
  1140. query="session.status:[healthy, errored]",
  1141. groupBy="session.status",
  1142. )
  1143. assert response.status_code == 200, response.content
  1144. assert result_sorted(response.data)["groups"] == [
  1145. {
  1146. "by": {"session.status": "errored"},
  1147. "totals": {"sum(session)": 2},
  1148. "series": {"sum(session)": [2]},
  1149. },
  1150. {
  1151. "by": {"session.status": "healthy"},
  1152. "totals": {"sum(session)": 6},
  1153. "series": {"sum(session)": [6]},
  1154. },
  1155. ]
  1156. response = req(field=["sum(session)"], query="session.status:healthy release:foo@1.1.0")
  1157. assert response.status_code == 200, response.content
  1158. assert result_sorted(response.data)["groups"] == [
  1159. {"by": {}, "series": {"sum(session)": [1]}, "totals": {"sum(session)": 1}}
  1160. ]
  1161. response = req(field=["sum(session)"], query="session.status:healthy OR release:foo@1.1.0")
  1162. assert response.status_code == 400, response.data
  1163. assert response.data == {"detail": "Unable to parse condition with session.status"}
  1164. # count_unique(user) does not work with multiple session statuses selected
  1165. response = req(field=["count_unique(user)"], query="session.status:[healthy, errored]")
  1166. assert response.status_code == 400, response.data
  1167. assert response.data == {
  1168. "detail": "Cannot filter count_unique by multiple session.status unless it is in groupBy"
  1169. }
  1170. response = req(field=["p95(session.duration)"], query="session.status:abnormal")
  1171. assert response.status_code == 200, response.content
  1172. assert result_sorted(response.data)["groups"] == []
  1173. @freeze_time(MOCK_DATETIME)
  1174. def test_filter_by_session_status_with_groupby(self):
  1175. default_request = {
  1176. "project": [-1],
  1177. "statsPeriod": "1d",
  1178. "interval": "1d",
  1179. "groupBy": "release",
  1180. }
  1181. def req(**kwargs):
  1182. return self.do_request(dict(default_request, **kwargs))
  1183. response = req(field=["sum(session)"], query="session.status:healthy")
  1184. assert response.status_code == 200, response.content
  1185. assert result_sorted(response.data)["groups"] == [
  1186. {
  1187. "by": {"release": "foo@1.0.0"},
  1188. "series": {"sum(session)": [5]},
  1189. "totals": {"sum(session)": 5},
  1190. },
  1191. {
  1192. "by": {"release": "foo@1.1.0"},
  1193. "series": {"sum(session)": [1]},
  1194. "totals": {"sum(session)": 1},
  1195. },
  1196. {
  1197. "by": {"release": "foo@1.2.0"},
  1198. "series": {"sum(session)": [0]},
  1199. "totals": {"sum(session)": 0},
  1200. },
  1201. ]
  1202. @freeze_time(MOCK_DATETIME)
  1203. def test_filter_by_session_status_with_orderby(self):
  1204. default_request = {
  1205. "project": [-1],
  1206. "statsPeriod": "1d",
  1207. "interval": "1d",
  1208. }
  1209. def req(**kwargs):
  1210. return self.do_request(dict(default_request, **kwargs))
  1211. response = req(
  1212. field=["sum(session)"],
  1213. query="session.status:[abnormal,crashed]",
  1214. groupBy="release",
  1215. orderBy="sum(session)",
  1216. )
  1217. assert response.status_code == 400, response.content
  1218. assert response.data == {"detail": "Cannot order by sum(session) with the current filters"}
  1219. response = req(
  1220. field=["sum(session)"],
  1221. query="session.status:healthy",
  1222. groupBy="release",
  1223. orderBy="sum(session)",
  1224. )
  1225. assert response.status_code == 400, response.content
  1226. assert response.data == {"detail": "Cannot order by sum(session) with the current filters"}
  1227. @freeze_time(MOCK_DATETIME)
  1228. def test_crash_rate(self):
  1229. default_request = {
  1230. "project": [-1],
  1231. "statsPeriod": "1d",
  1232. "interval": "1d",
  1233. "field": ["crash_rate(session)"],
  1234. }
  1235. def req(**kwargs):
  1236. return self.do_request(dict(default_request, **kwargs))
  1237. # 1 - filter session.status
  1238. response = req(
  1239. query="session.status:[abnormal,crashed]",
  1240. )
  1241. assert response.status_code == 400, response.content
  1242. assert response.data == {
  1243. "detail": "Cannot filter field crash_rate(session) by session.status"
  1244. }
  1245. # 2 - group by session.status
  1246. response = req(
  1247. groupBy="session.status",
  1248. )
  1249. assert response.status_code == 400, response.content
  1250. assert response.data == {
  1251. "detail": "Cannot group field crash_rate(session) by session.status"
  1252. }
  1253. # 4 - fetch all
  1254. response = req(
  1255. field=[
  1256. "crash_rate(session)",
  1257. "crash_rate(user)",
  1258. "crash_free_rate(session)",
  1259. "crash_free_rate(user)",
  1260. ],
  1261. groupBy=["release", "environment"],
  1262. orderBy=["crash_free_rate(session)"],
  1263. query="release:foo@1.0.0",
  1264. )
  1265. assert response.status_code == 200, response.content
  1266. assert response.data["groups"] == [
  1267. {
  1268. "by": {"environment": "production", "release": "foo@1.0.0"},
  1269. "series": {
  1270. "crash_free_rate(session)": [0.8333333333333334],
  1271. "crash_free_rate(user)": [1.0],
  1272. "crash_rate(session)": [0.16666666666666666],
  1273. "crash_rate(user)": [0.0],
  1274. },
  1275. "totals": {
  1276. "crash_free_rate(session)": 0.8333333333333334,
  1277. "crash_free_rate(user)": 1.0,
  1278. "crash_rate(session)": 0.16666666666666666,
  1279. "crash_rate(user)": 0.0,
  1280. },
  1281. },
  1282. {
  1283. "by": {"environment": "development", "release": "foo@1.0.0"},
  1284. "series": {
  1285. "crash_free_rate(session)": [1.0],
  1286. "crash_free_rate(user)": [None],
  1287. "crash_rate(session)": [0.0],
  1288. "crash_rate(user)": [None],
  1289. },
  1290. "totals": {
  1291. "crash_free_rate(session)": 1.0,
  1292. "crash_free_rate(user)": None,
  1293. "crash_rate(session)": 0.0,
  1294. "crash_rate(user)": None,
  1295. },
  1296. },
  1297. ]
  1298. @freeze_time(MOCK_DATETIME)
  1299. def test_pagination(self):
  1300. def do_request(cursor):
  1301. return self.do_request(
  1302. {
  1303. "project": self.project.id, # project without users
  1304. "statsPeriod": "1d",
  1305. "interval": "1d",
  1306. "field": ["count_unique(user)", "sum(session)"],
  1307. "query": "",
  1308. "groupBy": "release",
  1309. "orderBy": "sum(session)",
  1310. "per_page": 1,
  1311. **({"cursor": cursor} if cursor else {}),
  1312. }
  1313. )
  1314. response = do_request(None)
  1315. assert response.status_code == 200, response.data
  1316. assert len(response.data["groups"]) == 1
  1317. assert response.data["groups"] == [
  1318. {
  1319. "by": {"release": "foo@1.1.0"},
  1320. "series": {"count_unique(user)": [0], "sum(session)": [1]},
  1321. "totals": {"count_unique(user)": 0, "sum(session)": 1},
  1322. }
  1323. ]
  1324. links = {link["rel"]: link for url, link in parse_link_header(response["Link"]).items()}
  1325. assert links["previous"]["results"] == "false"
  1326. assert links["next"]["results"] == "true"
  1327. response = do_request(links["next"]["cursor"])
  1328. assert response.status_code == 200, response.data
  1329. assert len(response.data["groups"]) == 1
  1330. assert response.data["groups"] == [
  1331. {
  1332. "by": {"release": "foo@1.0.0"},
  1333. "series": {"count_unique(user)": [0], "sum(session)": [3]},
  1334. "totals": {"count_unique(user)": 0, "sum(session)": 3},
  1335. }
  1336. ]
  1337. links = {link["rel"]: link for url, link in parse_link_header(response["Link"]).items()}
  1338. assert links["previous"]["results"] == "true"
  1339. assert links["next"]["results"] == "false"
  1340. def test_unrestricted_date_range(self):
  1341. response = self.do_request(
  1342. {
  1343. "project": [-1],
  1344. "statsPeriod": "7h",
  1345. "interval": "5m",
  1346. "field": ["sum(session)"],
  1347. }
  1348. )
  1349. assert response.status_code == 200
  1350. @freeze_time(MOCK_DATETIME)
  1351. def test_release_is_empty(self):
  1352. self.store_session(
  1353. make_session(
  1354. self.project1, started=SESSION_STARTED + 12 * 60, release="", environment=""
  1355. )
  1356. )
  1357. for query in ('release:"" environment:""', 'release:"" OR environment:""'):
  1358. # Empty strings are invalid values for releases and environments, but we should still handle those cases correctly at the query layer
  1359. response = self.do_request(
  1360. {
  1361. "project": self.project.id, # project without users
  1362. "statsPeriod": "1d",
  1363. "interval": "1d",
  1364. "field": ["sum(session)"],
  1365. "query": query,
  1366. "groupBy": ["release", "environment"],
  1367. }
  1368. )
  1369. assert response.status_code == 200, response.content
  1370. assert result_sorted(response.data)["groups"] == [
  1371. {
  1372. "by": {"environment": "", "release": ""},
  1373. "series": {"sum(session)": [1]},
  1374. "totals": {"sum(session)": 1},
  1375. }
  1376. ]
  1377. @patch("sentry.api.endpoints.organization_sessions.release_health", MetricsReleaseHealthBackend())
  1378. class SessionsMetricsSortReleaseTimestampTest(SessionMetricsReleaseHealthTestCase, APITestCase):
  1379. def do_request(self, query, user=None, org=None):
  1380. self.login_as(user=user or self.user)
  1381. url = reverse(
  1382. "sentry-api-0-organization-sessions",
  1383. kwargs={"organization_slug": (org or self.organization).slug},
  1384. )
  1385. return self.client.get(url, query, format="json")
  1386. @freeze_time(MOCK_DATETIME)
  1387. def test_order_by_with_no_releases(self):
  1388. """
  1389. Test that ensures if we have no releases in the preflight query when trying to order by
  1390. `release.timestamp`, we get no groups.
  1391. Essentially testing the empty preflight query filters branch.
  1392. """
  1393. project_random = self.create_project()
  1394. for _ in range(0, 2):
  1395. self.store_session(make_session(project_random))
  1396. self.store_session(make_session(project_random, status="crashed"))
  1397. response = self.do_request(
  1398. {
  1399. "project": project_random.id,
  1400. "statsPeriod": "1d",
  1401. "interval": "1d",
  1402. "field": ["crash_free_rate(session)"],
  1403. "groupBy": ["release"],
  1404. "orderBy": "-release.timestamp",
  1405. "per_page": 3,
  1406. }
  1407. )
  1408. assert response.data["groups"] == []
  1409. def test_order_by_max_limit(self):
  1410. response = self.do_request(
  1411. {
  1412. "project": self.project.id,
  1413. "statsPeriod": "1d",
  1414. "interval": "1d",
  1415. "field": ["crash_free_rate(session)"],
  1416. "groupBy": ["release"],
  1417. "orderBy": "-release.timestamp",
  1418. "per_page": 103,
  1419. }
  1420. )
  1421. assert response.data["detail"] == (
  1422. "This limit is too high for queries that requests a preflight query. "
  1423. "Please choose a limit below 100"
  1424. )
  1425. @freeze_time(MOCK_DATETIME)
  1426. def test_order_by(self):
  1427. """
  1428. Test that ensures that we are able to get the crash_free_rate for the most 2 recent
  1429. releases when grouping by release
  1430. """
  1431. # Step 1: Create 3 releases
  1432. release1b = self.create_release(version="1B")
  1433. release1c = self.create_release(version="1C")
  1434. release1d = self.create_release(version="1D")
  1435. # Step 2: Create crash free rate for each of those releases
  1436. # Release 1c -> 66.7% Crash free rate
  1437. for _ in range(0, 2):
  1438. self.store_session(make_session(self.project, release=release1c.version))
  1439. self.store_session(make_session(self.project, release=release1c.version, status="crashed"))
  1440. # Release 1b -> 33.3% Crash free rate
  1441. for _ in range(0, 2):
  1442. self.store_session(
  1443. make_session(self.project, release=release1b.version, status="crashed")
  1444. )
  1445. self.store_session(make_session(self.project, release=release1b.version))
  1446. # Create Sessions in each of these releases
  1447. # Release 1d -> 80% Crash free rate
  1448. for _ in range(0, 4):
  1449. self.store_session(make_session(self.project, release=release1d.version))
  1450. self.store_session(make_session(self.project, release=release1d.version, status="crashed"))
  1451. # Step 3: Make request
  1452. response = self.do_request(
  1453. {
  1454. "project": self.project.id, # project without users
  1455. "statsPeriod": "1d",
  1456. "interval": "1d",
  1457. "field": ["crash_free_rate(session)"],
  1458. "groupBy": ["release"],
  1459. "orderBy": "-release.timestamp",
  1460. "per_page": 3,
  1461. }
  1462. )
  1463. # Step 4: Validate Results
  1464. assert response.data["groups"] == [
  1465. {
  1466. "by": {"release": "1D"},
  1467. "totals": {"crash_free_rate(session)": 0.8},
  1468. "series": {"crash_free_rate(session)": [0.8]},
  1469. },
  1470. {
  1471. "by": {"release": "1C"},
  1472. "totals": {"crash_free_rate(session)": 0.6666666666666667},
  1473. "series": {"crash_free_rate(session)": [0.6666666666666667]},
  1474. },
  1475. {
  1476. "by": {"release": "1B"},
  1477. "totals": {"crash_free_rate(session)": 0.33333333333333337},
  1478. "series": {"crash_free_rate(session)": [0.33333333333333337]},
  1479. },
  1480. ]
  1481. @freeze_time(MOCK_DATETIME)
  1482. def test_order_by_with_session_status_groupby(self):
  1483. """
  1484. Test that ensures we are able to group by session.status and order by `release.timestamp`
  1485. since `release.timestamp` is generated from a preflight query
  1486. """
  1487. rando_project = self.create_project()
  1488. release_1a = self.create_release(project=rando_project, version="1A")
  1489. release_1b = self.create_release(project=rando_project, version="1B")
  1490. # Release 1B sessions
  1491. for _ in range(4):
  1492. self.store_session(
  1493. make_session(rando_project, release=release_1b.version, status="crashed")
  1494. )
  1495. for _ in range(10):
  1496. self.store_session(make_session(rando_project, release=release_1b.version))
  1497. for _ in range(3):
  1498. self.store_session(make_session(rando_project, errors=1, release=release_1b.version))
  1499. # Release 1A sessions
  1500. for _ in range(0, 2):
  1501. self.store_session(
  1502. make_session(rando_project, release=release_1a.version, status="crashed")
  1503. )
  1504. self.store_session(make_session(rando_project, release=release_1a.version))
  1505. for _ in range(3):
  1506. self.store_session(make_session(rando_project, errors=1, release=release_1a.version))
  1507. response = self.do_request(
  1508. {
  1509. "project": rando_project.id,
  1510. "statsPeriod": "1d",
  1511. "interval": "1d",
  1512. "field": ["sum(session)"],
  1513. "groupBy": ["release", "session.status"],
  1514. "orderBy": "-release.timestamp",
  1515. }
  1516. )
  1517. assert response.data["groups"] == [
  1518. {
  1519. "by": {"release": "1B", "session.status": "abnormal"},
  1520. "totals": {"sum(session)": 0},
  1521. "series": {"sum(session)": [0]},
  1522. },
  1523. {
  1524. "by": {"release": "1B", "session.status": "crashed"},
  1525. "totals": {"sum(session)": 4},
  1526. "series": {"sum(session)": [4]},
  1527. },
  1528. {
  1529. "by": {"release": "1B", "session.status": "errored"},
  1530. "totals": {"sum(session)": 3},
  1531. "series": {"sum(session)": [3]},
  1532. },
  1533. {
  1534. "by": {"release": "1B", "session.status": "healthy"},
  1535. "totals": {"sum(session)": 10},
  1536. "series": {"sum(session)": [10]},
  1537. },
  1538. {
  1539. "by": {"release": "1A", "session.status": "abnormal"},
  1540. "totals": {"sum(session)": 0},
  1541. "series": {"sum(session)": [0]},
  1542. },
  1543. {
  1544. "by": {"release": "1A", "session.status": "crashed"},
  1545. "totals": {"sum(session)": 2},
  1546. "series": {"sum(session)": [2]},
  1547. },
  1548. {
  1549. "by": {"release": "1A", "session.status": "errored"},
  1550. "totals": {"sum(session)": 3},
  1551. "series": {"sum(session)": [3]},
  1552. },
  1553. {
  1554. "by": {"release": "1A", "session.status": "healthy"},
  1555. "totals": {"sum(session)": 1},
  1556. "series": {"sum(session)": [1]},
  1557. },
  1558. ]
  1559. @freeze_time(MOCK_DATETIME)
  1560. def test_order_by_with_limit(self):
  1561. rando_project = self.create_project()
  1562. # Create two releases with no metrics data and then two releases with metric data
  1563. release_1a = self.create_release(project=rando_project, version="1A")
  1564. release_1b = self.create_release(project=rando_project, version="1B")
  1565. self.create_release(project=rando_project, version="1C")
  1566. self.create_release(project=rando_project, version="1D")
  1567. self.store_session(make_session(rando_project, release=release_1a.version))
  1568. self.store_session(make_session(rando_project, release=release_1b.version))
  1569. self.store_session(
  1570. make_session(rando_project, release=release_1b.version, status="crashed")
  1571. )
  1572. response = self.do_request(
  1573. {
  1574. "project": rando_project.id,
  1575. "statsPeriod": "1d",
  1576. "interval": "1d",
  1577. "field": ["sum(session)"],
  1578. "groupBy": ["release"],
  1579. "orderBy": "-release.timestamp",
  1580. "per_page": 3,
  1581. }
  1582. )
  1583. assert response.data["groups"] == [
  1584. {
  1585. "by": {"release": "1D"},
  1586. "totals": {"sum(session)": 0},
  1587. "series": {"sum(session)": [0]},
  1588. },
  1589. {
  1590. "by": {"release": "1C"},
  1591. "totals": {"sum(session)": 0},
  1592. "series": {"sum(session)": [0]},
  1593. },
  1594. {
  1595. "by": {"release": "1B"},
  1596. "totals": {"sum(session)": 2},
  1597. "series": {"sum(session)": [2]},
  1598. },
  1599. ]
  1600. response = self.do_request(
  1601. {
  1602. "project": rando_project.id,
  1603. "statsPeriod": "1d",
  1604. "interval": "1d",
  1605. "field": ["sum(session)"],
  1606. "groupBy": ["release", "session.status"],
  1607. "orderBy": "-release.timestamp",
  1608. "per_page": 4,
  1609. }
  1610. )
  1611. assert response.data["groups"] == [
  1612. {
  1613. "by": {"release": "1D", "session.status": None},
  1614. "totals": {"sum(session)": 0},
  1615. "series": {"sum(session)": [0]},
  1616. },
  1617. {
  1618. "by": {"release": "1C", "session.status": None},
  1619. "totals": {"sum(session)": 0},
  1620. "series": {"sum(session)": [0]},
  1621. },
  1622. {
  1623. "by": {"release": "1B", "session.status": "abnormal"},
  1624. "totals": {"sum(session)": 0},
  1625. "series": {"sum(session)": [0]},
  1626. },
  1627. {
  1628. "by": {"release": "1B", "session.status": "crashed"},
  1629. "totals": {"sum(session)": 1},
  1630. "series": {"sum(session)": [1]},
  1631. },
  1632. ]
  1633. response = self.do_request(
  1634. {
  1635. "project": rando_project.id,
  1636. "statsPeriod": "1d",
  1637. "interval": "1d",
  1638. "field": ["sum(session)"],
  1639. "groupBy": ["release", "session.status", "project"],
  1640. "orderBy": "-release.timestamp",
  1641. "per_page": 2,
  1642. }
  1643. )
  1644. assert response.data["groups"] == [
  1645. {
  1646. "by": {"release": "1D", "session.status": None, "project": None},
  1647. "totals": {"sum(session)": 0},
  1648. "series": {"sum(session)": [0]},
  1649. },
  1650. {
  1651. "by": {"release": "1C", "session.status": None, "project": None},
  1652. "totals": {"sum(session)": 0},
  1653. "series": {"sum(session)": [0]},
  1654. },
  1655. ]
  1656. @freeze_time(MOCK_DATETIME)
  1657. def test_order_by_with_limit_and_offset(self):
  1658. rando_project = self.create_project()
  1659. # Create two releases with no metrics data and then two releases with metric data
  1660. release_1a = self.create_release(project=rando_project, version="1A")
  1661. release_1b = self.create_release(project=rando_project, version="1B")
  1662. self.create_release(project=rando_project, version="1C")
  1663. self.create_release(project=rando_project, version="1D")
  1664. self.store_session(make_session(rando_project, release=release_1a.version))
  1665. self.store_session(make_session(rando_project, release=release_1b.version))
  1666. response = self.do_request(
  1667. {
  1668. "project": rando_project.id,
  1669. "statsPeriod": "1d",
  1670. "interval": "1d",
  1671. "field": ["sum(session)"],
  1672. "groupBy": ["release"],
  1673. "orderBy": "-release.timestamp",
  1674. "per_page": 3,
  1675. "cursor": Cursor(0, 1),
  1676. }
  1677. )
  1678. assert response.data["detail"] == (
  1679. "Passing an offset value greater than 0 when ordering by release.timestamp "
  1680. "is not permitted"
  1681. )
  1682. @freeze_time(MOCK_DATETIME)
  1683. def test_order_by_with_environment_filter_on_preflight(self):
  1684. rando_project = self.create_project()
  1685. rando_env = self.create_environment(name="rando_env", project=self.project)
  1686. # Create two releases with no metrics data and then two releases with metric data
  1687. release_1a = self.create_release(
  1688. project=rando_project, version="1A", environments=[rando_env]
  1689. )
  1690. release_1b = self.create_release(
  1691. project=rando_project, version="1B", environments=[rando_env]
  1692. )
  1693. release_1c = self.create_release(project=rando_project, version="1C")
  1694. release_1d = self.create_release(project=rando_project, version="1D")
  1695. self.store_session(
  1696. make_session(rando_project, release=release_1a.version, environment="rando_env")
  1697. )
  1698. self.store_session(
  1699. make_session(rando_project, release=release_1b.version, environment="rando_env")
  1700. )
  1701. self.store_session(make_session(rando_project, release=release_1c.version))
  1702. self.store_session(make_session(rando_project, release=release_1d.version))
  1703. # Test env condition with IN
  1704. response = self.do_request(
  1705. {
  1706. "project": rando_project.id,
  1707. "statsPeriod": "1d",
  1708. "interval": "1d",
  1709. "field": ["sum(session)"],
  1710. "query": "environment:[rando_env,rando_enc2]",
  1711. "groupBy": ["release", "environment"],
  1712. "orderBy": "-release.timestamp",
  1713. "per_page": 4,
  1714. }
  1715. )
  1716. assert response.data["groups"] == [
  1717. {
  1718. "by": {"release": "1B", "environment": "rando_env"},
  1719. "totals": {"sum(session)": 1},
  1720. "series": {"sum(session)": [1]},
  1721. },
  1722. {
  1723. "by": {"release": "1A", "environment": "rando_env"},
  1724. "totals": {"sum(session)": 1},
  1725. "series": {"sum(session)": [1]},
  1726. },
  1727. ]
  1728. # Test env condition with NOT IN
  1729. response = self.do_request(
  1730. {
  1731. "project": rando_project.id,
  1732. "statsPeriod": "1d",
  1733. "interval": "1d",
  1734. "field": ["sum(session)"],
  1735. "query": "!environment:[rando_env,rando_enc2]",
  1736. "groupBy": ["release", "environment"],
  1737. "orderBy": "-release.timestamp",
  1738. "per_page": 4,
  1739. }
  1740. )
  1741. assert response.data["groups"] == [
  1742. {
  1743. "by": {"release": "1D", "environment": "production"},
  1744. "totals": {"sum(session)": 1},
  1745. "series": {"sum(session)": [1]},
  1746. },
  1747. {
  1748. "by": {"release": "1C", "environment": "production"},
  1749. "totals": {"sum(session)": 1},
  1750. "series": {"sum(session)": [1]},
  1751. },
  1752. ]
  1753. # Test env condition with invalid OR operation
  1754. response = self.do_request(
  1755. {
  1756. "project": rando_project.id,
  1757. "statsPeriod": "1d",
  1758. "interval": "1d",
  1759. "field": ["sum(session)"],
  1760. "query": "environment:rando_env OR environment:rando_enc2",
  1761. "groupBy": ["release", "environment"],
  1762. "orderBy": "-release.timestamp",
  1763. "per_page": 4,
  1764. }
  1765. )
  1766. assert response.json()["detail"] == "Unable to parse condition with environment"
  1767. @freeze_time(MOCK_DATETIME)
  1768. def test_order_by_without_release_groupby(self):
  1769. rando_project = self.create_project()
  1770. response = self.do_request(
  1771. {
  1772. "project": rando_project.id,
  1773. "statsPeriod": "1d",
  1774. "interval": "1d",
  1775. "query": "session.status:[crashed,errored]",
  1776. "field": ["sum(session)"],
  1777. "orderBy": "-release.timestamp",
  1778. "per_page": 2,
  1779. }
  1780. )
  1781. assert response.data["detail"] == (
  1782. "To sort by release.timestamp, tag release must be in the groupBy"
  1783. )
  1784. @freeze_time(MOCK_DATETIME)
  1785. def test_order_by_release_with_session_status_current_filter(self):
  1786. rando_project = self.create_project()
  1787. release_1a = self.create_release(project=rando_project, version="1A")
  1788. release_1b = self.create_release(project=rando_project, version="1B")
  1789. # Release 1B sessions
  1790. for _ in range(4):
  1791. self.store_session(
  1792. make_session(rando_project, release=release_1b.version, status="crashed")
  1793. )
  1794. for _ in range(10):
  1795. self.store_session(make_session(rando_project, release=release_1b.version))
  1796. for _ in range(3):
  1797. self.store_session(make_session(rando_project, errors=1, release=release_1b.version))
  1798. # Release 1A sessions
  1799. for _ in range(0, 2):
  1800. self.store_session(
  1801. make_session(rando_project, release=release_1a.version, status="crashed")
  1802. )
  1803. self.store_session(make_session(rando_project, release=release_1a.version))
  1804. for _ in range(3):
  1805. self.store_session(make_session(rando_project, errors=1, release=release_1a.version))
  1806. response = self.do_request(
  1807. {
  1808. "project": rando_project.id,
  1809. "statsPeriod": "1d",
  1810. "interval": "1d",
  1811. "query": "session.status:[crashed,errored]",
  1812. "field": ["sum(session)"],
  1813. "groupBy": ["release"],
  1814. "orderBy": "-release.timestamp",
  1815. }
  1816. )
  1817. assert response.data["groups"] == [
  1818. {
  1819. "by": {"release": "1B"},
  1820. "totals": {"sum(session)": 7},
  1821. "series": {"sum(session)": [7]},
  1822. },
  1823. {
  1824. "by": {"release": "1A"},
  1825. "totals": {"sum(session)": 5},
  1826. "series": {"sum(session)": [5]},
  1827. },
  1828. ]
  1829. @patch(
  1830. "sentry.api.endpoints.organization_sessions.release_health",
  1831. DuplexReleaseHealthBackend(datetime.datetime(2022, 4, 28, 16, 0, tzinfo=datetime.timezone.utc)),
  1832. )
  1833. class DuplexTestCase(SessionMetricsTestCase, APITestCase):
  1834. """Tests specific to the duplex backend"""
  1835. def do_request(self, query, user=None, org=None):
  1836. self.login_as(user=user or self.user)
  1837. url = reverse(
  1838. "sentry-api-0-organization-sessions",
  1839. kwargs={"organization_slug": (org or self.organization).slug},
  1840. )
  1841. return self.client.get(url, query, format="json")
  1842. @freeze_time(MOCK_DATETIME)
  1843. def test_invalid_params(self):
  1844. """InvalidParams in metrics backend leads to 400 response when return-metrics is enabled"""
  1845. self.create_project()
  1846. with Feature("organizations:release-health-return-metrics"):
  1847. response = self.do_request(
  1848. {
  1849. "project": [-1],
  1850. "statsPeriod": ["24h"],
  1851. "interval": ["1h"],
  1852. "field": ["crash_rate(session)"],
  1853. "groupBy": ["session.status"], # Cannot group crash rate by session status
  1854. }
  1855. )
  1856. assert response.status_code == 400
  1857. assert response.data == {
  1858. "detail": "Cannot group field crash_rate(session) by session.status"
  1859. }