Debian Codegraph @

tests/test_asyncio.py

raw symbols SCIP
1 import asyncio
2 import sys
3 import time
4 from functools import wraps
5
6 import pytest
7 from conftest import get_config, network_delay
8
9 from bonsai import LDAPEntry
10 from bonsai.asyncio import AIOConnectionPool
11 from bonsai.pool import ClosedPool
12 import bonsai.errors
13
14 if sys.platform == "win32" and sys.version_info.minor >= 8:
15 # Enforce SelectorEventLoop as it's no longer default on Windows since Python 3.8.
16 asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
17
18
19 def asyncio_test(func):
20 @wraps(func)
21 def wrapper(*args, **kwargs):
22 future = func(*args, **kwargs)
23 asyncio.run(future)
24
25 return wrapper
26
27
28 @asyncio_test
29 async def test_connection(client):
30 """Test opening a connection."""
31 conn = await client.connect(True)
32 assert conn is not None
33 assert conn.closed == False
34
35
36 @asyncio_test
37 async def test_search(client):
38 """Test search."""
39 async with client.connect(True) as conn:
40 res = await conn.search()
41 assert res is not None
42
43
44 @asyncio_test
45 async def test_add_and_delete(client, basedn):
46 """Test adding and deleting an LDAP entry."""
47 async with client.connect(True) as conn:
48 entry = LDAPEntry("cn=async_test,%s" % basedn)
49 entry["objectclass"] = [
50 "top",
51 "inetOrgPerson",
52 "person",
53 "organizationalPerson",
54 ]
55 entry["sn"] = "async_test"
56 try:
57 await conn.add(entry)
58 except bonsai.errors.AlreadyExists:
59 await conn.delete(entry.dn)
60 await conn.add(entry)
61 except:
62 pytest.fail("Unexpected error.")
63 res = await conn.search()
64 assert entry in res
65 await entry.delete()
66 res = await conn.search()
67 assert entry not in res
68
69
70 @asyncio_test
71 async def test_recursive_delete(client, basedn):
72 """Test removing a subtree recursively."""
73 org1 = bonsai.LDAPEntry("ou=testusers,%s" % basedn)
74 org1.update({"objectclass": ["organizationalUnit", "top"], "ou": "testusers"})
75 org2 = bonsai.LDAPEntry("ou=tops,ou=testusers,%s" % basedn)
76 org2.update({"objectclass": ["organizationalUnit", "top"], "ou": "tops"})
77 entry = bonsai.LDAPEntry("cn=tester,ou=tops,ou=testusers,%s" % basedn)
78 entry.update(
79 {"objectclass": ["top", "inetorgperson"], "cn": "tester", "sn": "example"}
80 )
81 try:
82 with (await client.connect(True)) as conn:
83 await conn.add(org1)
84 await conn.add(org2)
85 await conn.add(entry)
86 with pytest.raises(bonsai.errors.NotAllowedOnNonleaf):
87 await conn.delete(org1.dn)
88 await conn.delete(org1.dn, recursive=True)
89 res = await conn.search(org1.dn, 2)
90 assert res == []
91 except bonsai.LDAPError as err:
92 pytest.fail("Recursive delete is failed: %s" % err)
93
94
95 @asyncio_test
96 async def test_modify_and_rename(client, basedn):
97 """Test modifying and renaming LDAP entry."""
98 async with client.connect(True) as conn:
99 entry = LDAPEntry("cn=async_test,%s" % basedn)
100 entry["objectclass"] = [
101 "top",
102 "inetOrgPerson",
103 "person",
104 "organizationalPerson",
105 ]
106 entry["sn"] = "async_test"
107 oldname = "cn=async_test,%s" % basedn
108 newname = "cn=async_test2,%s" % basedn
109 res = await conn.search(newname, 0)
110 if res:
111 await res[0].delete()
112 try:
113 await conn.add(entry)
114 except bonsai.errors.AlreadyExists:
115 await conn.delete(entry.dn)
116 await conn.add(entry)
117 except:
118 pytest.fail("Unexpected error.")
119 entry["sn"] = "async_test2"
120 await entry.modify()
121 await entry.rename(newname)
122 res = await conn.search(entry.dn, 0, attrlist=["sn"])
123 assert entry["sn"] == res[0]["sn"]
124 res = await conn.search(oldname, 0)
125 assert res == []
126 await conn.delete(entry.dn)
127
128
129 @asyncio_test
130 async def test_obj_err(client, basedn):
131 """Test object class violation error."""
132 entry = LDAPEntry("cn=async_test,%s" % basedn)
133 entry["cn"] = ["async_test"]
134 with pytest.raises(bonsai.errors.ObjectClassViolation):
135 async with client.connect(True) as conn:
136 await conn.add(entry)
137
138
139 @asyncio_test
140 async def test_whoami(client):
141 """Test whoami."""
142 async with client.connect(True) as conn:
143 cfg = get_config()
144 obj = await conn.whoami()
145 expected_res = [
146 "dn:%s" % cfg["SIMPLEAUTH"]["user"],
147 cfg["SIMPLEAUTH"]["adusername"],
148 ]
149 assert obj in expected_res
150
151
152 @pytest.mark.timeout(18)
153 @asyncio_test
154 async def test_connection_timeout(client):
155 """Test connection timeout."""
156 with network_delay(6.0):
157 with pytest.raises(asyncio.TimeoutError):
158 await client.connect(True, timeout=8.0)
159
160
161 @pytest.mark.timeout(18)
162 @asyncio_test
163 async def test_search_timeout(client):
164 """Test search timeout."""
165 async with client.connect(True) as conn:
166 with network_delay(5.1):
167 with pytest.raises(asyncio.TimeoutError):
168 await conn.search(timeout=4.0)
169
170
171 @asyncio_test
172 async def test_paged_search(client, basedn):
173 """Test paged results control."""
174 client.auto_page_acquire = False
175 search_dn = "ou=nerdherd,%s" % basedn
176 async with client.connect(True) as conn:
177 res = await conn.paged_search(search_dn, 1, page_size=2)
178 for ent in res:
179 assert isinstance(ent, bonsai.LDAPEntry)
180 page = 1 # First page is already acquired.
181 while True:
182 if len(res) > 2:
183 pytest.fail("The size of the page is greater than expected.")
184 msgid = res.acquire_next_page()
185 if msgid is None:
186 break
187 res = await conn.get_result(msgid)
188 page += 1
189 assert page == 3
190
191
192 @asyncio_test
193 async def test_paged_search_with_auto_acq(client, basedn):
194 """Test paged search with auto page acquiring."""
195 search_dn = "ou=nerdherd,%s" % basedn
196 async with client.connect(True) as conn:
197 cnt = 0
198 result = await conn.paged_search(search_dn, 1, page_size=3)
199 async for item in result:
200 assert isinstance(item, LDAPEntry)
201 cnt += 1
202 assert cnt == 6
203
204
205 @asyncio_test
206 async def test_async_with(client):
207 """Test async with context manager (with backward compatibility)."""
208 mgr = client.connect(True)
209 aexit = type(mgr).__aexit__
210 aenter = type(mgr).__aenter__(mgr)
211
212 conn = await aenter
213 try:
214 assert conn.closed == False
215 _ = await conn.whoami()
216 except:
217 if not (await aexit(mgr, *sys.exc_info())):
218 raise
219 else:
220 await aexit(mgr, None, None, None)
221 assert conn.closed
222
223
224 async def keep(pool, delay):
225 conn = await pool.get()
226 await asyncio.sleep(delay)
227 await pool.put(conn)
228
229
230 @asyncio_test
231 async def test_pool_get_put(client):
232 """Test getting and putting back connection from pool."""
233 delay = 2
234 pool = AIOConnectionPool(client, minconn=1, maxconn=1)
235 with pytest.raises(ClosedPool):
236 _ = await pool.get()
237 await pool.open()
238 assert pool.closed == False
239 assert pool.idle_connection == 1
240 task1 = asyncio.ensure_future(keep(pool, delay))
241 task2 = asyncio.ensure_future(keep(pool, delay))
242 start = time.time()
243 await task1
244 await task2
245 assert time.time() - start >= delay * 2
246 # With enough connection in the pool for both tasks.
247 pool.max_connection = 2
248 task1 = asyncio.ensure_future(keep(pool, delay))
249 task2 = asyncio.ensure_future(keep(pool, delay))
250 start = time.time()
251 await task1
252 await task2
253 assert time.time() - start >= delay
254
255
256 @asyncio_test
257 async def test_pool_close(client):
258 """Test closing the pool."""
259 pool = AIOConnectionPool(client, minconn=1, maxconn=1)
260 await pool.open()
261 assert pool.closed == False
262 assert pool.idle_connection == 1
263 await pool.close()
264 assert pool.closed == True
265 assert pool.idle_connection == 0
266
267
268 @asyncio_test
269 async def test_pool_pass_param(client):
270 """Test passing parameter to connect."""
271 pool = AIOConnectionPool(client, minconn=1, maxconn=1, timeout=0)
272 with pytest.raises(asyncio.TimeoutError):
273 await pool.open()
274 _ = await pool.get()
275
276
277 @asyncio_test
278 async def test_pool_spawn(client):
279 """Test context manager."""
280 pool = AIOConnectionPool(client, minconn=1, maxconn=1)
281 assert pool.idle_connection == 0
282 async with pool.spawn() as conn:
283 assert pool.shared_connection == 1
284 _ = await conn.whoami()
285 assert pool.idle_connection == 1
286 assert pool.shared_connection == 0