File: test_connection.py

package info (click to toggle)
aioftp 0.27.2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 628 kB
  • sloc: python: 5,574; makefile: 172
file content (296 lines) | stat: -rw-r--r-- 10,071 bytes parent folder | download | duplicates (2)
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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
import asyncio
import ipaddress

import pytest

import aioftp


@pytest.mark.asyncio
async def test_client_without_server(pair_factory, unused_tcp_port_factory):
    f = pair_factory(connected=False, logged=False, do_quit=False)
    async with f as pair:
        pass
    with pytest.raises(OSError):
        await pair.client.connect("127.0.0.1", unused_tcp_port_factory())


@pytest.mark.asyncio
async def test_connection(pair_factory):
    async with pair_factory(connected=True, logged=False, do_quit=False):
        pass


@pytest.mark.asyncio
async def test_quit(pair_factory):
    async with pair_factory(connected=True, logged=False, do_quit=True):
        pass


@pytest.mark.asyncio
async def test_not_implemented(pair_factory, expect_codes_in_exception):
    async with pair_factory() as pair:
        with expect_codes_in_exception("502"):
            await pair.client.command("FOOBAR", "2xx", "1xx")


@pytest.mark.asyncio
async def test_type_success(pair_factory, expect_codes_in_exception):
    async with pair_factory() as pair:
        await pair.client.get_passive_connection("A")


@pytest.mark.asyncio
async def test_custom_passive_commands(pair_factory):
    async with pair_factory(host="127.0.0.1") as pair:
        pair.client._passive_commands = None
        await pair.client.get_passive_connection(
            "A",
            commands=["pasv", "epsv"],
        )


@pytest.mark.asyncio
async def test_extra_pasv_connection(pair_factory):
    async with pair_factory() as pair:
        r, w = await pair.client.get_passive_connection()
        er, ew = await pair.client.get_passive_connection()
        with pytest.raises((ConnectionResetError, BrokenPipeError)):
            while True:
                w.write(b"-" * aioftp.DEFAULT_BLOCK_SIZE)
                await w.drain()


@pytest.mark.parametrize("method", ["epsv", "pasv"])
@pytest.mark.asyncio
async def test_closing_passive_connection(pair_factory, method):
    async with pair_factory(host="127.0.0.1") as pair:
        r, w = await pair.client.get_passive_connection(commands=[method])
        host, port, *_ = w.transport.get_extra_info("peername")
        nr, nw = await asyncio.open_connection(host, port)
        with pytest.raises((ConnectionResetError, BrokenPipeError)):
            while True:
                nw.write(b"-" * aioftp.DEFAULT_BLOCK_SIZE)
                await nw.drain()


@pytest.mark.asyncio
async def test_pasv_connection_ports_not_added(pair_factory):
    async with pair_factory() as pair:
        r, w = await pair.client.get_passive_connection()
        assert pair.server.available_data_ports is None


@pytest.mark.asyncio
async def test_pasv_connection_ports(
    pair_factory,
    Server,
    unused_tcp_port_factory,
):
    ports = [unused_tcp_port_factory(), unused_tcp_port_factory()]
    async with pair_factory(None, Server(data_ports=ports)) as pair:
        r, w = await pair.client.get_passive_connection()
        host, port, *_ = w.transport.get_extra_info("peername")
        assert port in ports
        assert pair.server.available_data_ports.qsize() == 1


@pytest.mark.asyncio
async def test_data_ports_remains_empty(pair_factory, Server):
    async with pair_factory(None, Server(data_ports=[])) as pair:
        assert pair.server.available_data_ports.qsize() == 0


@pytest.mark.asyncio
async def test_pasv_connection_port_reused(
    pair_factory,
    Server,
    unused_tcp_port,
):
    s = Server(data_ports=[unused_tcp_port])
    async with pair_factory(None, s) as pair:
        r, w = await pair.client.get_passive_connection()
        host, port, *_ = w.transport.get_extra_info("peername")
        assert port == unused_tcp_port
        assert pair.server.available_data_ports.qsize() == 0
        w.close()
        await pair.client.quit()
        pair.client.close()
        assert pair.server.available_data_ports.qsize() == 1
        await pair.client.connect(
            pair.server.server_host,
            pair.server.server_port,
        )
        await pair.client.login()
        r, w = await pair.client.get_passive_connection()
        host, port, *_ = w.transport.get_extra_info("peername")
        assert port == unused_tcp_port
        assert pair.server.available_data_ports.qsize() == 0


@pytest.mark.asyncio
async def test_pasv_connection_pasv_forced_response_address(pair_factory, Server):
    def ipv4_used():
        try:
            ipaddress.IPv4Address(pair.host)
            return True
        except ValueError:
            return False

    # using TEST-NET-1 address
    ipv4_address = "192.0.2.1"
    async with pair_factory(
        server=Server(ipv4_pasv_forced_response_address=ipv4_address),
    ) as pair:
        assert pair.server.ipv4_pasv_forced_response_address == ipv4_address

        if ipv4_used():
            # The connection should fail here because the server starts to listen for
            # the passive connections on the host (IPv4 address) that is used
            # by the control channel. In reality, if the server is behind NAT,
            # the server is reached with the defined external IPv4 address,
            # i.e. we can check that the connection to
            # pair.server.ipv4_pasv_forced_response_address failed to know that
            # the server returned correct external IP
            # ...
            # but we can't use check like this:
            # with pytest.raises(OSError):
            #     await pair.client.get_passive_connection(commands=["pasv"])
            # because there is no such ipv4 which will be non-routable, so
            # we can only check `PASV` response
            ip, _ = await pair.client._do_pasv()
            assert ip == ipv4_address

        # With epsv the connection should open as that does not use the
        # external IPv4 address but just tells the client the port to connect
        # to
        await pair.client.get_passive_connection(commands=["epsv"])


@pytest.mark.parametrize("method", ["epsv", "pasv"])
@pytest.mark.asyncio
async def test_pasv_connection_no_free_port(
    pair_factory,
    Server,
    expect_codes_in_exception,
    method,
):
    s = Server(data_ports=[])
    async with pair_factory(None, s, do_quit=False, host="127.0.0.1") as pair:
        assert pair.server.available_data_ports.qsize() == 0
        with expect_codes_in_exception("421"):
            await pair.client.get_passive_connection(commands=[method])


@pytest.mark.asyncio
async def test_pasv_connection_busy_port(
    pair_factory,
    Server,
    unused_tcp_port_factory,
):
    ports = [unused_tcp_port_factory(), unused_tcp_port_factory()]
    async with pair_factory(None, Server(data_ports=ports)) as pair:
        conflicting_server = await asyncio.start_server(
            lambda r, w: w.close(),
            host=pair.server.server_host,
            port=ports[0],
        )
        r, w = await pair.client.get_passive_connection()
        host, port, *_ = w.transport.get_extra_info("peername")
        assert port == ports[1]
        assert pair.server.available_data_ports.qsize() == 1
    conflicting_server.close()
    await conflicting_server.wait_closed()


@pytest.mark.asyncio
async def test_pasv_connection_busy_port2(
    pair_factory,
    Server,
    unused_tcp_port_factory,
    expect_codes_in_exception,
):
    ports = [unused_tcp_port_factory()]
    s = Server(data_ports=ports)
    async with pair_factory(None, s, do_quit=False) as pair:
        conflicting_server = await asyncio.start_server(
            lambda r, w: w.close(),
            host=pair.server.server_host,
            port=ports[0],
        )
        with expect_codes_in_exception("421"):
            await pair.client.get_passive_connection()
    conflicting_server.close()
    await conflicting_server.wait_closed()


@pytest.mark.asyncio
async def test_server_shutdown(pair_factory):
    async with pair_factory(do_quit=False) as pair:
        await pair.client.list()
        await pair.server.close()
        with pytest.raises(ConnectionResetError):
            await pair.client.list()


@pytest.mark.asyncio
async def test_client_session_context_manager(pair_factory):
    async with pair_factory(connected=False) as pair:
        async with aioftp.Client.context(*pair.server.address) as client:
            await client.list()


@pytest.mark.asyncio
async def test_long_login_sequence_fail(
    pair_factory,
    expect_codes_in_exception,
):
    class CustomServer(aioftp.Server):
        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)
            self.commands_mapping["acct"] = self.acct

        async def user(self, connection, rest):
            connection.response("331")
            return True

        async def pass_(self, connection, rest):
            connection.response("332")
            return True

        async def acct(self, connection, rest):
            connection.response("333")
            return True

    factory = pair_factory(
        logged=False,
        server_factory=CustomServer,
        do_quit=False,
    )
    async with factory as pair:
        with expect_codes_in_exception("333"):
            await pair.client.login()


@pytest.mark.asyncio
async def test_bad_sublines_seq(pair_factory, expect_codes_in_exception):
    class CustomServer(aioftp.Server):
        async def write_response(self, stream, code, lines="", list=False):
            import functools

            lines = aioftp.wrap_with_container(lines)
            write = functools.partial(self.write_line, stream)
            *body, tail = lines
            for line in body:
                await write(code + "-" + line)
            await write(str(int(code) + 1) + "-" + tail)
            await write(code + " " + tail)

    factory = pair_factory(connected=False, server_factory=CustomServer)
    async with factory as pair:
        with expect_codes_in_exception("220"):
            await pair.client.connect(
                pair.server.server_host,
                pair.server.server_port,
            )
            await pair.client.login()