test_organization_sessions.py 76 KB

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