Skip to content

Commit 44ec042

Browse files
committed
Add Currency.random() function
1 parent e94ed9d commit 44ec042

2 files changed

Lines changed: 19 additions & 0 deletions

File tree

CodaClient.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
#!/usr/bin/python3
22

3+
import random
34
import requests
45
import time
56
import json
@@ -32,6 +33,18 @@ def __nanocodas_from_string(_cls, s):
3233
else:
3334
raise Exception('invalid coda currency format: %s' % s)
3435

36+
@classmethod
37+
def random(_cls, lower_bound, upper_bound):
38+
if not (isinstance(lower_bound, Currency) and isinstance(upper_bound, Currency)):
39+
raise Exception('invalid call to Currency.random: lower and upper bound must be instances of Currency')
40+
if not upper_bound.nanocodas() >= lower_bound.nanocodas():
41+
raise Exception('invalid call to Currency.random: upper_bound is not greater than lower_bound')
42+
if lower_bound == upper_bound:
43+
return lower_bound
44+
bound_range = upper_bound.nanocodas() - lower_bound.nanocodas()
45+
delta = random.randint(0, bound_range)
46+
return lower_bound + Currency(delta, format=CurrencyFormat.NANO)
47+
3548
def __init__(self, value, format=CurrencyFormat.WHOLE):
3649
if format == CurrencyFormat.WHOLE:
3750
if isinstance(value, int):

tests/test_currency.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,3 +38,9 @@ def test_mul_int():
3838

3939
def test_mul_currency():
4040
assert (Currency(5) * Currency(2, format=CurrencyFormat.NANO)).nanocodas() == 10 * precision
41+
42+
def test_random():
43+
assert (Currency.random(Currency(5), Currency(5)).nanocodas() == 5 * precision)
44+
for _ in range(25):
45+
rand = Currency.random(Currency(3, format=CurrencyFormat.NANO), Currency(5, format=CurrencyFormat.NANO))
46+
assert (3 <= rand.nanocodas () and rand.nanocodas() <= 5)

0 commit comments

Comments
 (0)