|
3 | 3 |
|
4 | 4 | from django.test.utils import override_settings
|
5 | 5 |
|
6 |
| -from ansible_base.jwt_consumer.common.util import generate_x_trusted_proxy_header, validate_x_trusted_proxy_header |
| 6 | +from ansible_base.jwt_consumer.common.util import _load_pem_private_key, generate_x_trusted_proxy_header, validate_x_trusted_proxy_header |
7 | 7 |
|
8 | 8 |
|
9 | 9 | class TestValidateTrustedProxy:
|
@@ -71,3 +71,26 @@ def test_validate_x_trusted_proxy_header_invalid_signature(self, random_public_k
|
71 | 71 | # 0 is invalid bytes
|
72 | 72 | timestamp, junk = header.split('-')
|
73 | 73 | assert validate_x_trusted_proxy_header(f"{timestamp}-0") is False
|
| 74 | + |
| 75 | + def test_generate_x_trusted_proxy_header(self, rsa_keypair, rsa_keypair_factory): |
| 76 | + """ |
| 77 | + This test ensures that, for the same key, the function is called only once. |
| 78 | + Otherwise, the function is not called and the return value is returned from the cache. |
| 79 | + """ |
| 80 | + _load_pem_private_key.cache_clear() |
| 81 | + new_rsa_keypair = rsa_keypair_factory() |
| 82 | + |
| 83 | + # Create a mock private key that has the sign method |
| 84 | + mock_private_key = mock.Mock() |
| 85 | + mock_private_key.sign.return_value = b'fake_signature' |
| 86 | + |
| 87 | + for keypair in [rsa_keypair, new_rsa_keypair]: |
| 88 | + with mock.patch("cryptography.hazmat.primitives.serialization.load_pem_private_key", return_value=mock_private_key) as mock_load_pem: |
| 89 | + # Call the function multiple times |
| 90 | + generate_x_trusted_proxy_header(keypair.private) |
| 91 | + generate_x_trusted_proxy_header(keypair.private) |
| 92 | + generate_x_trusted_proxy_header(keypair.private) |
| 93 | + |
| 94 | + # Verify the function is called only once due to caching |
| 95 | + assert mock_load_pem.call_count == 1 |
| 96 | + mock_load_pem.assert_called_with(bytes(keypair.private, 'utf-8'), password=None) |
0 commit comments