[Git][debian-gis-team/pytest-recording][upstream] New upstream version 0.14.1
Antonio Valentino (@antonio.valentino)
gitlab at salsa.debian.org
Sat Nov 7 15:15:33 GMT 2026
Antonio Valentino pushed to branch upstream at Debian GIS Project / pytest-recording
Commits:
181227e6 by Antonio Valentino at 2026-11-07T15:10:25+00:00
New upstream version 0.14.1
- - - - -
11 changed files:
- .github/workflows/build.yml
- .github/workflows/commit.yml
- .github/workflows/release.yml
- README.rst
- + SECURITY.md
- docs/changelog.rst
- pyproject.toml
- src/pytest_recording/network.py
- tests/test_blocking_network.py
- tests/test_plugin.py
- tests/test_recording.py
Changes:
=====================================
.github/workflows/build.yml
=====================================
@@ -16,30 +16,30 @@ on:
jobs:
pre-commit:
name: Generic pre-commit checks
- runs-on: ubuntu-24.04
+ runs-on: ubuntu-26.04
steps:
- - uses: actions/checkout at v6
+ - uses: actions/checkout at v7
with:
fetch-depth: 1
- - uses: actions/setup-python at v6
+ - uses: actions/setup-python at v7
with:
- python-version: 3.x
+ python-version: "3.15"
- run: pip install pre-commit
- run: SKIP=mypy pre-commit run --all-files
mypy:
name: Mypy
- runs-on: ubuntu-24.04
+ runs-on: ubuntu-26.04
steps:
- - uses: actions/checkout at v6
+ - uses: actions/checkout at v7
with:
fetch-depth: 1
- - uses: actions/setup-python at v6
+ - uses: actions/setup-python at v7
with:
- python-version: 3.x
+ python-version: "3.15"
- run: pip install pre-commit
- run: pre-commit run mypy --all-files
@@ -72,9 +72,7 @@ jobs:
python: "3.15"
os_version: "ubuntu-24.04"
- - tox_job: pypy3-no_pycurl
- python: "pypy3.11"
- os_version: "windows-2022"
+ # No PyPy on Windows: brotlicffi (needed by pytest-httpbin) fails to import there
- tox_job: py310
python: "3.10"
os_version: "windows-2022"
@@ -95,11 +93,11 @@ jobs:
os_version: "windows-2022"
steps:
- - uses: actions/checkout at v6
+ - uses: actions/checkout at v7
with:
fetch-depth: 1
- - uses: actions/setup-python at v6
+ - uses: actions/setup-python at v7
with:
python-version: ${{ matrix.python }}
allow-prereleases: true
@@ -118,6 +116,6 @@ jobs:
- run: coverage xml -i
- name: Upload coverage to Codecov
- uses: codecov/codecov-action at v7.0.0
+ uses: codecov/codecov-action at v7.1.1
with:
file: ./coverage.xml
=====================================
.github/workflows/commit.yml
=====================================
@@ -12,7 +12,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Check out code
- uses: actions/checkout at v6
+ uses: actions/checkout at v7
with:
fetch-depth: 0
- name: Run commitsar
=====================================
.github/workflows/release.yml
=====================================
@@ -11,7 +11,7 @@ jobs:
steps:
- uses: actions/checkout at master
- name: Set up Python 3
- uses: actions/setup-python at v6
+ uses: actions/setup-python at v7
with:
python-version: 3.x
=====================================
README.rst
=====================================
@@ -186,7 +186,7 @@ To have more confidence that your tests will not go over the wire, you can block
...
# in case of access
- RuntimeError: Network is disabled
+ RuntimeError: Network is disabled for host '...'
Besides marks, the network access could be blocked globally with ``--block-network`` command-line option.
@@ -221,7 +221,7 @@ It is possible to allow access to specified hosts during network blocking:
@pytest.mark.block_network(allowed_hosts=["httpbin.*"])
def test_access():
assert requests.get("http://httpbin.org/get").text == '{"get": true}'
- with pytest.raises(RuntimeError, match=r"^Network is disabled$"):
+ with pytest.raises(RuntimeError, match=r"^Network is disabled for host "):
requests.get("http://example.com")
Or via command-line option:
=====================================
SECURITY.md
=====================================
@@ -0,0 +1,24 @@
+# Security Policy
+
+## Supported Versions
+
+Only the latest release gets security fixes.
+
+## Reporting a Vulnerability
+
+[Open a private security advisory](https://github.com/kiwicom/pytest-recording/security/advisories/new)
+or email dmitry at dygalo.dev. Do not open a public issue.
+
+Include:
+
+- the affected version
+- steps to reproduce or a proof of concept
+- a suggested fix, if you have one
+
+Expect a first reply within a few days.
+
+## Disclosure
+
+Security fixes ship in regular patch releases, and the [changelog](docs/changelog.rst) lists them.
+After the fix is released, you may publish your findings.
+I publish a GitHub security advisory and request a CVE when the issue warrants one.
=====================================
docs/changelog.rst
=====================================
@@ -6,6 +6,12 @@ Changelog
`Unreleased`_
-------------
+`0.14.1`_ - 2026-11-02
+----------------------
+
+- Allow ``socket.socketpair()`` inside the blocking context, so asyncio event loops can be built on Windows. `#212`_
+- Include the blocked host in the ``Network is disabled`` error message. `#190`_
+
`0.14.0`_ - 2026-10-02
----------------------
@@ -222,7 +228,8 @@ Added
- Initial public release
-.. _Unreleased: https://github.com/kiwicom/pytest-recording/compare/v0.14.0...HEAD
+.. _Unreleased: https://github.com/kiwicom/pytest-recording/compare/v0.14.1...HEAD
+.. _0.14.1: https://github.com/kiwicom/pytest-recording/compare/v0.14.0...v0.14.1
.. _0.14.0: https://github.com/kiwicom/pytest-recording/compare/v0.13.4...v0.14.0
.. _0.13.4: https://github.com/kiwicom/pytest-recording/compare/v0.13.3...v0.13.4
.. _0.13.3: https://github.com/kiwicom/pytest-recording/compare/v0.13.2...v0.13.3
@@ -251,9 +258,11 @@ Added
.. _0.2.0: https://github.com/kiwicom/pytest-recording/compare/v0.1.0...v0.2.0
.. _#205: https://github.com/kiwicom/pytest-recording/pull/205
+.. _#190: https://github.com/kiwicom/pytest-recording/pull/190
.. _#185: https://github.com/kiwicom/pytest-recording/pull/185
.. _#174: https://github.com/kiwicom/pytest-recording/issues/174
.. _#172: https://github.com/kiwicom/pytest-recording/issues/172
+.. _#212: https://github.com/kiwicom/pytest-recording/issues/212
.. _#170: https://github.com/kiwicom/pytest-recording/issues/170
.. _#145: https://github.com/kiwicom/pytest-recording/issues/145
.. _#118: https://github.com/kiwicom/pytest-recording/pull/118
=====================================
pyproject.toml
=====================================
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
[project]
name = "pytest-recording"
-version = "0.14.0"
+version = "0.14.1"
description = "A pytest plugin powered by VCR.py to record and replay HTTP traffic"
keywords = ["pytest", "vcr", "network", "mock"]
authors = [{ name = "Dmitry Dygalo", email = "dmitry at dygalo.dev" }]
@@ -41,7 +41,7 @@ tests = [
"pytest-httpbin",
"pytest-mock",
"requests",
- "Werkzeug==3.1.8"
+ "Werkzeug==3.1.9"
]
dev = ["pytest_recording[tests]"]
=====================================
src/pytest_recording/network.py
=====================================
@@ -1,6 +1,7 @@
import re
import socket
import sys
+import threading
from contextlib import contextmanager
from dataclasses import dataclass, field
from typing import Any, Callable, Iterator, List, Optional, Tuple, Union
@@ -25,7 +26,7 @@ try:
host = urlparse(self.url).hostname
if not host or is_host_in_allowed_hosts(host, _allowed_hosts):
return getattr(handle, item)
- raise RuntimeError("Network is disabled")
+ raise RuntimeError(f"Network is disabled for host {host!r}")
if item == "handle":
return handle
if item == "setopt":
@@ -51,6 +52,21 @@ except ImportError:
# But methods that could connect to remote are patched to prevent network access
_original_connect = socket.socket.connect
_original_connect_ex = socket.socket.connect_ex
+_original_socketpair = socket.socketpair
+
+# `socket.socketpair()` is emulated on Windows with a real loopback `connect()`, and asyncio builds
+# every event loop's self-pipe that way. Without an exemption the guard blocks the event loop
+# itself instead of the network, so the whole asyncio suite dies at setup.
+#
+# The exemption is set only while a `socketpair()` call is running, and it is thread-local: a
+# plain module-level flag would also unblock every other thread's connections for the duration of
+# that call, and a test suite running thread pools would silently lose the guard.
+_socketpair_state = threading.local()
+
+
+def _inside_socketpair() -> bool:
+ return getattr(_socketpair_state, "active", False)
+
# Global switch for pycurl disabling
_disable_pycurl = False
@@ -102,18 +118,34 @@ def unblock_pycurl() -> None:
_allowed_hosts = None
+def make_socketpair_guard(original_func: Callable) -> Callable:
+ def socketpair_guard(*args: Any, **kwargs: Any) -> Tuple[Any, Any]:
+ previous = getattr(_socketpair_state, "active", False)
+ _socketpair_state.active = True
+ try:
+ return original_func(*args, **kwargs)
+ finally:
+ _socketpair_state.active = previous
+
+ return socketpair_guard
+
+
def block_socket(allowed_hosts: Optional[List[str]] = None) -> None:
socket.socket.connect = make_network_guard(_original_connect, allowed_hosts=allowed_hosts) # type: ignore
socket.socket.connect_ex = make_network_guard(_original_connect_ex, allowed_hosts=allowed_hosts) # type: ignore
+ socket.socketpair = make_socketpair_guard(_original_socketpair) # type: ignore
def unblock_socket() -> None:
socket.socket.connect = _original_connect # type: ignore
socket.socket.connect_ex = _original_connect_ex # type: ignore
+ socket.socketpair = _original_socketpair # type: ignore
def make_network_guard(original_func: Callable, allowed_hosts: Optional[List[str]] = None) -> Callable:
def network_guard(self: Any, address: Union[Tuple, str, bytes], *args: Any, **kwargs: Any) -> Any:
+ if _inside_socketpair():
+ return original_func(self, address, *args, **kwargs)
host = "" # type: Union[str, bytes, bytearray]
if self.family in (socket.AF_INET, socket.AF_INET6):
host = address[0] # type: ignore
@@ -121,7 +153,7 @@ def make_network_guard(original_func: Callable, allowed_hosts: Optional[List[str
host = address # type: ignore
if is_host_in_allowed_hosts(host, allowed_hosts):
return original_func(self, address, *args, **kwargs)
- raise RuntimeError("Network is disabled")
+ raise RuntimeError(f"Network is disabled for host {host!r}")
return network_guard
=====================================
tests/test_blocking_network.py
=====================================
@@ -1,5 +1,7 @@
+import asyncio
import json
import sys
+import threading
from io import BytesIO
from socket import AF_INET, SOCK_RAW, SOCK_STREAM, socket
@@ -8,6 +10,7 @@ import requests
import vcr.errors
from packaging import version
+from pytest_recording import network
from pytest_recording.network import blocking_context
# Windows doesn’t have AF_NETLINK & AF_UNIX
@@ -59,7 +62,7 @@ def test_recording(httpbin):
@pytest.mark.block_network
def test_error(httpbin):
- with pytest.raises(RuntimeError, match=r"^Network is disabled$"):
+ with pytest.raises(RuntimeError, match=r"^Network is disabled for host '127.0.0.1'$"):
assert requests.get(httpbin.url + "/ip").status_code == 200
"""
)
@@ -88,7 +91,7 @@ def test_recording(httpbin):
@pytest.mark.block_network
def test_error(httpbin):
- with pytest.raises(RuntimeError, match=r"^Network is disabled$"):
+ with pytest.raises(RuntimeError, match=r"^Network is disabled for host '127.0.0.1'$"):
assert requests.get(httpbin.url + "/ip").status_code == 200
"""
)
@@ -112,7 +115,7 @@ def test_recording(httpbin):
@pytest.mark.block_network
def test_error(httpbin):
- with pytest.raises(RuntimeError, match=r"^Network is disabled$"):
+ with pytest.raises(RuntimeError, match=r"^Network is disabled for host '127.0.0.1'$"):
assert requests.get(httpbin.url + "/ip").status_code == 200
"""
)
@@ -141,7 +144,7 @@ import pytest
@pytest.mark.block_network
def test_no_blocking(httpbin):
_, port = httpbin.url.rsplit(":", 1)
- with pytest.raises(RuntimeError, match=r"^Network is disabled$"):
+ with pytest.raises(RuntimeError, match=r"^Network is disabled for host '127.0.0.1'$"):
call(int(port))
"""
)
@@ -170,7 +173,7 @@ def test_block_network_allowed_socket():
@skip_unix
@pytest.mark.block_network(allowed_hosts=["./allowed_socket"])
def test_block_network_blocked_socket():
- with pytest.raises(RuntimeError, match=r"^Network is disabled$"):
+ with pytest.raises(RuntimeError, match=r"^Network is disabled for host './blocked_socket'$"):
call("./blocked_socket", AF_UNIX, SOCK_STREAM)
@@ -179,7 +182,7 @@ def test_block_network_blocked_socket():
@skip_netlink
@pytest.mark.block_network(allowed_hosts=["./allowed_socket", "127.0.0.1", "0"])
def test_blocked():
- with pytest.raises(RuntimeError, match=r"^Network is disabled$"):
+ with pytest.raises(RuntimeError, match=r"^Network is disabled for host ''$"):
call((0, 0), AF_NETLINK, SOCK_RAW)
@@ -189,7 +192,7 @@ def test_blocked():
@pytest.mark.block_network
@pytest.mark.vcr
def test_with_vcr_mark(httpbin):
- with pytest.raises(vcr.errors.CannotOverwriteExistingCassetteException, match=r"overwrite existing cassette"):
+ with pytest.raises(vcr.errors.CannotOverwriteExistingCassetteException):
requests.get(httpbin.url + "/ip")
assert socket.connect.__name__ == "network_guard"
assert socket.connect_ex.__name__ == "network_guard"
@@ -197,20 +200,20 @@ def test_with_vcr_mark(httpbin):
@pytest.mark.block_network
def test_no_vcr_mark(httpbin):
- with pytest.raises(RuntimeError, match=r"^Network is disabled$"):
+ with pytest.raises(RuntimeError, match=r"^Network is disabled for host '127.0.0.1'$"):
requests.get(httpbin.url + "/ip")
@pytest.mark.block_network(allowed_hosts=["127.0.0.2"])
def test_no_vcr_mark_bytes():
- with pytest.raises(RuntimeError, match=r"^Network is disabled$"):
+ with pytest.raises(RuntimeError, match=r"^Network is disabled for host b'127.0.0.1'$"):
with socket(AF_INET, SOCK_STREAM) as sock:
sock.connect((b"127.0.0.1", 80))
@pytest.mark.block_network(allowed_hosts=["127.0.0.2"])
def test_no_vcr_mark_bytearray():
- with pytest.raises(RuntimeError, match=r"^Network is disabled$"):
+ with pytest.raises(RuntimeError, match=r"^Network is disabled for host bytearray\(b'127.0.0.1'\)$"):
with socket(AF_INET, SOCK_STREAM) as sock:
sock.connect((bytearray(b"127.0.0.1"), 80))
@@ -256,7 +259,7 @@ def test_allowed(httpbin):
{marker}
def test_blocked():
- with pytest.raises(RuntimeError, match="^Network is disabled$"):
+ with pytest.raises(RuntimeError, match="^Network is disabled for host "):
requests.get("http://example.com")
assert socket.socket.connect.__name__ == "network_guard"
assert socket.socket.connect_ex.__name__ == "network_guard"
@@ -281,14 +284,14 @@ import vcr.errors
@pytest.mark.vcr
def test_with_vcr_mark(httpbin):
- with pytest.raises(vcr.errors.CannotOverwriteExistingCassetteException, match=r"overwrite existing cassette"):
+ with pytest.raises(vcr.errors.CannotOverwriteExistingCassetteException):
requests.get(httpbin.url + "/ip")
assert socket.socket.connect.__name__ == "network_guard"
assert socket.socket.connect_ex.__name__ == "network_guard"
def test_no_vcr_mark(httpbin):
- with pytest.raises(RuntimeError, match=r"^Network is disabled$"):
+ with pytest.raises(RuntimeError, match=r"^Network is disabled for host '127.0.0.1'$"):
requests.get(httpbin.url + "/ip")
"""
)
@@ -312,7 +315,7 @@ def test_recording(httpbin):
assert requests.get(httpbin.url + "/ip").status_code == 200
def test_no_vcr_mark(httpbin):
- with pytest.raises(RuntimeError, match=r"^Network is disabled$"):
+ with pytest.raises(RuntimeError, match=r"^Network is disabled for host '127.0.0.1'$"):
requests.get(httpbin.url + "/ip")
"""
)
@@ -335,7 +338,7 @@ def test_pycurl_error(httpbin):
c = pycurl.Curl()
c.setopt(c.URL, httpbin.url + "/ip") # type: ignore[attr-defined]
c.setopt(c.WRITEDATA, buffer) # type: ignore[attr-defined]
- with pytest.raises(RuntimeError, match=r"^Network is disabled$"):
+ with pytest.raises(RuntimeError, match=r"^Network is disabled for host '127.0.0.1'$"):
c.perform()
c.close()
@@ -374,7 +377,7 @@ def test_pycurl_with_allowed_hosts_blocked(httpbin):
c = pycurl.Curl()
c.setopt(c.URL, "http://example.com") # type: ignore[attr-defined]
c.setopt(c.WRITEDATA, buffer) # type: ignore[attr-defined]
- with pytest.raises(RuntimeError, match=r"^Network is disabled$"):
+ with pytest.raises(RuntimeError, match=r"^Network is disabled for host 'example.com'$"):
c.perform()
c.close()
@@ -450,3 +453,75 @@ def test_request():
result.assert_outcomes(error=1)
expected = "Invalid arguments to `block_network`. It accepts only the following keyword arguments: `allowed_hosts`."
assert expected in result.stdout.str()
+
+
+def test_socketpair_is_allowed_while_network_is_blocked():
+ # `socketpair()` is emulated on Windows with a real loopback `connect()`, which the guard used
+ # to reject - the socket is in-process, so it must not count as network access.
+ with blocking_context():
+ left, right = network.socket.socketpair()
+ try:
+ left.sendall(b"ping")
+ assert right.recv(4) == b"ping"
+ finally:
+ left.close()
+ right.close()
+
+ # A real remote connect is still blocked.
+ probe = socket(AF_INET, SOCK_STREAM)
+ try:
+ with pytest.raises(RuntimeError, match="Network is disabled"):
+ probe.connect(("192.0.2.1", 80))
+ finally:
+ probe.close()
+
+
+ at pytest.mark.skipif(sys.platform != "win32", reason="only Windows builds the self-pipe from socketpair()")
+def test_event_loop_can_be_created_while_network_is_blocked():
+ # asyncio builds every event loop's self-pipe with socketpair(), so before the guard exempted
+ # it, every asyncio test died at setup with "Network is disabled".
+ with blocking_context():
+ loop = asyncio.new_event_loop()
+ loop.close()
+
+
+def test_socketpair_exemption_does_not_leak_to_other_threads(monkeypatch):
+ # The exemption is thread-local on purpose: a module-level flag would unblock every other
+ # thread's connections for as long as one thread sits inside `socketpair()`.
+ started = threading.Event()
+ release = threading.Event()
+ real_socketpair = network._original_socketpair
+
+ def slow_socketpair(*args, **kwargs):
+ started.set()
+ assert release.wait(10), "main thread never released the socketpair call"
+ return real_socketpair(*args, **kwargs)
+
+ monkeypatch.setattr(network, "_original_socketpair", slow_socketpair)
+
+ made: "list[tuple[socket, socket]]" = []
+
+ def worker_target() -> None:
+ made.append(network.socket.socketpair())
+
+ worker = threading.Thread(target=worker_target)
+
+ with blocking_context():
+ worker.start()
+ assert started.wait(10), "worker never entered socketpair()"
+ try:
+ # While that call is in flight, this thread is still not allowed to connect.
+ probe = socket(AF_INET, SOCK_STREAM)
+ try:
+ with pytest.raises(RuntimeError, match="Network is disabled"):
+ probe.connect(("192.0.2.1", 80))
+ finally:
+ probe.close()
+ finally:
+ release.set()
+ worker.join(10)
+
+ assert not worker.is_alive()
+ left, right = made[0]
+ left.close()
+ right.close()
=====================================
tests/test_plugin.py
=====================================
@@ -27,12 +27,7 @@ def test_help_message(testdir):
result.stdout.fnmatch_lines(["recording:", "*--record-mode=*", "*VCR.py record mode.*"])
-def test_pytest_vcr_incompatibility(testdir, mocker):
- try:
- mocker.patch("pluggy._manager.PluginManager.has_plugin", return_value=True)
- except (AttributeError, ImportError):
- # Older `pluggy`
- mocker.patch("pluggy.manager.PluginManager.has_plugin", return_value=True)
+def test_pytest_vcr_incompatibility(testdir):
testdir.makepyfile(
"""
def test_():
@@ -40,8 +35,8 @@ def test_pytest_vcr_incompatibility(testdir, mocker):
"""
)
- # Record mode depends on the passed CMD arguments
- result = testdir.runpytest()
+ # `pytest-vcr` registers its plugin as `vcr`
+ result = testdir.runpytest("-p", "vcr")
assert (
"INTERNALERROR> RuntimeError: `pytest-recording` is incompatible with `pytest-vcr`. "
"Please, uninstall `pytest-vcr` in order to use `pytest-recording`." in result.errlines
=====================================
tests/test_recording.py
=====================================
@@ -512,6 +512,7 @@ import requests
[
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' * 5,
],
+ ids=str,
)
def test_with_parametrize(httpbin,data):
assert requests.get(httpbin.url + "/get").status_code == 200
View it on GitLab: https://salsa.debian.org/debian-gis-team/pytest-recording/-/commit/181227e6430bc479ed1615dd885a5638d65f043f
--
View it on GitLab: https://salsa.debian.org/debian-gis-team/pytest-recording/-/commit/181227e6430bc479ed1615dd885a5638d65f043f
You're receiving this email because of your account on salsa.debian.org. Manage all notifications: https://salsa.debian.org/-/profile/notifications | Help: https://salsa.debian.org/help
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://alioth-lists.debian.net/pipermail/pkg-grass-devel/attachments/20261107/e1e1b0fe/attachment-0001.htm>
More information about the Pkg-grass-devel
mailing list