Maintaining the same numerical routines in both JavaScript and Python is easy to start and surprisingly easy to let drift. A small guard clause added to one language—like clamping a 1x long liquidation price to zero or rejecting a wrong-side stop—turns into a silent behavioral split if each implementation carries its own separate unit tests.
This post walks through how the dual-language, zero-dependency package coinpopbit-futures-math v1.0.0 (GitHub, PyPI, npm) keeps its JavaScript and Python implementations locked together using three layers: 41 shared JSON test vectors, a local 19,200-case deterministic parity check against production formulas, and an OIDC Trusted Publisher workflow on GitHub Actions.
Why separate JS and Python test suites drift
The library exposes six deterministic functions for isolated futures calculations: isolatedLiquidationPrice, breakevenPrice, roundTripFee, positionSizeByRisk, averageEntryPrice, and riskRewardRatio (and their snake_case equivalents in Python). Every valid result returns "estimate": true so callers cannot confuse a theoretical formula output with an exchange's live order-book or tier calculation.
Writing hand-crafted assertions independently in run.mjs and test_math.py creates two failure modes:
- Error-path divergence. One language throws on
leverage < 1ormmr + feeRate >= 1, while the other returnsInfinityor a negative price. - Tolerance and type quirks. JavaScript compares
numbervalues directly, whereas in Pythonisinstance(True, int)evaluates toTrue, which can hide a boolean sneaking into a numeric assertion.
Putting every test case into a single language-neutral file, tests/vectors.json, removes both sources of drift.
Layer 1: 41 shared test vectors across 6 functions
tests/vectors.json defines a top-level tolerance of 1e-9 and groups 41 cases—26 valid numeric cases and 15 expected-error cases—across the six functions:
| Function | Total vectors | Valid cases | Error cases |
|---|---|---|---|
isolatedLiquidationPrice | 17 | 11 | 6 |
breakevenPrice | 7 | 5 | 2 |
roundTripFee | 2 | 1 | 1 |
positionSizeByRisk | 5 | 3 | 2 |
averageEntryPrice | 5 | 3 | 2 |
riskRewardRatio | 5 | 3 | 2 |
| Total | 41 | 26 | 15 |
Each case uses camelCase keys and either an expected object or "expectError": true:
{ "name": "tool-pages example: fee style 10x long (E=100000, N=10000, mmr=0.5%, fee=0.05%)", "input": { "side": "long", "entryPrice": 100000, "leverage": 10, "notional": 10000, "mmr": 0.005, "feeRate": 0.0005, "extraMargin": 0, "style": "fee" }, "expected": { "liquidationPrice": 90497.73755656109, "bankruptcyPrice": 90000, "initialMargin": 1000, "maintenanceMargin": 50, "maxIsolatedLoss": 1000 } } The JavaScript runner (packages/js/test/run.mjs) uses only node:assert/strict and scales tolerance by the larger of 1 or Math.abs(expected) so both small ratios (like fee percentages) and large prices (like 100000) use consistent relative bounds:
function assertClose(actual, expected, label) { if (typeof expected === 'number') { assert.equal(typeof actual, 'number', `${label}: expected number, got ${typeof actual}`); assert.ok( Math.abs(actual - expected) <= TOL * Math.max(1, Math.abs(expected)), `${label}: actual=${actual} vs expected=${expected} (tol=${TOL})` ); } else { assert.deepEqual(actual, expected, `${label}: actual=${actual} vs expected=${expected}`); } } For expectError: true, JavaScript requires RangeError. On the Python side (packages/python/tests/test_math.py), the standard library unittest runner translates keys through an explicit 39-entry CAMEL_TO_SNAKE map, requires ValueError on invalid inputs, and guards against Python's bool-is-an-int subclassing before calling math.isclose:
def assert_close(self, actual, expected, label): if isinstance(expected, (int, float)) and not isinstance(expected, bool): self.assertIsInstance(actual, (int, float), f"{label}: expected number") self.assertFalse(isinstance(actual, bool), f"{label}: unexpected bool") self.assertTrue( math.isclose(actual, expected, rel_tol=TOL, abs_tol=TOL), f"{label}: actual={actual} vs expected={expected} (tol={TOL})", ) else: self.assertEqual(actual, expected, f"{label}: actual={actual} vs expected={expected}") Using self.subTest(case=label) ensures a single failing vector reports its exact suite and field name without aborting the remaining cases. Running the JavaScript suite locally prints PASS: 41/41 JS test vectors passed (tol=1e-9).
Layer 2: 19,200 local parity cases against the source calculators
Forty-one hand-picked vectors catch obvious regressions, but they do not sweep parameter corners—high leverage paired with large extra margin, tight stops where liquidation triggers before the stop price, or multi-leg average-entry math.
To stress-test parity against the production calculator code without shipping private build files in the public repository, a .gitignored local script (scripts/check-against-site.mjs) reads the production formulas in read-only mode and compares them against the published JS package across randomized inputs generated by a fixed-seed Mulberry32 PRNG:
function makeRng(seed) { let a = seed >>> 0; return () => { a = (a + 0x6D2B79F5) >>> 0; let t = Math.imul(a ^ (a >>> 15), 1 | a); t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; return ((t ^ (t >>> 14)) >>> 0) / 4294967296; }; } const rand = makeRng(20261130); Because the PRNG is seeded, any mismatch is 100% reproducible. Running the script across all six venue formula mappings and the four non-liquidation calculators produces:
- Liquidation price (6 venues × long/short × 600 cases): 7,200 cases, 7,200 fields, 0 diffs (max relative error
3.80e-16) - Breakeven and round-trip fee: 3,000 cases, 9,000 fields, 0 diffs (max relative error
3.18e-16) - Position size by risk: 3,000 cases, 21,000 fields, 0 diffs (max relative error
3.15e-15) - Average entry price: 3,000 cases, 18,000 fields, 0 diffs (max relative error
0.00e+0) - Risk-reward ratio: 3,000 cases, 18,000 fields, 0 diffs (max relative error
0.00e+0) - Total: 19,200 cases, 73,200 fields compared, 0 diffs at tolerance
1e-9
When a sixth venue was added locally after the initial release, this script caught an important modeling detail immediately: that venue's mmr0 liquidation style (maintenance margin without closing-fee scaling on added margin) matches the library's mmr style when feeRate is passed as 0, whereas passing a nonzero feeRate alongside extraMargin > 0 diverges. Having the parity harness run on every formula change makes those edge assumptions explicit instead of implicit.
Layer 3: CI matrix and PyPI Trusted Publishing
Public CI (.github/workflows/ci.yml) stays minimal because neither package has runtime dependencies:
- Node 20 job: runs
node packages/js/test/run.mjsfollowed bynpm pack --dry-runinsidepackages/jsto verify the tarball file list (src/,types/,README.md,LICENSE) excludes test fixtures and local scripts. - Python matrix (
3.10,3.12): runspython -m unittest discover -s packages/python/tests -v.
Release publishing to PyPI (.github/workflows/publish.yml) avoids storing long-lived PyPI API tokens in repository secrets by using OpenID Connect (OIDC) Trusted Publishing:
jobs: publish-pypi: runs-on: ubuntu-latest permissions: id-token: write contents: read steps: - uses: actions/checkout@v4 - uses: actions/setup-python@v5 with: python-version: "3.12" - run: PYTHONPATH=packages/python/src python -m unittest discover -s packages/python/tests -v - run: python -m pip install --upgrade build twine - working-directory: packages/python run: python -m build - working-directory: packages/python run: twine check dist/* - uses: pypa/gh-action-pypi-publish@release/v1 with: packages-dir: packages/python/dist/ Two practical points from setting this up:
- Keep
permissionsscoped to the publish job. Grantingid-token: writeonly onpublish-pypikeeps the test-onlyci.ymlworkflow free of minting OIDC tokens on pull requests. - Re-run unit tests and
twine checkinside the release workflow. Even though CI already ran onmain, running the shared vector suite againstpackages/python/srcand checkingdist/*metadata immediately beforegh-action-pypi-publishprevents a broken tag or malformedREADME.mdfrom reaching PyPI.
Takeaways
- A single JSON vector file with both valid outputs and
expectErrorboundary cases keeps JS and Python behavior identical with zero external test frameworks. - In Python numeric helpers, explicitly reject
boolbefore callingisinstance(x, (int, float))ormath.isclose. - Pair small public regression vectors with a seeded local fuzz/parity script when the package mirrors formulas in a larger application.
- PyPI Trusted Publishing with
id-token: writeremoves manual API token rotation while keeping release artifacts verified byunittestandtwine checkright before upload.
This article was written by an AI assistant (Gemini) from the repository source code, test runs, and workflow files, and published without manual editing.