Statistics
| Branch: | Tag: | Revision:

root / snf-astakos-app / astakos / im / tests / common.py @ 7e24cd42

History | View | Annotate | Download (6.1 kB)

1
# Copyright 2011 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

    
58
from urllib import quote
59
from datetime import timedelta
60

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

    
66
from django.conf import settings
67

    
68

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

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

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

    
88

    
89
class AstakosTestClient(Client):
90
    pass
91

    
92

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

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

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

    
110
            self.tokens[key] = value
111

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

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

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

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

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

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

    
140

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

    
146

    
147
def get_local_user(username, **kwargs):
148
        try:
149
            return AstakosUser.objects.get(email=username)
150
        except:
151
            user_params = {
152
                'username': username,
153
                'email': username,
154
                'is_active': True,
155
                'activation_sent': datetime.now(),
156
                'email_verified': True
157
            }
158
            user_params.update(kwargs)
159
            user = AstakosUser(**user_params)
160
            user.set_password(kwargs.get('password', 'password'))
161
            user.renew_verification_code()
162
            user.save()
163
            user.add_auth_provider('local', auth_backend='astakos')
164
            if kwargs.get('is_active', True):
165
                user.is_active = True
166
            else:
167
                user.is_active = False
168
            user.save()
169
            return user
170

    
171

    
172
def get_mailbox(email):
173
    mails = []
174
    for sent_email in mail.outbox:
175
        for recipient in sent_email.recipients():
176
            if email in recipient:
177
                mails.append(sent_email)
178
    return mails
179

    
180

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