Skip to content

Instantly share code, notes, and snippets.

@curzona
Last active February 16, 2024 16:26
Show Gist options
  • Save curzona/0616d4752f44f2ff8914 to your computer and use it in GitHub Desktop.
Save curzona/0616d4752f44f2ff8914 to your computer and use it in GitHub Desktop.
pytest with monkeypatch __buildin__.open
import __builtin__
from StringIO import StringIO
import os
import ConfigParser
import pytest
class MockFileManager():
def __init__(self):
self.files = {}
self._open = __builtin__.open
def open(self, name, mode='r', buffering=-1, **options):
name = os.path.abspath(name)
if mode.startswith('r') and name not in self.files:
# We have to let some files through
return self._open(name, mode, buffering, **options)
# This causes stracktraces not to display
#raise IOError(2, "No such file or directory: '%s'" % name)
if mode.startswith('w') or \
(mode.startswith('a') and name not in self.files):
buf = StringIO()
buf.close = lambda: None
self.files[name] = buf
buf = self.files[name]
if mode.startswith('r'):
buf.seek(0)
elif mode.startswith('a'):
buf.seek(0)
return buf
def write(self, name, text):
name = os.path.abspath(name)
buf = StringIO(text)
buf.close = lambda: None
self.files[name] = buf
def read(self, name):
name = os.path.abspath(name)
if name not in self.files:
raise IOError(2, "No such file or directory: '%s'" % name)
return self.files[name].getvalue()
@pytest.fixture
def mockopen(monkeypatch):
manager = MockFileManager()
monkeypatch.setattr(__builtin__, 'open', manager.open)
return manager
import pytest
simpleconfig = """[section]\nkey = value\n\n"""
def test_monkeypatch_open_read(mockopen):
filename = 'somefile.txt'
mockopen.write(filename, simpleconfig)
parser = ConfigParser.ConfigParser()
parser.read(filename)
assert parser.sections() == ['section']
def test_monkeypatch_open_write(mockopen):
parser = ConfigParser.ConfigParser()
parser.add_section('section')
parser.set('section', 'key', 'value')
filename = 'somefile.txt'
parser.write(open(filename, 'wb'))
assert mockopen.read(filename) == simpleconfig
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment