|
7 | 7 |
|
8 | 8 | import pytest
|
9 | 9 | import vcr
|
| 10 | +import vcr.patch |
10 | 11 |
|
11 | 12 |
|
12 | 13 | def get_request_hash(request):
|
@@ -198,3 +199,40 @@ def vcr_fixture(request):
|
198 | 199 | # Use the cassette for this test
|
199 | 200 | with my_vcr.use_cassette(f"{cassette_name}.yaml"):
|
200 | 201 | yield
|
| 202 | + |
| 203 | + |
| 204 | +original_exit = vcr.patch.ConnectionRemover.__exit__ |
| 205 | + |
| 206 | + |
| 207 | +def safe_exit(self, *args): |
| 208 | + """Create safer ConnectionRemover.__exit__.""" |
| 209 | + for pool, connections in self._connection_pool_to_connections.items(): |
| 210 | + readd_connections = [] |
| 211 | + # Get all connections from the pool first |
| 212 | + while pool.pool and not pool.pool.empty(): |
| 213 | + connection = pool.pool.get() |
| 214 | + if isinstance(connection, self._connection_class): |
| 215 | + try: |
| 216 | + # Use a safer way to remove - check first if it exists |
| 217 | + if connection in connections: |
| 218 | + connections.remove(connection) |
| 219 | + connection.close() |
| 220 | + except (KeyError, RuntimeError): |
| 221 | + # Just close the connection if we can't remove it properly |
| 222 | + connection.close() |
| 223 | + else: |
| 224 | + readd_connections.append(connection) |
| 225 | + |
| 226 | + # Add connections back to the pool |
| 227 | + for connection in readd_connections: |
| 228 | + pool._put_conn(connection) |
| 229 | + |
| 230 | + # Use a copy of the set for iteration to avoid modification issues |
| 231 | + for connection in list(connections): |
| 232 | + try: |
| 233 | + connection.close() |
| 234 | + except Exception: |
| 235 | + pass # Ignore any errors while closing connections |
| 236 | + |
| 237 | + |
| 238 | +vcr.patch.ConnectionRemover.__exit__ = safe_exit |
0 commit comments