Debian Codegraph @

tests/conftest.py

raw
1 """
2 Pytest fixtures and config.
3 """
4
5 import asyncio
6 import email.header
7 import email.message
8 import email.mime.multipart
9 import email.mime.text
10 import socket
11 import ssl
12 import sys
13 from collections.abc import AsyncGenerator, Callable, Generator, Mapping
14 from pathlib import Path
15 from typing import Any
16
17 import hypothesis
18 import pytest
19 import pytest_asyncio
20 import trustme
21 from aiosmtpd.controller import Controller as SMTPDController
22 from aiosmtpd.smtp import SMTP as SMTPD
23
24 from aiosmtplib import SMTP
25
26 from .auth import DummySMTPAuth
27 from .compat import cleanup_server
28 from .smtpd import RecordingHandler, TestSMTPD
29
30
31 try:
32 import uvloop
33 except ImportError:
34 HAS_UVLOOP = False
35 else:
36 HAS_UVLOOP = True
37 BASE_CERT_PATH = Path("tests/certs/")
38 IS_PYPY = hasattr(sys, "pypy_version_info")
39
40 # pypy can take a while to generate data, so don't fail the test due to health checks.
41 if IS_PYPY:
42 base_settings = hypothesis.settings(
43 suppress_health_check=(hypothesis.HealthCheck.too_slow,)
44 )
45 else:
46 base_settings = hypothesis.settings()
47 hypothesis.settings.register_profile("dev", parent=base_settings, max_examples=10)
48 hypothesis.settings.register_profile("ci", parent=base_settings, max_examples=100)
49
50
51 class ParamFixtureRequest(pytest.FixtureRequest):
52 param: Any
53
54
55 class EchoServerProtocol(asyncio.Protocol):
56 def connection_made(self, transport: asyncio.BaseTransport) -> None:
57 self.transport = transport
58
59 def data_received(self, data: bytes) -> None:
60 self.transport.write(data) # type: ignore
61
62
63 def pytest_addoption(parser: Any) -> None:
64 parser.addoption(
65 "--event-loop",
66 action="store",
67 dest="event_loop_type",
68 default="asyncio",
69 choices=["asyncio", "uvloop"],
70 help="event loop to run tests on",
71 )
72 parser.addoption(
73 "--bind-addr",
74 action="store",
75 default="127.0.0.1",
76 help="address to bind on for network tests",
77 )
78
79
80 def pytest_collection_modifyitems(
81 config: pytest.Config, items: list[pytest.Item]
82 ) -> None:
83 if config.getoption("event_loop_type") == "uvloop":
84 for item in items:
85 if "skip_if_uvloop" in item.keywords:
86 marker = pytest.mark.skip(reason="skipped on uvloop")
87 item.add_marker(marker)
88
89
90 @pytest_asyncio.fixture
91 async def debug_event_loop() -> AsyncGenerator[asyncio.AbstractEventLoop]:
92 event_loop = asyncio.get_running_loop()
93 previous_debug = event_loop.get_debug()
94 event_loop.set_debug(True)
95
96 yield event_loop
97
98 event_loop.set_debug(previous_debug)
99
100
101 def pytest_asyncio_loop_factories(
102 config: pytest.Config, item: pytest.Item
103 ) -> Mapping[str, Callable[[], asyncio.AbstractEventLoop]]:
104 if config.getoption("event_loop_type") == "uvloop":
105 if not HAS_UVLOOP:
106 raise RuntimeError("uvloop not installed.")
107 return {"uvloop": uvloop.new_event_loop}
108
109 return {"asyncio": asyncio.new_event_loop}
110
111
112 # Session scoped static values #
113
114
115 @pytest.fixture(scope="session")
116 def bind_address(request: pytest.FixtureRequest) -> str:
117 """Server side address for socket binding"""
118 return str(request.config.getoption("--bind-addr"))
119
120
121 @pytest.fixture(scope="session")
122 def hostname(bind_address: str) -> str:
123 return bind_address
124
125
126 @pytest.fixture(scope="session")
127 def recipient_str() -> str:
128 return "[email protected]"
129
130
131 @pytest.fixture(scope="session")
132 def sender_str() -> str:
133 return "[email protected]"
134
135
136 @pytest.fixture(scope="session")
137 def message_str(recipient_str: str, sender_str: str) -> str:
138 return (
139 "Content-Type: multipart/mixed; "
140 'boundary="===============6842273139637972052=="\n'
141 "MIME-Version: 1.0\n"
142 f"To: {recipient_str}\n"
143 f"From: {sender_str}\n"
144 "Subject: A message\n\n"
145 "--===============6842273139637972052==\n"
146 'Content-Type: text/plain; charset="us-ascii"\n'
147 "MIME-Version: 1.0\n"
148 "Content-Transfer-Encoding: 7bit\n\n"
149 "Hello World\n"
150 "--===============6842273139637972052==--\n"
151 )
152
153
154 @pytest.fixture(scope="session")
155 def message_bytes(message_str: str) -> bytes:
156 return message_str.encode("ascii")
157
158
159 @pytest.fixture(scope="session")
160 def smtpd_class() -> type[SMTPD]:
161 return TestSMTPD
162
163
164 @pytest.fixture(scope="session")
165 def cert_authority() -> trustme.CA:
166 return trustme.CA()
167
168
169 @pytest.fixture(scope="session")
170 def unknown_cert_authority() -> trustme.CA:
171 return trustme.CA()
172
173
174 @pytest.fixture(scope="session")
175 def valid_server_cert(cert_authority: trustme.CA, hostname: str) -> trustme.LeafCert:
176 return cert_authority.issue_cert(hostname)
177
178
179 @pytest.fixture(scope="session")
180 def valid_client_cert(cert_authority: trustme.CA, hostname: str) -> trustme.LeafCert:
181 return cert_authority.issue_cert(f"user@{hostname}")
182
183
184 @pytest.fixture(scope="session")
185 def unknown_client_cert(
186 unknown_cert_authority: trustme.CA, hostname: str
187 ) -> trustme.LeafCert:
188 return unknown_cert_authority.issue_cert(f"user@{hostname}")
189
190
191 @pytest.fixture(scope="session")
192 def client_tls_context(
193 cert_authority: trustme.CA, valid_client_cert: trustme.LeafCert
194 ) -> ssl.SSLContext:
195 tls_context = ssl.create_default_context()
196 cert_authority.configure_trust(tls_context)
197 valid_client_cert.configure_cert(tls_context)
198
199 return tls_context
200
201
202 @pytest.fixture(scope="session")
203 def unknown_client_tls_context(
204 unknown_cert_authority: trustme.CA, unknown_client_cert: trustme.LeafCert
205 ) -> ssl.SSLContext:
206 tls_context = ssl.create_default_context()
207 unknown_cert_authority.configure_trust(tls_context)
208 unknown_client_cert.configure_cert(tls_context)
209
210 return tls_context
211
212
213 @pytest.fixture(scope="session")
214 def server_tls_context(
215 cert_authority: trustme.CA, valid_server_cert: trustme.LeafCert
216 ) -> ssl.SSLContext:
217 tls_context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
218 cert_authority.configure_trust(tls_context)
219 valid_server_cert.configure_cert(tls_context)
220 tls_context.verify_mode = ssl.CERT_OPTIONAL
221
222 return tls_context
223
224
225 @pytest.fixture(scope="session")
226 def ca_cert_path(
227 tmp_path_factory: pytest.TempPathFactory, cert_authority: trustme.CA
228 ) -> str:
229 tmp_path = tmp_path_factory.mktemp("cacert")
230
231 cert_authority.cert_pem.write_to_path(tmp_path / "ca.pem")
232
233 return str(tmp_path / "ca.pem")
234
235
236 @pytest.fixture(scope="session")
237 def valid_cert_path(
238 tmp_path_factory: pytest.TempPathFactory, valid_client_cert: trustme.LeafCert
239 ) -> str:
240 tmp_path = tmp_path_factory.mktemp("cert-valid-pem")
241 for pem in valid_client_cert.cert_chain_pems:
242 pem.write_to_path(tmp_path / "valid.pem", append=True)
243
244 return str(tmp_path / "valid.pem")
245
246
247 @pytest.fixture(scope="session")
248 def valid_key_path(
249 tmp_path_factory: pytest.TempPathFactory, valid_client_cert: trustme.LeafCert
250 ) -> str:
251 tmp_path = tmp_path_factory.mktemp("cert-valid-key")
252
253 valid_client_cert.private_key_pem.write_to_path(tmp_path / "valid.key")
254
255 return str(tmp_path / "valid.key")
256
257
258 @pytest.fixture(scope="session")
259 def invalid_cert_path(
260 tmp_path_factory: pytest.TempPathFactory, unknown_client_cert: trustme.LeafCert
261 ) -> str:
262 tmp_path = tmp_path_factory.mktemp("cert-invalid-pem")
263 for pem in unknown_client_cert.cert_chain_pems:
264 pem.write_to_path(tmp_path / "invalid.pem", append=True)
265
266 return str(tmp_path / "invalid.pem")
267
268
269 @pytest.fixture(scope="session")
270 def invalid_key_path(
271 tmp_path_factory: pytest.TempPathFactory, unknown_client_cert: trustme.LeafCert
272 ) -> str:
273 tmp_path = tmp_path_factory.mktemp("cert-invalid-key")
274 unknown_client_cert.private_key_pem.write_to_path(tmp_path / "invalid.key")
275 return str(tmp_path / "invalid.key")
276
277
278 @pytest.fixture(scope="session")
279 def auth_username() -> str:
280 return "test"
281
282
283 @pytest.fixture(scope="session")
284 def auth_password() -> str:
285 return "test"
286
287
288 # Auth #
289
290
291 @pytest.fixture(scope="function")
292 def mock_auth() -> DummySMTPAuth:
293 return DummySMTPAuth()
294
295
296 # Messages #
297
298
299 @pytest.fixture(scope="function")
300 def compat32_message(recipient_str: str, sender_str: str) -> email.message.Message:
301 message = email.message.Message()
302 message["To"] = email.header.Header(recipient_str)
303 message["From"] = email.header.Header(sender_str)
304 message["Subject"] = "A message"
305 message.set_payload("Hello World")
306
307 return message
308
309
310 @pytest.fixture(scope="function")
311 def mime_message(
312 recipient_str: str, sender_str: str
313 ) -> email.mime.multipart.MIMEMultipart:
314 message = email.mime.multipart.MIMEMultipart()
315 message["To"] = recipient_str
316 message["From"] = sender_str
317 message["Subject"] = "A message"
318 message.attach(email.mime.text.MIMEText("Hello World"))
319
320 return message
321
322
323 @pytest.fixture(scope="function")
324 def email_message(recipient_str: str, sender_str: str) -> email.message.EmailMessage:
325 message = email.message.EmailMessage()
326 message["To"] = recipient_str
327 message["From"] = sender_str
328 message["Subject"] = "A message"
329 message.set_payload("Hello World")
330
331 return message
332
333
334 @pytest.fixture(scope="function")
335 def message(
336 request: pytest.FixtureRequest,
337 email_message: email.message.EmailMessage,
338 compat32_message: email.message.Message,
339 mime_message: email.mime.multipart.MIMEMultipart,
340 message_str: str,
341 message_bytes: bytes,
342 ) -> email.message.EmailMessage | email.message.Message | str | bytes:
343 if not hasattr(request, "param"):
344 return email_message
345
346 if request.param == "compat32_message":
347 return compat32_message
348 elif request.param == "mime_message":
349 return mime_message
350 elif request.param == "str":
351 return message_str
352 elif request.param == "bytes":
353 return message_bytes
354 else:
355 return email_message
356
357
358 # Server helpers and factories #
359
360
361 @pytest.fixture(scope="function")
362 def received_messages() -> list[email.message.EmailMessage]:
363 return []
364
365
366 @pytest.fixture(scope="function")
367 def received_commands() -> list[tuple[str, tuple[Any, ...]]]:
368 return []
369
370
371 @pytest.fixture(scope="function")
372 def smtpd_responses() -> list[str]:
373 return []
374
375
376 @pytest.fixture(scope="function")
377 def smtpd_handler(
378 received_messages: list[email.message.EmailMessage],
379 received_commands: list[tuple[str, tuple[Any, ...]]],
380 smtpd_responses: list[str],
381 ) -> RecordingHandler:
382 return RecordingHandler(received_messages, received_commands, smtpd_responses)
383
384
385 @pytest.fixture(scope="session")
386 def smtpd_auth_callback(
387 auth_username: str, auth_password: str
388 ) -> Callable[[str, bytes, bytes], bool]:
389 def auth_callback(mechanism: str, username: bytes, password: bytes) -> bool:
390 return bool(
391 username.decode("utf-8") == auth_username
392 and password.decode("utf-8") == auth_password
393 )
394
395 return auth_callback
396
397
398 @pytest.fixture(scope="function")
399 def socket_path(tmp_path: Path) -> Path:
400 if sys.platform.startswith("darwin"):
401 # Work around OSError: AF_UNIX path too long
402 tmp_dir = Path("/tmp") # nosec
403 else:
404 tmp_dir = tmp_path
405
406 index = 0
407 socket_path = tmp_dir / f"aiosmtplib-test{index}"
408 while socket_path.exists():
409 index += 1
410 socket_path = tmp_dir / f"aiosmtplib-test{index}"
411
412 return socket_path
413
414
415 # Servers #
416
417
418 @pytest.fixture(scope="function")
419 def smtpd_factory(
420 request: pytest.FixtureRequest,
421 monkeypatch: pytest.MonkeyPatch,
422 hostname: str,
423 smtpd_handler: RecordingHandler,
424 server_tls_context: ssl.SSLContext,
425 smtpd_auth_callback: Callable[[str, bytes, bytes], bool],
426 ) -> Callable[[], SMTPD]:
427 smtpd_options_marker = request.node.get_closest_marker("smtpd_options")
428 if smtpd_options_marker is None:
429 smtpd_options = {}
430 else:
431 smtpd_options = smtpd_options_marker.kwargs
432
433 smtpd_mocks_marker = request.node.get_closest_marker("smtpd_mocks")
434 if smtpd_mocks_marker is None:
435 smtpd_mocks = {}
436 else:
437 smtpd_mocks = smtpd_mocks_marker.kwargs
438
439 for attr, mock_fn in smtpd_mocks.items():
440 monkeypatch.setattr(TestSMTPD, attr, mock_fn)
441
442 smtpd_tls_context = (
443 server_tls_context
444 if smtpd_options.get("starttls", True) or smtpd_options.get("tls", False)
445 else None
446 )
447
448 def factory() -> SMTPD:
449 return TestSMTPD(
450 smtpd_handler,
451 hostname=hostname,
452 enable_SMTPUTF8=smtpd_options.get("smtputf8", False),
453 decode_data=smtpd_options.get("7bit", False),
454 tls_context=smtpd_tls_context,
455 auth_callback=smtpd_auth_callback,
456 )
457
458 return factory
459
460
461 @pytest_asyncio.fixture(scope="function")
462 async def smtpd_server(
463 request: pytest.FixtureRequest,
464 bind_address: str,
465 server_tls_context: ssl.SSLContext,
466 smtpd_factory: Callable[[], SMTPD],
467 ) -> AsyncGenerator[asyncio.AbstractServer]:
468 smtpd_options_marker = request.node.get_closest_marker("smtpd_options")
469 if smtpd_options_marker is None:
470 smtpd_options = {}
471 else:
472 smtpd_options = smtpd_options_marker.kwargs
473
474 create_server_kwargs = {
475 "host": bind_address,
476 "port": 0,
477 "family": socket.AF_INET,
478 }
479 if smtpd_options.get("tls", False):
480 create_server_kwargs["ssl"] = server_tls_context
481
482 event_loop = asyncio.get_running_loop()
483 server = await event_loop.create_server(smtpd_factory, **create_server_kwargs)
484
485 yield server
486
487 server.close()
488 try:
489 await cleanup_server(server)
490 except RuntimeError:
491 pass
492
493
494 @pytest_asyncio.fixture(scope="function")
495 async def echo_server(bind_address: str) -> AsyncGenerator[asyncio.AbstractServer]:
496 event_loop = asyncio.get_running_loop()
497 server = await event_loop.create_server(
498 EchoServerProtocol, host=bind_address, port=0, family=socket.AF_INET
499 )
500
501 yield server
502
503 server.close()
504 try:
505 await cleanup_server(server)
506 except RuntimeError:
507 pass
508
509
510 @pytest_asyncio.fixture(scope="function")
511 async def smtpd_server_socket_path(
512 request: pytest.FixtureRequest,
513 socket_path: str | bytes | Path,
514 server_tls_context: ssl.SSLContext,
515 smtpd_factory: Callable[[], SMTPD],
516 ) -> AsyncGenerator[asyncio.AbstractServer]:
517 smtpd_options_marker = request.node.get_closest_marker("smtpd_options")
518 if smtpd_options_marker is None:
519 smtpd_options = {}
520 else:
521 smtpd_options = smtpd_options_marker.kwargs
522
523 event_loop = asyncio.get_running_loop()
524 server = await event_loop.create_unix_server(
525 smtpd_factory,
526 path=socket_path, # type: ignore
527 ssl=server_tls_context if smtpd_options.get("tls", False) else None,
528 )
529
530 yield server
531
532 server.close()
533 try:
534 await cleanup_server(server)
535 except RuntimeError:
536 pass
537
538
539 @pytest.fixture(scope="function")
540 def smtpd_controller(
541 bind_address: str,
542 unused_tcp_port: int,
543 smtpd_handler: RecordingHandler,
544 ) -> Generator[SMTPDController, None, None]:
545 port = unused_tcp_port
546 controller: SMTPDController | None
547 controller = SMTPDController(smtpd_handler, hostname=bind_address, port=port)
548 controller.start()
549
550 yield controller
551
552 controller.stop()
553
554
555 @pytest.fixture(scope="function")
556 def smtpd_server_threaded(smtpd_controller: SMTPDController) -> asyncio.AbstractServer:
557 server: asyncio.AbstractServer = smtpd_controller.server
558 return server
559
560
561 # Running server ports #
562
563
564 @pytest_asyncio.fixture(scope="function")
565 async def smtpd_server_port(smtpd_server: asyncio.Server) -> int:
566 return int(smtpd_server.sockets[0].getsockname()[1])
567
568
569 @pytest_asyncio.fixture(scope="function")
570 async def echo_server_port(echo_server: asyncio.Server) -> int:
571 return int(echo_server.sockets[0].getsockname()[1])
572
573
574 @pytest.fixture(scope="function")
575 def smtpd_server_threaded_port(smtpd_controller: SMTPDController) -> int:
576 port: int = smtpd_controller.port
577 return port
578
579
580 # SMTP Clients #
581
582
583 @pytest_asyncio.fixture(scope="function")
584 async def smtp_client(
585 request: pytest.FixtureRequest,
586 hostname: str,
587 smtpd_server_port: int,
588 client_tls_context: ssl.SSLContext,
589 ) -> SMTP:
590 smtp_client_options_marker = request.node.get_closest_marker("smtp_client_options")
591 if smtp_client_options_marker is None:
592 smtp_client_options = {}
593 else:
594 smtp_client_options = smtp_client_options_marker.kwargs
595
596 smtp_client_options.setdefault("tls_context", client_tls_context)
597 smtp_client_options.setdefault("start_tls", False)
598
599 return SMTP(
600 hostname=hostname,
601 port=smtpd_server_port,
602 timeout=1.0,
603 **smtp_client_options,
604 )
605
606
607 @pytest_asyncio.fixture(scope="function")
608 async def smtp_client_threaded(
609 hostname: str, smtpd_server_threaded_port: int, client_tls_context: ssl.SSLContext
610 ) -> SMTP:
611 return SMTP(
612 hostname=hostname,
613 port=smtpd_server_threaded_port,
614 timeout=1.0,
615 start_tls=False,
616 tls_context=client_tls_context,
617 )