Add failing test for fetchLiveVaultBalance

This commit is contained in:
Keith Solomon
2026-08-05 09:29:16 -05:00
parent 0613d00fbb
commit 61fb15336e
+83
View File
@@ -0,0 +1,83 @@
<?php
/**
* Test for fetchLiveVaultBalance() — the live vault balance helper.
*
* Uses a swappable test hook so we don't make real API calls.
*
* Run: php tests/live_balance_test.php
* Exit code 0 = pass.
*/
declare(strict_types=1);
if (!defined('USER_KEYS')) {
define('USER_KEYS', [
'zarathos' => 'test-key-not-used',
'symos' => 'test-key-not-used',
]);
}
require_once __DIR__ . '/../includes/exceptions.php';
require_once __DIR__ . '/../includes/utilities.php';
function fail(string $message): void {
fwrite(STDERR, "FAIL: $message\n");
exit(1);
}
function assertSame($expected, $actual, string $label): void {
if ($expected !== $actual) {
$exp = var_export($expected, true);
$act = var_export($actual, true);
fail("$label: expected $exp, got $act");
}
}
// Test hook: when set, fetchLiveVaultBalance calls this closure instead of
// executeApiCall. The closure receives ($url, $apiKey) and returns the
// decoded response array (or throws).
$GLOBALS['liveBalanceTestHook'] = null;
function liveBalanceHook($url, $apiKey) {
$hook = $GLOBALS['liveBalanceTestHook'] ?? null;
if ($hook === null) {
fail('Test hook not set — fetchLiveVaultBalance called executeApiCall');
}
return $hook($url, $apiKey);
}
// --- Test 1: success path returns the vault amount as int ---
$GLOBALS['liveBalanceTestHook'] = function ($url, $apiKey) {
assertSame('zarathos', $apiKey === 'test-key-not-used' ? 'zarathos' : 'symos', 'api key routed');
// (just verify the hook got called)
return ['money' => ['vault' => 160627669, 'wallet' => 4000]];
};
$balance = fetchLiveVaultBalance('zarathos');
assertSame(160627669, $balance, 'success returns vault amount');
// --- Test 2: failure path returns null ---
$GLOBALS['liveBalanceTestHook'] = function () {
throw new CurlErrorException('connection refused');
};
$balance = fetchLiveVaultBalance('zarathos');
assertSame(null, $balance, 'failure returns null');
// --- Test 3: missing money.vault returns null ---
$GLOBALS['liveBalanceTestHook'] = function () {
return ['error' => ['code' => 4]];
};
$balance = fetchLiveVaultBalance('zarathos');
assertSame(null, $balance, 'missing field returns null');
// --- Test 4: cache: second call does not invoke the hook twice ---
$invocations = 0;
$GLOBALS['liveBalanceTestHook'] = function () use (&$invocations) {
$invocations++;
return ['money' => ['vault' => 100]];
};
fetchLiveVaultBalance('symos');
fetchLiveVaultBalance('symos');
fetchLiveVaultBalance('symos');
assertSame(1, $invocations, 'cache prevents repeated fetches');
echo "OK: fetchLiveVaultBalance tests passed.\n";