I'm trying to use python's mock.patch to implement unit tests with nose.
class A:
def setUp(self):
self.b = 8 #contrived example
@patch.object('module.class', 'function', lambda x: self.b)
def testOne(self):
# do test #
Here, patch complains that it doesnt know self (which is correct). What is best way to get this kind of functionality in a clean fashion?
I know I can use a global variable, or that I can mock it within the test (but that involves me cleaning up the objects at the end of the test).
You cannot use
self
on method decorator because you are in the class definition and the object doesn't exist. If you really want to access toself
and not just use some static values you can consider follow approach:totest
is a module in my python path andfn
is the method that I would patch, moreover I'm using a fixedreturn_value
instead a function for a more readable exampleIn
testOne()
I usepatch
as a context and I will have the full access toself
. IntestTwo()
(that is my standard way) I set up my mockm
at the start of the test and then use it.Finally I used
patch()
instead ofpatch.object()
because I don't really understand why you needpatch.object()
but you can change it as you like.