1
votes

I have the following code:

class Messenger(object):
    def __init__(self):
        # Class Type of what messages will be created as.
        message_class = Message

    def publish(self, body):
        # Instantiate object of type stored in `message_class`
        message = message_class(body)
        message.publish()

I want to assert that the Message.publish() method is called. How do I achieve this?

I've already tried the following ways:

  1. Assign message_class to Mock or Mock(). If I debug what message_class(body) returns, it is a Mock, but I don't seem to be able to get the instance and assert it (because the Mock I assign in my test is not the instance used, it is the Type).
  2. Patch Message class with decorator. Whenever I do this it seems like it does not catch it. When I debug what message_class(body) returns its of Message type, not Mock.
  3. Try to mock the __init__ method of message_class in hopes that I can set the instance that is returned whenever the code tries to Instantiate the message. Does not work, throws errors because the __init__ method is not suppose to have a return value.
1

1 Answers

0
votes

If you were storing the actual instance, I'd say you could do something like messenger.message.publish.assert_called_once, but since message_class is being stored, it makes it slightly trickier. Given that, you can pull the return_value from the mocked class and check the call that way. Here's how I did it:

Messenger. Note the slight modification to assign message_class to self. I'm assuming you meant to do that, otherwise it wouldn't work without some global funkiness:

'''messenger.py'''
class Message(object):
    def __init__(self, body):
        self.body = body

    def publish(self):
        print('message published: {}'.format(self.body))


class Messenger(object):
    def __init__(self):
        # Class Type of what messages will be created as.
        self.message_class = Message

    def publish(self, body):
        # Instantiate object of type stored in `message_class`
        message = self.message_class(body)
        message.publish()

Test:

'''test_messenger.py'''    
from unittest import mock, TestCase

from messenger import Messenger

class TestMessenger(TestCase):
    @mock.patch('messenger.Message')
    def test_publish(self, mock_message):
        messenger = Messenger()
        messenger.publish('test body')
        # .return_value gives the mock instance, from there you can make your assertions
        mock_message.return_value.publish.assert_called_once()