1
+ import contextlib
2
+
1
3
from django .contrib .auth import get_user_model
4
+ from django .contrib .auth .signals import user_logged_in
2
5
from django .utils .timezone import now
3
6
from rest_framework import status
4
7
from rest_framework .reverse import reverse
5
8
6
9
from kobo .apps .audit_log .models import AuditAction , AuditLog
10
+ from kobo .apps .audit_log .signals import create_access_log
7
11
from kpi .tests .base_test_case import BaseTestCase
8
12
from kpi .urls .router_api_v2 import URL_NAMESPACE as ROUTER_URL_NAMESPACE
9
13
10
14
15
+ @contextlib .contextmanager
16
+ def skip_login_access_log ():
17
+ """
18
+ Context manager for skipping the creation of an access log on login
19
+
20
+ Disconnects the method that creates access logs from the user_logged_in signal within the contextmanager block.
21
+ Useful when you want full control over the audit logs produced in a test.
22
+ """
23
+ user_logged_in .disconnect (create_access_log )
24
+ yield
25
+ user_logged_in .connect (create_access_log )
26
+
27
+
11
28
class ApiAuditLogTestCase (BaseTestCase ):
12
29
13
30
fixtures = ['test_data' ]
@@ -48,17 +65,20 @@ def test_list_as_superuser(self):
48
65
date_created = date_created ,
49
66
action = AuditAction .DELETE
50
67
)
51
- self .client .login (username = 'admin' , password = 'pass' )
52
- expected = [{
53
- 'app_label' : 'foo' ,
54
- 'model_name' : 'bar' ,
55
- 'object_id' : 1 ,
56
- 'user' : 'http://testserver/api/v2/users/someuser/' ,
57
- 'user_uid' : someuser .extra_details .uid ,
58
- 'action' : 'DELETE' ,
59
- 'metadata' : {},
60
- 'date_created' : date_created ,
61
- }]
68
+ with skip_login_access_log ():
69
+ self .client .login (username = 'admin' , password = 'pass' )
70
+ expected = [
71
+ {
72
+ 'app_label' : 'foo' ,
73
+ 'model_name' : 'bar' ,
74
+ 'object_id' : 1 ,
75
+ 'user' : 'http://testserver/api/v2/users/someuser/' ,
76
+ 'user_uid' : someuser .extra_details .uid ,
77
+ 'action' : 'DELETE' ,
78
+ 'metadata' : {},
79
+ 'date_created' : date_created ,
80
+ },
81
+ ]
62
82
response = self .client .get (self .audit_log_list_url )
63
83
audit_logs_count = AuditLog .objects .count ()
64
84
assert response .status_code == status .HTTP_200_OK
@@ -85,7 +105,8 @@ def test_filter_list(self):
85
105
date_created = date_created ,
86
106
action = AuditAction .DELETE ,
87
107
)
88
- self .client .login (username = 'admin' , password = 'pass' )
108
+ with skip_login_access_log ():
109
+ self .client .login (username = 'admin' , password = 'pass' )
89
110
expected = [{
90
111
'app_label' : 'foo' ,
91
112
'model_name' : 'bar' ,
0 commit comments