Skip to content

Instantly share code, notes, and snippets.

@krak3n
Last active March 2, 2019 19:37
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save krak3n/5884562 to your computer and use it in GitHub Desktop.
Save krak3n/5884562 to your computer and use it in GitHub Desktop.
Mocking open for ConfigParser.RawConfigParser.readfp() for unit testing.
import io
import six
from mock import patch
from six.moves import configparser as ConfigParser
data = """
[section]
key = value
"""
if six.PY3:
func = 'builtins.open'
else:
func = '__builtin__.open'
patcher = patch(func, return_value=io.BytesIO(data))
patcher.start()
parser = ConfigParser.RawConfigParser(allow_no_value=True)
parser.readfp(open('im_not_real.cfg'))
parser.items('section')
>>> [('key', 'value')]
patcher.stop()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment