Skip to content
Source
Sign inSign up
TanStack/schemas
Open History to see the last commit

unit-card.test.ts

78 lines2.4 KB

1import { describe, expect, it } from 'vitest'
2import { price } from './evaluate.ts'
3import { GPT_4O } from './fixtures/gpt-4o.ts'
4import { rateCardSchema } from './rate-card.schema.ts'
5import { compileUnitCard } from './unit-card.ts'
6import type { UnitCardSpec } from './unit-card.ts'
7​
8const source = GPT_4O.source
9​
10const compile = (spec: UnitCardSpec) => {
11 const card = compileUnitCard(spec, source)
12 if (!card) throw new Error('did not compile')
13 expect(rateCardSchema.safeParse(card).success).toBe(true)
14 return card
16​
17describe('compileUnitCard', () => {
18 it('prices a flat per-unit rate the caller measures', () => {
19 const card = compile({
20 quantity: { param: 'audio_seconds', bound: 'usage' },
21 rates: 0.006 / 60,
22 })
23 expect(price(card, {}, { audio_seconds: 600 })).toBeCloseTo(0.06, 9)
24 // No default: a duration nobody stated is not guessed at.
25 expect(() => price(card)).toThrow(
26 expect.objectContaining({ code: 'bad-input' }),
27 )
28 })
29​
30 it('looks the rate up by a request field', () => {
31 const card = compile({
32 quantity: { param: 'seconds', bound: 'request' },
33 keys: [{ param: 'size', values: ['720x1280', '1792x1024'] }],
34 rates: { '720x1280': 0.3, '1792x1024': 0.5 },
35 })
36 expect(price(card, { seconds: 8, size: '1792x1024' })).toBe(4)
37 expect(() => price(card, { seconds: 8, size: '3840x2160' })).toThrow(
38 expect.objectContaining({ code: 'bad-input' }),
39 )
40 })
41​
42 it('looks the rate up by two dimensions', () => {
43 const card = compile({
44 keys: [
45 { param: 'quality', values: ['low', 'medium'], default: 'low' },
46 { param: 'resolution', values: ['1k', '2k'], default: '1k' },
47 ],
48 rates: {
49 low: { '1k': 0.04, '2k': 0.06 },
50 medium: { '1k': 0.06, '2k': 0.08 },
51 },
52 })
53 expect(price(card, {})).toBe(0.04)
54 expect(price(card, { quality: 'medium', resolution: '2k' })).toBe(0.08)
55 })
56​
57 it('is null when a rate is missing, zero or uncovered', () => {
58 expect(compileUnitCard({ rates: 0 }, source)).toBeNull()
59 expect(
60 compileUnitCard(
61 {
62 keys: [{ param: 'size', values: ['720p', '1080p'] }],
63 rates: { '720p': 0.1 },
64 },
65 source,
66 ),
67 ).toBeNull()
68 expect(
69 compileUnitCard(
70 {
71 keys: [{ param: 'size', values: ['720p'], default: '4k' }],
72 rates: { '720p': 0.1 },
73 },
74 source,
75 ),
76 ).toBeNull()
77 })
78})