File: test_connect.py

package info (click to toggle)
aiosmtplib 4.0.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 572 kB
  • sloc: python: 5,516; makefile: 20; sh: 6
file content (453 lines) | stat: -rw-r--r-- 13,282 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
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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
"""
Connectivity tests.
"""

import asyncio
import pathlib
import socket
from typing import Any, Union

import pytest
from aiosmtpd.smtp import SMTP as SMTPD

from aiosmtplib import (
    SMTP,
    SMTPConnectError,
    SMTPResponseException,
    SMTPServerDisconnected,
    SMTPStatus,
)

from .smtpd import (
    mock_response_done_then_close,
    mock_response_delayed_close,
    mock_response_unavailable,
    mock_response_disconnect,
    mock_response_eof,
    mock_response_start_data_disconnect,
    mock_response_tls_ready_disconnect,
)


async def close_during_read_response(smtpd: SMTPD, *args: Any, **kwargs: Any) -> None:
    # Read one line of data, then cut the connection.
    await smtpd.push(f"{SMTPStatus.start_input} End data with <CR><LF>.<CR><LF>")

    await smtpd._reader.readline()
    smtpd.transport.close()


async def test_plain_smtp_connect(
    smtp_client: SMTP, smtpd_server: asyncio.AbstractServer
) -> None:
    """
    Use an explicit connect/quit here, as other tests use the context manager.
    """
    await smtp_client.connect()
    assert smtp_client.is_connected

    await smtp_client.quit()
    assert not smtp_client.is_connected


async def test_quit_then_connect_ok(
    smtp_client: SMTP, smtpd_server: asyncio.AbstractServer
) -> None:
    async with smtp_client:
        response = await smtp_client.quit()
        assert response.code == SMTPStatus.closing

        # Next command should fail
        with pytest.raises(SMTPServerDisconnected):
            response = await smtp_client.noop()

        await smtp_client.connect()

        # after reconnect, it should work again
        response = await smtp_client.noop()
        assert response.code == SMTPStatus.completed


@pytest.mark.smtpd_mocks(_handle_client=mock_response_unavailable)
async def test_bad_connect_response_raises_error(smtp_client: SMTP) -> None:
    with pytest.raises(SMTPConnectError):
        await smtp_client.connect()

    assert smtp_client.transport is None
    assert smtp_client.protocol is None


@pytest.mark.smtpd_mocks(_handle_client=mock_response_eof)
async def test_eof_on_connect_raises_connect_error(smtp_client: SMTP) -> None:
    with pytest.raises(SMTPConnectError):
        await smtp_client.connect()

    assert smtp_client.transport is None
    assert smtp_client.protocol is None


@pytest.mark.smtpd_mocks(_handle_client=mock_response_disconnect)
async def test_close_on_connect_raises_connect_error(smtp_client: SMTP) -> None:
    with pytest.raises(SMTPConnectError):
        await smtp_client.connect()

    assert not smtp_client.is_connected


@pytest.mark.smtpd_mocks(smtp_NOOP=mock_response_unavailable)
async def test_421_closes_connection(smtp_client: SMTP) -> None:
    await smtp_client.connect()

    with pytest.raises(SMTPResponseException):
        await smtp_client.noop()

    assert not smtp_client.is_connected


async def test_connect_error_with_no_server(
    hostname: str, unused_tcp_port: int
) -> None:
    client = SMTP(hostname=hostname, port=unused_tcp_port, timeout=1.0)

    with pytest.raises(SMTPConnectError):
        # SMTPConnectTimeoutError vs SMTPConnectError here depends on
        # processing time.
        await client.connect()


@pytest.mark.smtpd_mocks(smtp_NOOP=mock_response_disconnect)
async def test_disconnected_server_raises_on_client_read(smtp_client: SMTP) -> None:
    await smtp_client.connect()

    with pytest.raises(SMTPServerDisconnected):
        await smtp_client.execute_command(b"NOOP")

    assert not smtp_client.is_connected


@pytest.mark.smtpd_mocks(smtp_NOOP=mock_response_eof)
async def test_disconnected_server_raises_on_client_write(smtp_client: SMTP) -> None:
    await smtp_client.connect()

    with pytest.raises(SMTPServerDisconnected):
        await smtp_client.execute_command(b"NOOP")

    assert not smtp_client.is_connected


@pytest.mark.smtpd_mocks(smtp_DATA=mock_response_disconnect)
async def test_disconnected_server_raises_on_data_read(smtp_client: SMTP) -> None:
    await smtp_client.connect()
    await smtp_client.ehlo()
    await smtp_client.mail("sender@example.com")
    await smtp_client.rcpt("recipient@example.com")

    with pytest.raises(SMTPServerDisconnected):
        await smtp_client.data("A MESSAGE")

    assert not smtp_client.is_connected


async def test_disconnected_server_raises_on_data_write(
    smtp_client: SMTP,
    smtpd_server: asyncio.AbstractServer,
    smtpd_class: type[SMTPD],
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    monkeypatch.setattr(smtpd_class, "smtp_DATA", close_during_read_response)

    await smtp_client.connect()
    await smtp_client.ehlo()
    await smtp_client.mail("sender@example.com")
    await smtp_client.rcpt("recipient@example.com")
    with pytest.raises(SMTPServerDisconnected):
        await smtp_client.data("A MESSAGE\nLINE2")

    assert not smtp_client.is_connected


@pytest.mark.smtpd_mocks(smtp_STARTTLS=mock_response_disconnect)
async def test_disconnected_server_raises_on_starttls(smtp_client: SMTP) -> None:
    await smtp_client.connect()
    await smtp_client.ehlo()

    async def mock_ehlo_or_helo_if_needed() -> None:
        pass

    smtp_client._ehlo_or_helo_if_needed = mock_ehlo_or_helo_if_needed

    with pytest.raises(SMTPServerDisconnected):
        await smtp_client.starttls(timeout=1.0)

    assert not smtp_client.is_connected


async def test_context_manager(
    smtp_client: SMTP, smtpd_server: asyncio.AbstractServer
) -> None:
    async with smtp_client:
        assert smtp_client.is_connected

        response = await smtp_client.noop()
        assert response.code == SMTPStatus.completed

    assert not smtp_client.is_connected


@pytest.mark.smtpd_mocks(smtp_NOOP=mock_response_disconnect)
async def test_context_manager_disconnect_handling(smtp_client: SMTP) -> None:
    """
    Exceptions can be raised, but the context manager should handle
    disconnection.
    """
    async with smtp_client:
        assert smtp_client.is_connected

        try:
            await smtp_client.noop()
        except SMTPServerDisconnected:
            pass

    assert not smtp_client.is_connected


async def test_context_manager_exception_quits(
    smtp_client: SMTP,
    smtpd_server: asyncio.AbstractServer,
    received_commands: list[tuple[str, tuple[Any, ...]]],
) -> None:
    with pytest.raises(ZeroDivisionError):
        async with smtp_client:
            1 / 0  # noqa

    assert received_commands[-1][0] == "QUIT"


async def test_context_manager_connect_exception_closes(
    smtp_client: SMTP,
    smtpd_server: asyncio.AbstractServer,
    received_commands: list[tuple[str, tuple[Any, ...]]],
) -> None:
    with pytest.raises(ConnectionError):
        async with smtp_client:
            raise ConnectionError("Failed!")

    assert len(received_commands) == 0


async def test_context_manager_with_manual_connection(
    smtp_client: SMTP, smtpd_server: asyncio.AbstractServer
) -> None:
    await smtp_client.connect()

    assert smtp_client.is_connected

    async with smtp_client:
        assert smtp_client.is_connected

        await smtp_client.quit()

        assert not smtp_client.is_connected

    assert not smtp_client.is_connected


async def test_context_manager_double_entry(
    smtp_client: SMTP, smtpd_server: asyncio.AbstractServer
) -> None:
    async with smtp_client:
        async with smtp_client:
            assert smtp_client.is_connected
            response = await smtp_client.noop()
            assert response.code == SMTPStatus.completed

        # The first exit should disconnect us
        assert not smtp_client.is_connected
    assert not smtp_client.is_connected


async def test_connect_error_second_attempt(
    hostname: str, unused_tcp_port: int
) -> None:
    client = SMTP(hostname=hostname, port=unused_tcp_port, timeout=1.0)

    with pytest.raises(SMTPConnectError):
        await client.connect()

    with pytest.raises(SMTPConnectError):
        await client.connect()


@pytest.mark.smtpd_mocks(smtp_EHLO=mock_response_done_then_close)
async def test_server_unexpected_disconnect_on_command_then_reconnect(
    smtp_client: SMTP,
) -> None:
    await smtp_client.connect()
    await smtp_client.ehlo()

    with pytest.raises(SMTPServerDisconnected):
        await smtp_client.noop()

    assert not smtp_client.is_connected
    assert not smtp_client._connect_lock.locked()

    await asyncio.wait_for(smtp_client.connect(), 1.0)

    assert smtp_client.is_connected


@pytest.mark.smtpd_mocks(smtp_STARTTLS=mock_response_tls_ready_disconnect)
async def test_server_unexpected_disconnect_on_starttls_then_reconnect(
    smtp_client: SMTP,
) -> None:
    await smtp_client.connect()
    await smtp_client.ehlo()

    with pytest.raises(SMTPServerDisconnected):
        await smtp_client.starttls()

    assert not smtp_client.is_connected
    assert not smtp_client._connect_lock.locked()

    await asyncio.wait_for(smtp_client.connect(), 1.0)

    assert smtp_client.is_connected


@pytest.mark.smtpd_mocks(smtp_DATA=mock_response_start_data_disconnect)
async def test_server_unexpected_disconnect_on_data_then_reconnect(
    smtp_client: SMTP,
) -> None:
    await smtp_client.connect()
    await smtp_client.ehlo()
    await smtp_client.mail("j@example.com")
    await smtp_client.rcpt("test@example.com")

    with pytest.raises(SMTPServerDisconnected):
        await smtp_client.data(b"Test message")

    assert not smtp_client.is_connected
    assert not smtp_client._connect_lock.locked()

    await asyncio.wait_for(smtp_client.connect(), 1.0)

    assert smtp_client.is_connected


@pytest.mark.smtpd_mocks(smtp_EHLO=mock_response_delayed_close)
async def test_server_unexpected_disconnect_with_delay(
    smtp_client: SMTP,
) -> None:
    await smtp_client.connect()
    await smtp_client.ehlo()

    # Wait for the delayed close
    await asyncio.sleep(0.2)

    assert not smtp_client.is_connected
    assert not smtp_client._connect_lock.locked()

    await asyncio.wait_for(smtp_client.connect(), 1.0)

    assert smtp_client.is_connected


async def test_connect_with_login(
    smtp_client: SMTP,
    smtpd_server: asyncio.AbstractServer,
    received_commands: list[tuple[str, tuple[Any, ...]]],
    auth_username: str,
    auth_password: str,
) -> None:
    # STARTTLS is required for login
    await smtp_client.connect(
        start_tls=True,
        username=auth_username,
        password=auth_password,
    )

    assert "AUTH" in [command[0] for command in received_commands]

    await smtp_client.quit()


@pytest.mark.smtpd_options(starttls=False)
async def test_connect_with_no_starttls_support(smtp_client: SMTP) -> None:
    await smtp_client.connect()

    assert smtp_client.is_connected
    assert not smtp_client.protocol._over_ssl

    await smtp_client.quit()


async def test_connect_via_socket(
    smtp_client: SMTP, hostname: str, smtpd_server_port: int
) -> None:
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
        sock.connect((hostname, smtpd_server_port))

        await smtp_client.connect(hostname=None, port=None, sock=sock)
        response = await smtp_client.ehlo()

    assert response.code == SMTPStatus.completed


async def test_connect_via_socket_path(
    smtp_client: SMTP,
    smtpd_server_socket_path: asyncio.AbstractServer,
    socket_path: Union[pathlib.Path, str, bytes],
) -> None:
    await smtp_client.connect(hostname=None, port=None, socket_path=socket_path)
    response = await smtp_client.ehlo()

    assert response.code == SMTPStatus.completed


@pytest.mark.smtpd_mocks(smtp_NOOP=mock_response_eof)
async def test_disconnected_server_get_transport_info(smtp_client: SMTP) -> None:
    await smtp_client.connect()

    with pytest.raises(SMTPServerDisconnected):
        await smtp_client.execute_command(b"NOOP")

    with pytest.raises(SMTPServerDisconnected, match="Server not connected"):
        smtp_client.get_transport_info("sslcontext")


@pytest.mark.smtpd_mocks(smtp_NOOP=mock_response_eof)
async def test_disconnected_server_data(smtp_client: SMTP) -> None:
    await smtp_client.connect()

    with pytest.raises(SMTPServerDisconnected):
        await smtp_client.execute_command(b"NOOP")

    async def mock_ehlo_or_helo_if_needed() -> None:
        pass

    smtp_client._ehlo_or_helo_if_needed = mock_ehlo_or_helo_if_needed

    with pytest.raises(SMTPServerDisconnected):
        await smtp_client.data("123")


async def test_create_connection_runtime_error_on_missing_loop(
    smtp_client: SMTP,
) -> None:
    client = SMTP(timeout=1.0)
    with pytest.raises(RuntimeError, match="No event loop set"):
        await client._create_connection(1.0)


async def test_create_connection_runtime_error_on_missing_hostname() -> None:
    client = SMTP(hostname=None, port=None, timeout=1.0)
    client.loop = asyncio.get_running_loop()
    with pytest.raises(RuntimeError, match="No hostname provided"):
        await client._create_connection(1.0)


async def test_create_connection_runtime_error_on_missing_port() -> None:
    client = SMTP(hostname="localhost", port=None, timeout=1.0)
    client.loop = asyncio.get_running_loop()
    with pytest.raises(RuntimeError, match="No port provided"):
        await client._create_connection(1.0)