Statistics
| Branch: | Tag: | Revision:

root / snf-django-lib / snf_django / utils / testing.py @ d2b8ec7b

History | View | Annotate | Download (6.2 kB)

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

    
35
from contextlib import contextmanager
36
from django.test import TestCase
37
from django.utils import simplejson as json
38
from mock import patch
39

    
40

    
41
@contextmanager
42
def override_settings(settings, **kwargs):
43
    """
44
    Helper context manager to override django settings within the provided
45
    context.
46

47
    All keyword arguments provided are set to the django settings object and
48
    get reverted/removed when the manager exits.
49

50
    >>> from synnefo.util.testing import override_settings
51
    >>> from django.conf import settings
52
    >>> with override_settings(settings, DEBUG=True):
53
    >>>     assert settings.DEBUG == True
54

55
    The special arguemnt ``prefix`` can be set to prefix all setting keys with
56
    the provided value.
57

58
    >>> from django.conf import settings
59
    >>> from django.core import mail
60
    >>> with override_settings(settings, CONTACT_EMAILS=['kpap@grnet.gr'],
61
    >>>                        prefix='MYAPP_'):
62
    >>>     from django.core.mail import send_mail
63
    >>>     send_mail("hello", "I love you kpap", settings.DEFAULT_FROM_EMAIL,
64
    >>>               settings.MYAPP_CONTACT_EMAILS)
65
    >>>     assert 'kpap@grnet.gr' in mail.mailbox[0].recipients()
66

67
    If you plan to reuse it
68

69
    >>> import functools
70
    >>> from synnefo.util.testing import override_settings
71
    >>> from django.conf import settings
72
    >>> myapp_settings = functools.partial(override_settings, prefix='MYAPP_')
73
    >>> with myapp_settings(CONTACT_EMAILS=['kpap@grnet.gr'])
74
    >>>     assert settings.MYAPP_CONTACT_EMAILS == ['kpap@grnet.gr']
75

76
    """
77

    
78
    _prefix = kwargs.get('prefix', '')
79
    prefix = lambda key: '%s%s' % (_prefix, key)
80

    
81
    oldkeys = [k for k in dir(settings) if k.upper() == k]
82
    oldsettings = dict([(k, getattr(settings, k)) for k in oldkeys])
83

    
84
    toremove = []
85
    for key, value in kwargs.iteritems():
86
        key = prefix(key)
87
        if not hasattr(settings, key):
88
            toremove.append(key)
89
        setattr(settings, key, value)
90

    
91
    yield
92

    
93
    # Remove keys that didn't exist
94
    for key in toremove:
95
        delattr(settings, key)
96

    
97
    # Remove keys that added during the execution of the context
98
    if kwargs.get('reset_changes', True):
99
        newkeys = [k for k in dir(settings) if k.upper() == k]
100
        for key in newkeys:
101
            if not key in oldkeys:
102
                delattr(settings, key)
103

    
104
    # Revert old keys
105
    for key in oldkeys:
106
        if key == key.upper():
107
            setattr(settings, key, oldsettings.get(key))
108

    
109

    
110
def with_settings(settings, prefix='', **override):
111
    def wrapper(func):
112
        def inner(*args, **kwargs):
113
            with override_settings(settings, prefix=prefix, **override):
114
                ret = func(*args, **kwargs)
115
            return ret
116
        return inner
117
    return wrapper
118

    
119

    
120
@contextmanager
121
def astakos_user(user):
122
    """
123
    Context manager to mock astakos response.
124

125
    usage:
126
    with astakos_user("user@user.com"):
127
        .... make api calls ....
128

129
    """
130
    with patch("snf_django.lib.api.get_token") as get_token:
131
        get_token.return_value = "DummyToken"
132
        with patch('astakosclient.AstakosClient.get_user_info') as m:
133
            m.return_value = {"uuid": user}
134
            yield
135

    
136

    
137
class BaseAPITest(TestCase):
138
    def get(self, url, user='user', *args, **kwargs):
139
        with astakos_user(user):
140
            response = self.client.get(url, *args, **kwargs)
141
        return response
142

    
143
    def delete(self, url, user='user'):
144
        with astakos_user(user):
145
            response = self.client.delete(url)
146
        return response
147

    
148
    def post(self, url, user='user', params={}, ctype='json', *args, **kwargs):
149
        if ctype == 'json':
150
            content_type = 'application/json'
151
        with astakos_user(user):
152
            response = self.client.post(url, params, content_type=content_type,
153
                                        *args, **kwargs)
154
        return response
155

    
156
    def put(self, url, user='user', params={}, ctype='json', *args, **kwargs):
157
        if ctype == 'json':
158
            content_type = 'application/json'
159
        with astakos_user(user):
160
            response = self.client.put(url, params, content_type=content_type,
161
                                       *args, **kwargs)
162
        return response
163

    
164
    def assertSuccess(self, response):
165
        self.assertTrue(response.status_code in [200, 203, 204])
166

    
167
    def assertFault(self, response, status_code, name):
168
        self.assertEqual(response.status_code, status_code)
169
        fault = json.loads(response.content)
170
        self.assertEqual(fault.keys(), [name])
171

    
172
    def assertBadRequest(self, response):
173
        self.assertFault(response, 400, 'badRequest')
174

    
175
    def assertItemNotFound(self, response):
176
        self.assertFault(response, 404, 'itemNotFound')