|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +from unittest.mock import Mock |
| 4 | + |
| 5 | +import pytest |
| 6 | + |
| 7 | +import mesh_client |
| 8 | + |
| 9 | + |
| 10 | +class SSLContextStub: |
| 11 | + def __init__(self) -> None: |
| 12 | + self.load_cert_chain = Mock() |
| 13 | + self.load_verify_locations = Mock() |
| 14 | + self.minimum_version = None |
| 15 | + self.check_hostname = None |
| 16 | + self.verify_mode = None |
| 17 | + self.hostname_checks_common_name = None |
| 18 | + |
| 19 | + |
| 20 | +@pytest.mark.parametrize( |
| 21 | + ("certs", "loads_cert_chain_called"), |
| 22 | + [ |
| 23 | + (("client.crt", "client.key"), True), |
| 24 | + (None, False), |
| 25 | + (["client.crt", "client.key"], True), |
| 26 | + ], |
| 27 | +) |
| 28 | +def test_create_ssl_context_loads_cert_chain( |
| 29 | + monkeypatch, certs: tuple[str, str] | list[str] | None, loads_cert_chain_called: bool |
| 30 | +): |
| 31 | + |
| 32 | + dummy_context = SSLContextStub() |
| 33 | + monkeypatch.setattr(mesh_client, "create_urllib3_context", lambda: dummy_context) |
| 34 | + |
| 35 | + adapter = mesh_client.SSLContextAdapter(cert=certs, verify=None) # type: ignore[arg-type] |
| 36 | + dummy_context.load_cert_chain.reset_mock() |
| 37 | + |
| 38 | + context = adapter.create_ssl_context() |
| 39 | + |
| 40 | + assert context is dummy_context |
| 41 | + |
| 42 | + if loads_cert_chain_called: |
| 43 | + assert certs is not None |
| 44 | + dummy_context.load_cert_chain.assert_called_with(*certs) |
| 45 | + else: |
| 46 | + dummy_context.load_cert_chain.assert_not_called() |
| 47 | + |
| 48 | + |
| 49 | +@pytest.mark.parametrize("verify", [True, False, "/path/to/ca.pem", b"/path/to/ca.pem", None]) |
| 50 | +def test_create_ssl_context_loads_verify_locations_when_verify_is_provided( |
| 51 | + monkeypatch, verify: bool | str | bytes | None |
| 52 | +): |
| 53 | + |
| 54 | + dummy_context = SSLContextStub() |
| 55 | + monkeypatch.setattr(mesh_client, "create_urllib3_context", lambda: dummy_context) |
| 56 | + |
| 57 | + adapter = mesh_client.SSLContextAdapter(cert=None, verify=verify) # type: ignore[arg-type] |
| 58 | + context = adapter.create_ssl_context() |
| 59 | + |
| 60 | + assert context is dummy_context |
| 61 | + |
| 62 | + if type(verify) in (str, bytes): |
| 63 | + dummy_context.load_verify_locations.assert_called_with(verify) |
| 64 | + else: |
| 65 | + dummy_context.load_verify_locations.assert_not_called() |
0 commit comments