test_organization_sessions.py 87 KB

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