简体   繁体   中英

Partially mock a method in unittest `setUp`

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 Bg inside the test, but not Bh . I got some idea from https://docs.python.org/3/library/unittest.mock-examples.html#partial-mocking , but Bg is still not mocked.

Thank you!

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM