File: test_resolver.py

package info (click to toggle)
python-aiohttp 3.5.1-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, buster, sid
  • size: 5,612 kB
  • sloc: python: 36,917; ansic: 15,734; makefile: 365; sh: 83
file content (217 lines) | stat: -rw-r--r-- 7,738 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
import asyncio
import ipaddress
import socket
from unittest.mock import Mock, patch

import pytest

from aiohttp.resolver import AsyncResolver, DefaultResolver, ThreadedResolver


try:
    import aiodns
    gethostbyname = hasattr(aiodns.DNSResolver, 'gethostbyname')
except ImportError:
    aiodns = None
    gethostbyname = False


class FakeResult:
    def __init__(self, addresses):
        self.addresses = addresses


class FakeQueryResult:
    def __init__(self, host):
        self.host = host


async def fake_result(addresses):
    return FakeResult(addresses=tuple(addresses))


async def fake_query_result(result):
    return [FakeQueryResult(host=h)
            for h in result]


def fake_addrinfo(hosts):
    async def fake(*args, **kwargs):
        if not hosts:
            raise socket.gaierror

        return list([(None, None, None, None, [h, 0])
                     for h in hosts])

    return fake


@pytest.mark.skipif(not gethostbyname, reason="aiodns 1.1 required")
async def test_async_resolver_positive_lookup(loop) -> None:
    with patch('aiodns.DNSResolver') as mock:
        mock().gethostbyname.return_value = fake_result(['127.0.0.1'])
        resolver = AsyncResolver(loop=loop)
        real = await resolver.resolve('www.python.org')
        ipaddress.ip_address(real[0]['host'])
        mock().gethostbyname.assert_called_with('www.python.org',
                                                socket.AF_INET)


@pytest.mark.skipif(aiodns is None, reason="aiodns required")
async def test_async_resolver_query_positive_lookup(loop) -> None:
    with patch('aiodns.DNSResolver') as mock:
        del mock().gethostbyname
        mock().query.return_value = fake_query_result(['127.0.0.1'])
        resolver = AsyncResolver(loop=loop)
        real = await resolver.resolve('www.python.org')
        ipaddress.ip_address(real[0]['host'])
        mock().query.assert_called_with('www.python.org', 'A')


@pytest.mark.skipif(not gethostbyname, reason="aiodns 1.1 required")
async def test_async_resolver_multiple_replies(loop) -> None:
    with patch('aiodns.DNSResolver') as mock:
        ips = ['127.0.0.1', '127.0.0.2', '127.0.0.3', '127.0.0.4']
        mock().gethostbyname.return_value = fake_result(ips)
        resolver = AsyncResolver(loop=loop)
        real = await resolver.resolve('www.google.com')
        ips = [ipaddress.ip_address(x['host']) for x in real]
        assert len(ips) > 3, "Expecting multiple addresses"


@pytest.mark.skipif(aiodns is None, reason="aiodns required")
async def test_async_resolver_query_multiple_replies(loop) -> None:
    with patch('aiodns.DNSResolver') as mock:
        del mock().gethostbyname
        ips = ['127.0.0.1', '127.0.0.2', '127.0.0.3', '127.0.0.4']
        mock().query.return_value = fake_query_result(ips)
        resolver = AsyncResolver(loop=loop)
        real = await resolver.resolve('www.google.com')
        ips = [ipaddress.ip_address(x['host']) for x in real]


@pytest.mark.skipif(not gethostbyname, reason="aiodns 1.1 required")
async def test_async_resolver_negative_lookup(loop) -> None:
    with patch('aiodns.DNSResolver') as mock:
        mock().gethostbyname.side_effect = aiodns.error.DNSError()
        resolver = AsyncResolver(loop=loop)
        with pytest.raises(OSError):
            await resolver.resolve('doesnotexist.bla')


@pytest.mark.skipif(aiodns is None, reason="aiodns required")
async def test_async_resolver_query_negative_lookup(loop) -> None:
    with patch('aiodns.DNSResolver') as mock:
        del mock().gethostbyname
        mock().query.side_effect = aiodns.error.DNSError()
        resolver = AsyncResolver(loop=loop)
        with pytest.raises(OSError):
            await resolver.resolve('doesnotexist.bla')


@pytest.mark.skipif(aiodns is None, reason="aiodns required")
async def test_async_resolver_no_hosts_in_query(loop) -> None:
    with patch('aiodns.DNSResolver') as mock:
        del mock().gethostbyname
        mock().query.return_value = fake_query_result([])
        resolver = AsyncResolver(loop=loop)
        with pytest.raises(OSError):
            await resolver.resolve('doesnotexist.bla')


@pytest.mark.skipif(not gethostbyname, reason="aiodns 1.1 required")
async def test_async_resolver_no_hosts_in_gethostbyname(loop) -> None:
    with patch('aiodns.DNSResolver') as mock:
        mock().gethostbyname.return_value = fake_result([])
        resolver = AsyncResolver(loop=loop)
        with pytest.raises(OSError):
            await resolver.resolve('doesnotexist.bla')


async def test_threaded_resolver_positive_lookup() -> None:
    loop = Mock()
    loop.getaddrinfo = fake_addrinfo(["127.0.0.1"])
    resolver = ThreadedResolver(loop=loop)
    real = await resolver.resolve('www.python.org')
    ipaddress.ip_address(real[0]['host'])


async def test_threaded_resolver_multiple_replies() -> None:
    loop = Mock()
    ips = ['127.0.0.1', '127.0.0.2', '127.0.0.3', '127.0.0.4']
    loop.getaddrinfo = fake_addrinfo(ips)
    resolver = ThreadedResolver(loop=loop)
    real = await resolver.resolve('www.google.com')
    ips = [ipaddress.ip_address(x['host']) for x in real]
    assert len(ips) > 3, "Expecting multiple addresses"


async def test_threaded_negative_lookup() -> None:
    loop = Mock()
    ips = []
    loop.getaddrinfo = fake_addrinfo(ips)
    resolver = ThreadedResolver(loop=loop)
    with pytest.raises(socket.gaierror):
        await resolver.resolve('doesnotexist.bla')


async def test_close_for_threaded_resolver(loop) -> None:
    resolver = ThreadedResolver(loop=loop)
    await resolver.close()


@pytest.mark.skipif(aiodns is None, reason="aiodns required")
async def test_close_for_async_resolver(loop) -> None:
    resolver = AsyncResolver(loop=loop)
    await resolver.close()


async def test_default_loop_for_threaded_resolver(loop) -> None:
    asyncio.set_event_loop(loop)
    resolver = ThreadedResolver()
    assert resolver._loop is loop


@pytest.mark.skipif(aiodns is None, reason="aiodns required")
async def test_default_loop_for_async_resolver(loop) -> None:
    asyncio.set_event_loop(loop)
    resolver = AsyncResolver()
    assert resolver._loop is loop


@pytest.mark.skipif(not gethostbyname, reason="aiodns 1.1 required")
async def test_async_resolver_ipv6_positive_lookup(loop) -> None:
    with patch('aiodns.DNSResolver') as mock:
        mock().gethostbyname.return_value = fake_result(['::1'])
        resolver = AsyncResolver(loop=loop)
        real = await resolver.resolve('www.python.org',
                                      family=socket.AF_INET6)
        ipaddress.ip_address(real[0]['host'])
        mock().gethostbyname.assert_called_with('www.python.org',
                                                socket.AF_INET6)


@pytest.mark.skipif(aiodns is None, reason="aiodns required")
async def test_async_resolver_query_ipv6_positive_lookup(loop) -> None:
    with patch('aiodns.DNSResolver') as mock:
        del mock().gethostbyname
        mock().query.return_value = fake_query_result(['::1'])
        resolver = AsyncResolver(loop=loop)
        real = await resolver.resolve('www.python.org',
                                      family=socket.AF_INET6)
        ipaddress.ip_address(real[0]['host'])
        mock().query.assert_called_with('www.python.org', 'AAAA')


async def test_async_resolver_aiodns_not_present(loop, monkeypatch) -> None:
    monkeypatch.setattr("aiohttp.resolver.aiodns", None)
    with pytest.raises(RuntimeError):
        AsyncResolver(loop=loop)


def test_default_resolver() -> None:
    # if gethostbyname:
    #     assert DefaultResolver is AsyncResolver
    # else:
    #     assert DefaultResolver is ThreadedResolver
    assert DefaultResolver is ThreadedResolver