I'm trying to use py.test
to test some code that does various LDAP
searches, and modifications.
I'm using pytest-mock
, but I'm having trouble understanding how to mock out the creation of the an LDAP object, and control what it returns when a search_s()
is called on the mocked object.
I thought this would do what I wanted, but the test fails, the count shows the generator function find_users()
never yields anything.
import pytest
# Here is some code to simply test mocking out ldap.initialize(), and
# controlling the return value from calls to search_s()
import ldap
def find_users(ldap_url, admin_user, admin_password, userbase):
lobj = ldap.initialize(ldap_url)
lobj.simple_bind_s(admin_user, admin_password)
for i in lobj.search_s(userbase, ldap.SCOPE_SUBTREE, '*'):
yield i[1]['uid'][0]
class TestMocking:
@pytest.fixture()
def no_ldap(self, mocker):
return mocker.patch('ldap.initialize')
def test_ad_one_user(self, no_ldap):
# try and modify how search_s() would return
no_ldap.search_s.return_value = ('', {'uid': ['happy times']})
count = 0
for i in find_users('', '', '', ''):
count += 1
assert i=='happy times'
assert count == 1