Created
December 24, 2013 16:53
-
-
Save Xion/8115579 to your computer and use it in GitHub Desktop.
Mocking "the filesystem" by stubbing built-in open() in Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Example function that reads a file and does something with it. | |
""" | |
import re | |
import sys | |
def list_shell_aliases(script): | |
"""Find all command aliases defined in a shell script. | |
Aliases are created though the ``alias`` command:: | |
alias foo='bar -x' | |
:param script: Path to shell script file | |
:return: Dictionary mapping alias name to its definition | |
""" | |
with open(script, 'r') as f: | |
script_code = f.read() | |
alias_re = re.compile(r''' | |
^ \s* alias \s+ (\w+) = ['"](.*)['"] $ | |
''', re.VERBOSE | re.MULTILINE) | |
return dict((m.group(1), m.group(2)) | |
for m in alias_re.finditer(script_code)) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
try: | |
import __builtin__ as builtins # Python 2.x | |
except ImportError: | |
import builtins | |
import os | |
import sys | |
from mocktest import mock, TestCase, when | |
def mock_file_read(filename, content): | |
fp = mock('open_result') | |
old__open = open | |
when(builtins).open.then_return(old__open) | |
when(builtins).open(filename, 'r').then_return(fp) | |
when(fp).__enter__.then_return(fp) | |
when(fp).read().then_return(content) | |
when(fp).__exit__.then_return(False) # don't squelch exceptions | |
import listshellaliases as __unit__ | |
class ListShellAliases(TestCase): | |
SCRIPT = '~/.fooshrc' | |
def test_empty_script(self): | |
mock_file_read(self.SCRIPT, '') | |
self.assertEquals({}, __unit__.list_shell_aliases(self.SCRIPT)) | |
def test_no_aliases(self): | |
mock_file_read(self.SCRIPT, os.linesep.join([ | |
'if [ -f ~/.bash_aliases ]; then', | |
' source ~/.bash_aliases', | |
'fi', | |
])) | |
self.assertEquals({}, __unit__.list_shell_aliases(self.SCRIPT)) | |
def test_one(self): | |
mock_file_read(self.SCRIPT, os.linesep.join([ | |
'alias foo="bar -x"', | |
])) | |
self.assertEquals({'foo': 'bar -x'}, | |
__unit__.list_shell_aliases(self.SCRIPT)) | |
if __name__ == '__main__': | |
import unittest | |
unittest.main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment