user1427661
user1427661

Reputation: 11784

Setting Properties on Mock Not Working

I'm trying to create a Mock of a library's (Hammock) call to a POST method that has an attribute status_code. Here is my test code:

def test_send_text(self):
    Hammock.POST = Mock(status_code=201)
    print Hammock.POST.status_code
    self.task.payload = fixtures.text_payload

    self.task.send_text()
    # ········
    Hammock.POST.assert_any_call()

When I print Hammock.POST.status_code, I get what I expect -- 201. However, when we move into the code I'm testing:

response = self.twilio_api('Messages.json').POST(data=self.payload)
print '*' * 10
print response
print response.status_code
if response.status_code == 201:
    self.logger.info('Text message successfully sent.')
else:
    raise NotificationDispatchError('Twilio request failed. {}. {}'.format(response.status_code,
        response.content))

Things get weird. response is, indeed, a Mock object. But response.status_code, instead of being 201 like when I try it in the test, is an object: <Mock name='mock().status_code' id='4374061968'>. Why is my mocked attribute working in the test code and not in the code that I'm testing?

Upvotes: 1

Views: 328

Answers (1)

Silfheed
Silfheed

Reputation: 12211

The issue is POST().status_code vs POST.status_code. POST.status_code will indeed == 201, but the return object from POST() is a completely new mock object.

What you are looking for is roughly

Hammock.POST = Mock()
Hammock.POST.return_value = Mock(status_code=201)

Upvotes: 1

Related Questions