44from concurrent .futures import ThreadPoolExecutor
55import unittest
66
7- from quant_platform_kit .ibkr .connection import connect_ib , ensure_event_loop
7+ from quant_platform_kit .ibkr .connection import connect_ib , ensure_event_loop , probe_tcp_endpoint
88
99
1010class IbkrConnectionTests (unittest .TestCase ):
@@ -31,11 +31,80 @@ class FakeIB:
3131 def connect (self , host , port , clientId , timeout ):
3232 observed ["args" ] = (host , port , clientId , timeout )
3333
34- ib = connect_ib ("127.0.0.1" , 4001 , 9 , ib_factory = FakeIB )
34+ class FakeConnection :
35+ def close (self ):
36+ observed ["socket_closed" ] = True
37+
38+ def fake_socket_create_connection (address , timeout ):
39+ observed ["socket_args" ] = (address , timeout )
40+ return FakeConnection ()
41+
42+ ib = connect_ib (
43+ "127.0.0.1" ,
44+ 4001 ,
45+ 9 ,
46+ socket_create_connection = fake_socket_create_connection ,
47+ ib_factory = FakeIB ,
48+ )
3549
3650 self .assertIsInstance (ib , FakeIB )
3751 self .assertEqual (observed ["args" ], ("127.0.0.1" , 4001 , 9 , 20 ))
3852
3953
54+ def test_probe_tcp_endpoint_wraps_timeout (self ) -> None :
55+ def fake_socket_create_connection (_address , _timeout ):
56+ raise TimeoutError ()
57+
58+ with self .assertRaisesRegex (TimeoutError , r'TCP preflight timed out for 10\.0\.0\.8:4002' ):
59+ probe_tcp_endpoint (
60+ '10.0.0.8' ,
61+ 4002 ,
62+ timeout = 2.5 ,
63+ socket_create_connection = fake_socket_create_connection ,
64+ )
65+
66+ def test_probe_tcp_endpoint_wraps_os_error (self ) -> None :
67+ def fake_socket_create_connection (_address , _timeout ):
68+ raise OSError ('connection refused' )
69+
70+ with self .assertRaisesRegex (ConnectionError , r'TCP preflight failed for 10\.0\.0\.8:4002: connection refused' ):
71+ probe_tcp_endpoint (
72+ '10.0.0.8' ,
73+ 4002 ,
74+ timeout = 2.5 ,
75+ socket_create_connection = fake_socket_create_connection ,
76+ )
77+
78+ def test_connect_ib_runs_tcp_preflight_before_ib_connect (self ) -> None :
79+ observed : dict [str , object ] = {}
80+
81+ class FakeConnection :
82+ def close (self ):
83+ observed ['socket_closed' ] = True
84+
85+ def fake_socket_create_connection (address , timeout ):
86+ observed ['socket_args' ] = (address , timeout )
87+ return FakeConnection ()
88+
89+ class FakeIB :
90+ def connect (self , host , port , clientId , timeout ):
91+ observed ['ib_args' ] = (host , port , clientId , timeout )
92+
93+ ib = connect_ib (
94+ '10.0.0.8' ,
95+ 4002 ,
96+ 9 ,
97+ timeout = 20 ,
98+ tcp_preflight_timeout = 3.5 ,
99+ socket_create_connection = fake_socket_create_connection ,
100+ ib_factory = FakeIB ,
101+ )
102+
103+ self .assertIsInstance (ib , FakeIB )
104+ self .assertEqual (observed ['socket_args' ], (('10.0.0.8' , 4002 ), 3.5 ))
105+ self .assertTrue (observed ['socket_closed' ])
106+ self .assertEqual (observed ['ib_args' ], ('10.0.0.8' , 4002 , 9 , 20 ))
107+
108+
40109if __name__ == "__main__" :
41110 unittest .main ()
0 commit comments