1

I am trying to test a function I created to send a welcome e-mail to a user. But, to do this, I have to mock the function that actually sends it (inside the welcome e-mail function). I have the following folder structure:

app/
   __init__.py
   mail.py
tests/
   __init__.py
   conftest.py
   test_mail.py

This is the code I have in mail.py

import flask_mail

mail = flask_mail.Mail()

def send_mail(subject, sender, recipients, text_body, html_body):
    msg = flask_mail.Message(subject, sender=sender, recipients=recipients, body=text_body, html=html_body)
    mail.send(msg)


def send_sign_up_mail(user):
    subject = "Test subject"
    sender = ("Test sender", "testsender@gmail.com")
    recipients = [user.email]
    text_body = "text body"
    html_body = f"Test html body"
    send_mail(subject, sender, recipients, text_body, html_body)

And this is code of test_mail.py, the test I am trying to create:

from unittest import mock
from app.mail import send_sign_up_mail

@mock.patch('app.mail.send_mail')
def test_send_sign_up_mail(mock_send_mail, user):

send_sign_up_mail(user)

assert mock_send_mail.call_count == 1

The argument user is a fixture I created, and it is working, so, don't need to worry about that.

Using a pdb debugger, I checked that the send_mail function is not being mocked inside of send_sign_up_mail.

leodaher
  • 11
  • 4
  • Not sure, but could be possible the order of the params is not correct, as the patch method will append the `mock_send_mail` over the arguments of the function, which means you will receive the user in the first place? Did you try the same thing using a context manager? – edgarzamora Nov 06 '19 at 13:03
  • Yes, I tried using a context manager and got the same result. – leodaher Nov 06 '19 at 13:07
  • Could be possible that in your `app/__innit__.py` are you exporting the `mail` variable, so the patch is applied to the wrong place? As you have a `mail` variable defined inside a `mail.py` file... just in case. – edgarzamora Nov 06 '19 at 14:44
  • Found the problem. I am not exporting the `mail` variable in `app/__init__.py`, but I do import a variable called `mail` from `app/mail.py`, so my guess is the patch was applied to it. Thanks for the help! – leodaher Nov 06 '19 at 19:17

0 Answers0