testing functions

6 views
Skip to first unread message

ikame

unread,
Apr 16, 2012, 5:39:16 AM4/16/12
to pydo...@googlegroups.com
Hi, I have this question for some time now, I have the following code in a module:

import email_lib 

def send_email(to, text, html):
    message = email_lib.Message(...)
    message.text = text
    message.html = html 
    email_lib.Connection().send(message) 
 
My question is, using PyDoubles, which is the best way to test that function? Can I mock up the entire library using PyDoubles?

Thanks in advance

Miguel Angel

unread,
Apr 16, 2012, 5:20:25 PM4/16/12
to pydo...@googlegroups.com
Hi there!!

You cannot test this. But you can use some tricks :D

Every external data should be injected to be mocked, so:

import email_lib 

message = build_email(to, text, html)
send_email(email_lib.Connection(), message)

def build_email(to, text, html):
    message = email_lib.Message(...)
    message.text = text
    message.html = html 

def send_email(connection, message):
    connection.send(message) 

Now you can test every function: build_email by testing the result and send_email mocking the connection :D

You only have to accomplish with the Single Responsability Principle :D

See you!
--
Miguel Ángel García Martínez

Anler Hernandez Peral

unread,
Apr 17, 2012, 5:10:39 AM4/17/12
to pydo...@googlegroups.com
Hey thanks a lot, that's exactly what I wanted to know ... so, it's time to do some refactor ;)

--
anler
Reply all
Reply to author
Forward
0 new messages