Skip to content

Instantly share code, notes, and snippets.

@packrat386
Created November 23, 2020 01:53
Show Gist options
  • Save packrat386/cc7158d2c2dcd01e8d27b2e9f4b6311e to your computer and use it in GitHub Desktop.
Save packrat386/cc7158d2c2dcd01e8d27b2e9f4b6311e to your computer and use it in GitHub Desktop.
Unit test mocking example in python
def name_replay(we, they):
return timestamp()+ '_' + we + '_vs_' + they
def timestamp():
# not yet implemented
return
[acoyle01] wtfpy > ll
total 16
drwxr-xr-x 2 acoyle users 4096 Nov 22 19:53 .
drwxr-xr-x 20 acoyle users 4096 Nov 22 19:38 ..
-rw-r--r-- 1 acoyle users 131 Nov 22 19:45 namer.py
-rw-r--r-- 1 acoyle users 731 Nov 22 19:50 test_namer.py
[acoyle01] wtfpy > python3 test_namer.py -v
test_name_replay_mocked (__main__.TestNameReplay) ... ok
test_name_replay_with_decorator (__main__.TestNameReplay) ... ok
----------------------------------------------------------------------
Ran 2 tests in 0.001s
OK
import unittest
from unittest.mock import MagicMock
from unittest.mock import patch
import namer
class TestNameReplay(unittest.TestCase):
def test_name_replay_mocked(self):
mock_timestamp = MagicMock()
mock_timestamp.return_value = '202011221945'
namer.timestamp = mock_timestamp
name = namer.name_replay('packrat', 'jy')
self.assertEqual(name, '202011221945_packrat_vs_jy')
@patch('namer.timestamp')
def test_name_replay_with_decorator(self, mock_timestamp):
mock_timestamp.return_value = '202011221945'
name = namer.name_replay('packrat', 'jy')
self.assertEqual(name, '202011221945_packrat_vs_jy')
if __name__ == '__main__':
unittest.main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment