Skip to content

Instantly share code, notes, and snippets.

@hectorcanto
Created February 8, 2019 15:19
Show Gist options
  • Save hectorcanto/2ade84b5a173b8c90c87f7eaaf71d01c to your computer and use it in GitHub Desktop.
Save hectorcanto/2ade84b5a173b8c90c87f7eaaf71d01c to your computer and use it in GitHub Desktop.
Three examples of mocking, patching methods of a class.
import pytest
class Simple_Class:
def method(self):
return 1
def another_method(self):
return 2
def test_instance_patch(mocker):
simple_instance = Simple_Class()
another_instance = Simple_Class()
mocker.patch.object(simple_instance, "method", return_value=3)
assert simple_instance.method() == 3
assert another_instance.method() == 1
def test_class_patch(mocker):
mocker.patch.object(Simple_Class, "method", return_value=3)
simple_instance = Simple_Class()
another_instance = Simple_Class()
assert simple_instance.method() == 3
assert another_instance.method() == 3
def test_class_with_side_effect(mocker):
mocker.patch.object(Simple_Class, "method", side_effect=AttributeError("Side effect"))
simple_instance = Simple_Class()
with pytest.raises(AttributeError) as exception:
simple_instance.method()
assert exception.msg == "Side effect"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment