Statistics
| Branch: | Tag: | Revision:

root / snf-astakos-app / astakos / im / tests / common.py @ 1808f7bc

History | View | Annotate | Download (6 kB)

1
# Copyright 2011, 2012, 2013 GRNET S.A. All rights reserved.
2
#
3
# Redistribution and use in source and binary forms, with or
4
# without modification, are permitted provided that the following
5
# conditions are met:
6
#
7
#   1. Redistributions of source code must retain the above
8
#      copyright notice, this list of conditions and the following
9
#      disclaimer.
10
#
11
#   2. Redistributions in binary form must reproduce the above
12
#      copyright notice, this list of conditions and the following
13
#      disclaimer in the documentation and/or other materials
14
#      provided with the distribution.
15
#
16
# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
17
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
19
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
20
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
23
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
24
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
26
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27
# POSSIBILITY OF SUCH DAMAGE.
28
#
29
# The views and conclusions contained in the software and
30
# documentation are those of the authors and should not be
31
# interpreted as representing official policies, either expressed
32
# or implied, of GRNET S.A.
33

    
34
from contextlib import contextmanager
35

    
36
import copy
37
import datetime
38
import functools
39

    
40
from snf_django.utils.testing import with_settings, override_settings, \
41
    assertIn, assertGreater, assertRaises
42

    
43
from django.test import Client
44
from django.test import TestCase
45
from django.core import mail
46
from django.http import SimpleCookie, HttpRequest, QueryDict
47
from django.utils.importlib import import_module
48
from django.utils import simplejson as json
49

    
50
from astakos.im.activation_backends import *
51
from astakos.im.views.target.shibboleth import Tokens as ShibbolethTokens
52
from astakos.im.models import *
53
from astakos.im import functions
54
from astakos.im import settings as astakos_settings
55
from astakos.im import forms
56
from astakos.im import activation_backends
57
from astakos.im import auth as auth_functions
58

    
59
from urllib import quote
60
from datetime import timedelta
61

    
62
from astakos.im import messages
63
from astakos.im import auth_providers
64
from astakos.im import quotas
65
from astakos.im import register
66

    
67
from django.conf import settings
68

    
69

    
70
# set some common settings
71
astakos_settings.EMAILCHANGE_ENABLED = True
72
astakos_settings.RECAPTCHA_ENABLED = False
73

    
74
settings.LOGGING_SETUP['disable_existing_loggers'] = False
75

    
76
# shortcut decorators to override provider settings
77
# e.g. shibboleth_settings(ENABLED=True) will set
78
# ASTAKOS_AUTH_PROVIDER_SHIBBOLETH_ENABLED = True in global synnefo settings
79
prefixes = {'providers': 'AUTH_PROVIDER_',
80
            'shibboleth': 'ASTAKOS_AUTH_PROVIDER_SHIBBOLETH_',
81
            'local': 'ASTAKOS_AUTH_PROVIDER_LOCAL_'}
82
im_settings = functools.partial(with_settings, astakos_settings)
83
shibboleth_settings = functools.partial(with_settings,
84
                                        settings,
85
                                        prefix=prefixes['shibboleth'])
86
localauth_settings = functools.partial(with_settings, settings,
87
                                       prefix=prefixes['local'])
88

    
89

    
90
class AstakosTestClient(Client):
91
    pass
92

    
93

    
94
class ShibbolethClient(AstakosTestClient):
95
    """
96
    A shibboleth agnostic client.
97
    """
98
    VALID_TOKENS = filter(lambda x: not x.startswith("_"),
99
                          dir(ShibbolethTokens))
100

    
101
    def __init__(self, *args, **kwargs):
102
        self.tokens = kwargs.pop('tokens', {})
103
        super(ShibbolethClient, self).__init__(*args, **kwargs)
104

    
105
    def set_tokens(self, **kwargs):
106
        for key, value in kwargs.iteritems():
107
            key = 'SHIB_%s' % key.upper()
108
            if not key in self.VALID_TOKENS:
109
                raise Exception('Invalid shibboleth token')
110

    
111
            self.tokens[key] = value
112

    
113
    def unset_tokens(self, *keys):
114
        for key in keys:
115
            key = 'SHIB_%s' % param.upper()
116
            if key in self.tokens:
117
                del self.tokens[key]
118

    
119
    def reset_tokens(self):
120
        self.tokens = {}
121

    
122
    def get_http_token(self, key):
123
        http_header = getattr(ShibbolethTokens, key)
124
        return http_header
125

    
126
    def request(self, **request):
127
        """
128
        Transform valid shibboleth tokens to http headers
129
        """
130
        for token, value in self.tokens.iteritems():
131
            request[self.get_http_token(token)] = value
132

    
133
        for param in request.keys():
134
            key = 'SHIB_%s' % param.upper()
135
            if key in self.VALID_TOKENS:
136
                request[self.get_http_token(key)] = request[param]
137
                del request[param]
138

    
139
        return super(ShibbolethClient, self).request(**request)
140

    
141

    
142
def get_user_client(username, password="password"):
143
    client = Client()
144
    client.login(username=username, password=password)
145
    return client
146

    
147

    
148
def get_local_user(username, **kwargs):
149
    try:
150
        return AstakosUser.objects.get(email=username)
151
    except:
152
        user = auth_functions.make_local_user(email=username,
153
                                              has_signed_terms=True)
154
        user.set_password(kwargs.pop('password', 'password'))
155

    
156
        for key, value in kwargs.iteritems():
157
            setattr(user, key, value)
158
        user.save()
159

    
160
        if kwargs.get("is_active", True):
161
            backend = activation_backends.get_backend()
162
            backend.verify_user(user, user.verification_code)
163
            backend.accept_user(user)
164

    
165
        return user
166

    
167

    
168
def get_mailbox(email):
169
    mails = []
170
    for sent_email in mail.outbox:
171
        for recipient in sent_email.recipients():
172
            if email in recipient:
173
                mails.append(sent_email)
174
    return mails
175

    
176

    
177
def reverse_with_next(next_reverse, base_reverse='login'):
178
    return reverse(base_reverse) + '?next=%s' % reverse(next_reverse)