pytest plugin

overview

  • provides a new fixture for pytest called mocker which wraps the standard mock library
  • undoes mocking automatically at the end of the test, apparently according to the documentation

installation

  • pip install pytest-mock

usage

  • example for mocking a function

    test_example.py
    import pytest
     
    from my_module import calculate
     
    class MockLogger:
    	def info(self, *args, **kwargs):
    		return "FOO"
     
    def test_example(mocker):
    	mock_calculate = mocker.patch('my_module.calculate')
    	mock_calculate.return_value = 42
     
    	# can do this as well
    	mocker.patch('my_module.procrastinate').return_value = "foo"
     
    	# to patch with a different module
    	mocker.patch('my_module.dev_logger', MockLogger)
     
    	result = calculate(2, 3)
    	assert result == 42
  • example using django model

    test_example.py
    import pytest
     
    from app.models import ExampleModel
     
    # to patch the django model objects.get fn
    def test_example1(mocker):
    	mock_object = mocker.Mock(spec=ExampleModel)
    	mock_object_instance = mocker.patch.object(
    		ExampleModel.objects, "get"
    	)
    	mock_object_instance.return_value = mock_object
     
    	# another way to mock return_value for method inside a
    	# class
    	mock_object.method_in_class.return_value = "foo"
     
    # to raise an exception
    def test_example2(mocker):
    	mock_object_instance = mocker.patch.object(ExampleModel.objects, "get")
    	mock_object_instance.side_effect = ExampleModel.DoesNotExist