: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
import { router } from 'kea-router'
import { expectLogic } from 'kea-test-utils'
import { useMocks } from '~/mocks/jest'
import { initKeaTests } from '~/test/init'
import { FilterLogicalOperator } from '~/types'
import { LogsViewerGroupBy } from 'products/logs/frontend/components/LogsViewer/config/logsViewerConfigLogic'
import {
SERVICE_NAME_FILTER,
SEVERITY_LEVEL_FILTER,
facetSelection,
} from 'products/logs/frontend/components/LogsViewer/FacetRail/facetFilters'
import { logsSceneLogic } from './logsSceneLogic'
describe('logsSceneLogic', () => {
let logic: ReturnType<typeof logsSceneLogic.build>
// The two legacy params fold into filterGroup, which is where the selection lives.
const selectedLevels = (): string[] =>
facetSelection(logic.values.filters.filterGroup, SEVERITY_LEVEL_FILTER).included
const selectedServices = (): string[] =>
facetSelection(logic.values.filters.filterGroup, SERVICE_NAME_FILTER).included
beforeEach(async () => {
useMocks({
post: {
'/api/environments/:team_id/logs/query/': () => [200, { results: [], maxExportableLogs: 5000 }],
'/api/environments/:team_id/logs/sparkline/': () => [200, []],
'/api/projects/:team_id/logs/anomalies/series_bands/': () => [
200,
{
service_name: 'checkout',
window_start: '2026-08-10T10:00:00Z',
window_end: '2026-08-17T10:00:00Z',
interval_minutes: 60,
series_truncated: false,
series: [],
},
],
},
})
initKeaTests()
logic = logsSceneLogic()
logic.mount()
await expectLogic(logic).toFinishAllListeners()
})
afterEach(() => {
logic.unmount()
})
describe('URL parameter parsing', () => {
it.each([
['JSON string array', '["error","warn"]', ['error', 'warn']],
['single item JSON array', '["info"]', ['info']],
['empty JSON array', '[]', []],
])('parses severityLevels from %s', async (_, urlValue, expected) => {
await expectLogic(logic, () => {
router.actions.push('/logs', { severityLevels: urlValue })
}).toFinishAllListeners()
expect(selectedLevels()).toEqual(expected)
})
it.each([
['JSON string array', '["my-service","other-service"]', ['my-service', 'other-service']],
['single item JSON array', '["api"]', ['api']],
])('parses serviceNames from %s', async (_, urlValue, expected) => {
await expectLogic(logic, () => {
router.actions.push('/logs', { serviceNames: urlValue })
}).toFinishAllListeners()
expect(selectedServices()).toEqual(expected)
})
it.each<[string, string]>([
['severityLevels', '["error"]'],
['serviceNames', '["api"]'],
])('drops the %s param once it has been applied', async (param, urlValue) => {
await expectLogic(logic, () => {
router.actions.push('/logs', { [param]: urlValue })
}).toFinishAllListeners()
// Left in place, the param is read again on every later URL change and folds its
// selection back in, contradicting whatever the rail did to it since.
expect(router.values.searchParams[param]).toBeUndefined()
expect(router.values.searchParams.filterGroup).not.toBeUndefined()
})
it.each<[string, string, string[], string[]]>([
[
'a group that already selects the facet wins over the param',
'["error"]',
['error', 'warn'],
['error', 'warn'],
],
['a group silent about the facet lets the param through', '["error"]', [], ['error']],
])('%s', async (_, param, groupLevels, expected) => {
const values = groupLevels.length
? [{ key: 'severity_level', type: 'log', operator: 'exact', value: groupLevels }]
: []
await expectLogic(logic, () => {
router.actions.push('/logs', {
severityLevels: param,
filterGroup: JSON.stringify({
type: FilterLogicalOperator.And,
values: [{ type: FilterLogicalOperator.And, values }],
}),
})
}).toFinishAllListeners()
expect(selectedLevels()).toEqual(expected)
})
it('filters out malformed JSON as invalid severity level', async () => {
await expectLogic(logic, () => {
router.actions.push('/logs', { severityLevels: 'not-valid-json[' })
}).toFinishAllListeners()
// parseTagsFilter falls back to comma-separated parsing, then validation filters invalid levels
expect(selectedLevels()).toEqual([])
})
it('filters out non-array JSON as invalid severity level', async () => {
await expectLogic(logic, () => {
router.actions.push('/logs', { severityLevels: '"just-a-string"' })
}).toFinishAllListeners()
// parseTagsFilter falls back to comma-separated parsing, then validation filters invalid levels
expect(selectedLevels()).toEqual([])
})
it('handles comma-separated values via parseTagsFilter', async () => {
await expectLogic(logic, () => {
router.actions.push('/logs', { severityLevels: 'error,warn,info' })
}).toFinishAllListeners()
expect(selectedLevels()).toEqual(['error', 'warn', 'info'])
})
it.each([
['a valid lens', 'patterns', 'patterns'],
['an unrecognised lens falls back to the default', 'nonsense', 'logs'],
])('applies viewMode from the URL: %s', async (_, urlValue, expected) => {
await expectLogic(logic, () => {
router.actions.push('/logs', { viewMode: urlValue })
}).toFinishAllListeners()
expect(logic.values.viewMode).toEqual(expected)
})
it('syncs lens switches back to the URL, dropping the param for the default lens', async () => {
// The round-trip contract for shareable lens links: switching to Patterns writes
// ?viewMode=patterns, and returning to Logs (the default) removes the param
// instead of pinning viewMode=logs into every copied URL.
await expectLogic(logic, () => {
logic.actions.setViewMode('patterns')
}).toFinishAllListeners()
expect(router.values.searchParams.viewMode).toEqual('patterns')
await expectLogic(logic, () => {
logic.actions.setViewMode('logs')
}).toFinishAllListeners()
expect(router.values.searchParams.viewMode).toBeUndefined()
})
it.each([
['completely invalid value', '["invalid-level"]', []],
['typo in valid level', '["debug123"]', []],
['mix of valid and invalid', '["error","not-a-level","warn"]', ['error', 'warn']],
['invalid comma-separated', 'invalid,also-invalid', []],
])('filters out invalid severity levels (%s)', async (_, urlValue, expected) => {
await expectLogic(logic, () => {
router.actions.push('/logs', { severityLevels: urlValue })
}).toFinishAllListeners()
expect(selectedLevels()).toEqual(expected)
})
it('parses a stringified filterGroup from the URL (e.g. a cross-product session link)', async () => {
const filterGroup = {
type: 'AND',
values: [{ type: 'OR', values: [{ key: 'posthogSessionId', value: ['sess-1'], operator: 'exact' }] }],
}
await expectLogic(logic, () => {
router.actions.push('/logs', { filterGroup: JSON.stringify(filterGroup) })
}).toFinishAllListeners()
expect(logic.values.filters.filterGroup).toEqual(filterGroup)
})
it('ignores a malformed filterGroup in the URL', async () => {
const before = logic.values.filters.filterGroup
await expectLogic(logic, () => {
router.actions.push('/logs', { filterGroup: '{not valid json' })
}).toFinishAllListeners()
expect(logic.values.filters.filterGroup).toEqual(before)
})
})
describe('activeTab URL sync', () => {
it('defaults to viewer', () => {
expect(logic.values.activeTab).toEqual('viewer')
})
it.each([
['viewer', 'viewer'],
['anomalies', 'anomalies'],
['configuration', 'configuration'],
])('parses valid activeTab "%s" from URL', async (urlValue, expected) => {
await expectLogic(logic, () => {
router.actions.push('/logs', { activeTab: urlValue })
}).toFinishAllListeners()
expect(logic.values.activeTab).toEqual(expected)
})
it.each([
['unknown string', 'invalid'],
['array', ['viewer']],
['object', { key: 'viewer' }],
['number', 42],
])('ignores invalid activeTab (%s)', async (_, urlValue) => {
await expectLogic(logic, () => {
router.actions.push('/logs', { activeTab: urlValue })
}).toFinishAllListeners()
expect(logic.values.activeTab).toEqual('viewer')
})
it('syncs activeTab to URL on setActiveTab', async () => {
await expectLogic(logic, () => {
logic.actions.setActiveTab('configuration')
}).toFinishAllListeners()
expect(logic.values.activeTab).toEqual('configuration')
expect(router.values.searchParams).toHaveProperty('activeTab', 'configuration')
})
it('removes activeTab from URL when set to default', async () => {
// First set to non-default
await expectLogic(logic, () => {
logic.actions.setActiveTab('configuration')
}).toFinishAllListeners()
// Then set back to default
await expectLogic(logic, () => {
logic.actions.setActiveTab('viewer')
}).toFinishAllListeners()
expect(logic.values.activeTab).toEqual('viewer')
expect(router.values.searchParams).not.toHaveProperty('activeTab')
})
})
describe('facetNameSearch URL sync', () => {
it('parses facetNameSearch from URL', async () => {
await expectLogic(logic, () => {
router.actions.push('/logs', { facetNameSearch: 'namespace' })
}).toFinishAllListeners()
expect(logic.values.facetNameSearch).toEqual('namespace')
})
it('syncs facetNameSearch to URL on setFacetNameSearch', async () => {
await expectLogic(logic, () => {
logic.actions.setFacetNameSearch('kube')
}).toFinishAllListeners()
expect(logic.values.facetNameSearch).toEqual('kube')
expect(router.values.searchParams).toHaveProperty('facetNameSearch', 'kube')
})
it('removes facetNameSearch from URL when cleared', async () => {
await expectLogic(logic, () => {
logic.actions.setFacetNameSearch('kube')
}).toFinishAllListeners()
await expectLogic(logic, () => {
logic.actions.setFacetNameSearch('')
}).toFinishAllListeners()
expect(logic.values.facetNameSearch).toEqual('')
expect(router.values.searchParams).not.toHaveProperty('facetNameSearch')
})
})
describe('anomalies tab URL sync', () => {
// A write arms the sync guard, which clears on a macrotask that `toFinishAllListeners`
// does not flush. A real back-navigation lands long after that tick.
const flushUrlSyncGuard = async (): Promise<void> => {
await new Promise((resolve) => setTimeout(resolve, 0))
}
const onAnomaliesTab = async (): Promise<void> => {
await expectLogic(logic, () => {
logic.actions.setActiveTab('anomalies')
}).toFinishAllListeners()
}
it('reads the service and the window off the URL', async () => {
await expectLogic(logic, () => {
router.actions.push('/logs', {
activeTab: 'anomalies',
anomaliesService: 'checkout',
anomaliesDateRange: { date_from: '-24h' },
})
}).toFinishAllListeners()
expect(logic.values.anomaliesService).toEqual('checkout')
expect(logic.values.anomaliesDateRange).toEqual({ date_from: '-24h' })
})
it('ignores the params while another tab is shown', async () => {
// Reading a service fetches its band charts, so an ungated read would fire that
// request from any URL change made on the viewer.
await expectLogic(logic, () => {
router.actions.push('/logs', { anomaliesService: 'checkout' })
}).toFinishAllListeners()
expect(logic.values.anomaliesService).toBeNull()
})
it('returns the picker to the default window when the param goes', async () => {
// This is the Back case: stepping past the change that wrote the param has to
// return the default week, not keep the older pick.
await expectLogic(logic, () => {
router.actions.push('/logs', {
activeTab: 'anomalies',
anomaliesDateRange: { date_from: '-24h' },
})
}).toFinishAllListeners()
await flushUrlSyncGuard()
await expectLogic(logic, () => {
router.actions.push('/logs', { activeTab: 'anomalies' })
}).toFinishAllListeners()
expect(logic.values.anomaliesDateRange).toEqual({ date_from: '-7d' })
})
it('falls back to the default window when the param is not a date range', async () => {
// A hand-edited or stale URL must not push a shape the picker and the band request
// cannot read.
await expectLogic(logic, () => {
router.actions.push('/logs', {
activeTab: 'anomalies',
anomaliesDateRange: ['-24h'],
})
}).toFinishAllListeners()
expect(logic.values.anomaliesDateRange).toEqual({ date_from: '-7d' })
})
it('writes both params, and drops each one at its default', async () => {
await onAnomaliesTab()
await expectLogic(logic, () => {
logic.actions.setAnomaliesService('checkout')
logic.actions.setAnomaliesDateRange({ date_from: '-24h' })
}).toFinishAllListeners()
expect(router.values.searchParams).toHaveProperty('anomaliesService', 'checkout')
expect(router.values.searchParams.anomaliesDateRange).toEqual({ date_from: '-24h' })
// Left in the URL, the default week would ride along in every link from this tab.
await expectLogic(logic, () => {
logic.actions.setAnomaliesService(null)
logic.actions.setAnomaliesDateRange({ date_from: '-7d' })
}).toFinishAllListeners()
expect(router.values.searchParams).not.toHaveProperty('anomaliesService')
expect(router.values.searchParams).not.toHaveProperty('anomaliesDateRange')
})
it('leaves the viewer own service and window params alone', async () => {
// Both tabs live under one URL. Sharing `dateRange` would move the viewer window,
// and `serviceNames` is deleted by the viewer writer, so the pick would not survive.
await expectLogic(logic, () => {
router.actions.push('/logs', {
activeTab: 'anomalies',
dateRange: { date_from: '-1h' },
})
}).toFinishAllListeners()
await expectLogic(logic, () => {
logic.actions.setAnomaliesService('checkout')
logic.actions.setAnomaliesDateRange({ date_from: '-24h' })
}).toFinishAllListeners()
expect(logic.values.filters.dateRange).toEqual({ date_from: '-1h' })
expect(router.values.searchParams.dateRange).toEqual({ date_from: '-1h' })
})
it('carries the params in and out of the URL with the tab', async () => {
// A clicked bucket sends the user to the viewer on a URL that has neither param, so
// the selection has to go back into the URL when the tab comes back.
await onAnomaliesTab()
await expectLogic(logic, () => {
logic.actions.setAnomaliesService('checkout')
}).toFinishAllListeners()
await expectLogic(logic, () => {
logic.actions.setActiveTab('viewer')
}).toFinishAllListeners()
expect(router.values.searchParams).not.toHaveProperty('anomaliesService')
await onAnomaliesTab()
expect(router.values.searchParams).toHaveProperty('anomaliesService', 'checkout')
})
})
describe('groupBys URL sync', () => {
// The URL-sync guard clears on a macrotask (setTimeout(0)), so a write followed by a
// router push in the same tick would see the guard still set and skip re-parsing. Flush
// it between the two so each step exercises the real urlToAction path.
const flushUrlSyncGuard = (): Promise<void> => new Promise((resolve) => setTimeout(resolve, 0))
const GROUP_BYS: LogsViewerGroupBy[] = [
{ key: 'service.name', source: 'resource' },
{ key: 'severity_level', source: 'column' },
]
it('parses groupBys from the URL', async () => {
await expectLogic(logic, () => {
router.actions.push('/logs', { groupBys: JSON.stringify(GROUP_BYS) })
}).toFinishAllListeners()
expect(logic.values.groupBys).toEqual(GROUP_BYS)
})
it.each([
['a dimension with no source', '[{"key":"only-a-key"}]'],
['an empty key', '[{"key":"","source":"resource"}]'],
['a column source the endpoint cannot group by', '[{"key":"service.name","source":"column"}]'],
])('leaves the live grouping alone for %s', async (_name, param) => {
await expectLogic(logic, () => {
logic.actions.setGroupBys(GROUP_BYS)
}).toFinishAllListeners()
await flushUrlSyncGuard()
await expectLogic(logic, () => {
router.actions.push('/logs', { groupBys: param })
}).toFinishAllListeners()
expect(logic.values.groupBys).toEqual(GROUP_BYS)
})
it('drops duplicate dimensions from the URL', async () => {
await expectLogic(logic, () => {
router.actions.push('/logs', { groupBys: JSON.stringify([...GROUP_BYS, GROUP_BYS[0]]) })
}).toFinishAllListeners()
expect(logic.values.groupBys).toEqual(GROUP_BYS)
})
it('caps groupBys from the URL at the dimension limit', async () => {
const overCap: LogsViewerGroupBy[] = [
{ key: 'a', source: 'resource' },
{ key: 'b', source: 'resource' },
{ key: 'c', source: 'resource' },
{ key: 'd', source: 'resource' },
{ key: 'e', source: 'resource' },
]
await expectLogic(logic, () => {
router.actions.push('/logs', { groupBys: JSON.stringify(overCap) })
}).toFinishAllListeners()
expect(logic.values.groupBys).toEqual(overCap.slice(0, 4))
})
it('resets the grouping when the param is absent', async () => {
await expectLogic(logic, () => {
logic.actions.setGroupBys(GROUP_BYS)
}).toFinishAllListeners()
await flushUrlSyncGuard()
await expectLogic(logic, () => {
router.actions.push('/logs', {})
}).toFinishAllListeners()
expect(logic.values.groupBys).toEqual([])
})
it('syncs the grouping to the URL and drops the param when empty', async () => {
await expectLogic(logic, () => {
logic.actions.setGroupBys(GROUP_BYS)
}).toFinishAllListeners()
expect(router.values.searchParams.groupBys).toEqual(GROUP_BYS)
await expectLogic(logic, () => {
logic.actions.setGroupBys([])
}).toFinishAllListeners()
expect(router.values.searchParams).not.toHaveProperty('groupBys')
})
})
describe('patterns compare URL sync', () => {
it.each([
['the preceding baseline', 'preceding', true, 'preceding'],
['the last-week baseline', 'lastWeek', true, 'lastWeek'],
['an unrecognised baseline leaves compare off', 'nonsense', false, 'preceding'],
])('applies compare from the URL: %s', async (_, urlValue, expectedEnabled, expectedBaseline) => {
await expectLogic(logic, () => {
router.actions.push('/logs', { compare: urlValue })
}).toFinishAllListeners()
expect(logic.values.compareEnabled).toEqual(expectedEnabled)
expect(logic.values.baselineMode).toEqual(expectedBaseline)
})
it('writes the baseline while compare is on and drops the param when it is off', async () => {
await expectLogic(logic, () => {
logic.actions.setCompareEnabled(true)
}).toFinishAllListeners()
expect(router.values.searchParams.compare).toEqual('preceding')
await expectLogic(logic, () => {
logic.actions.setBaselineMode('lastWeek')
}).toFinishAllListeners()
expect(router.values.searchParams.compare).toEqual('lastWeek')
await expectLogic(logic, () => {
logic.actions.setCompareEnabled(false)
}).toFinishAllListeners()
expect(router.values.searchParams).not.toHaveProperty('compare')
})
})
})