33import pytest
44import asyncio
55import time
6+ from async_timeout import timeout
67from cx_Oracle_async import *
78import cx_Oracle
9+ import threading
810
911async def create_long_query (oracle_pool ):
1012 async with oracle_pool .acquire () as conn :
1113 cursor = await conn .cursor ()
1214 try :
13- await cursor .execute ("BEGIN DBMS_LOCK.SLEEP(:a); END;" ,(20 ,))
15+ await cursor .execute ("BEGIN DBMS_LOCK.SLEEP(:a); END;" ,(10 ,))
1416 except Exception as e :
1517 assert isinstance (e , cx_Oracle .OperationalError )
1618
19+ def create_long_query_sync (oracle_pool ):
20+ '''
21+ use sync function in order to avoid pytest loop never stop bug.
22+ '''
23+ try :
24+ conn = oracle_pool ._pool .acquire ()
25+ cursor = conn .cursor ()
26+ cursor .execute ("BEGIN DBMS_LOCK.SLEEP(:a); END;" ,(10 ,))
27+ except :
28+ ...
29+
1730@pytest .mark .asyncio
1831async def test_force_close ():
1932 loop = asyncio .get_running_loop ()
2033 dsn = makedsn ('localhost' ,'1521' ,sid = 'xe' )
2134 INAQ = 0.5
22- oracle_pool = await create_pool (user = 'system' ,password = 'oracle' ,dsn = dsn ,max = 4 )
23- loop = asyncio .get_running_loop ()
35+ oracle_pool = await create_pool (user = 'system' ,password = 'oracle' ,dsn = dsn )
2436 loop .create_task (create_long_query (oracle_pool ))
2537 st_time = time .time ()
2638 await asyncio .sleep (2 )
27- await oracle_pool .close (force = True )
39+ await oracle_pool .close (force = True , interrupt = False )
40+ ed_time = time .time ()
41+ assert (10 - INAQ ) <= (ed_time - st_time ) <= (10 + INAQ )
42+
43+ # test occupy
44+ oracle_pool = await create_pool (user = 'system' ,password = 'oracle' ,dsn = dsn ,max = 4 )
45+ conn = await oracle_pool .acquire ()
46+ conn = await oracle_pool .acquire ()
47+ assert len (oracle_pool ._occupied ) == 2
48+ conn = await oracle_pool .acquire ()
49+ assert len (oracle_pool ._occupied ) == 3
50+ st_time = time .time ()
51+ await asyncio .sleep (2 )
52+ async with timeout (2 ):
53+ # no running task , return immediately
54+ await oracle_pool .close (force = True , interrupt = False )
55+ ed_time = time .time ()
56+ assert (2 - INAQ ) <= (ed_time - st_time ) <= (2 + INAQ )
57+
58+ # test interrupt
59+ oracle_pool = await create_pool (user = 'system' ,password = 'oracle' ,dsn = dsn ,max = 4 )
60+ st_time = time .time ()
61+ t = threading .Thread (target = create_long_query_sync , args = (oracle_pool ,))
62+ t .setDaemon (True )
63+ t .start ()
64+ await asyncio .sleep (2 )
65+ exception_flag = False
66+ try :
67+ async with timeout (2 ):
68+ # no response forever
69+ await oracle_pool .close (force = True , interrupt = True )
70+ except Exception as e :
71+ exception_flag = True
72+ assert isinstance (e , asyncio .TimeoutError )
2873 ed_time = time .time ()
29- assert (ed_time - st_time ) <= (20 - INAQ )
74+ assert exception_flag
75+ assert (4 - INAQ ) <= (ed_time - st_time ) <= (10 - INAQ )
0 commit comments