Python 模拟补丁 ldap3 搜索响应

Python Mock patch ldap3 search response

我正在尝试模拟以下函数,但我不确定如何模拟连接响应:

def get_user_res(user, pass):
    res = None
    server = Server('my_server')
    connnection = Connection(server, user, pass, strategy=SAFE_SYNC, auto_bind=True)
    if connection.bind():
        connection.search(search_base, search_filter, SUBTREE)
        res = connection.response
        connection.unbind()
    return res
@mock.patch("ldap3.Server")
@mock.patch("ldap3.Connection.response")
def test_get_user_res(mock_connection, mock_server):
    mock_connection.return_value = ""
    retrived_res = get_user_res("fake_user","fake_password")
    expected_res = ""
    assert retrived_res == expected_res

根本问题是你在嘲笑错误的东西。如果你有一个名为 ldapclient.py 的文件,其中包含你的 get_user_rest 方法,就像这样(请注意,我已经重写了一些内容以使我们在编写测试时的生活更轻松):

import ldap3

server = ldap3.Server('my_server')
search_base = 'dc=example, dc=com'


def get_user_res(user, password, search_filter=None):
    res = None

    connection = ldap3.Connection(
        server, user, password,
        client_strategy=ldap3.SAFE_SYNC, auto_bind=True)

    if connection.bind():
        res = connection.search(search_base, search_filter, ldap3.SUBTREE)
        connection.unbind()

    return res

然后你需要模拟的是 ldap3.Connection class。但是由于您的测试在不同的模块中,您需要调用 @mock.patch('ldapclient.ldap3.Connection),假设您的测试定义如下:

import ldap3

from unittest import mock

import ldapclient


@mock.patch("ldapclient.ldap3.Connection")
def test_get_user_res(mock_connection_class):
    mock_connection = mock.Mock()
    mock_connection.search.return_value = 'fake_return'
    mock_connection_class.return_value = mock_connection

    retrived_res = ldapclient.get_user_res("fake_user", "fake_password")
    expected_res = "fake_return"
    assert retrived_res == expected_res

这里有几点需要注意:

  1. 如前所述,因为我们有import ldapclient,所以我们需要mock ldapclient.ldap3.Connection
  2. 我们使 ldap3.Connection class return 成为一个新的 mock.Mock 对象,因为我们希望能够模拟对象上的方法 returned调用 connection = ldap3.Connection(...)
  3. 我们将 search 方法 return 设为假值,以确保它按预期被调用。