1 # This is a pytest hook that skips tests that tries to access the network.
2 # These tests will immediately fail, then get marked as "Expected fail" (xfail).
4 from _pytest
.runner
import pytest_runtest_makereport
as orig_pytest_runtest_makereport
6 # We use BaseException to minimize the chance it gets caught and 'pass'ed
7 class NixNetworkAccessDeniedError(BaseException
):
10 def pytest_runtest_makereport(item
, call
):
12 Modifies test results after-the-fact. The function name is magic, see:
13 https://docs.pytest.org/en/7.1.x/reference/reference.html?highlight=pytest_runtest_makereport#std-hook-pytest_runtest_makereport
16 def iterate_exc_chain(exc
: Exception):
18 Recurses through exception chain, yielding all exceptions
21 if getattr(exc
, "__context__", None) is not None:
22 yield from iterate_exc_chain(exc
.__context
__)
23 if getattr(exc
, "__cause__", None) is not None:
24 yield from iterate_exc_chain(exc
.__cause
__)
26 tr
= orig_pytest_runtest_makereport(item
, call
)
27 if call
.excinfo
is not None:
28 for exc
in iterate_exc_chain(call
.excinfo
.value
):
29 if isinstance(exc
, NixNetworkAccessDeniedError
):
30 tr
.outcome
, tr
.wasxfail
= 'skipped', "reason: Requires network access."
31 if isinstance(exc
, FileNotFoundError
): # gradio specific
32 tr
.outcome
, tr
.wasxfail
= 'skipped', "reason: Pypi dist bad."
35 # replace network access with exception
37 def deny_network_access(*a
, **kw
):
38 raise NixNetworkAccessDeniedError
47 httpx
.AsyncClient
.get
= deny_network_access
48 httpx
.AsyncClient
.head
= deny_network_access
49 httpx
.Request
= deny_network_access
50 requests
.get
= deny_network_access
51 requests
.head
= deny_network_access
52 requests
.post
= deny_network_access
53 socket
.socket
.connect
= deny_network_access
54 urllib
.request
.Request
= deny_network_access
55 urllib
.request
.urlopen
= deny_network_access
56 urllib3
.connection
.HTTPSConnection
._new
_conn
= deny_network_access
57 websockets
.connect
= deny_network_access