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:
- import unittest
- import os
- import re
- from postclonado import Utils
- import mocker
- class UtilsTests(mocker.MockerTestCase):
- def testDiscardSymbolicLinksInFilesSearch(self):
- stubFile = 'filetmp'
- stubSymbolicLink = 'linktmp'
- basedir = '/tmp'
- mockListDir = self.mocker.replace("os.listdir")
- self.mocker.result([stubFile, stubSymbolicLink])
- mockIsLink = self.mocker.replace("os.path.islink")
- files = Utils.getAllDirectoryFilesRecursively(basedir)
- for file in files:
- print "-------", file
- if re.search(stubSymbolicLink, file):
- self.fail('Error, symbolic links are not being ignored')
When Utils.getAllDirectoryFilesRecursively call os.listdir and os.path.islink, it will be calling the replaced mock.