Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix ResourceWarning unclosed socket and re-enable and fix tornado tests #801

Merged
merged 28 commits into from
Jan 23, 2024
Merged
Show file tree
Hide file tree
Changes from 19 commits
Commits
Show all changes
28 commits
Select commit Hold shift + click to select a range
f414435
Fix ResourceWarning unclosed socket
Aug 7, 2023
17c78bf
Merge branch 'master' of github.com:kevin1024/vcrpy into fix-resource…
graingert Dec 15, 2023
556fd01
enable filterwarnings=error
graingert Dec 15, 2023
fa789e9
fix a KeyError
graingert Dec 15, 2023
bddec2e
use socketserver.ThreadingTCPServer as a contextmanager
graingert Dec 15, 2023
3919cb2
remember to close the VCRHTTPSConnection
graingert Dec 15, 2023
f075c8b
close aiohttp session on errors
graingert Dec 15, 2023
895ae20
use asyncio.run to run coroutines
graingert Dec 15, 2023
97de8a0
ignore warning from dateutil
graingert Dec 15, 2023
73d11e8
fix httpx resource warnings
graingert Dec 15, 2023
cf76592
remove redundant contextlib import
graingert Dec 15, 2023
356ff41
fix sync do_request().stream
graingert Dec 15, 2023
80614db
fix resource warning due to pytest-asyncio
graingert Dec 15, 2023
5cff354
Revert "fix a KeyError"
graingert Dec 15, 2023
d76c243
Revert "Fix ResourceWarning unclosed socket"
graingert Dec 15, 2023
d39c26b
remember to close removed connections
graingert Dec 15, 2023
8e13af2
use context manager for requests.Session
graingert Dec 15, 2023
cc4d03c
close unremoved connections (pool already removed the connection)
graingert Dec 15, 2023
ee6e790
Merge branch 'master' into fix-resource-warning-2
graingert Dec 15, 2023
5104b1f
Merge branch 'master' of github.com:kevin1024/vcrpy into fix-resource…
graingert Jan 23, 2024
666686b
restore pytest-tornado
graingert Jan 23, 2024
a093fb1
add new deprecation warnings for tornado tests
graingert Jan 23, 2024
c6667ac
restore scheme fixture for tests
graingert Jan 23, 2024
db1f5b0
tornado 6 changes raise_error behaviour
graingert Jan 23, 2024
6d7a842
fix test_tornado_exception_can_be_caught RuntimeError: generator rais…
graingert Jan 23, 2024
b7f6c2f
mark tornado tests as online
graingert Jan 23, 2024
42b4a5d
move off of mockbin on tornado tests also
graingert Jan 23, 2024
784b2dc
tornado test_redirects is no longer an online test
graingert Jan 23, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
8 changes: 8 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,15 @@ ignore-regex = "\\\\[fnrstv]"
# ignore-words-list = ''

[tool.pytest.ini_options]
addopts = [
"--strict-config",
"--strict-markers",
]
markers = ["online"]
filterwarnings = [
"error",
'''ignore:datetime\.datetime\.utcfromtimestamp\(\) is deprecated and scheduled for removal in a future version.*:DeprecationWarning'''
]
graingert marked this conversation as resolved.
Show resolved Hide resolved

[tool.ruff]
select = [
Expand Down
36 changes: 18 additions & 18 deletions tests/integration/aiohttp_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,24 +5,24 @@


async def aiohttp_request(loop, method, url, output="text", encoding="utf-8", content_type=None, **kwargs):
session = aiohttp.ClientSession(loop=loop)
response_ctx = session.request(method, url, **kwargs)

response = await response_ctx.__aenter__()
if output == "text":
content = await response.text()
elif output == "json":
content_type = content_type or "application/json"
content = await response.json(encoding=encoding, content_type=content_type)
elif output == "raw":
content = await response.read()
elif output == "stream":
content = await response.content.read()

response_ctx._resp.close()
await session.close()

return response, content
async with aiohttp.ClientSession(loop=loop) as session:
response_ctx = session.request(method, url, **kwargs)

response = await response_ctx.__aenter__()
if output == "text":
content = await response.text()
elif output == "json":
content_type = content_type or "application/json"
content = await response.json(encoding=encoding, content_type=content_type)
elif output == "raw":
content = await response.read()
elif output == "stream":
content = await response.content.read()

response_ctx._resp.close()
await session.close()

return response, content


def aiohttp_app():
Expand Down
15 changes: 10 additions & 5 deletions tests/integration/test_aiohttp.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import contextlib
import logging
import urllib.parse

Expand All @@ -14,10 +13,10 @@


def run_in_loop(fn):
with contextlib.closing(asyncio.new_event_loop()) as loop:
asyncio.set_event_loop(loop)
task = loop.create_task(fn(loop))
return loop.run_until_complete(task)
async def wrapper():
return await fn(asyncio.get_running_loop())

return asyncio.run(wrapper())


def request(method, url, output="text", **kwargs):
Expand Down Expand Up @@ -260,6 +259,12 @@ def test_aiohttp_test_client_json(aiohttp_client, tmpdir):
assert cassette.play_count == 1


def test_cleanup_from_pytest_asyncio():
# work around https://github.com/pytest-dev/pytest-asyncio/issues/724
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

asyncio.get_event_loop().close()
asyncio.set_event_loop(None)


@pytest.mark.online
def test_redirect(tmpdir, httpbin):
url = httpbin.url + "/redirect/2"
Expand Down
26 changes: 19 additions & 7 deletions tests/integration/test_httpx.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,25 +28,37 @@ class DoSyncRequest(BaseDoRequest):
_client_class = httpx.Client

def __enter__(self):
self._client = self._make_client()
return self

def __exit__(self, *args):
pass
self._client.close()
del self._client

@property
def client(self):
try:
return self._client
except AttributeError:
self._client = self._make_client()
return self._client
except AttributeError as e:
raise ValueError('To access sync client, use "with do_request() as client"') from e

def __call__(self, *args, **kwargs):
return self.client.request(*args, timeout=60, **kwargs)
if hasattr(self, "_client"):
return self.client.request(*args, timeout=60, **kwargs)

# Use one-time context and dispose of the client afterwards
with self:
return self.client.request(*args, timeout=60, **kwargs)

def stream(self, *args, **kwargs):
with self.client.stream(*args, **kwargs) as response:
return b"".join(response.iter_bytes())
if hasattr(self, "_client"):
with self.client.stream(*args, **kwargs) as response:
return b"".join(response.iter_bytes())

# Use one-time context and dispose of the client afterwards
with self:
with self.client.stream(*args, **kwargs) as response:
return b"".join(response.iter_bytes())


class DoAsyncRequest(BaseDoRequest):
Expand Down
12 changes: 6 additions & 6 deletions tests/integration/test_proxy.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,12 +39,12 @@ def do_GET(self):

@pytest.fixture(scope="session")
def proxy_server():
httpd = socketserver.ThreadingTCPServer(("", 0), Proxy)
proxy_process = threading.Thread(target=httpd.serve_forever)
proxy_process.start()
yield "http://{}:{}".format(*httpd.server_address)
httpd.shutdown()
proxy_process.join()
with socketserver.ThreadingTCPServer(("", 0), Proxy) as httpd:
proxy_process = threading.Thread(target=httpd.serve_forever)
proxy_process.start()
yield "http://{}:{}".format(*httpd.server_address)
httpd.shutdown()
proxy_process.join()


def test_use_proxy(tmpdir, httpbin, proxy_server):
Expand Down
10 changes: 5 additions & 5 deletions tests/integration/test_wild.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,12 +63,12 @@ def test_flickr_should_respond_with_200(tmpdir):
def test_cookies(tmpdir, httpbin):
testfile = str(tmpdir.join("cookies.yml"))
with vcr.use_cassette(testfile):
s = requests.Session()
s.get(httpbin.url + "/cookies/set?k1=v1&k2=v2")
assert s.cookies.keys() == ["k1", "k2"]
with requests.Session() as s:
s.get(httpbin.url + "/cookies/set?k1=v1&k2=v2")
assert s.cookies.keys() == ["k1", "k2"]

r2 = s.get(httpbin.url + "/cookies")
assert sorted(r2.json()["cookies"].keys()) == ["k1", "k2"]
r2 = s.get(httpbin.url + "/cookies")
assert sorted(r2.json()["cookies"].keys()) == ["k1", "k2"]


@pytest.mark.online
Expand Down
9 changes: 5 additions & 4 deletions tests/unit/test_stubs.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import contextlib
from unittest import mock

from pytest import mark
Expand All @@ -16,7 +17,7 @@ def test_setting_of_attributes_get_propagated_to_real_connection(self):
@mark.online
@mock.patch("vcr.cassette.Cassette.can_play_response_for", return_value=False)
def testing_connect(*args):
vcr_connection = VCRHTTPSConnection("www.google.com")
vcr_connection.cassette = Cassette("test", record_mode=mode.ALL)
vcr_connection.real_connection.connect()
assert vcr_connection.real_connection.sock is not None
with contextlib.closing(VCRHTTPSConnection("www.google.com")) as vcr_connection:
vcr_connection.cassette = Cassette("test", record_mode=mode.ALL)
vcr_connection.real_connection.connect()
assert vcr_connection.real_connection.sock is not None
7 changes: 3 additions & 4 deletions vcr/patch.py
Original file line number Diff line number Diff line change
Expand Up @@ -372,10 +372,6 @@ def add_connection_to_pool_entry(self, pool, connection):
if isinstance(connection, self._connection_class):
self._connection_pool_to_connections.setdefault(pool, set()).add(connection)

def remove_connection_to_pool_entry(self, pool, connection):
if isinstance(connection, self._connection_class):
self._connection_pool_to_connections[self._connection_class].remove(connection)

def __enter__(self):
return self

Expand All @@ -386,10 +382,13 @@ def __exit__(self, *args):
connection = pool.pool.get()
if isinstance(connection, self._connection_class):
connections.remove(connection)
connection.close()
else:
readd_connections.append(connection)
for connection in readd_connections:
pool._put_conn(connection)
for connection in connections:
connection.close()


def reset_patchers():
Expand Down