user7692855
user7692855

Reputation: 1418

Python unittest test passed in class method is called with

I have a method that takes two inputs a emailer class and a dict of data.

def send_email(data, email_client):
     **** various data checks and formatting *****
     response_code = email_client.create_email(recipient=receipient
                                               sender=sender
                                               etc...)

I am trying to write a unit test that will assert email_client.create_email was called with the correct values based on the input data.

In my test file I have

from emailer.email import send_email

class TestEmails(unittest.TestCase):

    def test_send_email(self):
        email.send_email(get_transactional_email_data, MagicMock())

I normally test what a method is called with by something similar to:

mock.assert_called_with(recipient=receipient
                       sender=sender
                       etc..)

However, since this time I'm testing what a passed in class is being called with (and a MagicMock) I don't know how it should be done.

Upvotes: 0

Views: 168

Answers (1)

Major Eccles
Major Eccles

Reputation: 491

I don't think you need MagicMock. Just create the mocks upfront

from emailer.email import send_email

class TestEmails(unittest.TestCase):

def test_send_email(self):
    myclient = Mock()
    mycreate = Mock()
    myclient.create_email = mycreate
    email.send_email(get_transactional_email_data, myclient)
    self.assertTrue(
        mycreate.called_with(sender='...')
    )

Upvotes: 1

Related Questions