2017-08-10 15:02:08 +02:00
|
|
|
from unittest import mock
|
2017-08-16 17:45:59 +02:00
|
|
|
from urllib.parse import parse_qs, urlparse
|
2017-08-10 15:02:08 +02:00
|
|
|
|
|
|
|
from django.http import QueryDict
|
|
|
|
from django.test import Client
|
2019-03-19 10:18:56 +01:00
|
|
|
from django.urls import reverse
|
2017-08-16 17:45:59 +02:00
|
|
|
from django.utils import timezone
|
2017-09-01 16:37:14 +02:00
|
|
|
from django.utils.functional import cached_property
|
2017-08-10 15:02:08 +02:00
|
|
|
|
|
|
|
from .utils import create_root, create_team, create_user
|
|
|
|
|
|
|
|
|
2017-08-16 17:45:59 +02:00
|
|
|
class TestCaseMixin:
|
2017-09-01 12:39:17 +02:00
|
|
|
"""Extends TestCase for kfet application tests."""
|
|
|
|
|
2017-08-16 17:45:59 +02:00
|
|
|
def assertForbidden(self, response):
|
2017-09-01 12:39:17 +02:00
|
|
|
"""
|
|
|
|
Test that the response (retrieved with a Client) is a denial of access.
|
|
|
|
|
|
|
|
The response should verify one of the following:
|
|
|
|
- its HTTP response code is 403,
|
|
|
|
- it redirects to the login page with a GET parameter named 'next'
|
|
|
|
whose value is the url of the requested page.
|
|
|
|
|
|
|
|
"""
|
2017-08-16 17:45:59 +02:00
|
|
|
request = response.wsgi_request
|
|
|
|
|
|
|
|
try:
|
|
|
|
try:
|
|
|
|
# Is this an HTTP Forbidden response ?
|
|
|
|
self.assertEqual(response.status_code, 403)
|
|
|
|
except AssertionError:
|
|
|
|
# A redirection to the login view is fine too.
|
|
|
|
|
|
|
|
# Let's build the login url with the 'next' param on current
|
|
|
|
# page.
|
|
|
|
full_path = request.get_full_path()
|
|
|
|
|
|
|
|
querystring = QueryDict(mutable=True)
|
2018-10-06 12:35:49 +02:00
|
|
|
querystring["next"] = full_path
|
2017-08-16 17:45:59 +02:00
|
|
|
|
2020-08-30 18:49:22 +02:00
|
|
|
login_url = "/gestion/login?" + querystring.urlencode(safe="/")
|
2017-08-16 17:45:59 +02:00
|
|
|
|
|
|
|
# We don't focus on what the login view does.
|
|
|
|
# So don't fetch the redirect.
|
2018-10-06 12:35:49 +02:00
|
|
|
self.assertRedirects(response, login_url, fetch_redirect_response=False)
|
2017-08-16 17:45:59 +02:00
|
|
|
except AssertionError:
|
|
|
|
raise AssertionError(
|
|
|
|
"%(http_method)s request at %(path)s should be forbidden for "
|
|
|
|
"%(username)s user.\n"
|
|
|
|
"Response isn't 403, nor a redirect to login view. Instead, "
|
2018-10-06 12:35:49 +02:00
|
|
|
"response code is %(code)d."
|
|
|
|
% {
|
|
|
|
"http_method": request.method,
|
|
|
|
"path": request.get_full_path(),
|
|
|
|
"username": (
|
2017-08-16 17:45:59 +02:00
|
|
|
"'{}'".format(request.user)
|
2017-11-19 18:41:39 +01:00
|
|
|
if request.user.is_authenticated
|
2018-10-06 12:35:49 +02:00
|
|
|
else "anonymous"
|
2017-08-16 17:45:59 +02:00
|
|
|
),
|
2018-10-06 12:35:49 +02:00
|
|
|
"code": response.status_code,
|
2017-08-16 17:45:59 +02:00
|
|
|
}
|
|
|
|
)
|
|
|
|
|
2018-10-06 12:35:49 +02:00
|
|
|
def assertForbiddenKfet(self, response, form_ctx="form"):
|
2017-09-01 12:39:17 +02:00
|
|
|
"""
|
|
|
|
Test that a response (retrieved with a Client) contains error due to
|
|
|
|
lack of kfet permissions.
|
|
|
|
|
|
|
|
It checks that 'Permission refusée' is present in the non-field errors
|
|
|
|
of the form of response context at key 'form_ctx', or present in
|
|
|
|
messages.
|
|
|
|
|
|
|
|
This should be used for pages which can be accessed by the kfet team
|
|
|
|
members, but require additionnal permission(s) to make an operation.
|
|
|
|
|
|
|
|
"""
|
2017-08-16 17:45:59 +02:00
|
|
|
try:
|
|
|
|
self.assertEqual(response.status_code, 200)
|
|
|
|
try:
|
|
|
|
form = response.context[form_ctx]
|
2021-02-20 19:18:21 +01:00
|
|
|
errors = [y for x in form.errors.as_data().values() for y in x]
|
|
|
|
self.assertTrue(any(e.code == "permission-denied" for e in errors))
|
2017-08-16 17:45:59 +02:00
|
|
|
except (AssertionError, AttributeError, KeyError):
|
2021-02-20 19:18:21 +01:00
|
|
|
self.assertTrue(
|
|
|
|
any(
|
|
|
|
"permission-denied" in msg.tags
|
|
|
|
for msg in response.context["messages"]
|
|
|
|
)
|
|
|
|
)
|
2017-08-16 17:45:59 +02:00
|
|
|
except AssertionError:
|
|
|
|
request = response.wsgi_request
|
|
|
|
raise AssertionError(
|
|
|
|
"%(http_method)s request at %(path)s should raise an error "
|
|
|
|
"for %(username)s user.\n"
|
|
|
|
"Cannot find any errors in non-field errors of form "
|
2018-10-06 12:35:49 +02:00
|
|
|
"'%(form_ctx)s', nor in messages."
|
|
|
|
% {
|
|
|
|
"http_method": request.method,
|
|
|
|
"path": request.get_full_path(),
|
|
|
|
"username": (
|
2017-08-16 17:45:59 +02:00
|
|
|
"'%s'" % request.user
|
2017-11-19 18:41:39 +01:00
|
|
|
if request.user.is_authenticated
|
2018-10-06 12:35:49 +02:00
|
|
|
else "anonymous"
|
2017-08-16 17:45:59 +02:00
|
|
|
),
|
2018-10-06 12:35:49 +02:00
|
|
|
"form_ctx": form_ctx,
|
2017-08-16 17:45:59 +02:00
|
|
|
}
|
|
|
|
)
|
|
|
|
|
|
|
|
def assertInstanceExpected(self, instance, expected):
|
2017-09-01 12:39:17 +02:00
|
|
|
"""
|
|
|
|
Test that the values of the attributes and without-argument methods of
|
|
|
|
'instance' are equal to 'expected' pairs.
|
|
|
|
"""
|
2017-08-16 17:45:59 +02:00
|
|
|
for attr, expected_value in expected.items():
|
|
|
|
value = getattr(instance, attr)
|
|
|
|
if callable(value):
|
|
|
|
value = value()
|
|
|
|
self.assertEqual(value, expected_value)
|
|
|
|
|
|
|
|
def assertUrlsEqual(self, actual, expected):
|
2017-09-01 12:39:17 +02:00
|
|
|
"""
|
|
|
|
Test that the url 'actual' is as 'expected'.
|
|
|
|
|
|
|
|
Arguments:
|
|
|
|
actual (str): Url to verify.
|
|
|
|
expected: Two forms are accepted.
|
|
|
|
* (str): Expected url. Strings equality is checked.
|
|
|
|
* (dict): Its keys must be attributes of 'urlparse(actual)'.
|
|
|
|
Equality is checked for each present key, except for
|
|
|
|
'query' which must be a dict of the expected query string
|
|
|
|
parameters.
|
|
|
|
|
|
|
|
"""
|
2017-08-16 17:45:59 +02:00
|
|
|
if type(expected) == dict:
|
|
|
|
parsed = urlparse(actual)
|
2017-09-01 12:39:17 +02:00
|
|
|
for part, expected_part in expected.items():
|
2018-10-06 12:35:49 +02:00
|
|
|
if part == "query":
|
2017-09-01 12:39:17 +02:00
|
|
|
self.assertDictEqual(
|
2018-10-06 12:35:49 +02:00
|
|
|
parse_qs(parsed.query), expected.get("query", {})
|
2017-09-01 12:39:17 +02:00
|
|
|
)
|
|
|
|
else:
|
|
|
|
self.assertEqual(getattr(parsed, part), expected_part)
|
2017-08-16 17:45:59 +02:00
|
|
|
else:
|
|
|
|
self.assertEqual(actual, expected)
|
|
|
|
|
|
|
|
|
|
|
|
class ViewTestCaseMixin(TestCaseMixin):
|
2017-09-01 12:39:17 +02:00
|
|
|
"""
|
|
|
|
TestCase extension to ease tests of kfet views.
|
|
|
|
|
|
|
|
|
|
|
|
Urls concerns
|
|
|
|
-------------
|
|
|
|
|
|
|
|
# Basic usage
|
|
|
|
|
|
|
|
Attributes:
|
|
|
|
url_name (str): Name of view under test, as given to 'reverse'
|
|
|
|
function.
|
|
|
|
url_args (list, optional): Will be given to 'reverse' call.
|
|
|
|
url_kwargs (dict, optional): Same.
|
|
|
|
url_expcted (str): What 'reverse' should return given previous
|
|
|
|
attributes.
|
|
|
|
|
|
|
|
View url can then be accessed at the 'url' attribute.
|
|
|
|
|
|
|
|
# Advanced usage
|
|
|
|
|
|
|
|
If multiple combinations of url name, args, kwargs can be used for a view,
|
|
|
|
it is possible to define 'urls_conf' attribute. It must be a list whose
|
|
|
|
each item is a dict defining arguments for 'reverse' call ('name', 'args',
|
|
|
|
'kwargs' keys) and its expected result ('expected' key).
|
|
|
|
|
|
|
|
The reversed urls can be accessed at the 't_urls' attribute.
|
|
|
|
|
|
|
|
|
|
|
|
Users concerns
|
|
|
|
--------------
|
|
|
|
|
|
|
|
During setup, three users are created with their kfet account:
|
|
|
|
- 'user': a basic user without any permission, account trigramme: 000,
|
|
|
|
- 'team': a user with kfet.is_team permission, account trigramme: 100,
|
2018-10-03 18:01:19 +02:00
|
|
|
- 'root': a superuser, account trigramme: 200,
|
|
|
|
- 'liq': if class attribute 'with_liq' is 'True', account
|
|
|
|
trigramme: LIQ.
|
2017-09-01 12:39:17 +02:00
|
|
|
Their password is their username.
|
|
|
|
|
2017-09-01 16:37:14 +02:00
|
|
|
One can create additionnal users with 'get_users_extra' method, or prevent
|
|
|
|
these 3 users to be created with 'get_users_base' method. See these two
|
|
|
|
methods for further informations.
|
2017-09-01 12:39:17 +02:00
|
|
|
|
|
|
|
By using 'register_user' method, these users can then be accessed at
|
|
|
|
'users' attribute by their label. Similarly, their kfet account is
|
|
|
|
registered on 'accounts' attribute.
|
|
|
|
|
|
|
|
A user label can be given to 'auth_user' attribute. The related user is
|
|
|
|
then authenticated on self.client during test setup. Its value defaults to
|
|
|
|
'None', meaning no user is authenticated.
|
|
|
|
|
|
|
|
|
|
|
|
Automated tests
|
|
|
|
---------------
|
|
|
|
|
|
|
|
# Url reverse
|
|
|
|
|
|
|
|
Based on url-related attributes/properties, the test 'test_urls' checks
|
|
|
|
that expected url is returned by 'reverse' (once with basic url usage and
|
|
|
|
each for advanced usage).
|
|
|
|
|
|
|
|
# Forbidden responses
|
|
|
|
|
|
|
|
The 'test_forbidden' test verifies that each user, from labels of
|
|
|
|
'auth_forbidden' attribute, can't access the url(s), i.e. response should
|
|
|
|
be a 403, or a redirect to login view.
|
|
|
|
|
|
|
|
Tested HTTP requests are given by 'http_methods' attribute. Additional data
|
|
|
|
can be given by defining an attribute '<method(lowercase)>_data'.
|
|
|
|
|
|
|
|
"""
|
2018-10-06 12:35:49 +02:00
|
|
|
|
2017-08-10 15:02:08 +02:00
|
|
|
url_name = None
|
|
|
|
url_expected = None
|
|
|
|
|
2018-10-06 12:35:49 +02:00
|
|
|
http_methods = ["GET"]
|
2017-08-16 17:45:59 +02:00
|
|
|
|
2017-08-10 15:02:08 +02:00
|
|
|
auth_user = None
|
|
|
|
auth_forbidden = []
|
|
|
|
|
2018-10-03 18:01:19 +02:00
|
|
|
with_liq = False
|
|
|
|
|
2017-08-10 15:02:08 +02:00
|
|
|
def setUp(self):
|
2017-09-01 12:39:17 +02:00
|
|
|
"""
|
|
|
|
Warning: Do not forget to call super().setUp() in subclasses.
|
|
|
|
"""
|
2017-08-10 15:02:08 +02:00
|
|
|
# Signals handlers on login/logout send messages.
|
|
|
|
# Due to the way the Django' test Client performs login, this raise an
|
|
|
|
# error. As workaround, we mock the Django' messages module.
|
2018-10-06 12:35:49 +02:00
|
|
|
patcher_messages = mock.patch("gestioncof.signals.messages")
|
2017-08-10 15:02:08 +02:00
|
|
|
patcher_messages.start()
|
|
|
|
self.addCleanup(patcher_messages.stop)
|
|
|
|
|
2017-08-16 17:45:59 +02:00
|
|
|
# A test can mock 'django.utils.timezone.now' and give this as return
|
|
|
|
# value. E.g. it is useful if the test checks values of 'auto_now' or
|
|
|
|
# 'auto_now_add' fields.
|
|
|
|
self.now = timezone.now()
|
|
|
|
|
2017-09-01 12:39:17 +02:00
|
|
|
# These attributes register users and accounts instances.
|
2017-08-10 15:02:08 +02:00
|
|
|
self.users = {}
|
|
|
|
self.accounts = {}
|
|
|
|
|
2017-09-01 16:37:14 +02:00
|
|
|
for label, user in dict(self.users_base, **self.users_extra).items():
|
2017-08-10 15:02:08 +02:00
|
|
|
self.register_user(label, user)
|
|
|
|
|
|
|
|
if self.auth_user:
|
2018-01-15 05:26:33 +01:00
|
|
|
self.client.force_login(self.users[self.auth_user])
|
2017-08-10 15:02:08 +02:00
|
|
|
|
2017-09-01 16:37:14 +02:00
|
|
|
def tearDown(self):
|
|
|
|
del self.users_base
|
|
|
|
del self.users_extra
|
|
|
|
|
|
|
|
def get_users_base(self):
|
|
|
|
"""
|
|
|
|
Dict of <label: user instance>.
|
|
|
|
|
|
|
|
Note: Don't access yourself this property. Use 'users_base' attribute
|
|
|
|
which cache the returned value from here.
|
|
|
|
It allows to give functions calls, which creates users instances, as
|
|
|
|
values here.
|
|
|
|
|
|
|
|
"""
|
2017-08-10 15:02:08 +02:00
|
|
|
# Format desc: username, password, trigramme
|
2018-10-03 18:01:19 +02:00
|
|
|
users_base = {
|
2017-08-10 15:02:08 +02:00
|
|
|
# user, user, 000
|
2018-10-06 12:35:49 +02:00
|
|
|
"user": create_user(),
|
2017-08-10 15:02:08 +02:00
|
|
|
# team, team, 100
|
2018-10-06 12:35:49 +02:00
|
|
|
"team": create_team(),
|
2017-08-10 15:02:08 +02:00
|
|
|
# root, root, 200
|
2018-10-06 12:35:49 +02:00
|
|
|
"root": create_root(),
|
2017-08-10 15:02:08 +02:00
|
|
|
}
|
2018-10-03 18:01:19 +02:00
|
|
|
if self.with_liq:
|
2018-10-06 12:35:49 +02:00
|
|
|
users_base["liq"] = create_user("liq", "LIQ")
|
2018-10-03 18:01:19 +02:00
|
|
|
return users_base
|
2017-08-10 15:02:08 +02:00
|
|
|
|
2017-09-01 16:37:14 +02:00
|
|
|
@cached_property
|
|
|
|
def users_base(self):
|
|
|
|
return self.get_users_base()
|
|
|
|
|
|
|
|
def get_users_extra(self):
|
|
|
|
"""
|
|
|
|
Dict of <label: user instance>.
|
|
|
|
|
|
|
|
Note: Don't access yourself this property. Use 'users_base' attribute
|
|
|
|
which cache the returned value from here.
|
|
|
|
It allows to give functions calls, which create users instances, as
|
|
|
|
values here.
|
|
|
|
|
|
|
|
"""
|
2017-08-10 15:02:08 +02:00
|
|
|
return {}
|
|
|
|
|
2017-09-01 16:37:14 +02:00
|
|
|
@cached_property
|
|
|
|
def users_extra(self):
|
|
|
|
return self.get_users_extra()
|
|
|
|
|
2017-08-10 15:02:08 +02:00
|
|
|
def register_user(self, label, user):
|
|
|
|
self.users[label] = user
|
2018-10-06 12:35:49 +02:00
|
|
|
if hasattr(user.profile, "account_kfet"):
|
2017-08-10 15:02:08 +02:00
|
|
|
self.accounts[label] = user.profile.account_kfet
|
|
|
|
|
2017-08-16 17:45:59 +02:00
|
|
|
def get_user(self, label):
|
|
|
|
if self.auth_user is not None:
|
|
|
|
return self.auth_user
|
|
|
|
return self.auth_user_mapping.get(label)
|
|
|
|
|
2017-08-10 15:02:08 +02:00
|
|
|
@property
|
|
|
|
def urls_conf(self):
|
2018-10-06 12:35:49 +02:00
|
|
|
return [
|
|
|
|
{
|
|
|
|
"name": self.url_name,
|
|
|
|
"args": getattr(self, "url_args", []),
|
|
|
|
"kwargs": getattr(self, "url_kwargs", {}),
|
|
|
|
"expected": self.url_expected,
|
|
|
|
}
|
|
|
|
]
|
2017-08-10 15:02:08 +02:00
|
|
|
|
|
|
|
@property
|
|
|
|
def t_urls(self):
|
|
|
|
return [
|
|
|
|
reverse(
|
2018-10-06 12:35:49 +02:00
|
|
|
url_conf["name"],
|
|
|
|
args=url_conf.get("args", []),
|
|
|
|
kwargs=url_conf.get("kwargs", {}),
|
2017-08-10 15:02:08 +02:00
|
|
|
)
|
2018-10-06 12:35:49 +02:00
|
|
|
for url_conf in self.urls_conf
|
|
|
|
]
|
2017-08-10 15:02:08 +02:00
|
|
|
|
|
|
|
@property
|
|
|
|
def url(self):
|
|
|
|
return self.t_urls[0]
|
|
|
|
|
|
|
|
def test_urls(self):
|
|
|
|
for url, conf in zip(self.t_urls, self.urls_conf):
|
2018-10-06 12:35:49 +02:00
|
|
|
self.assertEqual(url, conf["expected"])
|
2017-08-10 15:02:08 +02:00
|
|
|
|
|
|
|
def test_forbidden(self):
|
2017-08-16 17:45:59 +02:00
|
|
|
for method in self.http_methods:
|
|
|
|
for user in self.auth_forbidden:
|
|
|
|
for url in self.t_urls:
|
|
|
|
self.check_forbidden(method, url, user)
|
|
|
|
|
|
|
|
def check_forbidden(self, method, url, user=None):
|
|
|
|
method = method.lower()
|
|
|
|
client = Client()
|
|
|
|
if user is not None:
|
|
|
|
client.login(username=user, password=user)
|
|
|
|
|
|
|
|
send_request = getattr(client, method)
|
2018-10-06 12:35:49 +02:00
|
|
|
data = getattr(self, "{}_data".format(method), {})
|
2017-08-16 17:45:59 +02:00
|
|
|
|
|
|
|
r = send_request(url, data)
|
|
|
|
self.assertForbidden(r)
|