"""Offline tests for RunPod balance helpers (no network, no real API key).""" from __future__ import annotations import importlib import json import unittest from io import BytesIO from unittest import mock from urllib.error import HTTPError, URLError class RunpodBillingTests(unittest.TestCase): def setUp(self): self.billing = importlib.import_module("runpod_billing") def test_missing_key_formats_status(self): with mock.patch.dict("os.environ", {}, clear=True): text = self.billing.format_balance_markdown() self.assertIn("unavailable", text) self.assertIn("RUNPOD_API_KEY", text) def test_fetch_balance_success(self): payload = { "data": {"myself": {"clientBalance": 12.5, "currentSpendPerHr": 0.01}} } raw = json.dumps(payload).encode() class Resp: def __enter__(self): return self def __exit__(self, *args): return False def read(self): return raw with mock.patch.dict("os.environ", {"RUNPOD_API_KEY": "test-key"}): with mock.patch("urllib.request.urlopen", return_value=Resp()): balance, burn = self.billing.fetch_balance() self.assertEqual(balance, 12.5) self.assertEqual(burn, 0.01) def test_http_401_formats_gracefully(self): err = HTTPError( "https://api.runpod.io/graphql", 401, "Unauthorized", hdrs=None, fp=BytesIO(b"{}"), ) with mock.patch.dict("os.environ", {"RUNPOD_API_KEY": "bad-key"}): with mock.patch("urllib.request.urlopen", side_effect=err): text = self.billing.format_balance_markdown() self.assertIn("unavailable", text) self.assertIn("401", text) self.assertNotIn("bad-key", text) def test_url_error_formats_gracefully(self): with mock.patch.dict("os.environ", {"RUNPOD_API_KEY": "test-key"}): with mock.patch( "urllib.request.urlopen", side_effect=URLError("timed out"), ): text = self.billing.format_balance_markdown() self.assertIn("unavailable", text) self.assertNotIn("test-key", text) if __name__ == "__main__": unittest.main()