kiwicom / pytest-recording

A pytest plugin that allows recording network interactions via VCR.py
MIT License
445 stars 35 forks source link

Host names are not working in `allowed_hosts` #40

Open Stranger6667 opened 4 years ago

Stranger6667 commented 4 years ago

Example from the README file:

import pytest
import requests

@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$"):
        requests.get("http://example.com")

It will fail on the first line:

self = <socket.socket fd=10, family=AddressFamily.AF_INET, type=SocketKind.SOCK_STREAM, proto=6, laddr=('0.0.0.0', 0)>, address = ('100.25.11.135', 80), args = (), kwargs = {}, host = '100.25.11.135'

    def network_guard(self, address, *args, **kwargs):
        host = ""
        if self.family in (socket.AF_INET, socket.AF_INET6):
            host = address[0]
        elif self.family == socket.AF_UNIX:
            host = address
        if is_host_in_allowed_hosts(host, allowed_hosts):
            return original_func(self, address, *args, **kwargs)
>       raise RuntimeError("Network is disabled")
E       RuntimeError: Network is disabled
Stranger6667 commented 4 years ago

Not sure if it is possible to do on this level since we don't have the domain name when we connect to a socket. As an alternative - we can patch some known libraries (as VCR does) and then filter there, but it would be a too broad scope change. Maybe we can remove support for domain names and support only IP addresses

selevit commented 3 years ago

As an option - we can try to resolve the host ip if possible.