0

I have a method where I am converting dollars to cents before calling an api.

# money.py
def send_money(dollars):
    cents = dollars * 100
    return send_money_to_api(cents)

* This is not exactly my code. But this is sufficient for demonstration.

dollars's type is decimal.Decimal as it's actually coming from django's DecimalField.

I want to ensure that I am multiplying the amount by 100. I tried testing this using mock

import mock

from money import send_money

@mock.patch('money.operator.__mul__')
@mock.patch('money.send_money_to_api')
def test_money(self, api_mock, mul_mock):
    send_money(20)

    assert api_mock.called
    mul_mock.assert_any_call(20, 100)

It fails saying,

E   ImportError: No module named operator

How do I test this?

Hussain
  • 5,057
  • 6
  • 45
  • 71

1 Answers1

0

I was able to fix this after some great help from comments. Special thanks to @Sraw.

@mock.patch.object(decimal.Decimal, '__mul__')
@mock.patch('money.send_money_to_api')
def test_money(self, api_mock, mul_mock):
    send_money(20)

    assert api_mock.called
    mul_mock.assert_any_call(100)

An advantage of mocking decimal.Decimal instance method __mul__ is I can truly ensure that all the DecimalField values (which are mostly amounts) from database are converted.

Hussain
  • 5,057
  • 6
  • 45
  • 71