MCPcopy Create free account
hub / github.com/huggingface/evaluate / offline

Function offline

tests/utils.py:225–275  ·  view source on GitHub ↗

Simulate offline mode. There are three offline simulatiom modes: CONNECTION_FAILS (default mode): a ConnectionError is raised for each network call. Connection errors are created by mocking socket.socket CONNECTION_TIMES_OUT: the connection hangs until it times out.

(mode=OfflineSimulationMode.CONNECTION_FAILS, timeout=1e-16)

Source from the content-addressed store, hash-verified

223
224@contextmanager
225def offline(mode=OfflineSimulationMode.CONNECTION_FAILS, timeout=1e-16):
226 """
227 Simulate offline mode.
228
229 There are three offline simulatiom modes:
230
231 CONNECTION_FAILS (default mode): a ConnectionError is raised for each network call.
232 Connection errors are created by mocking socket.socket
233 CONNECTION_TIMES_OUT: the connection hangs until it times out.
234 The default timeout value is low (1e-16) to speed up the tests.
235 Timeout errors are created by mocking requests.request
236 HF_EVALUATE_OFFLINE_SET_TO_1: the HF_EVALUATE_OFFLINE environment variable is set to 1.
237 This makes the http/ftp calls of the library instantly fail and raise an OfflineModeEmabled error.
238 """
239 from requests import request as online_request
240
241 def timeout_request(method, url, **kwargs):
242 # Change the url to an invalid url so that the connection hangs
243 invalid_url = "https://10.255.255.1"
244 if kwargs.get("timeout") is None:
245 raise RequestWouldHangIndefinitelyError(
246 f"Tried a call to {url} in offline mode with no timeout set. Please set a timeout."
247 )
248 kwargs["timeout"] = timeout
249 try:
250 return online_request(method, invalid_url, **kwargs)
251 except Exception as e:
252 # The following changes in the error are just here to make the offline timeout error prettier
253 e.request.url = url
254 max_retry_error = e.args[0]
255 max_retry_error.args = (max_retry_error.args[0].replace("10.255.255.1", f"OfflineMock[{url}]"),)
256 e.args = (max_retry_error,)
257 raise
258
259 def offline_socket(*args, **kwargs):
260 raise OSError("Offline mode is enabled.")
261
262 if mode is OfflineSimulationMode.CONNECTION_FAILS:
263 # inspired from https://stackoverflow.com/a/18601897
264 with patch("socket.socket", offline_socket):
265 yield
266 elif mode is OfflineSimulationMode.CONNECTION_TIMES_OUT:
267 # inspired from https://stackoverflow.com/a/904609
268 with patch("requests.request", timeout_request):
269 with patch("requests.api.request", timeout_request):
270 yield
271 elif mode is OfflineSimulationMode.HF_EVALUATE_OFFLINE_SET_TO_1:
272 with patch("evaluate.config.HF_EVALUATE_OFFLINE", True):
273 yield
274 else:
275 raise ValueError("Please use a value from the OfflineSimulationMode enum.")
276
277
278@contextmanager

Calls

no outgoing calls

Used in the wild real call sites across dependent graphs

searching dependent graphs…