I'm using python mock for patching some functions and classes when testing views in Django.
If I run each test independently, all test works. But when I run the TestCase, some test dont work (the patch has not effect).
class ViewsTest(TestCase):
@mock.patch('extras.utils.get_user_category')
def test_select_test(self, mock_method):
mock_method.return_value = Category(id=1, name="Foo")
response = self.client.post(reverse('select_test', args=['Foo']))
self.assertEqual(200, self.client.post(reverse('select')).status_code)
@mock.patch('user_profile.models.Profile.categories')
def test_category_view(self, mock_related):
mock_related.all.return_value = []
self.assertEqual(200, self.client.post(reverse('category')).status_code)
I have a print int the views to see each mocked method, when it works it prints:
MagicMock name='get_user_category' id='162815756'
And when doesn't works I see:
function get_user_category at 0x8e0fb8c
I tried the patcher start() and stop() but I still have problems.
¿What is the problem?
Open /catalog/tests/test_models.py.TestCase , as shown: from django. test import TestCase # Create your tests here. Often you will add a test class for each model/view/form you want to test, with individual methods for testing specific functionality.
The workhorse: MagicMock The basic idea is that MagicMock a placeholder object with placeholder attributes that can be passed into any function. I can. mock a constant, mock an object with attributes, or mock a function, because a function is an object in Python and the attribute in this case is its return value.
The request factory The RequestFactory shares the same API as the test client. However, instead of behaving like a browser, the RequestFactory provides a way to generate a request instance that can be used as the first argument to any view.
Order in which tests are executedAll TestCase subclasses are run first. Then, all other Django-based tests (test cases based on SimpleTestCase , including TransactionTestCase ) are run with no particular ordering guaranteed nor enforced among them. Then any other unittest.
I had the same problem. You're probably pointing the wrong way.
Check this link. It helped me.
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