: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(hog-charts): add tests for vendored utils (#58092)
Sam Pennington0ed1054b5f9a
diff --git a/frontend/src/lib/hog-charts/utils/dayjs.test.ts b/frontend/src/lib/hog-charts/utils/dayjs.test.tsnew file mode 100644index 000000000000..4dfbd36f7080--- /dev/null+++ b/frontend/src/lib/hog-charts/utils/dayjs.test.ts@@ -0,0 +1,62 @@+import { dayjs, parseDateInTimezone } from './dayjs'++describe('parseDateInTimezone', () => {+ describe('strings without explicit timezone', () => {+ it('treats date-only strings as wall-clock in the given timezone', () => {+ const result = parseDateInTimezone('2026-03-08', 'America/New_York')+ expect(result.format('YYYY-MM-DD HH:mm')).toBe('2026-03-08 00:00')+ expect(result.format('Z')).toBe('-05:00')+ })++ it('treats datetime strings as wall-clock in the given timezone', () => {+ const result = parseDateInTimezone('2026-03-08 14:30:00', 'America/New_York')+ expect(result.format('YYYY-MM-DD HH:mm')).toBe('2026-03-08 14:30')+ })++ it('parses UTC wall-clock without shifting', () => {+ const result = parseDateInTimezone('2026-03-08 14:30:00', 'UTC')+ expect(result.utc().format('YYYY-MM-DD HH:mm')).toBe('2026-03-08 14:30')+ })+ })++ describe('strings with explicit timezone', () => {+ it.each([+ ['Z suffix', '2026-03-08T14:30:00Z'],+ ['lowercase z suffix', '2026-03-08T14:30:00z'],+ ['+00:00 offset', '2026-03-08T14:30:00+00:00'],+ ['negative offset', '2026-03-08T14:30:00-05:00'],+ ['no colon offset', '2026-03-08T14:30:00+0000'],+ ])('treats %s as a real instant', (_, dateStr) => {+ const result = parseDateInTimezone(dateStr, 'America/New_York')+ expect(result.isValid()).toBe(true)+ })++ it('converts an explicit UTC instant into the requested timezone', () => {+ // Pick a winter date well clear of DST transitions.+ const result = parseDateInTimezone('2026-01-15T14:30:00Z', 'America/New_York')+ expect(result.format('YYYY-MM-DD HH:mm')).toBe('2026-01-15 09:30')+ })+ })++ it('returns invalid Dayjs for unparseable input', () => {+ const result = parseDateInTimezone('not-a-date', 'UTC')+ expect(result.isValid()).toBe(false)+ })++ it('does not depend on the browser timezone for date-only strings', () => {+ const utc = parseDateInTimezone('2026-03-08', 'UTC')+ const tokyo = parseDateInTimezone('2026-03-08', 'Asia/Tokyo')+ expect(utc.format('YYYY-MM-DD')).toBe('2026-03-08')+ expect(tokyo.format('YYYY-MM-DD')).toBe('2026-03-08')+ })+})++describe('dayjs export', () => {+ it('has the timezone plugin extended', () => {+ expect(typeof dayjs.tz).toBe('function')+ })++ it('has the utc plugin extended', () => {+ expect(typeof dayjs.utc).toBe('function')+ })+})diff --git a/frontend/src/lib/hog-charts/utils/format.test.ts b/frontend/src/lib/hog-charts/utils/format.test.tsnew file mode 100644index 000000000000..6a04b2f336df--- /dev/null+++ b/frontend/src/lib/hog-charts/utils/format.test.ts@@ -0,0 +1,128 @@+import {+ compactNumber,+ formatCurrency,+ hexToRGBA,+ humanFriendlyCurrency,+ humanFriendlyDuration,+ humanFriendlyNumber,+ percentage,+} from './format'++const NBSP = ' '++describe('format helpers', () => {+ describe('humanFriendlyNumber', () => {+ it.each([+ ['integer with thousands separator', 1234, undefined, undefined, '1,234'],+ ['decimal rounded to 2 by default', 1234.5678, undefined, undefined, '1,234.57'],+ ['custom maximumFractionDigits', 1234.5678, 4, undefined, '1,234.5678'],+ ['minimumFractionDigits forces trailing zeros', 5, 2, 2, '5.00'],+ ['negative numbers', -1234, undefined, undefined, '-1,234'],+ ['zero', 0, undefined, undefined, '0'],+ ['NaN maxFractionDigits falls back to default', 1.234, NaN, undefined, '1.23'],+ ['out-of-range maxFractionDigits falls back to default', 1.234, 200, undefined, '1.23'],+ ['negative maxFractionDigits falls back to default', 1.234, -1, undefined, '1.23'],+ ] as const)('%s', (_, value, maxDigits, minDigits, expected) => {+ expect(humanFriendlyNumber(value, maxDigits, minDigits)).toBe(expected)+ })+ })++ describe('humanFriendlyCurrency', () => {+ it.each([+ ['number input', 1234.5, undefined, '$1,234.50'],+ ['string input', '1234.5', undefined, '$1,234.50'],+ ['undefined falls back to 0', undefined, undefined, '$0.00'],+ ['empty string falls back to 0', '', undefined, '$0.00'],+ ['custom precision', 1234.5678, 4, '$1,234.5678'],+ ['precision 0', 1234.5, 0, '$1,235'],+ ['invalid precision falls back to 2', 1.5, 200, '$1.50'],+ ] as const)('%s', (_, value, precision, expected) => {+ expect(humanFriendlyCurrency(value, precision)).toBe(expected)+ })+ })++ describe('humanFriendlyDuration', () => {+ it.each([+ ['empty string', '', '', undefined],+ ['null', null, '', undefined],+ ['undefined', undefined, '', undefined],+ ['maxUnits 0 returns empty', 90, '', { maxUnits: 0 }],+ ['zero', 0, '0s', undefined],+ ['sub-second renders as ms', 0.5, '500ms', undefined],+ ['exact second', 1, '1s', undefined],+ ['mid-minute', 90, `1m${NBSP}30s`, undefined],+ ['exact hour', 3600, '1h', undefined],+ ['hour + minute + second', 3661, `1h${NBSP}1m${NBSP}1s`, undefined],+ ['exact day', 86400, '1d', undefined],+ ['day + hour', 90000, `1d${NBSP}1h`, undefined],+ ['days suppress minutes/seconds', 90061, `1d${NBSP}1h`, undefined],+ ['negative', -90, `-1m${NBSP}30s`, undefined],+ ['negative forwards options', -90, '-1m', { maxUnits: 1 }],+ ['secondsPrecision rounds to N significant figures', 12.5, '13s', { secondsPrecision: 2 }],+ ['secondsFixed rounds to N fixed decimals', 12.5, '12.5s', { secondsFixed: 1 }],+ ['maxUnits 1 caps output', 3661, '1h', { maxUnits: 1 }],+ ['maxUnits 2 caps output', 3661, `1h${NBSP}1m`, { maxUnits: 2 }],+ ['string input parsed as number', '90', `1m${NBSP}30s`, undefined],+ ] as const)('%s', (_, value, expected, options) => {+ expect(humanFriendlyDuration(value, options)).toBe(expected)+ })+ })++ describe('percentage', () => {+ it.each([+ ['basic fraction', 0.234, undefined, undefined, '23.4%'],+ ['integer', 0.5, undefined, undefined, '50%'],+ ['negative', -0.25, undefined, undefined, '-25%'],+ ['Infinity', Infinity, undefined, undefined, '∞%'],+ ['custom max digits', 0.123456, 4, undefined, '12.3456%'],+ ['fixedPrecision pads zeros', 0.5, 2, true, '50.00%'],+ ] as const)('%s', (_, value, maxDigits, fixed, expected) => {+ expect(percentage(value, maxDigits, fixed)).toBe(expected)+ })+ })++ describe('compactNumber', () => {+ it.each([+ ['null returns dash', null, '-'],+ ['under 1000', 999, '999'],+ ['thousands', 1500, `1.5${NBSP}K`],+ ['millions', 1_500_000, `1.5${NBSP}M`],+ ['billions', 2_500_000_000, `2.5${NBSP}B`],+ ['trillions', 3_500_000_000_000, `3.5${NBSP}T`],+ ['negative thousands', -1500, `-1.5${NBSP}K`],+ ['rounded to 3 sig figs', 12345, `12.3${NBSP}K`],+ ['zero', 0, '0'],+ ] as const)('%s', (_, value, expected) => {+ expect(compactNumber(value)).toBe(expected)+ })+ })++ describe('formatCurrency', () => {+ it.each([+ ['USD prefixes with $', 1234, 'USD', '$1,234.00'],+ ['always uses 2 fixed decimal places', 1.5, 'USD', '$1.50'],+ ['EUR is prefixed in en-US locale', 1234, 'EUR', '€1,234.00'],+ ['GBP is prefixed', 1234, 'GBP', '£1,234.00'],+ ])('%s', (_, amount, currency, expected) => {+ expect(formatCurrency(amount, currency)).toBe(expected)+ })++ it('throws for invalid currency code', () => {+ expect(() => formatCurrency(1234, 'NOT-A-CURRENCY')).toThrow()+ })+ })++ describe('hexToRGBA', () => {+ it.each([+ ['6-digit hex', '#FF0000', 1, 'rgba(255,0,0,1)'],+ ['without hash prefix', 'FF0000', 1, 'rgba(255,0,0,1)'],+ ['lowercase hex', '#aabbcc', 0.5, 'rgba(170,187,204,0.5)'],+ ['shorthand 3-digit hex', '#f00', 1, 'rgba(255,0,0,1)'],+ ['8-digit hex preserves explicit alpha override', '#FF000080', 0.25, 'rgba(255,0,0,0.25)'],+ ['default alpha is 1', '#000000', undefined, 'rgba(0,0,0,1)'],+ ['malformed hex (wrong length) returns black', '#zz', 1, 'rgba(0,0,0,1)'],+ ])('%s', (_, hex, alpha, expected) => {+ expect(hexToRGBA(hex, alpha)).toBe(expected)+ })+ })+})diff --git a/frontend/src/lib/hog-charts/utils/statistics.test.ts b/frontend/src/lib/hog-charts/utils/statistics.test.tsnew file mode 100644index 000000000000..96ac30fe3b2a--- /dev/null+++ b/frontend/src/lib/hog-charts/utils/statistics.test.ts@@ -0,0 +1,140 @@+import { ciRanges, linearRegression, movingAverage, trendLine } from './statistics'++describe('linearRegression', () => {+ it('fits a perfect line through y = 2x + 1', () => {+ const result = linearRegression([+ [0, 1],+ [1, 3],+ [2, 5],+ [3, 7],+ ])+ expect(result.m).toBeCloseTo(2)+ expect(result.b).toBeCloseTo(1)+ })++ it('fits a flat line through constant y', () => {+ const result = linearRegression([+ [0, 5],+ [1, 5],+ [2, 5],+ ])+ expect(result.m).toBeCloseTo(0)+ expect(result.b).toBeCloseTo(5)+ })+})++describe('trendLine', () => {+ it('returns the input when fewer than 2 points', () => {+ expect(trendLine([])).toEqual([])+ expect(trendLine([5])).toEqual([5])+ })++ it('produces a perfect linear fit when input is already linear', () => {+ const result = trendLine([1, 3, 5, 7])+ expect(result).toEqual([1, 3, 5, 7])+ })++ it('produces a least-squares fit for noisy input', () => {+ const result = trendLine([0, 2, 1, 3, 4])+ expect(result.length).toBe(5)+ // monotonically increasing for upward trend+ for (let i = 1; i < result.length; i++) {+ expect(result[i]).toBeGreaterThanOrEqual(result[i - 1])+ }+ })++ describe('fitUpTo', () => {+ it('fits the regression to a prefix and extrapolates to the full length', () => {+ // First 3 points are y = x; tail is noisy. fitUpTo=3 → trend continues as y=x.+ const result = trendLine([0, 1, 2, 100, 200], 3)+ expect(result).toHaveLength(5)+ expect(result[0]).toBeCloseTo(0)+ expect(result[1]).toBeCloseTo(1)+ expect(result[2]).toBeCloseTo(2)+ expect(result[3]).toBeCloseTo(3)+ expect(result[4]).toBeCloseTo(4)+ })++ it('clamps fitUpTo to a minimum of 2', () => {+ // With fitUpTo=1 (clamped to 2), uses only the first 2 points → y = x.+ const result = trendLine([0, 1, 100, 200, 300], 1)+ expect(result[0]).toBeCloseTo(0)+ expect(result[1]).toBeCloseTo(1)+ expect(result[2]).toBeCloseTo(2)+ })++ it('clamps fitUpTo to the input length', () => {+ const result = trendLine([1, 3, 5], 999)+ expect(result).toEqual([1, 3, 5])+ })+ })+})++describe('movingAverage', () => {+ it('returns the input when fewer points than the window', () => {+ expect(movingAverage([1, 2, 3], 7)).toEqual([1, 2, 3])+ })++ it('smooths uniform input to itself', () => {+ const result = movingAverage([5, 5, 5, 5, 5, 5, 5, 5], 3)+ expect(result).toEqual([5, 5, 5, 5, 5, 5, 5, 5])+ })++ it('smooths a step change with a window-3 average', () => {+ const result = movingAverage([0, 0, 0, 3, 3, 3, 3, 3], 3)+ expect(result).toHaveLength(8)+ expect(result[0]).toBeCloseTo(0)+ expect(result[7]).toBeCloseTo(3)+ // middle values are between 0 and 3+ expect(result[3]).toBeGreaterThan(0)+ expect(result[3]).toBeLessThan(3)+ })++ it('defaults to a window of 7', () => {+ const result = movingAverage([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])+ const explicit = movingAverage([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 7)+ expect(result).toEqual(explicit)+ })+})++describe('ciRanges', () => {+ it('returns the input as both bounds when fewer than 2 values', () => {+ expect(ciRanges([])).toEqual([[], []])+ expect(ciRanges([5])).toEqual([[5], [5]])+ })++ it('produces lower ≤ value ≤ upper for each point', () => {+ const values = [10, 12, 8, 14, 9, 11, 13]+ const [lower, upper] = ciRanges(values)+ expect(lower).toHaveLength(values.length)+ expect(upper).toHaveLength(values.length)+ for (let i = 0; i < values.length; i++) {+ expect(lower[i]).toBeLessThanOrEqual(values[i])+ expect(upper[i]).toBeGreaterThanOrEqual(values[i])+ }+ })++ it('produces a symmetric band around each value', () => {+ const values = [10, 20, 30]+ const [lower, upper] = ciRanges(values)+ for (let i = 0; i < values.length; i++) {+ const halfBand = upper[i] - values[i]+ expect(values[i] - lower[i]).toBeCloseTo(halfBand)+ }+ })++ it('produces zero band for constant values', () => {+ const [lower, upper] = ciRanges([5, 5, 5, 5])+ expect(lower).toEqual([5, 5, 5, 5])+ expect(upper).toEqual([5, 5, 5, 5])+ })++ it('widens with higher confidence (0.99 vs 0.5)', () => {+ const values = [10, 12, 8, 14, 9, 11, 13]+ const narrow = ciRanges(values, 0.5)+ const wide = ciRanges(values, 0.99)+ for (let i = 0; i < values.length; i++) {+ expect(wide[1][i] - wide[0][i]).toBeGreaterThan(narrow[1][i] - narrow[0][i])+ }+ })+})