owenrusk.dev

errands

small jobs the runtime does for the studio.

git clone https://owenrusk.dev/errands.git

errands / tests/test_hosting.py -rw-r--r-- · 2129 bytes

 1 import io
 2 import json
 3 import unittest
 4 from decimal import Decimal
 5 
 6 from errands import hosting, settings
 7 
 8 LOOKUP = {"account": "20417", "balance": "$1,204.50", "history": []}
 9 
10 
11 def fake(payload, seen=None):
12     def fetch(request, timeout=None):
13         if seen is not None:
14             seen.append(request)
15         return io.BytesIO(json.dumps(payload).encode())
16 
17     return fetch
18 
19 
20 class BalanceTest(unittest.TestCase):
21     def test_reads_the_lookup(self):
22         seen = []
23         self.assertEqual(hosting.balance(fake(LOOKUP, seen)), Decimal("1204.50"))
24         self.assertEqual(seen, ["https://stillwater-hosting.com/api/accounts/20417"])
25 
26     def test_paid_up(self):
27         self.assertEqual(hosting.balance(fake({**LOOKUP, "balance": "$0.00"})), 0)
28 
29 
30 class PayTest(unittest.TestCase):
31     def setUp(self):
32         self.payments = settings.PAYMENTS
33         settings.PAYMENTS = True
34 
35     def tearDown(self):
36         settings.PAYMENTS = self.payments
37 
38     def test_off(self):
39         settings.PAYMENTS = False
40         seen = []
41         with self.assertRaises(RuntimeError):
42             hosting.pay(Decimal("10"), fake({}, seen), token="t")
43         self.assertEqual(hosting.pay_balance(fake(LOOKUP, seen), token="t"), Decimal("1204.50"))
44         self.assertEqual(len(seen), 1)
45 
46     def test_posts_a_payment(self):
47         seen = []
48         hosting.pay(Decimal("1204.5"), fake({"status": "accepted"}, seen), token="t")
49         request = seen[0]
50         self.assertEqual(request.full_url, "https://stillwater-hosting.com/api/accounts/20417/payments")
51         self.assertEqual(request.get_method(), "POST")
52         self.assertEqual(request.get_header("Authorization"), "Bearer t")
53         self.assertEqual(json.loads(request.data), {"amount": "1204.50", "method": "card on file"})
54 
55     def test_nothing_to_pay(self):
56         with self.assertRaises(ValueError):
57             hosting.pay(Decimal("0"), fake({}), token="t")
58 
59     def test_pay_balance_only_when_owed(self):
60         seen = []
61         self.assertEqual(hosting.pay_balance(fake({**LOOKUP, "balance": "$0.00"}, seen), token="t"), 0)
62         self.assertEqual(len(seen), 1)