Statistics
| Branch: | Tag: | Revision:

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

History | View | Annotate | Download (6 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, assertIn
41

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

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

    
57
from urllib import quote
58
from datetime import timedelta
59

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

    
65
from django.conf import settings
66

    
67

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

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

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

    
87

    
88
class AstakosTestClient(Client):
89
    pass
90

    
91

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

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

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

    
109
            self.tokens[key] = value
110

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

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

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

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

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

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

    
139

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

    
145

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

    
170

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