In : fake_str = mock.Mock(str)
In : fake_str.lower()
Out: <Mock name='mock.lower()'
In : fake_str.LOWER
In : def count(fs):
...: return len(fs.read())
In : fakefs = mock.Mock()
In : fakefs.read.return_value = "xx"
In : assert count(fakefs) == 2
• dependency should always pass from out side
• your design need to consider testability
Inversion of control
# not this
db = Database()
# write this
from mock import *
from StringIO import *
def do_print(): # hard to IoC
os = StringIO()
actual = os.getvalue()
expect = "hi"
assert expect in actual
• Q: How to maintain test case?
• refactor you test infrastructure often
• duplicated test code make you will feel tired
after interface changed
• Q: how much should I test?
• test the interface, not the implementation
• don’t test private method
• test public method
• Q: Test is slow, I don’t want to test
• write quick test
• mock time consuming object
• don’t execute time consuming test every time
• run failed test only while you meet error
Add test now
• My Project has no test …
• add test for new added code
• old code can add test latter
mock needs manage
• Mock is awesome, I want to mock every thing
• mock’s behavior may has error
• mock object tell you what you want to hear
• mock dependency is okay
• share mock among test modules
ﬁnding test utility
• Django mocks some service while testing
• GAE also provide mock while testing
• if you are using ORM, there a package that help
you mock ORM
After we have tests
• don’t forget to run test before you push codes
• nose can provide report
• nose can integration coverage report
• Nose is a good test driver
• unittest provide awesome test infrastructure
• any one want to share doctest?
• test and doc are combined !
• mock is used to fake a dependency, not every
A particular slide catching your eye?
Clipping is a handy way to collect important slides you want to go back to later.