Add and improve new_model unit tests

This commit is contained in:
sfigato 2020-11-27 19:41:45 +01:00
parent 95bc52ebd8
commit 67c7830ba4
Signed by: blallo
GPG Key ID: 0CBE577C9B72DC3F

View File

@ -7,6 +7,7 @@ import mock
import pytest
from phi.async_ldap.new_model import get_dn, User
from phi.async_ldap.mixins import Member
BASE_DN = "dc=test,dc=domain,dc=tld"
@ -16,18 +17,18 @@ class MockClient(object):
self.return_value = kwargs.get("return_value")
self.connect_called = False
self.conn = mock.MagicMock()
self.search_event = asyncio.Event()
self.add_event = asyncio.Event()
self.delete_event = asyncio.Event()
def connect_called_with_search(self):
self.conn.search.assert_called()
async def connect_called_with_search(self):
return await self.search_event.wait()
def connect_called_with_add(self):
self.conn.add.assert_called()
async def connect_called_with_add(self):
return await self.add_event.wait()
def connect_called_with_modify(self):
self.conn.modify.assert_called()
def connect_called_with_delete(self):
self.conn.delete.assert_called()
async def connect_called_with_delete(self):
return await self.delete_event.wait()
@property
def base_dn(self):
@ -38,15 +39,18 @@ class MockClient(object):
self.connect_called = True
async def _search(*a, **kw):
self.search_event.set()
return self.return_value
async def _add(*a, **kw):
self.add_event.set()
return self.return_value
async def _modify(*a, **kw):
return self.return_value
async def _delete(*a, **kw):
self.delete_event.set()
return self.return_value
self.conn.search = mock.MagicMock(side_effect=_search)
@ -93,4 +97,47 @@ async def test_User_add():
_ = await u.save()
assert _cl.connect_called
_cl.connect_called_with_add()
assert await _cl.connect_called_with_add()
@pytest.mark.asyncio
async def test_User_modify():
"""
This test does not use the MockClient check facilities because
of implementation details of the Entry class.
"""
_cl = MockClient(
return_value=[
LDAPEntry(f"uid=test_user,ou=Hackers,{BASE_DN}"),
]
)
u = User(_cl, "test_user")
# This is the asyncio equivalent of a semaphore
modified = asyncio.Event()
async def _mock_modify():
modified.set()
u._entry = mock.MagicMock()
u._entry.modify = mock.MagicMock(side_effect=_mock_modify)
u["cn"] = "random_cn"
_ = await u.modify()
assert _cl.connect_called
assert await _cl.connect_called_with_search()
# The `wait()` call here is needed to wait for `_mock_modify`
# to end its async execution
assert await modified.wait()
@pytest.mark.asyncio
async def test_User_delete():
_cl = MockClient(return_value=None)
u = User(_cl, "test_user")
_ = await u.delete()
assert _cl.connect_called
assert await _cl.connect_called_with_delete()