LiavK
LiavK

Reputation: 752

Patching an API using Python Mock

This test is giving me unusual problems:

Slightly simplified version of my test:

def test_credit_create_view(self):
    """ Can we create cards? """
    card_data = {'creditcard_data': 'blah blah blah'}
    with patch('apps.users.forms.CustomerAccount.psigate') as psigate:
        info = MagicMock()
        info.CardInfo.SerialNo = 42
        create = MagicMock(return_value=info)
        psigate.credit.return_value = create
        self.client.post('/make-creditcard-now', card_data)

The call I'm trying to mock looks like this:

psigate.credit().create().CardInfo.SerialNo

In the test, that call just returns a MagicMock object.

If I just look at the last three nodes in that call, I get the correct result:

create().CardInfo.SerialNo

returns 42

Why doesn't the full call to 'psigate.credit().create().CardInfo.SerialNo' return 42?

Upvotes: 1

Views: 140

Answers (1)

jwpeddle
jwpeddle

Reputation: 36

You're setting the return value of psigate.credit to create, meaning psigate.credit() is your mocked 'create', NOT psigate.credit().create. This would work as expected if you called psigate.credit()() instead.

When you call psigate.credit().create() you're dynamically creating a new MagicMock object, not calling the one you defined.

Upvotes: 2

Related Questions