Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing email implementation in Python

Assuming an email implementation as simple as the accepted answer on this post, what can be the best way to write a unit test for the implementation? (I do not want to shoot emails to a valid recipient as part of testing the implementation)

like image 798
name_masked Avatar asked Sep 14 '26 06:09

name_masked


1 Answers

First, make the part responsible for sending / receiving pluggable. Just make sure you can switch the class / function / object responsible for connecting / sending / receiving messages to / from the server.

Second, make this part act as real thing. Make sure this class / function / object will fake original class's / function's / object's behaviour as close as possible (take the same parameters, throw the same errors).

Third, fake different behaviours of this part during tests. Different behaviours of this class in different tests may include:

  • correct sending,
  • delayed sending,
  • connection timed out,
  • successful receiving,

and, depending on what your module really does (and how flexible it is, eg. if it can be used by someone else for coding), you can also include these behaviours:

  • error when incorrect parameters were passed,
  • wide range of other exceptions found here: http://docs.python.org/library/smtplib.html

It really largely depends on what your module does. You need to test, if it does these things properly. Do not test smtplib module, as it is already covered with tests. Do not test things irrelevant to your module - just things it does. It is possible, that some parts of your modules are untestable - in that case you have two options: change them to be testable, or leave them as they are (it is sometimes the most reasonable option for various reasons).

like image 189
Tadeck Avatar answered Sep 16 '26 20:09

Tadeck