Debian Codegraph @

tests/test_connect.py

raw
1 """
2 Connectivity tests.
3 """
4
5 import asyncio
6 import pathlib
7 import socket
8 from typing import Any
9
10 import pytest
11 from aiosmtpd.smtp import SMTP as SMTPD
12
13 from aiosmtplib import (
14 SMTP,
15 SMTPConnectError,
16 SMTPException,
17 SMTPResponseException,
18 SMTPServerDisconnected,
19 SMTPStatus,
20 )
21
22 from .smtpd import (
23 mock_response_done_then_close,
24 mock_response_delayed_close,
25 mock_response_unavailable,
26 mock_response_disconnect,
27 mock_response_eof,
28 mock_response_quit_error,
29 mock_response_start_data_disconnect,
30 mock_response_tls_ready_disconnect,
31 )
32
33
34 async def close_during_read_response(smtpd: SMTPD, *args: Any, **kwargs: Any) -> None:
35 # Read one line of data, then cut the connection.
36 await smtpd.push(f"{SMTPStatus.start_input} End data with <CR><LF>.<CR><LF>")
37
38 await smtpd._reader.readline()
39 smtpd.transport.close()
40
41
42 async def test_plain_smtp_connect(
43 smtp_client: SMTP, smtpd_server: asyncio.AbstractServer
44 ) -> None:
45 """
46 Use an explicit connect/quit here, as other tests use the context manager.
47 """
48 await smtp_client.connect()
49 assert smtp_client.is_connected
50
51 await smtp_client.quit()
52 assert not smtp_client.is_connected
53
54
55 async def test_quit_then_connect_ok(
56 smtp_client: SMTP, smtpd_server: asyncio.AbstractServer
57 ) -> None:
58 async with smtp_client:
59 response = await smtp_client.quit()
60 assert response.code == SMTPStatus.closing
61
62 # Next command should fail
63 with pytest.raises(SMTPServerDisconnected):
64 response = await smtp_client.noop()
65
66 await smtp_client.connect()
67
68 # after reconnect, it should work again
69 response = await smtp_client.noop()
70 assert response.code == SMTPStatus.completed
71
72
73 async def test_connect_while_connected_raises(
74 smtp_client: SMTP, smtpd_server: asyncio.AbstractServer
75 ) -> None:
76 await smtp_client.connect()
77 assert smtp_client.is_connected
78
79 # Connecting an already-connected client is an error, not a deadlock.
80 with pytest.raises(SMTPException, match="already connected"):
81 await asyncio.wait_for(smtp_client.connect(), 1.0)
82
83 # The existing connection is untouched.
84 assert smtp_client.is_connected
85 response = await smtp_client.noop()
86 assert response.code == SMTPStatus.completed
87
88
89 @pytest.mark.smtpd_mocks(_handle_client=mock_response_unavailable)
90 async def test_bad_connect_response_raises_error(smtp_client: SMTP) -> None:
91 with pytest.raises(SMTPConnectError):
92 await smtp_client.connect()
93
94 assert smtp_client.transport is None
95 assert smtp_client.protocol is None
96
97
98 @pytest.mark.smtpd_mocks(_handle_client=mock_response_eof)
99 async def test_eof_on_connect_raises_connect_error(smtp_client: SMTP) -> None:
100 with pytest.raises(SMTPConnectError):
101 await smtp_client.connect()
102
103 assert smtp_client.transport is None
104 assert smtp_client.protocol is None
105
106
107 @pytest.mark.smtpd_mocks(_handle_client=mock_response_disconnect)
108 async def test_close_on_connect_raises_connect_error(smtp_client: SMTP) -> None:
109 with pytest.raises(SMTPConnectError):
110 await smtp_client.connect()
111
112 assert not smtp_client.is_connected
113
114
115 @pytest.mark.smtpd_mocks(smtp_NOOP=mock_response_unavailable)
116 async def test_421_closes_connection(smtp_client: SMTP) -> None:
117 await smtp_client.connect()
118
119 with pytest.raises(SMTPResponseException):
120 await smtp_client.noop()
121
122 assert not smtp_client.is_connected
123
124
125 async def test_connect_error_with_no_server(
126 hostname: str, unused_tcp_port: int
127 ) -> None:
128 client = SMTP(hostname=hostname, port=unused_tcp_port, timeout=1.0)
129
130 with pytest.raises(SMTPConnectError):
131 # SMTPConnectTimeoutError vs SMTPConnectError here depends on
132 # processing time.
133 await client.connect()
134
135
136 @pytest.mark.smtpd_mocks(smtp_NOOP=mock_response_disconnect)
137 async def test_disconnected_server_raises_on_client_read(smtp_client: SMTP) -> None:
138 await smtp_client.connect()
139
140 with pytest.raises(SMTPServerDisconnected):
141 await smtp_client.execute_command(b"NOOP")
142
143 assert not smtp_client.is_connected
144
145
146 @pytest.mark.smtpd_mocks(smtp_NOOP=mock_response_eof)
147 async def test_disconnected_server_raises_on_client_write(smtp_client: SMTP) -> None:
148 await smtp_client.connect()
149
150 with pytest.raises(SMTPServerDisconnected):
151 await smtp_client.execute_command(b"NOOP")
152
153 assert not smtp_client.is_connected
154
155
156 @pytest.mark.smtpd_mocks(smtp_DATA=mock_response_disconnect)
157 async def test_disconnected_server_raises_on_data_read(smtp_client: SMTP) -> None:
158 await smtp_client.connect()
159 await smtp_client.ehlo()
160 await smtp_client.mail("[email protected]")
161 await smtp_client.rcpt("[email protected]")
162
163 with pytest.raises(SMTPServerDisconnected):
164 await smtp_client.data("A MESSAGE")
165
166 assert not smtp_client.is_connected
167
168
169 async def test_disconnected_server_raises_on_data_write(
170 smtp_client: SMTP,
171 smtpd_server: asyncio.AbstractServer,
172 smtpd_class: type[SMTPD],
173 monkeypatch: pytest.MonkeyPatch,
174 ) -> None:
175 monkeypatch.setattr(smtpd_class, "smtp_DATA", close_during_read_response)
176
177 await smtp_client.connect()
178 await smtp_client.ehlo()
179 await smtp_client.mail("[email protected]")
180 await smtp_client.rcpt("[email protected]")
181 with pytest.raises(SMTPServerDisconnected):
182 await smtp_client.data("A MESSAGE\nLINE2")
183
184 assert not smtp_client.is_connected
185
186
187 @pytest.mark.smtpd_mocks(smtp_STARTTLS=mock_response_disconnect)
188 async def test_disconnected_server_raises_on_starttls(smtp_client: SMTP) -> None:
189 await smtp_client.connect()
190 await smtp_client.ehlo()
191
192 async def mock_ehlo_or_helo_if_needed() -> None:
193 pass
194
195 smtp_client._ehlo_or_helo_if_needed = mock_ehlo_or_helo_if_needed
196
197 with pytest.raises(SMTPServerDisconnected):
198 await smtp_client.starttls(timeout=1.0)
199
200 assert not smtp_client.is_connected
201
202
203 async def test_context_manager(
204 smtp_client: SMTP, smtpd_server: asyncio.AbstractServer
205 ) -> None:
206 async with smtp_client:
207 assert smtp_client.is_connected
208
209 response = await smtp_client.noop()
210 assert response.code == SMTPStatus.completed
211
212 assert not smtp_client.is_connected
213
214
215 @pytest.mark.smtpd_mocks(smtp_NOOP=mock_response_disconnect)
216 async def test_context_manager_disconnect_handling(smtp_client: SMTP) -> None:
217 """
218 Exceptions can be raised, but the context manager should handle
219 disconnection.
220 """
221 async with smtp_client:
222 assert smtp_client.is_connected
223
224 try:
225 await smtp_client.noop()
226 except SMTPServerDisconnected:
227 pass
228
229 assert not smtp_client.is_connected
230
231
232 async def test_context_manager_exception_quits(
233 smtp_client: SMTP,
234 smtpd_server: asyncio.AbstractServer,
235 received_commands: list[tuple[str, tuple[Any, ...]]],
236 ) -> None:
237 with pytest.raises(ZeroDivisionError):
238 async with smtp_client:
239 1 / 0 # noqa
240
241 assert received_commands[-1][0] == "QUIT"
242
243
244 async def test_context_manager_connect_exception_closes(
245 smtp_client: SMTP,
246 smtpd_server: asyncio.AbstractServer,
247 received_commands: list[tuple[str, tuple[Any, ...]]],
248 ) -> None:
249 with pytest.raises(ConnectionError):
250 async with smtp_client:
251 raise ConnectionError("Failed!")
252
253 assert len(received_commands) == 0
254
255
256 async def test_context_manager_with_manual_connection(
257 smtp_client: SMTP, smtpd_server: asyncio.AbstractServer
258 ) -> None:
259 await smtp_client.connect()
260
261 assert smtp_client.is_connected
262
263 async with smtp_client:
264 assert smtp_client.is_connected
265
266 await smtp_client.quit()
267
268 assert not smtp_client.is_connected
269
270 assert not smtp_client.is_connected
271
272
273 async def test_context_manager_double_entry(
274 smtp_client: SMTP, smtpd_server: asyncio.AbstractServer
275 ) -> None:
276 async with smtp_client:
277 async with smtp_client:
278 assert smtp_client.is_connected
279 response = await smtp_client.noop()
280 assert response.code == SMTPStatus.completed
281
282 # The first exit should disconnect us
283 assert not smtp_client.is_connected
284 assert not smtp_client.is_connected
285
286
287 async def test_connect_error_second_attempt(
288 hostname: str, unused_tcp_port: int
289 ) -> None:
290 client = SMTP(hostname=hostname, port=unused_tcp_port, timeout=1.0)
291
292 with pytest.raises(SMTPConnectError):
293 await client.connect()
294
295 with pytest.raises(SMTPConnectError):
296 await client.connect()
297
298
299 @pytest.mark.smtpd_mocks(smtp_EHLO=mock_response_done_then_close)
300 async def test_server_unexpected_disconnect_on_command_then_reconnect(
301 smtp_client: SMTP,
302 ) -> None:
303 await smtp_client.connect()
304 await smtp_client.ehlo()
305
306 with pytest.raises(SMTPServerDisconnected):
307 await smtp_client.noop()
308
309 assert not smtp_client.is_connected
310 assert not smtp_client._connect_lock.locked()
311
312 await asyncio.wait_for(smtp_client.connect(), 1.0)
313
314 assert smtp_client.is_connected
315
316
317 @pytest.mark.smtpd_mocks(smtp_STARTTLS=mock_response_tls_ready_disconnect)
318 async def test_server_unexpected_disconnect_on_starttls_then_reconnect(
319 smtp_client: SMTP,
320 ) -> None:
321 await smtp_client.connect()
322 await smtp_client.ehlo()
323
324 with pytest.raises(SMTPServerDisconnected):
325 await smtp_client.starttls()
326
327 assert not smtp_client.is_connected
328 assert not smtp_client._connect_lock.locked()
329
330 await asyncio.wait_for(smtp_client.connect(), 1.0)
331
332 assert smtp_client.is_connected
333
334
335 @pytest.mark.smtpd_mocks(smtp_DATA=mock_response_start_data_disconnect)
336 async def test_server_unexpected_disconnect_on_data_then_reconnect(
337 smtp_client: SMTP,
338 ) -> None:
339 await smtp_client.connect()
340 await smtp_client.ehlo()
341 await smtp_client.mail("[email protected]")
342 await smtp_client.rcpt("[email protected]")
343
344 with pytest.raises(SMTPServerDisconnected):
345 await smtp_client.data(b"Test message")
346
347 assert not smtp_client.is_connected
348 assert not smtp_client._connect_lock.locked()
349
350 await asyncio.wait_for(smtp_client.connect(), 1.0)
351
352 assert smtp_client.is_connected
353
354
355 @pytest.mark.smtpd_mocks(smtp_EHLO=mock_response_delayed_close)
356 async def test_server_unexpected_disconnect_with_delay(
357 smtp_client: SMTP,
358 ) -> None:
359 await smtp_client.connect()
360 await smtp_client.ehlo()
361
362 # Wait for the delayed close
363 await asyncio.sleep(0.2)
364
365 assert not smtp_client.is_connected
366 assert not smtp_client._connect_lock.locked()
367
368 await asyncio.wait_for(smtp_client.connect(), 1.0)
369
370 assert smtp_client.is_connected
371
372
373 async def test_connect_with_login(
374 smtp_client: SMTP,
375 smtpd_server: asyncio.AbstractServer,
376 received_commands: list[tuple[str, tuple[Any, ...]]],
377 auth_username: str,
378 auth_password: str,
379 ) -> None:
380 # STARTTLS is required for login
381 await smtp_client.connect(
382 start_tls=True,
383 username=auth_username,
384 password=auth_password,
385 )
386
387 assert "AUTH" in [command[0] for command in received_commands]
388
389 await smtp_client.quit()
390
391
392 @pytest.mark.smtpd_options(starttls=False)
393 async def test_connect_with_no_starttls_support(smtp_client: SMTP) -> None:
394 await smtp_client.connect()
395
396 assert smtp_client.is_connected
397 assert not smtp_client.protocol._over_ssl
398
399 await smtp_client.quit()
400
401
402 async def test_connect_via_socket(
403 smtp_client: SMTP, hostname: str, smtpd_server_port: int
404 ) -> None:
405 with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
406 sock.connect((hostname, smtpd_server_port))
407
408 await smtp_client.connect(hostname=None, port=None, sock=sock)
409 response = await smtp_client.ehlo()
410
411 assert response.code == SMTPStatus.completed
412
413
414 async def test_connect_via_socket_path(
415 smtp_client: SMTP,
416 smtpd_server_socket_path: asyncio.AbstractServer,
417 socket_path: pathlib.Path | str | bytes,
418 ) -> None:
419 await smtp_client.connect(hostname=None, port=None, socket_path=socket_path)
420 response = await smtp_client.ehlo()
421
422 assert response.code == SMTPStatus.completed
423
424
425 @pytest.mark.smtpd_mocks(smtp_NOOP=mock_response_eof)
426 async def test_disconnected_server_get_transport_info(smtp_client: SMTP) -> None:
427 await smtp_client.connect()
428
429 with pytest.raises(SMTPServerDisconnected):
430 await smtp_client.execute_command(b"NOOP")
431
432 with pytest.raises(SMTPServerDisconnected, match="Server not connected"):
433 smtp_client.get_transport_info("sslcontext")
434
435
436 @pytest.mark.smtpd_mocks(smtp_NOOP=mock_response_eof)
437 async def test_disconnected_server_data(smtp_client: SMTP) -> None:
438 await smtp_client.connect()
439
440 with pytest.raises(SMTPServerDisconnected):
441 await smtp_client.execute_command(b"NOOP")
442
443 async def mock_ehlo_or_helo_if_needed() -> None:
444 pass
445
446 smtp_client._ehlo_or_helo_if_needed = mock_ehlo_or_helo_if_needed
447
448 with pytest.raises(SMTPServerDisconnected):
449 await smtp_client.data("123")
450
451
452 async def test_create_connection_runtime_error_on_missing_loop(
453 smtp_client: SMTP,
454 ) -> None:
455 client = SMTP(timeout=1.0)
456 with pytest.raises(RuntimeError, match="No event loop set"):
457 await client._create_connection(1.0)
458
459
460 def test_password_and_oauth_token_generator_mutually_exclusive() -> None:
461 """Test that password and oauth_token_generator cannot be used together."""
462
463 async def get_token() -> str:
464 return "token"
465
466 with pytest.raises(ValueError, match="mutually exclusive"):
467 SMTP(
468 hostname="localhost",
469 username="[email protected]",
470 password="password",
471 oauth_token_generator=get_token,
472 )
473
474
475 def test_oauth_token_generator_without_username() -> None:
476 """Test that oauth_token_generator can be set without username (error on connect)."""
477
478 async def get_token() -> str:
479 return "token"
480
481 # This should not raise on init - only on connect when auth is attempted
482 client = SMTP(hostname="localhost", oauth_token_generator=get_token)
483 assert client._oauth_token_generator is not None
484
485
486 async def test_connect_with_oauth_token_generator_no_xoauth2_support(
487 smtp_client: SMTP,
488 smtpd_server: asyncio.AbstractServer,
489 ) -> None:
490 """Test that oauth_token_generator raises when server doesn't support XOAUTH2."""
491
492 async def get_token() -> str:
493 return "test_token"
494
495 # Server doesn't advertise XOAUTH2
496 with pytest.raises(SMTPException, match="does not support XOAUTH2"):
497 await smtp_client.connect(
498 start_tls=True,
499 username="[email protected]",
500 oauth_token_generator=get_token,
501 )
502
503
504 async def test_connect_with_oauth_token_generator_no_username(
505 smtp_client: SMTP,
506 smtpd_server: asyncio.AbstractServer,
507 ) -> None:
508 """Test that oauth_token_generator requires username."""
509
510 async def get_token() -> str:
511 return "test_token"
512
513 with pytest.raises(SMTPException, match="username is required"):
514 await smtp_client.connect(
515 start_tls=True,
516 oauth_token_generator=get_token,
517 )
518
519
520 async def test_connect_cancellation_releases_lock(
521 smtp_client: SMTP,
522 smtpd_server: asyncio.AbstractServer,
523 monkeypatch: pytest.MonkeyPatch,
524 ) -> None:
525 async def slow_local_hostname() -> str:
526 await asyncio.sleep(10)
527 return "localhost"
528
529 monkeypatch.setattr(smtp_client, "_get_default_local_hostname", slow_local_hostname)
530
531 with pytest.raises(asyncio.TimeoutError):
532 await asyncio.wait_for(smtp_client.connect(), timeout=0.05)
533
534 monkeypatch.undo()
535
536 # Lock must be released so a subsequent connect() doesn't hang
537 await asyncio.wait_for(smtp_client.connect(), timeout=5.0)
538 assert smtp_client.is_connected
539 await smtp_client.quit()
540
541
542 @pytest.mark.smtpd_mocks(smtp_QUIT=mock_response_quit_error)
543 async def test_aexit_closes_connection_on_non_221_quit(smtp_client: SMTP) -> None:
544 async with smtp_client:
545 pass
546
547 assert not smtp_client.is_connected
548 assert smtp_client.transport is None
549
550
551 async def test_stale_connection_lost_does_not_sabotage_reconnect(
552 smtp_client: SMTP,
553 smtpd_server: asyncio.AbstractServer,
554 ) -> None:
555 await smtp_client.connect()
556 old_protocol = smtp_client.protocol
557
558 await smtp_client.quit()
559 await smtp_client.connect()
560
561 assert smtp_client.is_connected
562 assert smtp_client._connect_lock is not None
563 assert smtp_client._connect_lock.locked()
564
565 # Simulate a stale connection_lost from the old protocol arriving after reconnect
566 old_protocol.connection_lost(None)
567
568 assert smtp_client.is_connected
569 assert smtp_client._connect_lock.locked()