:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
chore(devex): serve environments mock handlers on the projects path (#104228)
Julian Beza545f868e4dc
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 2ae9462cdefa..c2f38b2864c5 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -2185,9 +2185,9 @@ snapshots:components-search--product-recents-and-starred--light:hash: v1.k794b7964.419cabcff30a22d68b283cf59562b74ca2d4910552fc4240e95b856303622508.0xCO-YA2i8xkqSjPXRWXjmLuVEiiP11XfIC6v9y77yUcomponents-search--searching--dark:- hash: v1.k794b7964.0acd271bf9ea3d0c88db1b21017625d5bb08728c7ed185696e54c4c7c6d948bf.d1iBj0uFxNNFaPvb8HpTllFJy74qfoeIhmpMgePbCdw+ hash: v1.k794b7964.8640758c2d98a5f809ee318f61dc1e7669888757862a940b220e241742894ae2.3-TrMOHcLmJQNhFO0CuB3dEBeLcO-Cx-6lPP3jmfqzccomponents-search--searching--light:- hash: v1.k794b7964.b43b9ee07664f85109b2f0df3fe70a6e96e1a1628f65cef847153bcc58b3060c.YndsQWYmB9PL0kLyV47NLINY3JU3a4xt0sm250U_jc8+ hash: v1.k794b7964.3576a4f0b13c1fc49b4613169cc28841b9e48e2cedb93f0e830ce0fc2078e2c5.zCWo8ojUtNkcXxli4ZyOxrXQUD-v5txUgteY328uCxEcomponents-sentencelist--full-sentence--dark:hash: v1.k794b7964.7e8e5dd2e09d246cc3668f362f2391fe67618bd1143aa393832297f5dc30e558.yptEWKc5RAUY613Fwd5cQ0VIinMvpdoI6cuKgagAGxkcomponents-sentencelist--full-sentence--light:@@ -8921,17 +8921,17 @@ snapshots:scenes-app-inbox-scoutowners--states--light:hash: v1.k794b7964.62cb1889d60cf91cae1d0337da5a9209f4a759a1ccfed6a67dd6d2b238e75f13.qvVHYAWE8wGdD83VE5OOHw6uveEUae2uieDQ6sExrrsscenes-app-inbox-scoutrepositoriespicker--create-dialog-variant--dark:- hash: v1.k794b7964.51ce19a60f3af8d8dc7ca734d620224a538aefdd702c69ff51f3d874176fbd16.D3gw2Henynv7Qikl-Ba01hW6AVs4fZpi8Q5ZVdIiWqI+ hash: v1.k794b7964.fe4ec44613c16c296545cf66b63d1a83edd3a76da19c125c87e536fb51300262.kJcUoqpQAiWgBAHVL_AyRz_jCjZ3EheRJnnuHmbT8KMscenes-app-inbox-scoutrepositoriespicker--create-dialog-variant--light:- hash: v1.k794b7964.de5b5591f1cfdb3c735ed1c5b60167fd6cd01ae223f12d7fe8d6271ea2fab380.wgGLU7RlkK52t7xYmo2TxERVuIYcDoZ4QGZgdQXf8vo+ hash: v1.k794b7964.b33ab1c8d8f19edfb9c3b7a36ce061236c023b58052e582c6a410ed7480cd44e.xbI0uOXdhyjhi37eYxJ39_ZnhZU5DlRrxxlvQCaJhdYscenes-app-inbox-scoutrepositoriespicker--no-git-hub-connection--dark:hash: v1.k794b7964.51ce19a60f3af8d8dc7ca734d620224a538aefdd702c69ff51f3d874176fbd16.uh6a42lBZBvfRGLU1MT29f0s_R7OZh5TKmWW0wqry7kscenes-app-inbox-scoutrepositoriespicker--no-git-hub-connection--light:hash: v1.k794b7964.de5b5591f1cfdb3c735ed1c5b60167fd6cd01ae223f12d7fe8d6271ea2fab380.8FcIUCK-QswsgoPF_-QXVwTwjOHHVZWmeSQXDqRWuekscenes-app-inbox-scoutrepositoriespicker--scout-settings-variant--dark:- hash: v1.k794b7964.2128db31daa2ae560ba3751bc889fc3847a6f6bd4b1c8b831b9c621a99db92e2.np3Gj7EBUDcSPMV8QY5TRstN1LIUk2UsoHn9yA0HzGE+ hash: v1.k794b7964.9b4874c8e13285dda52a8fb067f346ac64689d02bbc2a2596b7a7a3af56125db.2nRhGcvtif_b8mPYcOGPrIIRrh5iGGllZtzALyVPeDAscenes-app-inbox-scoutrepositoriespicker--scout-settings-variant--light:- hash: v1.k794b7964.a11cdab2114ddd1b6bc8d929da0d0b2c4e9cbc292d60e1adef64f93227e5a324.rL3wPJRk_-nRwk5unPytYNbzIlxyYLEjIf2lPkh_0Oc+ hash: v1.k794b7964.16f441a63e8731b717e4d005d8823de0fdb1d5543c78bc504d8a67c7f679b4dc.MblNmyNRlrU-qamnpatL6NO-Km-LtjKEIOWjYrm2IJIscenes-app-inbox-scoutsroster--large-fleet--dark:hash: v1.k794b7964.bc5496dd845ecda6f0ad12cfb26aef001eebb616144626a43170c8a67febd43b.OvZS68_NkWoY-DVfy1T244ykeLC7vL8vDumGQzNbnicscenes-app-inbox-scoutsroster--large-fleet--light:@@ -9513,9 +9513,9 @@ snapshots:scenes-app-mcp-analytics--intent-clustering--light:hash: v1.k794b7964.82fd6a9108a34ff8808b23b9c1e9255dcbe4f38562bb9e99333877dd303c08b2.qjDLxTHFZT3vcTHmPeG35-orU88GSS277RR2DdXxBdwscenes-app-mcp-analytics--sessions--dark:- hash: v1.k794b7964.44aa3c9fa772bb9eded167540eb89e298cf6177bb9e519b7f441e7ac30930d4b.P0WUpYTUWG8kBTkHiAwR_VNSN5fy5hTDsG_tQUBYeXM+ hash: v1.k794b7964.a66e676a524e1de75d68579adb63b097fc17ed5db94ca86dccbf9e6265b169ac.sVkiD6KMNejyrVPs1hOZjHQWspPL2a7lvOWA6VcPNpsscenes-app-mcp-analytics--sessions--light:- hash: v1.k794b7964.933f69d71848d27d415ae31b97f8da0aef07f0671170f3742535a8566543d960.wvnv4A8MWpj0U0E75HJCWXJzW0Wa7oSaWQLuWP625as+ hash: v1.k794b7964.16f1771f05843a7492f213219e671ca1f8ab3c6ca03e49af7f47e13e40525585.p72ZdNHtERLOxua-BOsZX5tyg9fPU2-1h_VSEr7aaGwscenes-app-mcp-analytics--tool-quality--dark:hash: v1.k794b7964.697b42ee7e043ae0dd4bf56ffcab59f24810196459f4303be1a418ed8e0f128d.hxsxWCzwdJI2stSHMmN6oMhjhsnPtB4iv8_OJxgzScsscenes-app-mcp-analytics--tool-quality--light:@@ -10365,9 +10365,9 @@ snapshots:scenes-app-replay-vision-test-account-filter-settings-dialog--default--light:hash: v1.k794b7964.8276936411550e5ab99aa3d216a442c6328a55434a4bcf273cbef46a39d940b4.asrT7Nd6P9HVchxOoJPfMOOttbQVP6XFXptRAtnXC3kscenes-app-saved-insights--empty-state--dark:- hash: v1.k794b7964.ff0f2df92187cffc330d9fc2cf2f72e93088e8857ebd24b56669d4f31b1d573e.sDfYAinczOzsIykVtv17_GSU9n5d88H5GILgilzNzfg+ hash: v1.k794b7964.8186a1849accab762928456f98db977a9b097cf28199d7e1eb6c1e841500852c.SXNRf2LgiH3DkvhwUukZcGqDXngv1kGiEhGYUAhlKC8scenes-app-saved-insights--empty-state--light:- hash: v1.k794b7964.06d078c331d25616e66f8a7fe17d2da64a4463dd5fef58488b48fed6dbe16c83.E7qIcHI8imJfuYrOeYjAG_Xc7u86HKN5iJ8JGjyZL14+ hash: v1.k794b7964.17b1a7279644a0f077b7af240abacbfba5119804f7415e0ff4a5bb42304a9175.A4sx2qMdjvE3fLJAAeY0L_4wiHTxLSeskjlRm0Z4QhQscenes-app-saved-insights--error-state--dark:hash: v1.k794b7964.97eca32497e04c403e975e4114a7a144c20ac2d32ab89f98aa247136ab2d0457.l3Iw0G-o40K5hWnI2rEHDZfJTzV282b0lm5fQvP14a0scenes-app-saved-insights--error-state--light:@@ -11009,9 +11009,9 @@ snapshots:scenes-app-user-research-topics--search-no-results--light:hash: v1.k794b7964.df68cd6d45b2bde2483ca01afef89795a1d3c09b5b552306ddbb7fc7f8648a4c.juGY6xHTE0kx3jJERSXTR2sUs7m5weh_JmiZ8J63uogscenes-app-user-research-topics--search-with-results--dark:- hash: v1.k794b7964.34897ca0b56375c1281d25c58dfc950d361c6845759e226ae50474b4fb8c9e14.uGcXobINl6x7_yR8lrOSIDcKrDswD6J0n2L6hK2Pbgs+ hash: v1.k794b7964.6b4b809c4dcc265d3fd26054001bc2a0ec6c74094d90ca2288a2168a1e648fdc.807rhmRuUxrSKGbJM0fCMHrnv6d-oO66hqP7Wp_sg2kscenes-app-user-research-topics--search-with-results--light:- hash: v1.k794b7964.98d8847cf3a0002a84aaa7190aff635f932da06776ae4dc0d089eb514d2f13ea.eCuYayD3vzkXhErGOng0EwUoWtogjgJpxdyG-nDX4nc+ hash: v1.k794b7964.0f765cd0cb884ffd297295a8d35203bcc28df4f3f06de2a8f2223936d6ebe2dd.UVp7M3TuCHNZywyhXP0cWDYlmdU8jbl_Pbx4bXu4HSUscenes-app-user-research-topics--topics-list--dark:hash: v1.k794b7964.2be1760894da7958ef5f9376996ae6262c5ab191ec957c533ae74ba4c742aead.dQcZiMIpSCQDJxp76ersiDmELB8efODSyJoZQCWpb8wscenes-app-user-research-topics--topics-list--light:diff --git a/frontend/src/mocks/utils.test.ts b/frontend/src/mocks/utils.test.tsnew file mode 100644index 000000000000..6d57864f76b5--- /dev/null+++ b/frontend/src/mocks/utils.test.ts@@ -0,0 +1,49 @@+import { useMocks } from '~/mocks/jest'++describe('mocksToHandlers', () => {+ it('answers a projects request with the handler registered on the environments twin', async () => {+ useMocks({ get: { '/api/environments/:team_id/alias_probe/': { hit: 'environments' } } })++ const response = await fetch('/api/projects/1/alias_probe/')++ expect(await response.json()).toEqual({ hit: 'environments' })+ })++ it('does not answer an environments request with a handler registered on the projects path', async () => {+ useMocks({ get: { '/api/projects/:team_id/alias_probe/': { hit: 'projects' } } })++ const response = await fetch('/api/environments/1/alias_probe/')++ // The unhandled-request floor from `jest.ts`, which proves the projects handler was not used.+ expect(await response.json()).toEqual({ results: [], count: 0, next: null, previous: null })+ })++ it.each([+ ['matching trailing slashes', '/api/environments/:team_id/alias_probe/', '/api/projects/:team_id/alias_probe/'],+ [+ 'mismatched trailing slashes',+ '/api/environments/:team_id/alias_probe/',+ '/api/projects/:team_id/alias_probe',+ ],+ ['different param names', '/api/environments/:team_id/alias_probe/', '/api/projects/:team/alias_probe/'],+ ])('keeps an explicit projects registration ahead of the twin, %s', async (_name, envPath, projectsPath) => {+ useMocks({ get: { [envPath]: { hit: 'environments' }, [projectsPath]: { hit: 'projects' } } })++ const response = await fetch('/api/projects/1/alias_probe/')++ expect(await response.json()).toEqual({ hit: 'projects' })+ })++ it('keeps a specific projects route ahead of a broader twin registered before it', async () => {+ useMocks({+ get: {+ '/api/environments/:id/alias_probe/:probeId': { hit: 'environments' },+ '/api/projects/:id/alias_probe/summary': { hit: 'projects' },+ },+ })++ const response = await fetch('/api/projects/1/alias_probe/summary')++ expect(await response.json()).toEqual({ hit: 'projects' })+ })+})diff --git a/frontend/src/mocks/utils.ts b/frontend/src/mocks/utils.tsindex b6d68f0d99ea..13888661588d 100644--- a/frontend/src/mocks/utils.ts+++ b/frontend/src/mocks/utils.ts@@ -43,26 +43,86 @@ const toResponse = (result: MockResult): Response => {return HttpResponse.json(result)}+const ENVIRONMENTS_PATH = /(^|\/)api\/environments\//++const withoutTrailingSlash = (path: string): string => path.replace(/\/$/, '')++// The key two registrations share when MSW matches them against the same requests. A `:param`+// segment matches any single segment, so its name carries no meaning, and a trailing slash is+// stripped before a handler is registered.+const matchKey = (path: string): string =>+ withoutTrailingSlash(path)+ .split('/')+ .map((segment) => (segment.startsWith(':') ? ':param' : segment))+ .join('/')++// `/api/environments/` is a deprecated alias of `/api/projects/`: EnvironmentsRewriteMiddleware+// rewrites it in-process to the same viewset, so a mock registered on one path must answer the+// other. Serving the twin here keeps the existing environments registrations working while the+// frontend moves to the canonical projects path.+// The alias is one-way on purpose. A projects registration never answers an environments request,+// so a hand-written environments URL left in source still fails its test.+const projectsTwinFor = (path: string, registeredPaths: Set<string>): string | null => {+ if (!ENVIRONMENTS_PATH.test(path)) {+ return null+ }+ const twin = path.replace(ENVIRONMENTS_PATH, '$1api/projects/')+ // The same route registered on both paths needs no twin.+ return registeredPaths.has(matchKey(twin)) ? null : twin+}++// True when `pattern` matches every request `other` matches and more, because it has a `:param`+// segment where `other` names a literal. MSW answers with the first match, so a looser pattern+// registered earlier hides the stricter one.+const covers = (pattern: string, other: string): boolean => {+ const loose = matchKey(pattern).split('/')+ const strict = matchKey(other).split('/')+ if (loose.length !== strict.length) {+ return false+ }+ let looserSomewhere = false+ for (let i = 0; i < loose.length; i++) {+ if (loose[i] === strict[i]) {+ continue+ }+ if (loose[i] !== ':param') {+ return false+ }+ looserSomewhere = true+ }+ return looserSomewhere+}+export const mocksToHandlers = (mocks: Mocks): HttpHandler[] => {const handlers: HttpHandler[] = []+ // A twin that would hide a projects route the map registers on purpose goes last instead of in+ // place. Only those move, because registration order decides which handler MSW picks and tests+ // depend on the order their mocks resolve in.+ const deferred: HttpHandler[] = []Object.entries(mocks).filter((entry): entry is [HttpMethod, Record<string, MockSignature>] => !!entry[1]).forEach(([method, mockHandlers]) => {+ const paths = Object.keys(mockHandlers)+ const registeredPaths = new Set(paths.map(matchKey))+ const projectsPaths = paths.filter((path) => !ENVIRONMENTS_PATH.test(path))Object.entries(mockHandlers).forEach(([path, handler]) => {- const pathWithoutTrailingSlash = path.replace(/\/$/, '')- handlers.push(- (http[method] as (typeof http)['get'])(pathWithoutTrailingSlash, async (info) => {- // Function handlers and static values support the same MockResult forms:- // a `[status, body]` tuple, a Response, or a plain JSON body. Static- // `[status, body]` tuples used to be serialized as a literal array body,- // which silently broke every mock relying on the status.- if (typeof handler === 'function') {- return toResponse(await handler(info))- }- return toResponse(handler as MockResult)- })- )+ // Function handlers and static values support the same MockResult forms: a+ // `[status, body]` tuple, a Response, or a plain JSON body. Static `[status, body]`+ // tuples used to be serialized as a literal array body, which silently broke every+ // mock relying on the status.+ const resolve = async (info: MockResolverInfo): Promise<Response> =>+ typeof handler === 'function' ? toResponse(await handler(info)) : toResponse(handler as MockResult)++ handlers.push((http[method] as (typeof http)['get'])(withoutTrailingSlash(path), resolve))++ const twin = projectsTwinFor(path, registeredPaths)+ if (twin) {+ const target = projectsPaths.some((projectsPath) => covers(twin, projectsPath))+ ? deferred+ : handlers+ target.push((http[method] as (typeof http)['get'])(withoutTrailingSlash(twin), resolve))+ }})})- return handlers+ return [...handlers, ...deferred]}diff --git a/products/subscriptions/frontend/components/Subscriptions/SubscriptionsModal.stories.tsx b/products/subscriptions/frontend/components/Subscriptions/SubscriptionsModal.stories.tsxindex cbd36410740f..3d81d6a31a58 100644--- a/products/subscriptions/frontend/components/Subscriptions/SubscriptionsModal.stories.tsx+++ b/products/subscriptions/frontend/components/Subscriptions/SubscriptionsModal.stories.tsx@@ -239,9 +239,10 @@ const meta: Meta<StoryArgs> = {'/api/environments/:id/subscriptions/:subId':formScenario === 'long-ai-prompt' ? LONG_AI_PROMPT_SUBSCRIPTION : createMockSubscription(),'/api/projects/:id/subscriptions/:subId/deliveries': { results: [] },- ...(freeTierSubscriptionCount !== undefined- ? { '/api/projects/:id/subscriptions/': { count: freeTierSubscriptionCount, results: [] } }- : {}),+ // subscriptionCountLogic counts through the generated client, which asks for the+ // projects path. Say the count every scenario means, because the contextual list+ // above is a different question and would read as a free-tier limit.+ '/api/projects/:id/subscriptions/': { count: freeTierSubscriptionCount ?? 0, results: [] },'/api/projects/:id/subscriptions/summary_quota': aiSummaryAtLimit? { active_count: 10, limit: 10, at_limit: true }: { active_count: 0, limit: 10, at_limit: false },