|
4 | 4 | from django.test import TestCase |
5 | 5 | from incuna_test_utils.utils import field_names |
6 | 6 |
|
7 | | -from pgcrypto import aggregates, proxy |
8 | | -from pgcrypto import fields |
| 7 | +from pgcrypto import aggregates, fields, proxy |
9 | 8 | from .factories import EncryptedModelFactory |
10 | 9 | from .forms import EncryptedForm |
11 | | -from .models import EncryptedModel |
12 | | - |
| 10 | +from .models import EncryptedModel, EncryptedModelWithManager |
13 | 11 |
|
14 | 12 | KEYED_FIELDS = (fields.TextDigestField, fields.TextHMACField) |
15 | 13 | EMAIL_PGP_FIELDS = (fields.EmailPGPPublicKeyField, fields.EmailPGPSymmetricKeyField) |
@@ -408,3 +406,44 @@ def test_null(self): |
408 | 406 | for field in fields: |
409 | 407 | with self.subTest(field=field): |
410 | 408 | self.assertEqual(getattr(instance, field), None) |
| 409 | + |
| 410 | + |
| 411 | +class TestPGPManager(TestCase): |
| 412 | + """Test `PGPManager` can be integrated in a `Django` model.""" |
| 413 | + model = EncryptedModelWithManager |
| 414 | + |
| 415 | + def test_auto_decryption(self): |
| 416 | + """Assert auto decryption via manager.""" |
| 417 | + expected_string = 'bonjour' |
| 418 | + expected_date = date(2016, 9, 1) |
| 419 | + expected_datetime = datetime(2016, 9, 1, 0, 0, 0) |
| 420 | + |
| 421 | + EncryptedModelFactory.create( |
| 422 | + digest_field=expected_string, |
| 423 | + hmac_field=expected_string, |
| 424 | + pgp_pub_field=expected_string, |
| 425 | + pgp_sym_field=expected_string, |
| 426 | + date_pgp_sym_field=expected_date, # Tests cast sql |
| 427 | + datetime_pgp_sym_field=expected_datetime, # Tests cast sql |
| 428 | + ) |
| 429 | + |
| 430 | + instance = self.model.objects.get() |
| 431 | + |
| 432 | + # Using `__dict__` bypasses "on the fly" decryption that normally occurs |
| 433 | + # if accessing a field that is not yet decrypted. |
| 434 | + # If decryption is not working, we get references to <In_Memory> classes |
| 435 | + self.assertEqual(instance.__dict__['pgp_pub_field'], expected_string) |
| 436 | + self.assertEqual(instance.__dict__['pgp_sym_field'], expected_string) |
| 437 | + self.assertEqual(instance.__dict__['date_pgp_sym_field'], expected_date) |
| 438 | + self.assertEqual(instance.__dict__['datetime_pgp_sym_field'], expected_datetime) |
| 439 | + |
| 440 | + # Ensure digest / hmac fields are unaffected |
| 441 | + count = self.model.objects.filter( |
| 442 | + digest_field__hash_of=expected_string |
| 443 | + ).count() |
| 444 | + self.assertEqual(count, 1) |
| 445 | + |
| 446 | + count = self.model.objects.filter( |
| 447 | + hmac_field__hash_of=expected_string |
| 448 | + ).count() |
| 449 | + self.assertEqual(count, 1) |
0 commit comments