From 0c34a03aa72e2767e299902ad385650d8ff79621 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rafael=20Mu=C3=B1oz=20C=C3=A1rdenas?= Date: Tue, 27 Mar 2018 13:54:51 +0200 Subject: [PATCH] Delete unused tola modules --- tola/admin.py | 44 --- tola/auth_pipeline.py | 97 ------ tola/forms.py | 162 --------- tola/middleware.py | 77 ----- tola/processor.py | 43 --- tola/security.py | 51 --- tola/settings/test_pkg.py | 2 - tola/tables.py | 24 -- tola/tests/test_oauth.py | 213 ------------ tola/tests/test_views.py | 671 -------------------------------------- tola/urls.py | 161 +-------- tola/urls_pkg.py | 5 - tola/util.py | 92 ------ tola/views.py | 406 ----------------------- 14 files changed, 5 insertions(+), 2043 deletions(-) delete mode 100644 tola/admin.py delete mode 100644 tola/auth_pipeline.py delete mode 100755 tola/forms.py delete mode 100644 tola/middleware.py delete mode 100755 tola/processor.py delete mode 100644 tola/security.py delete mode 100755 tola/tables.py delete mode 100644 tola/tests/test_oauth.py delete mode 100644 tola/tests/test_views.py mode change 100755 => 100644 tola/urls.py delete mode 100644 tola/urls_pkg.py delete mode 100755 tola/util.py delete mode 100755 tola/views.py diff --git a/tola/admin.py b/tola/admin.py deleted file mode 100644 index fce8b3b9e..000000000 --- a/tola/admin.py +++ /dev/null @@ -1,44 +0,0 @@ -from django.contrib import admin -from django.contrib.auth.models import User -from django.contrib.auth.admin import UserAdmin -from django import forms -from django.contrib.auth.forms import UserCreationForm, UserChangeForm - - -# use these form classes to enforce unique emails, if required -class UniqueEmailForm: - def clean_email(self): - qs = User.objects.filter(email=self.cleaned_data['email']) - if self.instance: - qs = qs.exclude(pk=self.instance.pk) - if qs.count(): - raise forms.ValidationError( - 'That email address is already in use') - else: - return self.cleaned_data['email'] - -class MyUserChangeForm(UniqueEmailForm, UserChangeForm): - email = forms.EmailField(required=True) - -class MyUserCreationForm(UniqueEmailForm, UserCreationForm): - email = forms.EmailField(required=True) - -class MyUserAdmin(UserAdmin): - # add the email field in to the initial add_user form - add_fieldsets = ( - (None, { - 'classes': ('wide',), - 'fields': ('username', 'email', 'password1', 'password2') - }), - ) - - actions = ['make_active', 'make_inactive'] - list_filter = ['is_active', 'is_staff', 'is_superuser', 'date_joined', - 'last_login'] - - form = MyUserChangeForm - add_form = MyUserCreationForm - -# Re-register UserAdmin with custom options -admin.site.unregister(User) -admin.site.register(User, MyUserAdmin) diff --git a/tola/auth_pipeline.py b/tola/auth_pipeline.py deleted file mode 100644 index 3707d021d..000000000 --- a/tola/auth_pipeline.py +++ /dev/null @@ -1,97 +0,0 @@ -import logging - -from django.contrib.auth.models import User -from django.contrib.sites.shortcuts import get_current_site -from django.shortcuts import render_to_response -from django.http import HttpResponseRedirect -from django.conf import settings - -from social_core.pipeline.partial import partial - -from workflow.models import (Country, TolaUser, TolaSites, Organization) - -logger = logging.getLogger(__name__) - - -def redirect_after_login(strategy, *args, **kwargs): - redirect = strategy.session_get('redirect_after_login') - strategy.session_set('next', redirect) - - -@partial -def check_user(strategy, details, backend, user=None, *args, **kwargs): - """ - Redirect the user to the registration page, if we haven't found - a user account yet. - """ - if user: - return {'is_new': False} - try: - user = User.objects.get(first_name=details['first_name'], - last_name=details['last_name'], - email=details['email']) - return { - 'is_new': True, - 'user': user - } - except User.DoesNotExist: - current_partial = kwargs.get('current_partial') - query_params = 'cus_fname={}&cus_lname={}&cus_email={}&' \ - 'organization_uuid={}&partial_token={}'.format( - details['first_name'], details['last_name'], - details['email'], details['organization_uuid'], - current_partial.token) - - redirect_url = '/accounts/register/?{}'.format(query_params) - return HttpResponseRedirect(redirect_url) - - -def auth_allowed(backend, details, response, *args, **kwargs): - """ - Verifies that the current auth process is valid. Emails, - domains whitelists and organization domains are applied (if defined). - """ - allowed = False - static_url = settings.STATIC_URL - - # Get whitelisted domains and emails defined in the settings - whitelisted_emails = backend.setting('WHITELISTED_EMAILS', []) - whitelisted_domains = backend.setting('WHITELISTED_DOMAINS', []) - - # Get the whitelisted domains defined in the TolaSites - site = get_current_site(None) - tola_site = TolaSites.objects.get(site=site) - if tola_site and tola_site.whitelisted_domains: - tola_domains = ','.join(tola_site.whitelisted_domains.split()) - tola_domains = tola_domains.split(',') - whitelisted_domains += tola_domains - - try: - email = details['email'] - except KeyError: - logger.warning('No email was passed in the details.') - allowed = False - else: - domain = email.split('@', 1)[1] - if whitelisted_emails or whitelisted_domains: - allowed = (email in whitelisted_emails or domain in - whitelisted_domains) - - # Check if the user email domain matches with one of the org oauth - # domains and add the organization uuid in the details - if not allowed: - try: - org_uuid = Organization.objects.values_list( - 'organization_uuid', flat=True).get( - oauth_domains__contains=[domain]) - details.update({'organization_uuid': org_uuid}) - allowed = True - except Organization.DoesNotExist: - pass - except Organization.MultipleObjectsReturned as e: - logger.warning('There is more than one Organization with ' - 'the domain {}.\n{}'.format(domain, e)) - - if not allowed: - return render_to_response('unauthorized.html', - context={'STATIC_URL': static_url}) diff --git a/tola/forms.py b/tola/forms.py deleted file mode 100755 index 69667f37a..000000000 --- a/tola/forms.py +++ /dev/null @@ -1,162 +0,0 @@ -import os - -from crispy_forms.helper import FormHelper -from crispy_forms.layout import * -from django import forms -from django.conf import settings -from django.contrib.auth.forms import UserChangeForm, UserCreationForm -from django.contrib.auth.models import User - -from tola import DEMO_BRANCH -from workflow.models import TolaUser, TolaBookmarks, Organization - - -class RegistrationForm(UserChangeForm): - """ - Form for registering a new account. - """ - def __init__(self, *args, **kwargs): - user = kwargs.pop('initial') - super(RegistrationForm, self).__init__(*args, **kwargs) - del self.fields['password'] - self.fields['tola_user_uuid'].widget = forms.HiddenInput() - # if they aren't a super user or User Admin don't let them change countries form field - if 'User Admin' not in user['username'].groups.values_list('name', flat=True) and not user['username'].is_superuser: - self.fields['countries'].widget.attrs['disabled'] = "disabled" - self.fields['country'].widget.attrs['disabled'] = "disabled" - - class Meta: - model = TolaUser - fields = '__all__' - - helper = FormHelper() - helper.form_method = 'post' - helper.form_class = 'form-horizontal' - helper.label_class = 'col-sm-2' - helper.field_class = 'col-sm-6' - helper.form_error_title = 'Form Errors' - helper.error_text_inline = True - helper.help_text_inline = True - helper.html5_required = True - helper.layout = Layout(Fieldset('', 'tola_user_uuid', 'title', 'name', 'employee_number', 'user', - 'country', 'countries'), - Submit('submit', 'Submit', css_class='btn-default'), - Reset('reset', 'Reset', css_class='btn-warning')) - - -class NewUserRegistrationForm(UserCreationForm): - """ - Form for registering a new account. - """ - class Meta: - model = User - fields = ['first_name', 'last_name', 'email', 'username'] - - def __init__(self, *args, **kwargs): - fname = kwargs.pop('first_name', None) - lname = kwargs.pop('last_name', None) - email = kwargs.pop('email', None) - super(NewUserRegistrationForm, self).__init__(*args, **kwargs) - - self.fields['first_name'].initial = fname - self.fields['last_name'].initial = lname - self.fields['email'].initial = email - - helper = FormHelper() - helper.form_method = 'post' - helper.form_class = 'form-horizontal' - helper.label_class = 'col-sm-2' - helper.field_class = 'col-sm-6' - helper.form_error_title = 'Form Errors' - helper.error_text_inline = True - helper.help_text_inline = True - helper.html5_required = True - helper.form_tag = False - - -class NewTolaUserRegistrationForm(forms.ModelForm): - """ - Form for registering a new account. - """ - class Meta: - model = TolaUser - fields = ['title', 'privacy_disclaimer_accepted'] - - org = forms.CharField() - - def clean_org(self): - try: - org = Organization.objects.get(name=self.cleaned_data['org']) - except Organization.DoesNotExist: - raise forms.ValidationError("The Organization was not found.") - else: - return org - - def __init__(self, *args, **kwargs): - self.helper = FormHelper() - self.helper.form_method = 'post' - self.helper.form_class = 'form-horizontal' - self.helper.form_error_title = 'Form Errors' - self.helper.error_text_inline = True - self.helper.help_text_inline = True - self.helper.html5_required = True - self.helper.form_tag = False - self.helper.layout = Layout( - Fieldset('', 'title', 'org',), - Fieldset('', - HTML(""" -
-
Notice/Disclaimer:
-
- {% if privacy_disclaimer %} - {{ privacy_disclaimer }} - {% else %} - {% include "registration/privacy_policy.html" %} - {% endif %} -
-
- """), - Div('privacy_disclaimer_accepted', - css_class="mt-2")), - ) - organization = kwargs.pop('org', None) - super(NewTolaUserRegistrationForm, self).__init__(*args, **kwargs) - - # Set default organization for demo environment - if settings.DEFAULT_ORG and os.getenv('APP_BRANCH') == DEMO_BRANCH: - self.fields['org'] = forms.CharField( - initial=settings.DEFAULT_ORG, disabled=True) - elif organization: - self.fields['org'] = forms.CharField( - initial=organization, disabled=True) - - self.fields['privacy_disclaimer_accepted'].required = True - - -class BookmarkForm(forms.ModelForm): - """ - Form for registering a new account. - """ - class Meta: - model = TolaBookmarks - fields = ['name', 'bookmark_url'] - - def __init__(self, *args, **kwargs): - super(BookmarkForm, self).__init__(*args, **kwargs) - - helper = FormHelper() - helper.form_method = 'post' - helper.form_class = 'form-horizontal' - helper.label_class = 'col-sm-2' - helper.field_class = 'col-sm-6' - helper.form_error_title = 'Form Errors' - helper.error_text_inline = True - helper.help_text_inline = True - helper.html5_required = True - helper.form_tag = True - helper.layout = Layout( - Fieldset('','name','bookmark_url'), - Submit('submit', 'Submit', css_class='btn-default'), - Reset('reset', 'Reset', css_class='btn-warning')) - - diff --git a/tola/middleware.py b/tola/middleware.py deleted file mode 100644 index a2695013a..000000000 --- a/tola/middleware.py +++ /dev/null @@ -1,77 +0,0 @@ -from threading import current_thread - -from django.template import Template, Context -from django.http import HttpResponse -from django.utils.deprecation import MiddlewareMixin -from rest_framework.exceptions import PermissionDenied - - -_current_users = {} - - -def get_user(): - """ - Request independent method to retrieve current user - from objects with no access to the current request - :return: The current user of the requesting thread - """ - thread = current_thread() - if thread not in _current_users: - return None - return _current_users[thread] - - -class TolaSecurityMiddleware(object): - - def __init__(self, get_response): - self.get_response = get_response - - def __call__(self, request): - # Add user object to thread-dependent storage - _current_users[current_thread()] = request.user - - response = self.get_response(request) - return response - - def process_exception(self, request, exception): - """ - Processes PermissionDenied Exceptions for model-level access control - :param request: - :param exception: - :return: - """ - # TODO change print to log - print("Middleware has caught an exception. exception={}".format(exception.message), type(exception)) - - if type(exception) == PermissionDenied: - t = Template("{'error':'Permission Denied'}") - response_html = t.render(Context({})) - - response = HttpResponse(response_html) - response.status_code = 403 - return response - - -class TolaRedirectMiddleware(object): - """ - Middleware to store redirects in the session until they are ready to be processed. - Redirects with 'next' are overwritten by Social Auth during the process and have to be restored at the - end of the Authentication pipeline - """ - def __init__(self, get_response): - self.get_response = get_response - - def __call__(self, request): - # store the next value of the inital request in the session - if 'next' in request.GET: - request.session["redirect_after_login"] = request.GET['next'] - - return self.get_response(request) - - -class DisableCsrfCheck(MiddlewareMixin): - - def process_request(self, req): - attr = '_dont_enforce_csrf_checks' - if not getattr(req, attr, False): - setattr(req, attr, True) diff --git a/tola/processor.py b/tola/processor.py deleted file mode 100755 index d2c6febb3..000000000 --- a/tola/processor.py +++ /dev/null @@ -1,43 +0,0 @@ -#add global variable for report server or not to all templates so we can hide elements that aren't wanted on the report server -from settings.local import REPORT_SERVER -from settings.local import OFFLINE_MODE -from settings.local import NON_LDAP -from workflow.models import Organization - -from django.conf import settings - -def report_server_check(request): - return {'report_server': REPORT_SERVER, 'offline_mode': OFFLINE_MODE, 'non_ldap': NON_LDAP} - - - -# get the organization labels from the user for each level of workflow for display in templates -def org_levels(request): - - try: - getOrg = Organization.objects.get(id=request.user.tola_user.country.organization.id) - workflowlevel1 = getOrg.level_1_label - workflowlevel2 = getOrg.level_2_label - workflowlevel3 = getOrg.level_3_label - except Exception, e: - workflowlevel1 = "Program" - workflowlevel2 = "Projects" - workflowlevel3 = "Activity" - - return {'WORKFLOWLEVEL1': workflowlevel1, 'WORKFLOWLEVEL2': workflowlevel2, 'WORKFLOWLEVEL3': workflowlevel3} - -def google_analytics(request): - """ - Use the variables returned in this function to render Google Analytics Tracking Code template. - """ - - ga_prop_id = getattr(settings, 'GOOGLE_ANALYTICS_PROPERTY_ID', False) - ga_domain = getattr(settings, 'GOOGLE_ANALYTICS_DOMAIN', False) - - if not settings.DEBUG and ga_prop_id and ga_domain: - return { - 'GOOGLE_ANALYTICS_PROPERTY_ID': ga_prop_id, - 'GOOGLE_ANALYTICS_DOMAIN': ga_domain, - } - return {} - diff --git a/tola/security.py b/tola/security.py deleted file mode 100644 index 8717dc8da..000000000 --- a/tola/security.py +++ /dev/null @@ -1,51 +0,0 @@ -from django.db import models -from tola.middleware import get_user -from guardian.shortcuts import get_perms -from rest_framework.exceptions import PermissionDenied -from tola.settings import local - -class SecurityModel(models.Model): - """ - Abstract Model to inherit security models from - """ - class Meta: - abstract = True - - def __init__(self, *args, **kwargs): - super(SecurityModel, self).__init__(*args, **kwargs) - - user = get_user() - if not local.DEBUG and user is not None: - print(type(self), user, get_perms(user, self)) - - need_perm = "view_"+str(self.__class__.__name__).lower() # The permission necessary to access the current model - if need_perm not in get_perms(user, self): - raise PermissionDenied("Not allowed") - - def save(self, *args, **kwargs): - create_perm = "add_"+str(self.__class__.__name__).lower() - edit_perm = "change_"+str(self.__class__.__name__).lower() - - user = get_user() - if not local.DEBUG and user is not None: - - perms = get_perms(user, self) - - if self.pk is None and create_perm not in perms: - raise PermissionDenied("Not allowed") - elif edit_perm not in perms: - raise PermissionDenied("Not allowed") - - super(SecurityModel, self).save(*args, **kwargs) - - def delete(self, *args, **kwargs): - delete_perm = "delete_"+str(self.__class__.__name__).lower() - - user = get_user() - if not local.DEBUG and user is not None: - perms = get_perms(user, self) - - if delete_perm not in perms: - raise PermissionDenied("Not allowed") - - super(SecurityModel, self).delete(*args, **kwargs) diff --git a/tola/settings/test_pkg.py b/tola/settings/test_pkg.py index 051e3fae0..85a1f04d6 100644 --- a/tola/settings/test_pkg.py +++ b/tola/settings/test_pkg.py @@ -21,6 +21,4 @@ INSTALLED_APPS = DJANGO_APPS + THIRD_PARTY_APPS + LOCAL_APPS -ROOT_URLCONF = 'tola.urls_pkg' - TEST_RUNNER = 'tola.pkg_testrunner.PackageTestSuiteRunner' diff --git a/tola/tables.py b/tola/tables.py deleted file mode 100755 index 8b765c457..000000000 --- a/tola/tables.py +++ /dev/null @@ -1,24 +0,0 @@ -import django_tables2 as tables -from django_tables2.utils import A - -from indicators.models import CollectedData - - -class IndicatorDataTable(tables.Table): - indicator__name = tables.LinkColumn('indicator_data_report', args=[A('indicator__id'), A('indicator__program__id'), 0]) - - class Meta: - model = CollectedData - attrs = {"class": "paleblue"} - fields = ('indicator__lop_target', 'actuals','indicator__program__name', 'indicator__number', 'indicator__name') - sequence = ('indicator__lop_target', 'actuals', 'indicator__program__name','indicator__number', 'indicator__name') - - -class CollectedDataTable(tables.Table): - agreement = tables.LinkColumn('projectagreement_update', args=[A('agreement_id')]) - - class Meta: - model = CollectedData - attrs = {"class": "paleblue"} - fields = ('targeted', 'achieved', 'description', 'logframe_indicator', 'sector', 'community', 'agreement', 'complete') - sequence = ('targeted', 'achieved', 'description', 'logframe_indicator', 'sector', 'community', 'agreement', 'complete') \ No newline at end of file diff --git a/tola/tests/test_oauth.py b/tola/tests/test_oauth.py deleted file mode 100644 index 65bf5f869..000000000 --- a/tola/tests/test_oauth.py +++ /dev/null @@ -1,213 +0,0 @@ -import logging -import imp - -from django.contrib.sites.shortcuts import get_current_site -from django.test import TestCase, Client -from mock import Mock, patch - -import factories -from tola import auth_pipeline - - -class OAuthTest(TestCase): - """ - Test cases for OAuth Provider interface - """ - # Fake classes for testing - class BackendTest(object): - def __init__(self): - self.WHITELISTED_EMAILS = [] - self.WHITELISTED_DOMAINS = [] - - def setting(self, name, default=None): - return self.__dict__.get(name, default) - - class CurrentPartialTest(object): - def __init__(self, token): - self.token = token - - def setUp(self): - logging.disable(logging.WARNING) - self.tola_user = factories.TolaUser() - self.org = factories.Organization(organization_uuid='12345') - self.country = factories.Country() - self.site = factories.TolaSites(site=get_current_site(None), - whitelisted_domains='testenv.com') - self.app = factories.Application(user=self.tola_user.user) - self.grant = factories.Grant(application=self.app, - user=self.tola_user.user) - - def tearDown(self): - logging.disable(logging.NOTSET) - - def test_authorization(self): - """ - Tests if the simple search responds - :return: - """ - self.tola_user.user.set_password('1234') - self.tola_user.user.save() - - c = Client(HTTP_USER_AGENT='Test/1.0') - c.login(username=self.tola_user.user.username, password='1234') - - # Get Authorization token - authorize_url = '/oauth/authorize?state=random_state_string' \ - '&client_id={}&response_type=code'.format( - self.app.client_id) - - response = c.get(authorize_url, follow=True) - self.assertContains( - response, "value=\"CXGVOGFnTAt5cQW6m5AxbGrRq1lzKNSrou31dWm9\"") - self.assertEqual(response.status_code, 200) - - def test_auth_allowed_in_whitelist(self): - backend = self.BackendTest() - details = {'email': self.tola_user.user.email} - result = auth_pipeline.auth_allowed(backend, details, None) - self.assertIsNone(result) - - def test_auth_allowed_not_in_whitelist(self): - backend = self.BackendTest() - details = {'email': self.tola_user.user.email} - self.site.whitelisted_domains = 'anotherdomain.com' - self.site.save() - response = auth_pipeline.auth_allowed(backend, details, None) - template_content = response.content - self.assertIn("You don't appear to have permissions to access " - "the system.", template_content) - self.assertIn("Please check with your organization to have access.", - template_content) - - def test_auth_allowed_in_oauth_domain(self): - self.site.whitelisted_domains = None - self.site.save() - self.org.oauth_domains = ['testenv.com'] - self.org.save() - - backend = self.BackendTest() - details = {'email': self.tola_user.user.email} - result = auth_pipeline.auth_allowed(backend, details, None) - self.assertIsNone(result) - - def test_auth_allowed_multi_oauth_domain(self): - self.site.whitelisted_domains = None - self.site.save() - self.org.oauth_domains = ['testenv.com'] - self.org.save() - factories.Organization(organization_uuid='6789', name='Another Org', - oauth_domains=['testenv.com']) - - backend = self.BackendTest() - details = {'email': self.tola_user.user.email} - response = auth_pipeline.auth_allowed(backend, details, None) - template_content = response.content - self.assertIn("You don't appear to have permissions to access " - "the system.", template_content) - self.assertIn("Please check with your organization to have access.", - template_content) - - def test_auth_allowed_no_whitelist_oauth_domain(self): - self.site.whitelisted_domains = None - self.site.save() - - backend = self.BackendTest() - details = {'email': self.tola_user.user.email} - response = auth_pipeline.auth_allowed(backend, details, None) - template_content = response.content - self.assertIn("You don't appear to have permissions to access " - "the system.", template_content) - self.assertIn("Please check with your organization to have access.", - template_content) - - def test_auth_allowed_no_email(self): - backend = self.BackendTest() - details = {} - response = auth_pipeline.auth_allowed(backend, details, None) - template_content = response.content - self.assertIn("You don't appear to have permissions to access " - "the system.", template_content) - self.assertIn("Please check with your organization to have access.", - template_content) - - def test_check_user_does_not_exist(self): - def kill_patches(): - patch.stopall() - imp.reload(auth_pipeline) - - self.addCleanup(kill_patches) - patch('social_core.pipeline.partial.partial', lambda x: x).start() - imp.reload(auth_pipeline) - - # Create the parameters for the check_user function - mocked = Mock() - c_partial = self.CurrentPartialTest('09876') - details = { - 'first_name': 'John', - 'last_name': 'Lennon', - 'email': 'johnlennon@test.com', - 'organization_uuid': self.org.organization_uuid, - } - kwargs = { - 'current_partial': c_partial - } - response = auth_pipeline.check_user(mocked, details, mocked, None, - mocked, **kwargs) - - # Create redirect URL to validate - query_params = 'cus_fname={}&cus_lname={}&cus_email={}&' \ - 'organization_uuid={}&partial_token={}'.format( - details['first_name'], details['last_name'], - details['email'], details['organization_uuid'], - c_partial.token) - redirect_url = '/accounts/register/?{}'.format(query_params) - - self.assertEqual(response.status_code, 302) - self.assertEqual(response.get('location'), redirect_url) - - def test_check_user_is_new(self): - def kill_patches(): - patch.stopall() - imp.reload(auth_pipeline) - - self.addCleanup(kill_patches) - patch('social_core.pipeline.partial.partial', lambda x: x).start() - imp.reload(auth_pipeline) - - # Create the parameters for the check_user function - mocked = Mock() - details = { - 'first_name': 'John', - 'last_name': 'Lennon', - 'email': 'johnlennon@test.com', - } - user = factories.User(first_name=details['first_name'], - last_name=details['last_name'], - email=details['email']) - result = auth_pipeline.check_user(mocked, details, mocked, None, - mocked, mocked) - self.assertTrue(result['is_new']) - self.assertEqual(result['user'], user) - - def test_check_user_is_not_new(self): - def kill_patches(): - patch.stopall() - imp.reload(auth_pipeline) - - self.addCleanup(kill_patches) - patch('social_core.pipeline.partial.partial', lambda x: x).start() - imp.reload(auth_pipeline) - - # Create the parameters for the check_user function - mocked = Mock() - details = { - 'first_name': 'John', - 'last_name': 'Lennon', - 'email': 'johnlennon@test.com', - } - user = factories.User(first_name=details['first_name'], - last_name=details['last_name'], - email=details['email']) - result = auth_pipeline.check_user(mocked, details, mocked, user, - mocked, mocked) - self.assertFalse(result['is_new']) diff --git a/tola/tests/test_views.py b/tola/tests/test_views.py deleted file mode 100644 index f3119c8cc..000000000 --- a/tola/tests/test_views.py +++ /dev/null @@ -1,671 +0,0 @@ -from importlib import import_module -import json -import logging -import os -import sys -from urlparse import urljoin - -from chargebee import InvalidRequestError, Subscription - -from django.contrib import auth -from django.contrib.auth.models import User, AnonymousUser -from django.contrib.sites.models import Site -from django.core.urlresolvers import clear_url_caches -from django.test import Client, RequestFactory, TestCase, override_settings -from django.conf import settings -from django.urls import reverse -from mock import Mock, patch - -import factories -from tola import views, DEMO_BRANCH -from workflow.models import (Organization, TolaUser, TolaSites, ROLE_VIEW_ONLY, - TITLE_CHOICES) - - -# TODO Extend View tests - - -class IndexViewTest(TestCase): - def setUp(self): - self.factory = RequestFactory() - self.tola_user = factories.TolaUser() - - def test_dispatch_unauthenticated(self): - request = self.factory.get('', follow=True) - request.user = AnonymousUser() - response = views.IndexView.as_view()(request) - self.assertEqual(response.status_code, 302) - self.assertIn(reverse('login'), response.url) - - @override_settings(TOLA_ACTIVITY_URL='https://tolaactivity.com') - @override_settings(TOLA_TRACK_URL='https://tolatrack.com/') - def test_dispatch_authenticated_with_urls_set(self): - request = self.factory.get('') - request.user = self.tola_user.user - response = views.IndexView.as_view()(request) - self.assertEqual(response.status_code, 200) - self.assertEqual(response.context_data['tolaactivity_url'], - 'https://tolaactivity.com') - self.assertEqual(response.context_data['tolatrack_url'], - 'https://tolatrack.com/') - template_content = response.render().content - self.assertIn('https://tolaactivity.com', template_content) - self.assertIn('https://tolatrack.com/', template_content) - - @override_settings(TOLA_ACTIVITY_URL='') - @override_settings(TOLA_TRACK_URL='') - def test_dispatch_authenticated_with_urls_not_set(self): - site = Site.objects.create(domain='api.toladata.com', name='API') - TolaSites.objects.create( - name='TolaData', - front_end_url='https://tolaactivity.com', - tola_tables_url='https://tolatrack.com', - site=site) - - request = self.factory.get('') - request.user = self.tola_user.user - response = views.IndexView.as_view()(request) - self.assertEqual(response.status_code, 200) - self.assertEqual(response.context_data['tolaactivity_url'], - 'https://tolaactivity.com') - self.assertEqual(response.context_data['tolatrack_url'], - 'https://tolatrack.com') - template_content = response.render().content - self.assertIn('https://tolaactivity.com', template_content) - self.assertIn('https://tolatrack.com', template_content) - - -class LoginViewTest(TestCase): - def tearDown(self): - os.environ['APP_BRANCH'] = '' - - def _reload_urlconf(self): - clear_url_caches() - if settings.ROOT_URLCONF in sys.modules: - reload(sys.modules[settings.ROOT_URLCONF]) - return import_module(settings.ROOT_URLCONF) - - @override_settings(CHARGEBEE_SIGNUP_ORG_URL='') - def test_org_signup_link(self): - # As the url_patterns are cached when python load the module, also the - # settings are cached there. As we want to override a setting, we need - # to reload also the urls in order to catch the new value. - self._reload_urlconf() - response = self.client.get(reverse('login'), follow=True) - template_content = response.content - self.assertIn( - ('' - 'Register Your Organization with TolaData'), - template_content) - - @override_settings(CHARGEBEE_SIGNUP_ORG_URL='https://chargebee.com/123') - def test_org_signup_link_chargebee(self): - # As the url_patterns are cached when python load the module, also the - # settings are cached there. As we want to override a setting, we need - # to reload also the urls in order to catch the new value. - self._reload_urlconf() - response = self.client.get(reverse('login'), follow=True) - template_content = response.content - self.assertIn( - ('' - 'Register Your Organization with TolaData'), - template_content) - - def test_with_social_auth_button(self): - self._reload_urlconf() - response = self.client.get(reverse('login'), follow=True) - template_content = response.content - self.assertIn('
', template_content) - self.assertIn('', template_content) - self.assertIn('', template_content) - - def test_without_social_auth_button(self): - os.environ['APP_BRANCH'] = DEMO_BRANCH - self._reload_urlconf() - response = self.client.get(reverse('login'), follow=True) - template_content = response.content - self.assertNotIn('