ut_obj.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. #!/usr/bin/env python3
  2. """
  3. test.unit_tests_d.ut_obj: data object unit tests for the MMGen suite
  4. """
  5. from decimal import Decimal
  6. from ..include.common import vmsg
  7. def coinamt_test(cls, aa, bb, ut):
  8. def do(desc, res, chk):
  9. vmsg(f'{desc:10} = {res:<{cls.max_prec+10}} [{type(res).__name__}]')
  10. if chk is not None:
  11. assert res == chk, f'{res} != {chk}'
  12. assert type(res) is cls, f'{type(res).__name__} != {cls.__name__}'
  13. vmsg(f'\nTesting {cls.__name__} arithmetic operations...')
  14. A, B = (Decimal(aa), Decimal(bb))
  15. a, b = (cls(aa), cls(bb))
  16. do('A', A, None)
  17. do('B', B, None)
  18. do('a', a, A)
  19. do('b', b, B)
  20. do('b + a', b + a, B + A)
  21. do('sum([b,a])', sum([b,a]), B + A)
  22. do('b - a', b - a, B - A)
  23. do('b * a', b * a, B * A)
  24. do('b * A', b * A, B * A)
  25. do('B * a', B * a, B * A)
  26. do('b / a', b / a, cls(B / A, from_decimal=True))
  27. do('b / A', b / A, cls(B / A, from_decimal=True))
  28. do('a / b', a / b, cls(A / B, from_decimal=True))
  29. do('a * a / a', a * a / a, A * A / A)
  30. do('a * b / a', a * b / a, A * B / A)
  31. do('a * b / b', a * b / b, A * B / B)
  32. vmsg(f'\nChecking {cls.__name__} error handling...')
  33. bad_data = (
  34. ('negation', 'NotImplementedError', 'not implemented', lambda: -a),
  35. ('modulus', 'NotImplementedError', 'not implemented', lambda: b % a),
  36. ('floor division', 'NotImplementedError', 'not implemented', lambda: b // a),
  37. ('negative result', 'ObjectInitError', 'cannot be negative', lambda: a - b),
  38. ('operand type', 'ValueError', 'incorrect type', lambda: a + B),
  39. ('operand type', 'ValueError', 'incorrect type', lambda: b - A),
  40. )
  41. if cls.max_amt is not None:
  42. bad_data += (
  43. ('result', 'ObjectInitError', 'too large', lambda: b + b),
  44. ('result', 'ObjectInitError', 'too large', lambda: b * b),
  45. )
  46. ut.process_bad_data(bad_data)
  47. vmsg('OK')
  48. class unit_tests:
  49. altcoin_deps = ('coinamt_alt', 'coinamt_alt2')
  50. def coinamt(self, name, ut, desc='BTCAmt class'):
  51. from mmgen.amt import BTCAmt
  52. for cls, aa, bb in (
  53. (BTCAmt, '1.2345', '11234567.897'),
  54. ):
  55. coinamt_test(cls, aa, bb, ut)
  56. return True
  57. def coinamt_alt(self, name, ut, desc='LTCAmt, XMRAmt and ETHAmt classes'):
  58. from mmgen.amt import LTCAmt, XMRAmt, ETHAmt
  59. for cls, aa, bb in (
  60. (LTCAmt, '1.2345', '44938271.588'),
  61. (XMRAmt, '1.2345', '11234567.98765432'),
  62. (ETHAmt, '1.2345', '11234567.98765432123456'),
  63. ):
  64. coinamt_test(cls, aa, bb, ut)
  65. return True