Skip to content

Instantly share code, notes, and snippets.

@LiamJolly
Last active March 15, 2017 09:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LiamJolly/62016dec527693364639fdc99e119672 to your computer and use it in GitHub Desktop.
Save LiamJolly/62016dec527693364639fdc99e119672 to your computer and use it in GitHub Desktop.
Unit tests for file_utils.py, demontrating mock_open.
import unittest
import mock
import file_utils
class FileUtilsTest(unittest.TestCase):
def test_read_file(self):
with mock.patch("__builtin__.open", mock.mock_open(read_data="MOCKED"), create=True) as mock_file:
result = file_utils.read_file("path")
mock_file.assert_called_once_with("path", "r")
assert result == "MOCKED"
def test_write_file(self):
with mock.patch("__builtin__.open", mock.mock_open(), create=True) as mock_file:
file_utils.write_file("path", "content")
mock_file.assert_called_once_with("path", "w")
mock_file.return_value.write.assert_called_once_with("content")
if __name__ == '__main__':
unittest.main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment