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).
3
4from _pytest.runner import pytest_runtest_makereport as orig_pytest_runtest_makereport
5
6# We use BaseException to minimize the chance it gets caught and 'pass'ed
7class NixNetworkAccessDeniedError(BaseException):
8 pass
9
10def pytest_runtest_makereport(item, call):
11 """
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
14 """
15
16 def iterate_exc_chain(exc: Exception):
17 """
18 Recurses through exception chain, yielding all exceptions
19 """
20 yield exc
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__)
25
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, httpx.ConnectError):
32 tr.outcome, tr.wasxfail = 'skipped', "reason: Requires network access."
33 if isinstance(exc, FileNotFoundError): # gradio specific
34 tr.outcome, tr.wasxfail = 'skipped', "reason: Pypi dist bad."
35 return tr
36
37# replace network access with exception
38
39def deny_network_access(*a, **kw):
40 raise NixNetworkAccessDeniedError
41
42import httpx
43import requests
44import socket
45import urllib
46import urllib3
47import websockets
48
49httpx.AsyncClient.get = deny_network_access
50httpx.AsyncClient.head = deny_network_access
51httpx.Request = deny_network_access
52requests.get = deny_network_access
53requests.head = deny_network_access
54requests.post = deny_network_access
55socket.socket.connect = deny_network_access
56urllib.request.Request = deny_network_access
57urllib.request.urlopen = deny_network_access
58urllib3.connection.HTTPSConnection._new_conn = deny_network_access
59websockets.connect = deny_network_access