Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

pyln: failing test msat from float str #4237

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions contrib/pyln-client/pyln/client/lightning.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,19 +49,19 @@ def __init__(self, v: Union[int, str, Decimal]):
"""
if isinstance(v, str):
if v.endswith("msat"):
self.millisatoshis = int(v[0:-4])
parsed = Decimal(v[0:-4])
elif v.endswith("sat"):
self.millisatoshis = int(v[0:-3]) * 1000
parsed = Decimal(v[0:-3]) * 1000
elif v.endswith("btc"):
self.millisatoshis = int(v[0:-3]) * 1000 * 10**8
parsed = Decimal(v[0:-3]) * 1000 * 10**8
else:
raise TypeError(
"Millisatoshi must be string with msat/sat/btc suffix or"
" int"
)
if self.millisatoshis != int(self.millisatoshis):
if parsed != int(parsed):
raise ValueError("Millisatoshi must be a whole number")
self.millisatoshis = int(self.millisatoshis)
self.millisatoshis = int(parsed)

elif isinstance(v, Millisatoshi):
self.millisatoshis = v.millisatoshis
Expand Down
27 changes: 27 additions & 0 deletions contrib/pyln-client/tests/test_units.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from pyln.client import Millisatoshi
import pytest # type: ignore


def test_to_approx_str():
Expand Down Expand Up @@ -34,3 +35,29 @@ def test_to_approx_str():
assert amount.to_approx_str() == "12btc"
amount = Millisatoshi('1200000000sat')
assert amount.to_approx_str(1) == "12btc" # note: no rounding


def test_floats():
# test parsing amounts from floating number strings
amount = Millisatoshi("0.01btc")
assert amount.to_satoshi() == 10**6
amount = Millisatoshi("1.01btc")
assert amount.to_satoshi() == 10**8 + 10**6
amount = Millisatoshi("0.1sat")
assert int(amount) == 100
amount = Millisatoshi("0.01sat")
assert int(amount) == 10
amount = Millisatoshi("1.1sat")
assert int(amount) == 1100

# test floating point arithmetic
amount = Millisatoshi("1000msat") * 0.1
assert int(amount) == 100

# sub millisatoshi are not a concept yet
with pytest.raises(ValueError, match='Millisatoshi must be a whole number'):
amount = Millisatoshi("0.000000000001btc")
with pytest.raises(ValueError, match='Millisatoshi must be a whole number'):
amount = Millisatoshi("0.0001sat")
with pytest.raises(ValueError, match='Millisatoshi must be a whole number'):
amount = Millisatoshi("0.1msat")