# Test a pricing policy like code

> Test pricing like code. Validate a policy in CI, write tests for what each plan allows and bills, test time-based behavior, and test policies in Stof with the Stof CLI.

# Test a policy

A pricing change is a code change: it can lock customers out or give features away. Test it the same way. The
engine is the same in tests as in production, so tests run against the real thing in milliseconds.

## Tests in TypeScript and Python

This uses Node's built-in test runner (`npx tsx --test pricing.test.ts`), or pytest in Python (`pytest test_policy.py`).
Vitest, Jest, and unittest work the same way.

<Tabs groupId="lang" queryString>
<TabItem value="typescript" label="TypeScript">

```ts
// In your repo: the policy file you ship, Ex. readFileSync('./policy.stof', 'utf8').
const policy = `
policy: {
    credits: {
        request: { label: 'API request' }
        ai_token: { label: 'AI token', price: { amount: 0.00002 } }
    }
    plans: {
        free: {
            default: true
            entitlements: {
                api: {
                    limit: {
                        credit: 'request', value: 1000
                        resets: true, reset_inc: 1day
                    }
                }
            }
        }
        pro: {
            entitlements: {
                api: {
                    limit: {
                        credit: 'request', value: 100_000
                        resets: true, reset_sch: 'monthly:1'
                    }
                }
                chat: {
                    limit: {
                        credit: 'ai_token', mode: 'soft', value: 2_000_000
                        resets: true
                    }
                }
                sso: {}
            }
        }
    }
}`;

// A fresh engine per test, so tests can't affect each other.
const engine = () => Limitr.new(policy);

test('the policy is valid', async () => {
    const [ok, message] = await (await engine()).valid();
    assert.ok(ok, message);
});

test('free customers get 1,000 API requests a day', async () => {
    const limitr = await engine();
    await limitr.ensureCustomer('t1');
    assert.equal(await limitr.allow('t1', 'api', 1000), true);
    assert.equal(await limitr.allow('t1', 'api', 1), false);
});

test('free customers have no AI chat or SSO', async () => {
    const limitr = await engine();
    await limitr.ensureCustomer('t2');
    assert.equal(await limitr.check('t2', 'chat', 1), false);
    assert.equal(await limitr.check('t2', 'sso'), false);
});

test('pro bills chat past 2M tokens', async () => {
    const limitr = await engine();
    await limitr.ensureCustomer('t3', 'pro');
    const bills: number[] = [];
    limitr.addHandler('test', (name, value) => {
        if (name === 'meter-overage') bills.push(JSON.parse(value as string).overage_price);
    });
    assert.equal(await limitr.allow('t3', 'chat', 2_500_000), true);
    assert.deepEqual(bills, [10]);                   // 500k tokens at $20 per million
});

test('upgrading keeps the usage counted so far', async () => {
    const limitr = await engine();
    await limitr.ensureCustomer('t4');
    await limitr.allow('t4', 'api', 600);
    await limitr.setCustomerPlan('t4', 'pro', false);
    assert.equal(await limitr.value('t4', 'api'), 600);
    assert.equal(await limitr.remaining('t4', 'api'), 99_400);
});
```

</TabItem>
<TabItem value="python" label="Python">

```python norun
# test_policy.py: run with `pytest`
from limitr import Limitr

# In your repo: the policy file you ship, Ex. open('policy.stof').read().
policy = """
policy: {
    credits: {
        request: { label: 'API request' }
        ai_token: { label: 'AI token', price: { amount: 0.00002 } }
    }
    plans: {
        free: {
            default: true
            entitlements: {
                api: {
                    limit: {
                        credit: 'request', value: 1000
                        resets: true, reset_inc: 1day
                    }
                }
            }
        }
        pro: {
            entitlements: {
                api: {
                    limit: {
                        credit: 'request', value: 100_000
                        resets: true, reset_sch: 'monthly:1'
                    }
                }
                chat: {
                    limit: {
                        credit: 'ai_token', mode: 'soft', value: 2_000_000
                        resets: true
                    }
                }
                sso: {}
            }
        }
    }
}"""

# A fresh engine per test, so tests can't affect each other.
@pytest.fixture
def limitr():
    return Limitr(policy)

def test_the_policy_is_valid(limitr):
    ok, message = limitr.valid()
    assert ok, message

def test_free_customers_get_1000_api_requests_a_day(limitr):
    limitr.ensure_customer('t1')
    assert limitr.allow('t1', 'api', 1000) is True
    assert limitr.allow('t1', 'api', 1) is False

def test_free_customers_have_no_ai_chat_or_sso(limitr):
    limitr.ensure_customer('t2')
    assert limitr.check('t2', 'chat', 1) is False
    assert limitr.check('t2', 'sso') is False

def test_pro_bills_chat_past_2m_tokens(limitr):
    limitr.ensure_customer('t3', 'pro')
    bills = []
    limitr.add_handler('test', lambda name, event: name == 'meter-overage' and bills.append(event['overage_price']))
    assert limitr.allow('t3', 'chat', 2_500_000) is True
    assert bills == [10]                             # 500k tokens at $20 per million

def test_upgrading_keeps_the_usage_counted_so_far(limitr):
    limitr.ensure_customer('t4')
    limitr.allow('t4', 'api', 600)
    limitr.set_customer_plan('t4', 'pro', False)
    assert limitr.value('t4', 'api') == 600
    assert limitr.remaining('t4', 'api') == 99_400
```

</TabItem>
</Tabs>

- **A fresh engine per test** keeps tests independent. Creating one takes a few milliseconds.
- **Test what the plan promises**: what's allowed, what's denied, what's billed, and what happens on plan changes.
- **Test the events you bill from.** Collect them with a handler and assert on the amounts.
- **Run them in CI** next to `valid()`, so a pricing change can't ship broken.

## Time-based behavior

Resets don't run on a timer; the engine notices a new period on the next call. To test a reset, give the test policy
a short period (`reset_inc: 1s`) and wait past it, or test the logic around it with `resets(id, entitlement)`, which
returns when the current period ends.

## Tests in Stof

Policies are [Stof](https://stof.dev) documents, so tests can live next to the policy, in Stof, and run with the Stof
CLI. They need the engine's source, from the [Limitr repo](https://github.com/dev-formata-io/limitr) (here at
`./limitr`):

```stof title="pricing.test.stof" norun
Limitr policy: {
    credits: {
        request: { label: 'API request' }
    }
    plans: {
        free: {
            default: true
            entitlements: {
                api: {
                    limit: {
                        credit: 'request', value: 1000
                        resets: true, reset_inc: 1day
                    }
                }
            }
        }
    }
}

#[test]
fn free_api_is_capped() {
    const p = self.policy;
    p.create_customer('t_free_api', 'free');
    assert(p.allow('t_free_api', 'api', 1000));
    assert_not(p.allow('t_free_api', 'api', 1));
    assert_eq(p.remaining('t_free_api', 'api'), 0);
}

#[test]
fn policy_is_valid() {
    assert(self.policy.valid());
}
```

```bash
stof test pricing.test.stof
stof test --leaks pricing.test.stof
```

- `Limitr policy: { ... }` gives the policy the engine's type, so `self.policy.allow(...)` works directly.
- Tests in a document run concurrently against the same document, so give each test its own customer IDs.
- `--leaks` runs the tests one at a time and fails any that leave objects behind. Run it when a policy has functions
  (cost functions, rules, notifications): see [Write policies in Stof](./write-stof-policies#memory).
