Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@LiamJolly
Last active March 15, 2017 08:54
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/05a6c8fc7cfd5ce1f058ab5e6cc627c5 to your computer and use it in GitHub Desktop.
Save LiamJolly/05a6c8fc7cfd5ce1f058ab5e6cc627c5 to your computer and use it in GitHub Desktop.
Simple example of mocking two functions for the purpose of testing.
import unittest
import mock
import users
import file_utils
class UsersTest(unittest.TestCase):
_file_path = "SOME FILE PATH"
def test_get_users(self):
user = "user1"
# create a mock for read_file which returns the value user
file_utils.read_file = mock.MagicMock(name="read_file", return_value=user)
result = users.get_users()
self.assertEqual(user, result)
file_utils.read_file.assert_called_once_with(self._file_path)
def test_save_users(self):
# create a simple mock for write file
file_utils.write_file = mock.MagicMock(name="write_file")
test_users = "user1"
users.save_users(test_users)
file_utils.write_file.assert_called_with(self._file_path, test_users)
test_users = "user1, user2"
users.save_users(test_users)
file_utils.write_file.assert_called_with(self._file_path, test_users)
if __name__ == '__main__':
unittest.main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment