| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
from unittest.mock import Mock, patch |
| 4 |
|
| 5 |
import pytest |
| 6 |
|
| 7 |
try: |
| 8 |
from urllib3.contrib.pyopenssl import extract_from_urllib3, inject_into_urllib3 |
| 9 |
except ImportError: |
| 10 |
pass |
| 11 |
|
| 12 |
|
| 13 |
def setup_module() -> None: |
| 14 |
try: |
| 15 |
from urllib3.contrib.pyopenssl import inject_into_urllib3 |
| 16 |
|
| 17 |
inject_into_urllib3() |
| 18 |
except ImportError as e: |
| 19 |
pytest.skip(f"Could not import PyOpenSSL: {e!r}") |
| 20 |
|
| 21 |
|
| 22 |
def teardown_module() -> None: |
| 23 |
try: |
| 24 |
from urllib3.contrib.pyopenssl import extract_from_urllib3 |
| 25 |
|
| 26 |
extract_from_urllib3() |
| 27 |
except ImportError: |
| 28 |
pass |
| 29 |
|
| 30 |
|
| 31 |
class TestPyOpenSSLInjection: |
| 32 |
""" |
| 33 |
Tests for error handling in pyopenssl's 'inject_into urllib3' |
| 34 |
""" |
| 35 |
|
| 36 |
def test_inject_validate_fail_cryptography(self) -> None: |
| 37 |
""" |
| 38 |
Injection should not be supported if cryptography is too old. |
| 39 |
""" |
| 40 |
try: |
| 41 |
with patch("cryptography.x509.extensions.Extensions") as mock: |
| 42 |
del mock.get_extension_for_class |
| 43 |
with pytest.raises(ImportError): |
| 44 |
inject_into_urllib3() |
| 45 |
finally: |
| 46 |
# `inject_into_urllib3` is not supposed to succeed. |
| 47 |
# If it does, this test should fail, but we need to |
| 48 |
# clean up so that subsequent tests are unaffected. |
| 49 |
extract_from_urllib3() |
| 50 |
|
| 51 |
def test_inject_validate_fail_pyopenssl(self) -> None: |
| 52 |
""" |
| 53 |
Injection should not be supported if pyOpenSSL is too old. |
| 54 |
""" |
| 55 |
try: |
| 56 |
return_val = Mock() |
| 57 |
del return_val._x509 |
| 58 |
with patch("OpenSSL.crypto.X509", return_value=return_val): |
| 59 |
with pytest.raises(ImportError): |
| 60 |
inject_into_urllib3() |
| 61 |
finally: |
| 62 |
# `inject_into_urllib3` is not supposed to succeed. |
| 63 |
# If it does, this test should fail, but we need to |
| 64 |
# clean up so that subsequent tests are unaffected. |
| 65 |
extract_from_urllib3() |