python - Django Rest Framework: How can I patch a serializer for unit testing, when it's used in the serializer_class attribute? -
i have serializer create() function. when post request, want function called , create new object. when in browser, works , calls function. inside test, says function not called. think have done wrong patch, because in api set serializer_class , class called somewhere inside framework. thought was, not need test this, because should guaranteed rest_framework, if way, framework should call function correct parameters.
# serializers.py class fooserializer(models.modelserializer): class meta: ... def create(self, validated_data): ... # apis.py class fooapi(generics.createapiview): serializer_class = fooserializer # tests.py @patch('apis.fooserializer'): def test_that_create_is_called(self, mock): mock.create = magicmock() mock.create.return_value = foo() # foo model response = self.client.post('/foo', {name: 'test'}) self.asserttrue(mock.create.called) # => output says "false not true"
your current code mocking entire serializer object, overkill , stop create method ever being called if it's expected called internal logic on serializer.
instead want patch single method - this:
@patch('apis.fooserializer', 'create')
now test method receives magicmock object instance has replaced create method.
so test method becomes:
def test_that_create_is_called(self, mock_method): response = self.client.post('/foo', {name: 'test'}) self.asserttrue(mock_method.called)
Comments
Post a Comment