miercuri, 20 mai 2009

Python and Mocker

In this tutorial I'll show you how you can test your algorithms by eliminating dependencies(filesystem, database, ldap, and so on). Doing like this, you can easily follow the business logic and assert for the expected results. In the following example, I'll show you how to eliminate filesystem dependency.

def complex_algorithm(objOpen=open):
#here comes the business logic

#here comes the filesystem dependency
f = objOpen("test_file.txt", "w")
f.write("simple test")
f.close()

We can easily see that I provided an argument(objOpen) with default value of open builtin. In this manner, I can inject a mocked function for testing and in a production environment, open builtin will be used. In the following paragraph, I present the "mocking" part:

def test_ComplexAlgorithm():
controller = Mocker()
objOpen = controller.mock()
fMocked = controller.mock()

objOpen.open("test_file.txt", "w")
controller.result(fMocked)

fMocked.write("simple test")

fMocked.close()

controller.replay()

complex_algorithm(objOpen.open)

This is all you need. If the function had returned a result you could have easily asserted it. For more informations about mocking visit the site http://labix.org/mocker.

Niciun comentariu:

Trimiteți un comentariu