在utils.py的Django unittest中模拟失败

时间:2016-04-12 10:17:20

标签: python django unit-testing python-3.x mocking

我正在尝试为名为search_ldap()的函数编写单元测试,该函数在给定特定用户名的LDAP服务器中搜索。以下是utils.py中的函数定义(注意:我使用Python 3):

from ldap3 import Server, Connection
def search_ldap(username):
    result = ()
    baseDN = "o=Universiteit van Tilburg,c=NL"
    searchFilter = '(uid={})'.format(username)
    attributes = ['givenName', 'cn', 'employeeNumber', 'mail']

    try:
        server = Server('ldap.example.com', use_ssl=True)
        conn = Connection(server, auto_bind=True)
        conn.search(baseDN, searchFilter, attributes=attributes)
        for a in attributes:
            result += (conn.response[0]['attributes'][a][0], )
    except Exception:
        raise LDAPError('Error in LDAP query')

    return result

当然,我不想在测试期间实际连接到ldap.example.com,因此我决定使用Python mock object library来模拟Server()我的单元测试中有}和Connection()个类。这是测试代码:

from unittest import mock
from django.test import TestCase
class LdapTest(TestCase):
    @mock.patch('ldap3.Server')
    @mock.patch('ldap3.Connection')
    def test_search_ldap(self, mockConnection, mockServer):
        from .utils import search_ldap
        search_ldap('username')
        self.assertTrue(mockServer.called)
        self.assertTrue(mockConnection.called)

此测试只是断言模拟的Server和Connection对象是实例化的。但是,不要这样做,因为当我使用./manage.py test运行测试时,我收到以下错误:

Creating test database for alias 'default'...
F.
======================================================================
FAIL: test_search_ldap (uvt_user.tests.LdapTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/usr/lib/python3.4/unittest/mock.py", line 1142, in patched
    return func(*args, **keywargs)
  File "/home/jj/projects/autodidact/uvt_user/tests.py", line 28, in test_search_ldap
    self.assertTrue(mockServer.called)
AssertionError: False is not true

----------------------------------------------------------------------
Ran 2 tests in 0.030s

FAILED (failures=1)
Destroying test database for alias 'default'...

为什么我的测试失败了?如何成功模拟ldap3的服务器和连接类?

2 个答案:

答案 0 :(得分:0)

要模拟课程,你应该用必要的方法提供它的虚假实现。例如:

class FakeServer:
    def call():
        pass

class LdapTest(TestCase):
    @mock.patch('ldap3.Server', FakeServer)
    def test_search_ldap(self):
        <do you checks here>

答案 1 :(得分:0)

使用patch(),在命名空间中对象进行修补是很重要的。这在文档的Where to patch部分进行了解释。做

之间存在根本区别
from ldap3 import Server
server = Server()

import ldap3
server = ldap3.Server()

在第一种情况下(也就是原始问题中的情况),名称“Server”属于当前模块。在第二种情况下,名称“Server”属于定义它的ldap3模块。以下Django unittest修补了正确的“服务器”和“连接”名称,应按预期工作:

from unittest import mock
from django.test import TestCase
class LdapTest(TestCase):
    @mock.patch('appname.utils.Server')
    @mock.patch('appname.utils.Connection')
    def test_search_ldap(self, mockConnection, mockServer):
        from .utils import search_ldap
        search_ldap('username')
        self.assertTrue(mockServer.called)
        self.assertTrue(mockConnection.called)