python - How to access object instance from mocked instance method when unit testing? -


in code below says foo_obj = ????, how can reference foo object instance, or better approach?

class foo(object):      def __init__(self):         self.hello = "hey!"      def bar(self):         return self.hello + " how's going?"  def side_effect_foo_bar(*args, **kwargs):     foo_obj = ????     return foo_obj.hello + " what's up?"  class testfoo(unittest.testcase):      @patch.object(foo, 'bar')     def test_bar(self, mocked_bar):         mocked_bar.side_effect = side_effect_foo_bar         foo = foo()         self.asserttrue(foo.bar() == "hey! what's up?") 

i figured out this:

http://mock.readthedocs.org/en/latest/examples.html#mocking-unbound-methods

the trick add autospec=true in @patch.object(foo, 'bar', autospec=true).

class foo(object):      def __init__(self):         self.hello = "hey!"      def bar(self):         return self.hello + " how's going?"  def side_effect_foo_bar(*args, **kwargs):     return args[0].hello + " what's up?"  class testfoo(unittest.testcase):      @patch.object(foo, 'bar', autospec=true)     def test_bar(self, mocked_bar):         mocked_bar.side_effect = side_effect_foo_bar         foo = foo()         self.asserttrue(foo.bar() == "hey! what's up?") 

Comments

Popular posts from this blog

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -

java - How to filter a backspace keyboard input -

java - Show Soft Keyboard when EditText Appears -