Tests for authens.shortcuts.register_cas_account

This commit is contained in:
Martin Pépin 2020-06-15 19:06:24 +02:00
parent cf4d80da13
commit 1cdc4a12d6
No known key found for this signature in database
GPG key ID: E7520278B1774448
2 changed files with 71 additions and 0 deletions

View file

@ -17,3 +17,27 @@ class FakeCASClient:
)
}
return self.cas_login, attributes, None
class FakeLDAPObject:
"""Fake object to be used in place of the result of `ldap.initialize`.
By default, always return the same entry 'johndoe'.
"""
def __init__(self, cas_login: str, entrance_year: int):
self.cas_login = cas_login
self.entrance_year = entrance_year
def search_s(self, base, scope, request, *args):
if request != "(uid={})".format(self.cas_login):
raise ValueError("I don't know how to answer this request!")
home_dir = "/users/{}/info/{}".format(self.entrance_year % 100, self.cas_login)
dn = "whatever"
attrs = {
"uid": [self.cas_login.encode("utf-8")],
"cn": ["{}'s long name".format(self.cas_login).encode("utf-8")],
"homeDirectory": [home_dir.encode("utf-8")],
}
return [(dn, attrs)]

View file

@ -0,0 +1,47 @@
from unittest import mock
from django.contrib.auth import get_user_model
from django.test import TestCase
from authens.models import CASAccount, OldCASAccount
from authens.shortcuts import register_cas_account
from authens.tests.cas_utils import FakeLDAPObject
User = get_user_model()
class TestRegisterCasAccount(TestCase):
@mock.patch("authens.shortcuts.ldap.initialize")
def test_register(self, mock_ldap_obj):
mock_ldap_obj.return_value = FakeLDAPObject("johndoe", 2019)
user = User.objects.create_user(username="whatever")
self.assertFalse(hasattr(user, "cas_account"))
register_cas_account(user, cas_login="johndoe")
user.refresh_from_db()
self.assertTrue(hasattr(user, "cas_account"))
self.assertEqual(user.cas_account.cas_login, "johndoe")
self.assertEqual(user.cas_account.entrance_year, 2019)
def test_cant_register_twice(self):
user = User.objects.create_user(username="whatever")
CASAccount.objects.create(user=user, cas_login="johndoe", entrance_year=2019)
with self.assertRaises(ValueError):
register_cas_account(user, cas_login="johndoe")
with self.assertRaises(ValueError):
register_cas_account(user, cas_login="janisjoplin")
self.assertEqual(CASAccount.objects.count(), 1)
def test_cant_register_old_account(self):
user = User.objects.create_user(username="whatever")
OldCASAccount.objects.create(user=user, cas_login="toto", entrance_year=2012)
with self.assertRaises(ValueError):
register_cas_account(user, cas_login="toto")
with self.assertRaises(ValueError):
register_cas_account(user, cas_login="ninasimone")
self.assertFalse(CASAccount.objects.exists())