Suppose I have the following code in a Python unit test:
aw = aps.Request("nv1") aw2 = aps.Request("nv2", aw)
Is there an easy way to assert that a particular method (in my case aw.Clear()
) was called during the second line of the test? e.g. is there something like this:
#pseudocode: assertMethodIsCalled(aw.Clear, lambda: aps.Request("nv2", aw))
assertEqual() in Python is a unittest library function that is used in unit testing to check the equality of two values. This function will take three parameters as input and return a boolean value depending upon the assert condition. If both input values are equal assertEqual() will return true else return false.
To begin with, MagicMock is a subclass of Mock . class MagicMock(MagicMixin, Mock) As a result, MagicMock provides everything that Mock provides and more. Rather than thinking of Mock as being a stripped down version of MagicMock, think of MagicMock as an extended version of Mock.
I use Mock (which is now unittest.mock on py3.3+) for this:
from mock import patch from PyQt4 import Qt @patch.object(Qt.QMessageBox, 'aboutQt') def testShowAboutQt(self, mock): self.win.actionAboutQt.trigger() self.assertTrue(mock.called)
For your case, it could look like this:
import mock from mock import patch def testClearWasCalled(self): aw = aps.Request("nv1") with patch.object(aw, 'Clear') as mock: aw2 = aps.Request("nv2", aw) mock.assert_called_with(42) # or mock.assert_called_once_with(42)
Mock supports quite a few useful features, including ways to patch an object or module, as well as checking that the right thing was called, etc etc.
Caveat emptor! (Buyer beware!)
If you mistype assert_called_with
(to assert_called_once
or assert_called_wiht
) your test may still run, as Mock will think this is a mocked function and happily go along, unless you use autospec=true
. For more info read assert_called_once: Threat or Menace.
Yes if you are using Python 3.3+. You can use the built-in unittest.mock
to assert method called. For Python 2.6+ use the rolling backport Mock
, which is the same thing.
Here is a quick example in your case:
from unittest.mock import MagicMock aw = aps.Request("nv1") aw.Clear = MagicMock() aw2 = aps.Request("nv2", aw) assert aw.Clear.called
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With