Unit Testing
https://chase-seibert.github.io/blog/2015/06/25/python-mocking-cookbook.html
https://santexgroup.com/wp-content/uploads/2014/10/mock_python.html#slide17
@patch(f'aiohttp.ClientSession.request')
def test_dispatch_send_should_call_session_request(
self, mock_client_session_request,
):
compute_wakeup_delay
of RequestProgressTrackerMODULE = 'project.util.reqtracker.RequestProgressTracker'
@patch(f'{MODULE}._compute_wakeup_delay', return_value=0)
def test_ack_request_should_remove_request_attribute(
self, mock_compute_wakeup_delay
):
>>> @patch('package.module.ClassName.attribute', sentinel.attribute)
... def test():
... from package.module import ClassName
... assert ClassName.attribute == sentinel.attribute
...
>>> test()
>>> class MyTest(unittest.TestCase):
... @patch.object(SomeClass, 'attribute', sentinel.attribute)
... def test_something(self):
... self.assertEqual(SomeClass.attribute, sentinel.attribute)
...
>>> original = SomeClass.attribute
>>> MyTest('test_something').test_something()
>>> assert SomeClass.attribute == original
>>> class MyTest(unittest.TestCase):
... @patch.object(SomeClass, 'static_method')
... def test_something(self, mock_method):
... SomeClass.static_method()
... mock_method.assert_called_with()
...
>>> MyTest('test_something').test_something()
func1 = MagicMock(return=('POST', {} , '/add'}
object.age = PropertyMock(return_value=34)
A useful attribute is side_effect. If you set this to an exception class or instance then the exception will be raised when the mock is called.
>>> mock = Mock(side_effect=Exception('Boom!'))
>>> mock()
Traceback (most recent call last):
...
Exception: Boom!
@patch('time.time', MagicMock(return_value=1530667543.3568835))
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from mymodule import rm
import mock
import unittest
class RmTestCase(unittest.TestCase):
@mock.patch('mymodule.os.path')
@mock.patch('mymodule.os')
def test_rm(self, mock_os, mock_path):
# set up the mock
mock_path.isfile.return_value = False
rm("any path")
# test that the remove call was NOT called.
self.assertFalse(mock_os.remove.called, "Failed to not remove the file if not present.")
# make the file 'exist'
mock_path.isfile.return_value = True
rm("any path")
mock_os.remove.assert_called_with("any path")
>>> mock = Mock(return_value=None)
>>> mock('foo', bar='baz')
>>> mock.assert_called_once_with('foo', bar='baz')
>>> mock('other', bar='values')
>>> mock.assert_called_once_with('other', bar='values')
Traceback (most recent call last):
...
AssertionError: Expected 'mock' to be called once. Called 2 times.
Assert that the mock was called exactly once and that that call was with the specified arguments.