|
| 1 | +from unittest.mock import Mock |
| 2 | +from cert_chain_resolver.exceptions import MissingCertProperty |
1 | 3 | from .fixtures import BUNDLE_FIXTURES, CERT_FIXTURES, certfixture_to_id
|
| 4 | +from cryptography import x509 |
2 | 5 | from cert_chain_resolver.models import Cert, CertificateChain
|
| 6 | +from cryptography.x509.oid import ExtensionOID, AuthorityInformationAccessOID, NameOID |
3 | 7 | import pytest
|
4 | 8 |
|
5 | 9 | try:
|
@@ -88,3 +92,52 @@ def test_certificatechain_constructs_from_pem_in_order(bundle):
|
88 | 92 |
|
89 | 93 | chain = CertificateChain.load_from_pem(pem_bundle)
|
90 | 94 | assert list(chain) == [Cert(x["cert_x509"]) for x in bundle]
|
| 95 | + |
| 96 | + |
| 97 | +@pytest.mark.parametrize( |
| 98 | + "prop,extension_oid,expected", |
| 99 | + [ |
| 100 | + ("ca_issuer_access_location", ExtensionOID.AUTHORITY_INFORMATION_ACCESS, None), |
| 101 | + ("subject_alternative_names", ExtensionOID.SUBJECT_ALTERNATIVE_NAME, []), |
| 102 | + ("is_ca", ExtensionOID.BASIC_CONSTRAINTS, False), |
| 103 | + ], |
| 104 | +) |
| 105 | +def test_missing_cert_extensions_return_defaults_when_missing( |
| 106 | + mocker, prop, extension_oid, expected |
| 107 | +): |
| 108 | + m = mocker.Mock(spec=x509.Certificate) |
| 109 | + mock_extensions = mocker.Mock() |
| 110 | + mock_extensions.get_extension_for_oid.side_effect = ( |
| 111 | + x509.extensions.ExtensionNotFound("Extension not found", extension_oid) |
| 112 | + ) |
| 113 | + m.extensions = mock_extensions |
| 114 | + c = Cert(m) |
| 115 | + assert getattr(c, prop) == expected |
| 116 | + |
| 117 | + |
| 118 | +@pytest.mark.parametrize( |
| 119 | + "prop,cert_prop, cert_value", |
| 120 | + [ |
| 121 | + ("signature_hash_algorithm", "signature_hash_algorithm", None), |
| 122 | + ("common_name", "subject", Mock(get_attributes_for_oid=Mock(return_value=[]))), |
| 123 | + ], |
| 124 | +) |
| 125 | +def test_missing_cert_properties_raise(mocker, prop, cert_prop, cert_value): |
| 126 | + m = mocker.Mock(spec=x509.Certificate) |
| 127 | + setattr(m, cert_prop, cert_value) |
| 128 | + c = Cert(m) |
| 129 | + |
| 130 | + with pytest.raises(MissingCertProperty): |
| 131 | + getattr(c, prop) |
| 132 | + |
| 133 | + |
| 134 | +def test_repr(): |
| 135 | + class CertOverride(Cert): |
| 136 | + subject = "Subject" |
| 137 | + issuer = "Issuer" |
| 138 | + common_name = "CN" |
| 139 | + __init__ = lambda *_: None |
| 140 | + |
| 141 | + c = CertOverride() |
| 142 | + |
| 143 | + assert repr(c) == '<Cert common_name="CN" subject="Subject" issuer="Issuer">' |
0 commit comments