pytest mock.patch无法成功模拟值

时间:2019-05-07 23:59:58

标签: python unit-testing mocking pytest

我有一些代码,想模拟来自Web连接的响应。但是事实证明,模拟功能对我不起作用。我的文件结构是:

..
|
..
├── _client.py
├── _mysvclogic.py
|   
├── _unittests
|   ├── testmysvc.py
| 
├── __init__.py

在client.py中,我有一个函数“ client_send_request”:

def client_send_request(request):
    try:
        response = send_request(request)
        return response
    except Exception as e:
        raise e

在mysvclogic.py中,我有一个要测试的函数“ request”,它将从“ client.py”中调用函数“ client_send_request”:

from A/B/C/client import client_send_request

def request(s):
    try:
        ....
        res = client_send_request(request)
        response = res * res
        ......
        return response

    except Exception as exc:
        logger.exception("error msg: " + exc +  "delivering error after uncaught exception:")
        raise SystemExit

在testmysvc.py中,我想测试mysvclogic的请求功能,所以我想模拟“ client_send_request”功能:

from A.B.C.client import client_send_request
@mock.patch("A.B.C.mysvclogic.client_send_request")
def test_mock(mock_send_request):
    mock_send_request.return_value = ValueA    
    s = xxx
    # based on input value of s, send_request's return value should be Value B
    # but if mock is successfully, send_request's return value should be Value A
    res = mysvclogic.request(s)
    print(res)
    assert (res == ValueA)

但是结果是,我得到了基于ValueB的资源,这意味着它不模拟“ client_send_request”的返回值。错误消息是:

mock_send_request = <MagicMock name='client_send_request' id='18446744071195317'>
    .....
    ...
     assert ValueA == ValueB

0 个答案:

没有答案