test_organization_sessions.py 80 KB

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