-
-
Notifications
You must be signed in to change notification settings - Fork 188
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
30 additions
and
18 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,15 +1,30 @@ | ||
import contextlib | ||
from unittest.mock import patch | ||
|
||
from allauth.account.models import EmailAddress | ||
from django.contrib.auth import get_user_model | ||
from django.contrib.auth.signals import user_logged_in | ||
from django.urls import resolve, reverse | ||
from trench.utils import get_mfa_model | ||
|
||
from kobo.apps.accounts.mfa.forms import MfaTokenForm | ||
from kobo.apps.audit_log.models import AuditAction, AuditLog | ||
from kobo.apps.audit_log.signals import create_access_log | ||
from kpi.tests.base_test_case import BaseTestCase | ||
|
||
|
||
@contextlib.contextmanager | ||
def skip_login_access_log(): | ||
""" | ||
Context manager for skipping the creation of an access log on login | ||
Disconnects the method that creates access logs from the user_logged_in signal within the contextmanager block. | ||
Useful when you want full control over the audit logs produced in a test. | ||
""" | ||
user_logged_in.disconnect(create_access_log) | ||
yield | ||
user_logged_in.connect(create_access_log) | ||
|
||
|
||
class AuditLogSignalsTestCase(BaseTestCase): | ||
""" | ||
Class for testing that logins produce AuditLogs. | ||
|
@@ -102,3 +117,16 @@ def test_mfa_login(self): | |
audit_log = AuditLog.objects.first() | ||
self.assertEqual(audit_log.user.id, AuditLogSignalsTestCase.user.id) | ||
self.assertEqual(audit_log.action, AuditAction.AUTH) | ||
|
||
def test_loginas(self): | ||
AuditLogSignalsTestCase.user.is_superuser = True | ||
AuditLogSignalsTestCase.user.save() | ||
new_user = get_user_model().objects.create_user('user2', '[email protected]', 'pass2') | ||
new_user.save() | ||
with skip_login_access_log(): | ||
self.client.login(username='user', password='pass') | ||
self.client.post(reverse('loginas-user-login', args=[new_user.id])) | ||
self.assertEqual(AuditLog.objects.count(), 1) | ||
audit_log = AuditLog.objects.first() | ||
self.assertEqual(audit_log.user.id, new_user.id) | ||
self.assertEqual(audit_log.action, AuditAction.AUTH) |