Skip to content

Instantly share code, notes, and snippets.

@aprotyas
Created July 1, 2022 07:09
Show Gist options
  • Save aprotyas/72c043776fcad34b782e26c6aeb737ae to your computer and use it in GitHub Desktop.
Save aprotyas/72c043776fcad34b782e26c6aeb737ae to your computer and use it in GitHub Desktop.
Patch unbound method using unittest.mock
"""Patch an unbound class method."""
from unittest import mock
import pytest
class MyClass():
"""Demo class."""
@classmethod
def my_method(self, arg: int = 0) -> int:
"""Return 0 when invoked without an argument."""
return arg
def my_method_mock(self: MyClass, arg: int = 1) -> int:
"""Return 1 when invoked without an argument."""
return arg
_my_method_patch = mock.patch.object(MyClass, "my_method", classmethod(my_method_mock))
def test_my_method() -> None:
"""Unit test for my_method function."""
obj = MyClass()
assert obj.my_method() == 0
@_my_method_patch
def test_my_method_mock() -> None:
"""Unit test for my_method_mock function."""
obj = MyClass()
assert obj.my_method() == 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment