Statistics
| Branch: | Tag: | Revision:

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

History | View | Annotate | Download (7.9 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
serial = 0
137

    
138

    
139
@contextmanager
140
def mocked_quotaholder(success=True):
141
    with patch("synnefo.quotas.Quotaholder.get") as astakos:
142
        global serial
143
        serial += 10
144

    
145
        def foo(*args, **kwargs):
146
            return (len(astakos.return_value.issue_one_commission.mock_calls) +
147
                    serial)
148
        astakos.return_value.issue_one_commission.side_effect = foo
149
        astakos.return_value.resolve_commissions.return_value = {"failed": []}
150
        yield
151

    
152

    
153
class BaseAPITest(TestCase):
154
    def get(self, url, user='user', *args, **kwargs):
155
        with astakos_user(user):
156
            response = self.client.get(url, *args, **kwargs)
157
        return response
158

    
159
    def delete(self, url, user='user'):
160
        with astakos_user(user):
161
            response = self.client.delete(url)
162
        return response
163

    
164
    def post(self, url, user='user', params={}, ctype='json', *args, **kwargs):
165
        if ctype == 'json':
166
            content_type = 'application/json'
167
        with astakos_user(user):
168
            response = self.client.post(url, params, content_type=content_type,
169
                                        *args, **kwargs)
170
        return response
171

    
172
    def put(self, url, user='user', params={}, ctype='json', *args, **kwargs):
173
        if ctype == 'json':
174
            content_type = 'application/json'
175
        with astakos_user(user):
176
            response = self.client.put(url, params, content_type=content_type,
177
                                       *args, **kwargs)
178
        return response
179

    
180
    def assertSuccess(self, response):
181
        self.assertTrue(response.status_code in [200, 203, 204])
182

    
183
    def assertFault(self, response, status_code, name):
184
        self.assertEqual(response.status_code, status_code)
185
        fault = json.loads(response.content)
186
        self.assertEqual(fault.keys(), [name])
187

    
188
    def assertBadRequest(self, response):
189
        self.assertFault(response, 400, 'badRequest')
190

    
191
    def assertItemNotFound(self, response):
192
        self.assertFault(response, 404, 'itemNotFound')
193

    
194
    def assertMethodNotAllowed(self, response):
195
        self.assertFault(response, 400, 'badRequest')
196
        try:
197
            error = json.loads(response.content)
198
        except ValueError:
199
            self.assertTrue(False)
200
        self.assertEqual(error['badRequest']['message'], 'Method not allowed')
201

    
202

    
203
# Imitate unittest assertions new in Python 2.7
204

    
205
class _AssertRaisesContext(object):
206
    """
207
    A context manager used to implement TestCase.assertRaises* methods.
208
    Adapted from unittest2.
209
    """
210

    
211
    def __init__(self, expected):
212
        self.expected = expected
213

    
214
    def __enter__(self):
215
        return self
216

    
217
    def __exit__(self, exc_type, exc_value, tb):
218
        if exc_type is None:
219
            try:
220
                exc_name = self.expected.__name__
221
            except AttributeError:
222
                exc_name = str(self.expected)
223
            raise AssertionError(
224
                "%s not raised" % (exc_name,))
225
        if not issubclass(exc_type, self.expected):
226
            # let unexpected exceptions pass through
227
            return False
228
        self.exception = exc_value  # store for later retrieval
229
        return True
230

    
231

    
232
def assertRaises(excClass):
233
    return _AssertRaisesContext(excClass)
234

    
235

    
236
def assertGreater(x, y):
237
    assert x > y
238

    
239

    
240
def assertIn(x, y):
241
    assert x in y