Mocking access to files in the filesystem

A common test to check a function that operates on the filesystem is to create dummy files in the filesystem. However that is dirty because you have to make sure you've got the permissions in the filesystem and you delete the dummy files after the tests and so.
Mocker lets you fake system calls so you can write the same test without creating files.
In the next sample I am testing a function that lists all files in a given folder, avoiding symbolic links.
I first fake the contents of the directory and then I say that one of them is a symb link. The outcome is nice:

  1.  
  2. import unittest
  3. import os
  4. import re
  5. from postclonado import Utils
  6. import mocker
  7.  
  8. class UtilsTests(mocker.MockerTestCase):
  9.  
  10. def testDiscardSymbolicLinksInFilesSearch(self):
  11. stubFile = 'filetmp'
  12. stubSymbolicLink = 'linktmp'
  13. basedir = '/tmp'
  14.  
  15. mockListDir = self.mocker.replace("os.listdir")
  16. mockListDir(basedir)
  17. self.mocker.result([stubFile, stubSymbolicLink])
  18. mockIsLink = self.mocker.replace("os.path.islink")
  19. mockIsLink(stubSymbolicLink)
  20. self.mocker.result(True)
  21.  
  22. self.mocker.replay()
  23.  
  24. files = Utils.getAllDirectoryFilesRecursively(basedir)
  25. for file in files:
  26. print "-------", file
  27. if re.search(stubSymbolicLink, file):
  28. self.fail('Error, symbolic links are not being ignored')
  29.  

When Utils.getAllDirectoryFilesRecursively call os.listdir and os.path.islink, it will be calling the replaced mock.

Enjoyed reading this post?
Subscribe to the RSS feed and have all new posts delivered straight to you.