47 lines
1.9 KiB
Python
47 lines
1.9 KiB
Python
"""Offline behavior and precision checks for native ETH amounts."""
|
|
|
|
import unittest
|
|
from decimal import Decimal, localcontext
|
|
|
|
from core import CryptoHubError, InvalidAmountError
|
|
from eth import WEI_PER_ETH, eth_to_wei, wei_to_eth
|
|
|
|
|
|
class EthUnitsTest(unittest.TestCase):
|
|
def test_exact_conversions(self):
|
|
for eth, wei in [("0", 0), ("1", WEI_PER_ETH), ("0.1", 10**17),
|
|
("0.000000000000000001", 1), ("1.0000000000000000000", WEI_PER_ETH)]:
|
|
with self.subTest(eth=eth):
|
|
self.assertEqual(eth_to_wei(eth), wei)
|
|
self.assertEqual(eth_to_wei(Decimal(eth)), wei)
|
|
self.assertEqual(wei_to_eth(wei), Decimal(eth))
|
|
|
|
def test_invalid_eth_is_rejected(self):
|
|
for amount in [0.1, True, 1, None, "", "invalid", "-1", "NaN", "sNaN",
|
|
"Infinity", "-Infinity", "0.0000000000000000001"]:
|
|
with self.subTest(amount=amount):
|
|
with self.assertRaises(InvalidAmountError):
|
|
eth_to_wei(amount)
|
|
|
|
def test_invalid_wei_is_rejected(self):
|
|
for amount in [-1, True, False, 1.0, "1", Decimal("1"), None]:
|
|
with self.subTest(amount=amount):
|
|
with self.assertRaises(InvalidAmountError):
|
|
wei_to_eth(amount)
|
|
|
|
def test_large_amount_round_trip_ignores_decimal_precision(self):
|
|
wei = 123456789012345678901234567890123456789
|
|
expected = Decimal("123456789012345678901.234567890123456789")
|
|
with localcontext() as context:
|
|
context.prec = 6
|
|
self.assertEqual(wei_to_eth(wei), expected)
|
|
self.assertEqual(eth_to_wei(expected), wei)
|
|
self.assertEqual(eth_to_wei(wei_to_eth(wei)), wei)
|
|
|
|
def test_invalid_amount_is_public_library_error(self):
|
|
self.assertIsInstance(InvalidAmountError("invalid"), CryptoHubError)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|