Skip to content

Instantly share code, notes, and snippets.

@iffy
Created September 22, 2014 16:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iffy/1e74511841622f7045f7 to your computer and use it in GitHub Desktop.
Save iffy/1e74511841622f7045f7 to your computer and use it in GitHub Desktop.
How do I patch a classmethod?
python -m unittest patch_classmethod
E
======================================================================
ERROR: test_usesCreate (patch_classmethod.someFuncTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "patch_classmethod.py", line 27, in test_usesCreate
someFunc('hey')
File "patch_classmethod.py", line 11, in someFunc
return Foo.create(arg)
TypeError: unbound method create() must be called with Foo instance as first argument (got str instance instead)
----------------------------------------------------------------------
Ran 1 test in 0.001s
FAILED (errors=1)
class Foo(object):
@classmethod
def create(self, arg):
foo = Foo()
foo.value = arg
return foo
def someFunc(arg):
return Foo.create(arg)
from unittest import TestCase
from mock import patch
class someFuncTest(TestCase):
def test_usesCreate(self):
"""
someFunc should use Foo.create to create the foo instance.
"""
with patch.object(Foo, 'create', autospec=Foo.create):
someFunc('hey')
Foo.create.assert_called_once_with('hey')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment