5
5
from bson .binary import Binary
6
6
from django .conf import settings
7
7
from django .db import connections
8
- from django .db .models import Model
9
8
10
9
from django_mongodb_backend .fields import EncryptedCharField
11
10
39
38
40
39
41
40
class EncryptedFieldTests (EncryptionTestCase ):
42
- def assertEncrypted (self , model_or_instance , field_name ):
43
- """
44
- Check if the field value in the database is stored as Binary.
45
- Works with either a Django model instance or a model class.
46
- """
47
-
48
- conn_params = connections ["encrypted" ].get_connection_params ()
41
+ def assertEncrypted (self , model , field ):
42
+ # Unencrypted connection to encrypted database
43
+ conn_params = connections ["default" ].get_connection_params ()
49
44
db_name = settings .DATABASES ["encrypted" ]["NAME" ]
50
-
51
- if conn_params .pop ("auto_encryption_opts" , False ):
52
- with pymongo .MongoClient (** conn_params ) as new_connection :
53
- if hasattr (model_or_instance , "_meta" ):
54
- collection_name = model_or_instance ._meta .db_table
55
- else :
56
- self .fail (f"Object { model_or_instance !r} is not a Django model or instance" )
57
-
58
- collection = new_connection [db_name ][collection_name ]
59
-
60
- # If it's an instance of a Django model, narrow to that _id
61
- if isinstance (model_or_instance , Model ):
62
- docs = collection .find (
63
- {"_id" : model_or_instance .pk , field_name : {"$exists" : True }}
64
- )
65
- else :
66
- # Otherwise it's a model class
67
- docs = collection .find ({field_name : {"$exists" : True }})
68
-
69
- found = False
70
- for doc in docs :
71
- found = True
72
- value = doc .get (field_name )
73
- self .assertTrue (
74
- isinstance (value , Binary ),
75
- msg = f"Field '{ field_name } ' in document { doc ['_id' ]} is "
76
- "not encrypted (type={type(value)})" ,
77
- )
78
-
79
- self .assertTrue (
80
- found ,
81
- msg = f"No documents with field '{ field_name } ' found in '{{collection_name}}'" ,
82
- )
83
-
84
- else :
85
- self .fail ("auto_encryption_opts is not configured; encryption not enabled." )
45
+ with pymongo .MongoClient (** conn_params ) as new_connection :
46
+ db = new_connection [db_name ]
47
+ collection_name = model ._meta .db_table
48
+ data = db [collection_name ].find ()[0 ]
49
+ self .assertIsInstance (data [field ], Binary )
86
50
87
51
88
52
class EncryptedEmbeddedModelTests (EncryptedFieldTests ):
@@ -98,6 +62,7 @@ def test_object(self):
98
62
self .assertEqual (patient .patient_record .ssn , "123-45-6789" )
99
63
self .assertEqual (patient .patient_record .billing .cc_type , "Visa" )
100
64
self .assertEqual (patient .patient_record .billing .cc_number , "4111111111111111" )
65
+ # self.assertEncrypted(patient, ["patient_record", "ssn"])
101
66
102
67
103
68
class EncryptedEmbeddedModelArrayTests (EncryptedFieldTests ):
0 commit comments