Skip to content

Commit 714c5ba

Browse files
committed
Clean up old versions of session cache tests
1 parent 14d51d2 commit 714c5ba

File tree

6 files changed

+63
-53
lines changed

6 files changed

+63
-53
lines changed

tests/core/providers/test_async_http_provider.py

Lines changed: 1 addition & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,6 @@
88
AsyncWeb3,
99
__version__ as web3py_version,
1010
)
11-
from web3._utils import (
12-
request,
13-
)
1411
from web3.eth import (
1512
AsyncEth,
1613
)
@@ -39,13 +36,6 @@
3936
URI = "http://mynode.local:8545"
4037

4138

42-
async def clean_async_session_cache():
43-
cache_data = request._async_session_cache._data
44-
while len(cache_data) > 0:
45-
_key, cached_session = cache_data.popitem()
46-
await cached_session.close()
47-
48-
4939
@pytest.mark.asyncio
5040
async def test_async_no_args() -> None:
5141
provider = AsyncHTTPProvider()
@@ -56,9 +46,6 @@ async def test_async_no_args() -> None:
5646
with pytest.raises(ProviderConnectionError):
5747
await w3.is_connected(show_traceback=True)
5848

59-
await clean_async_session_cache()
60-
assert len(request._async_session_cache) == 0
61-
6249

6350
def test_init_kwargs():
6451
provider = AsyncHTTPProvider(endpoint_uri=URI, request_kwargs={"timeout": 60})
@@ -103,7 +90,7 @@ async def test_async_user_provided_session() -> None:
10390
session = ClientSession()
10491
provider = AsyncHTTPProvider(endpoint_uri=URI)
10592
cached_session = await provider.cache_async_session(session)
106-
assert len(request._async_session_cache) == 1
93+
assert len(provider._request_session_manager.session_cache) == 1
10794
assert cached_session == session
10895

10996

tests/core/providers/test_http_provider.py

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,6 @@
1111
Web3,
1212
__version__ as web3py_version,
1313
)
14-
from web3._utils import (
15-
request,
16-
)
1714
from web3.eth import (
1815
Eth,
1916
)
@@ -94,10 +91,10 @@ def test_user_provided_session():
9491
session.mount("https://", adapter)
9592

9693
provider = HTTPProvider(endpoint_uri=URI, session=session)
94+
session = provider._request_session_manager.cache_and_return_session(URI)
9795
w3 = Web3(provider)
9896
assert w3.manager.provider == provider
9997

100-
session = request.cache_and_return_session(URI)
10198
adapter = session.get_adapter(URI)
10299
assert isinstance(adapter, HTTPAdapter)
103100
assert adapter._pool_connections == 20

tests/core/providers/test_http_request_retry.py

Lines changed: 18 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,9 @@ def test_default_request_retry_configuration_for_http_provider():
5252
def test_check_without_retry_config():
5353
w3 = Web3(HTTPProvider(exception_retry_configuration=None))
5454

55-
with patch("web3.providers.rpc.rpc.make_post_request") as make_post_request_mock:
55+
with patch(
56+
"web3.providers.rpc.rpc.RequestSessionManager.make_post_request"
57+
) as make_post_request_mock:
5658
make_post_request_mock.side_effect = Timeout
5759

5860
with pytest.raises(Timeout):
@@ -69,7 +71,10 @@ def test_check_if_retry_on_failure_true():
6971
assert check_if_retry_on_failure(method)
7072

7173

72-
@patch("web3.providers.rpc.rpc.make_post_request", side_effect=ConnectionError)
74+
@patch(
75+
"web3.providers.rpc.rpc.RequestSessionManager.make_post_request",
76+
side_effect=ConnectionError,
77+
)
7378
def test_check_send_transaction_called_once(make_post_request_mock, w3):
7479
with pytest.raises(ConnectionError):
7580
w3.provider.make_request(
@@ -78,7 +83,10 @@ def test_check_send_transaction_called_once(make_post_request_mock, w3):
7883
assert make_post_request_mock.call_count == 1
7984

8085

81-
@patch("web3.providers.rpc.rpc.make_post_request", side_effect=ConnectionError)
86+
@patch(
87+
"web3.providers.rpc.rpc.RequestSessionManager.make_post_request",
88+
side_effect=ConnectionError,
89+
)
8290
def test_valid_method_retried(make_post_request_mock, w3):
8391
with pytest.raises(ConnectionError):
8492
w3.provider.make_request(RPCEndpoint("eth_getBalance"), [f"0x{'00' * 20}"])
@@ -96,7 +104,10 @@ def test_exception_retry_config_is_strictly_on_http_provider():
96104
assert not hasattr(w3.provider, "exception_retry_configuration")
97105

98106

99-
@patch("web3.providers.rpc.rpc.make_post_request", side_effect=ConnectionError)
107+
@patch(
108+
"web3.providers.rpc.rpc.RequestSessionManager.make_post_request",
109+
side_effect=ConnectionError,
110+
)
100111
def test_exception_retry_middleware_with_allow_list_kwarg(make_post_request_mock):
101112
config = ExceptionRetryConfiguration(
102113
errors=(ConnectionError, HTTPError, Timeout, TooManyRedirects),
@@ -148,7 +159,7 @@ async def test_async_default_request_retry_configuration_for_http_provider():
148159
)
149160
async def test_async_check_retry_middleware(async_w3, error):
150161
with patch(
151-
"web3.providers.rpc.async_rpc.async_make_post_request"
162+
"web3.providers.rpc.async_rpc.RequestSessionManager.async_make_post_request"
152163
) as async_make_post_request_mock:
153164
async_make_post_request_mock.side_effect = error
154165

@@ -162,7 +173,7 @@ async def test_async_check_without_retry_config():
162173
w3 = AsyncWeb3(AsyncHTTPProvider(exception_retry_configuration=None))
163174

164175
with patch(
165-
"web3.providers.rpc.async_rpc.async_make_post_request"
176+
"web3.providers.rpc.async_rpc.RequestSessionManager.async_make_post_request"
166177
) as async_make_post_request_mock:
167178
async_make_post_request_mock.side_effect = TimeoutError
168179

@@ -181,7 +192,7 @@ async def test_async_exception_retry_middleware_with_allow_list_kwarg():
181192
async_w3 = AsyncWeb3(AsyncHTTPProvider(exception_retry_configuration=config))
182193

183194
with patch(
184-
"web3.providers.rpc.async_rpc.async_make_post_request"
195+
"web3.providers.rpc.async_rpc.RequestSessionManager.async_make_post_request"
185196
) as async_make_post_request_mock:
186197
async_make_post_request_mock.side_effect = TimeoutError
187198

tests/core/utilities/test_request.py

Lines changed: 39 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -33,8 +33,6 @@
3333
SimpleCache,
3434
)
3535

36-
request_session_manager = request.RequestSessionManager()
37-
3836

3937
class MockedResponse:
4038
def __init__(self, text="", status_code=200):
@@ -69,23 +67,20 @@ def check_adapters_mounted(session: Session):
6967
assert len(session.adapters) == 2
7068

7169

72-
def _simulate_call(uri):
70+
def _simulate_call(request_session_manager, uri):
7371
_session = request_session_manager.cache_and_return_session(uri)
7472

7573
# simulate a call taking 0.01s to return a response
7674
time.sleep(0.01)
7775
return _session
7876

7977

80-
@pytest.fixture(autouse=True)
81-
def setup_and_teardown():
82-
# clear session cache before and after each test
83-
request_session_manager.session_cache.clear()
84-
yield
85-
request_session_manager.session_cache.clear()
78+
@pytest.fixture
79+
def request_session_manager():
80+
return request.RequestSessionManager()
8681

8782

88-
def test_json_make_get_request(mocker):
83+
def test_session_manager_json_make_get_request(mocker, request_session_manager):
8984
mocker.patch("requests.Session.get", return_value=MockedResponse())
9085

9186
# Submit a first request to create a session with default parameters
@@ -105,7 +100,7 @@ def test_json_make_get_request(mocker):
105100
assert adapter._pool_maxsize == DEFAULT_POOLSIZE
106101

107102

108-
def test_make_post_request_no_args(mocker):
103+
def test_session_manager_make_post_request_no_args(mocker, request_session_manager):
109104
mocker.patch("requests.Session.post", return_value=MockedResponse())
110105

111106
# Submit a first request to create a session with default parameters
@@ -125,7 +120,7 @@ def test_make_post_request_no_args(mocker):
125120
assert adapter._pool_maxsize == DEFAULT_POOLSIZE
126121

127122

128-
def test_precached_session(mocker):
123+
def test_session_manager_precached_session(mocker, request_session_manager):
129124
mocker.patch("requests.Session.post", return_value=MockedResponse())
130125

131126
# Update the cache with a handcrafted session
@@ -155,7 +150,7 @@ def test_precached_session(mocker):
155150
assert adapter._pool_maxsize == 100
156151

157152

158-
def test_cache_session_class():
153+
def test_simple_cache_cache_session():
159154
cache = SimpleCache(2)
160155
_, evicted_items = cache.cache("1", "Hello1")
161156
assert cache.get_cache_entry("1") == "Hello1"
@@ -183,7 +178,9 @@ def test_cache_session_class():
183178
assert cache.get_cache_entry("1") is None
184179

185180

186-
def test_cache_does_not_close_session_before_a_call_when_multithreading():
181+
def test_session_manager_cache_does_not_close_session_before_a_call_when_multithreading(
182+
request_session_manager,
183+
):
187184
# save default values
188185
session_cache_default = request_session_manager.session_cache
189186
timeout_default = request.DEFAULT_TIMEOUT
@@ -194,7 +191,10 @@ def test_cache_does_not_close_session_before_a_call_when_multithreading():
194191
request.DEFAULT_TIMEOUT = _timeout_for_testing
195192

196193
with ThreadPoolExecutor(max_workers=len(UNIQUE_URIS)) as exc:
197-
all_sessions = [exc.submit(_simulate_call, uri) for uri in UNIQUE_URIS]
194+
all_sessions = [
195+
exc.submit(_simulate_call, request_session_manager, uri)
196+
for uri in UNIQUE_URIS
197+
]
198198

199199
# assert last session remains in cache, all others evicted
200200
cache_data = request_session_manager.session_cache._data
@@ -212,11 +212,16 @@ def test_cache_does_not_close_session_before_a_call_when_multithreading():
212212
request.DEFAULT_TIMEOUT = timeout_default
213213

214214

215-
def test_unique_cache_keys_created_per_thread_with_same_uri():
215+
def test_session_manager_unique_cache_keys_created_per_thread_with_same_uri(
216+
request_session_manager,
217+
):
216218
# somewhat inspired by issue #2680
217219

218220
with ThreadPoolExecutor(max_workers=2) as exc:
219-
test_sessions = [exc.submit(_simulate_call, TEST_URI) for _ in range(2)]
221+
test_sessions = [
222+
exc.submit(_simulate_call, request_session_manager, TEST_URI)
223+
for _ in range(2)
224+
]
220225

221226
# assert unique keys are generated per thread for the same uri
222227
assert len(request_session_manager.session_cache._data) == 2
@@ -251,7 +256,9 @@ def raise_for_status() -> None:
251256

252257

253258
@pytest.mark.asyncio
254-
async def test_async_json_make_get_request(mocker):
259+
async def test_session_manager_async_json_make_get_request(
260+
mocker, request_session_manager
261+
):
255262
mocker.patch("aiohttp.ClientSession.get", return_value=AsyncMockedResponse())
256263

257264
# Submit a first request to create a session with default parameters
@@ -272,7 +279,7 @@ async def test_async_json_make_get_request(mocker):
272279

273280

274281
@pytest.mark.asyncio
275-
async def test_async_make_post_request(mocker):
282+
async def test_session_manager_async_make_post_request(mocker, request_session_manager):
276283
mocker.patch("aiohttp.ClientSession.post", return_value=AsyncMockedResponse())
277284

278285
# Submit a first request to create a session with default parameters
@@ -296,7 +303,7 @@ async def test_async_make_post_request(mocker):
296303

297304

298305
@pytest.mark.asyncio
299-
async def test_async_precached_session():
306+
async def test_session_manager_async_precached_session(request_session_manager):
300307
# Add a session
301308
session = ClientSession()
302309
await request_session_manager.async_cache_and_return_session(TEST_URI, session)
@@ -322,7 +329,9 @@ async def test_async_precached_session():
322329

323330

324331
@pytest.mark.asyncio
325-
async def test_async_cache_does_not_close_session_before_a_call_when_multithreading():
332+
async def test_session_manager_async_cache_does_not_close_session_before_a_call_when_multithreading( # noqa: E501
333+
request_session_manager,
334+
):
326335
# save default values
327336
session_cache_default = request_session_manager.session_cache
328337
timeout_default = request.DEFAULT_TIMEOUT
@@ -368,7 +377,9 @@ async def cache_uri_and_return_session(uri):
368377

369378

370379
@pytest.mark.asyncio
371-
async def test_async_unique_cache_keys_created_per_thread_with_same_uri():
380+
async def test_session_manager_async_unique_cache_keys_created_per_thread_with_same_uri(
381+
request_session_manager,
382+
):
372383
# inspired by issue #2680
373384
# Note: unique event loops for each thread are important here
374385

@@ -407,7 +418,9 @@ def target_function(endpoint_uri):
407418

408419

409420
@pytest.mark.asyncio
410-
async def test_async_use_new_session_if_loop_closed_for_cached_session():
421+
async def test_session_manager_async_use_new_session_if_loop_closed_for_cached_session(
422+
request_session_manager,
423+
):
411424
# create new loop, cache a session wihin the loop, close the loop
412425
loop1 = asyncio.new_event_loop()
413426

@@ -448,7 +461,9 @@ async def test_async_use_new_session_if_loop_closed_for_cached_session():
448461

449462

450463
@pytest.mark.asyncio
451-
async def test_async_use_new_session_if_session_closed_for_cached_session():
464+
async def test_session_manager_async_use_new_session_if_session_closed_for_cached_session( # noqa: E501
465+
request_session_manager,
466+
):
452467
# create a session, close it, and cache it at the cache key for TEST_URI
453468
session1 = ClientSession(raise_for_status=True)
454469
await session1.close()

web3/providers/rpc/async_rpc.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -55,9 +55,7 @@
5555
class AsyncHTTPProvider(AsyncJSONBaseProvider):
5656
logger = logging.getLogger("web3.providers.AsyncHTTPProvider")
5757
endpoint_uri = None
58-
5958
_request_kwargs = None
60-
_request_session_manager = RequestSessionManager()
6159

6260
def __init__(
6361
self,
@@ -68,6 +66,8 @@ def __init__(
6866
] = empty,
6967
**kwargs: Any,
7068
) -> None:
69+
self._request_session_manager = RequestSessionManager()
70+
7171
if endpoint_uri is None:
7272
self.endpoint_uri = (
7373
self._request_session_manager.get_default_http_endpoint()

web3/providers/rpc/rpc.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -58,9 +58,7 @@
5858
class HTTPProvider(JSONBaseProvider):
5959
logger = logging.getLogger("web3.providers.HTTPProvider")
6060
endpoint_uri = None
61-
6261
_request_kwargs = None
63-
_request_session_manager = RequestSessionManager()
6462

6563
def __init__(
6664
self,
@@ -72,6 +70,8 @@ def __init__(
7270
] = empty,
7371
**kwargs: Any,
7472
) -> None:
73+
self._request_session_manager = RequestSessionManager()
74+
7575
if endpoint_uri is None:
7676
self.endpoint_uri = (
7777
self._request_session_manager.get_default_http_endpoint()

0 commit comments

Comments
 (0)