Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
133 views
in Technique[技术] by (71.8m points)

python - How to patch a local function?

def f(a):
    return a*2

def g(a):
    return f(a)

g(1)
# 2

with patch("f") as mock_f:
    mock_f.return_value = 123
    g(1)

What I want to achieve is that f always returns 123 and hence g(1) also returns 123. Instead I get an error message:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
~Anaconda3libunittestmock.py in _get_target(target)
   1547     try:
-> 1548         target, attribute = target.rsplit('.', 1)
   1549     except (TypeError, ValueError):

ValueError: not enough values to unpack (expected 2, got 1)

During handling of the above exception, another exception occurred:

TypeError                                 Traceback (most recent call last)
<ipython-input-52-4dac247bb108> in <module>
      8 # 2
      9 
---> 10 with patch("f") as mock_f:
     11     mock_f.return_value = 123
     12     g(1)

~Anaconda3libunittestmock.py in patch(target, new, spec, create, spec_set, autospec, new_callable, **kwargs)
   1702     available for alternate use-cases.
   1703     """
-> 1704     getter, attribute = _get_target(target)
   1705     return _patch(
   1706         getter, attribute, new, spec, create,

~Anaconda3libunittestmock.py in _get_target(target)
   1548         target, attribute = target.rsplit('.', 1)
   1549     except (TypeError, ValueError):
-> 1550         raise TypeError("Need a valid target to patch. You supplied: %r" %
   1551                         (target,))
   1552     getter = lambda: _importer(target)

TypeError: Need a valid target to patch. You supplied: 'f'
question from:https://stackoverflow.com/questions/65938262/how-to-patch-a-local-function

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Please try this.

from unittest.mock import patch

def f(a):
    return a * 2


def g(a):
    return f(a)


with patch("__main__.f") as mock_f:
    mock_f.return_value = 2
    result = g(1)
    assert result == 2

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...