Skip to content

Instantly share code, notes, and snippets.

@ViktorovEugene
Last active July 4, 2021 11:55
Show Gist options
  • Save ViktorovEugene/27d76ad2d94c88170d7b to your computer and use it in GitHub Desktop.
Save ViktorovEugene/27d76ad2d94c88170d7b to your computer and use it in GitHub Desktop.
mocking of builtins (python2/3)
"""
This is the example of mocking the builtin `open` function in python 2/3.
"""
from __future__ import print_function
import sys
import unittest
if sys.version_info.major == 3:
from unittest import mock
else:
# Expect the `mock` package for python 2.
# https://pypi.python.org/pypi/mock
import mock
def use_of_open():
"""
Example function, with usage of the builtin `open` function.
:return: indented content's string of this file
:rtype: string
"""
with open(__file__) as f_:
my_content = f_.read()
return my_content
class TestMockOpen(unittest.TestCase):
def test_mock_the_open(self):
"""
Mocking the builtins open function adaptively for python 2/3
:return: None
"""
# Get a appropriate "builtin" module name for pythons 2/3.
if sys.version_info.major == 3:
builtin_module_name = 'builtins'
else:
builtin_module_name = '__builtin__'
mock_data = """\
spam 1
eggs 2
pig 3"""
with mock.patch('{}.open'.format(builtin_module_name),
mock.mock_open(read_data=mock_data),
create=False
):
content = use_of_open()
self.assertEqual(
content,
mock_data,
'Mocked `open` should return `mock_data` test value!'
)
if __name__ == '__main__':
unittest.main()
@Hossam-Abdin
Copy link

I am working on such a project for now, and I think having including future library and explicitly importing open in the code can solve the issue

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment