22
33import socket
44import threading
5- import time
65from contextlib import closing
76from unittest import mock
87
98import pytest
109
10+ from reflex .testing import DEFAULT_TIMEOUT , AppHarness
1111from reflex .utils .processes import is_process_on_port
1212
1313
@@ -116,9 +116,11 @@ def test_is_process_on_port_permission_error():
116116def test_is_process_on_port_concurrent_access ():
117117 """Test is_process_on_port works correctly with concurrent access."""
118118 shared = None
119+ is_open = threading .Event ()
120+ do_close = threading .Event ()
119121
120122 def create_server_and_test ():
121- nonlocal shared
123+ nonlocal do_close , is_open , shared
122124 server = socket .socket (socket .AF_INET , socket .SOCK_STREAM )
123125 server .bind (("" , 0 ))
124126
@@ -127,23 +129,27 @@ def create_server_and_test():
127129 port = server .getsockname ()[1 ]
128130 shared = port
129131
130- # Small delay to ensure the test runs while server is active
131- time .sleep (0.1 )
132+ is_open .set ()
133+ do_close .wait (timeout = DEFAULT_TIMEOUT )
134+
132135 server .close ()
133136
134137 thread = threading .Thread (target = create_server_and_test )
135138 thread .start ()
139+ is_open .wait (timeout = DEFAULT_TIMEOUT )
136140
137- # Wait a bit for the server to start
138- time .sleep (0.05 )
139-
140- assert shared is not None
141-
142- # Port should be occupied while server is running (both bound-only and listening)
143- assert is_process_on_port (shared )
141+ try :
142+ assert shared is not None
144143
145- thread .join ()
144+ # Port should be occupied while server is running (both bound-only and listening)
145+ assert AppHarness ._poll_for (
146+ lambda : shared is not None and is_process_on_port (shared )
147+ )
148+ finally :
149+ do_close .set ()
150+ thread .join (timeout = DEFAULT_TIMEOUT )
146151
147152 # Give it a moment for the socket to be fully released
148- time .sleep (0.1 )
149- assert not is_process_on_port (shared )
153+ assert AppHarness ._poll_for (
154+ lambda : shared is not None and not is_process_on_port (shared )
155+ )
0 commit comments