[Tutor] Writing unit tests that involve email

Steven D'Aprano steve at pearwood.info
Wed Jul 17 06:04:15 CEST 2013


On 17/07/13 13:34, Arnel Legaspi wrote:

> the trouble I have is on making the unit tests run such that
> it
> will force the script I'm testing to send the email. If I just use the
> script
> on my own, it does send the emails, no problem. With the unit tests I've
> written, it's not doing so.


How does your script send emails? At some place, there will be something that effectively does the following steps:

* build email
* send email

I recommend that your script has a function that does each: somewhere you have something that says

def build_email_body(arg1, arg2, arg3):
     ...


def send_email(body):
     ...


Then you can test each separately. In your unit tests, you just call build_email_body and sees if it returns the correct data, no sending required; and then you call send_email and see that it actually sends an email.


Oh, all of this assumes that the unit test imports your script! This makes it critical that your script includes something like this at the end:


def run():  # or "main", if you prefer
     # script logic goes in here


if __name__ == '__main__':
     run()



Then your tests can import the script without it automatically running.



-- 
Steven


More information about the Tutor mailing list