0

I am trying to understand the mock/patch framework, but have a problem. Here are my simplified codes:

file_a.py
class A:
  def f(self): 
    b = B()
    b.g()
    b.h()

file_b.py
class B:
  def g(self):
    return network_requests(...)

  def h(self):
    return "This is should not be mocked."

file_test.py
class SomeTests:
  def setUp(self):
    with patch('file_b.B', autospec=True) as mock:
      mock.g.return_value = "Mocked value"
      mock.side_effect = lambda : B()
    self.a = A()

  def test(self):
    self.a.f()

Essentially I want to mock only B.g inside the test, but not B.h. I got some idea from https://docs.python.org/3/library/unittest.mock-examples.html#partial-mocking, but B.g is still not mocked.

Thank you!

AoZ
  • 139
  • 1
  • 3
  • 10

1 Answers1

1

In the example that you linked the key problem is

Unfortunately datetime.date is written in C

That is why you need to mock the module and wrap what you don't want to mock (You cannot patch C methods directly).

Is all other cases (patch python objects) you can use just :

with patch('file_b.B.g', autospec=True) as mock_g:
  mock_g.return_value = "Mocked value"

Anyway take care that your patch will be active just in the with context, out of it you will find the original reference. To have a better control of the context it you can use also decorators, start() and stop().

I strongly encourage you read carefully patch and where to patch.

Michele d'Amico
  • 22,111
  • 8
  • 69
  • 76