getsentry / responses

A utility for mocking out the Python Requests library.
Apache License 2.0
4.17k stars 356 forks source link

responses 0.24 no longer works with pytest-socket #691

Closed divad closed 1 year ago

divad commented 1 year ago

Describe the bug

We use pytest-socket to prevent socket/network access during tests. In this commit (https://github.com/getsentry/responses/commit/87db9df3dc4d2778eee37c3bb7b29f5e3aeb5d9e) responses now uses a dummy socket, which breaks tests when used with pytest-socket:

  File "/app/path/here.py", line 44, in function_name_here
    resp = requests.get(url, timeout=5)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/site-packages/requests/api.py", line 73, in get
    return request("get", url, params=params, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/site-packages/requests/api.py", line 59, in request
    return session.request(method=method, url=url, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/site-packages/requests/sessions.py", line 589, in request
    resp = self.send(prep, **send_kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/site-packages/requests/sessions.py", line 703, in send
    r = adapter.send(request, **kwargs)
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/site-packages/responses/__init__.py", line 1128, in send
    return self._on_request(adapter, request, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/site-packages/responses/__init__.py", line 1063, in _on_request
    request, match.get_response(request)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/site-packages/responses/__init__.py", line 607, in get_response
    return _form_response(body, headers, status)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/site-packages/responses/__init__.py", line 522, in _form_response
    dummy_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/site-packages/pytest_socket.py", line 80, in __new__
    raise SocketBlockedError()
pytest_socket.SocketBlockedError: A test tried to use socket.socket.

A workaround is to tell pytest-socket to allow socket access to 127.0.0.1, although this somewhat reduces the purpose of pytest-socket. Would it be possible to add a flag or feature to responses where it uses the old behaviour or in some other way does not use socket ?

Additional context

No response

Version of responses

0.24

Steps to Reproduce

Use responses 0.24 and pytest-socket

Expected Result

Expected: responses does not use socket

Actual Result

Actual: responses uses socket