1from six.moves.urllib.request import urlopen 2import socket 3from contextlib import contextmanager 4import vcr 5 6 7@contextmanager 8def overridden_dns(overrides): 9 """ 10 Monkeypatch socket.getaddrinfo() to override DNS lookups (name will resolve 11 to address) 12 """ 13 real_getaddrinfo = socket.getaddrinfo 14 15 def fake_getaddrinfo(*args, **kwargs): 16 if args[0] in overrides: 17 address = overrides[args[0]] 18 return [(2, 1, 6, '', (address, args[1]))] 19 return real_getaddrinfo(*args, **kwargs) 20 socket.getaddrinfo = fake_getaddrinfo 21 yield 22 socket.getaddrinfo = real_getaddrinfo 23 24 25def test_ignore_localhost(tmpdir, httpbin): 26 with overridden_dns({'httpbin.org': '127.0.0.1'}): 27 cass_file = str(tmpdir.join('filter_qs.yaml')) 28 with vcr.use_cassette(cass_file, ignore_localhost=True) as cass: 29 urlopen('http://localhost:{}/'.format(httpbin.port)) 30 assert len(cass) == 0 31 urlopen('http://httpbin.org:{}/'.format(httpbin.port)) 32 assert len(cass) == 1 33 34 35def test_ignore_httpbin(tmpdir, httpbin): 36 with overridden_dns({'httpbin.org': '127.0.0.1'}): 37 cass_file = str(tmpdir.join('filter_qs.yaml')) 38 with vcr.use_cassette( 39 cass_file, 40 ignore_hosts=['httpbin.org'] 41 ) as cass: 42 urlopen('http://httpbin.org:{}/'.format(httpbin.port)) 43 assert len(cass) == 0 44 urlopen('http://localhost:{}/'.format(httpbin.port)) 45 assert len(cass) == 1 46 47 48def test_ignore_localhost_and_httpbin(tmpdir, httpbin): 49 with overridden_dns({'httpbin.org': '127.0.0.1'}): 50 cass_file = str(tmpdir.join('filter_qs.yaml')) 51 with vcr.use_cassette( 52 cass_file, 53 ignore_hosts=['httpbin.org'], 54 ignore_localhost=True 55 ) as cass: 56 urlopen('http://httpbin.org:{}'.format(httpbin.port)) 57 urlopen('http://localhost:{}'.format(httpbin.port)) 58 assert len(cass) == 0 59 60 61def test_ignore_localhost_twice(tmpdir, httpbin): 62 with overridden_dns({'httpbin.org': '127.0.0.1'}): 63 cass_file = str(tmpdir.join('filter_qs.yaml')) 64 with vcr.use_cassette(cass_file, ignore_localhost=True) as cass: 65 urlopen('http://localhost:{}'.format(httpbin.port)) 66 assert len(cass) == 0 67 urlopen('http://httpbin.org:{}'.format(httpbin.port)) 68 assert len(cass) == 1 69 with vcr.use_cassette(cass_file, ignore_localhost=True) as cass: 70 assert len(cass) == 1 71 urlopen('http://localhost:{}'.format(httpbin.port)) 72 urlopen('http://httpbin.org:{}'.format(httpbin.port)) 73 assert len(cass) == 1 74