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


from contextlib import contextmanager
36
37
from django.test import TestCase
from django.utils import simplejson as json
38
from django.utils.encoding import smart_unicode
39
from mock import patch
40
41
42
43
44
45
46
47
48
49
50
51
52
53


@contextmanager
def override_settings(settings, **kwargs):
    """
    Helper context manager to override django settings within the provided
    context.

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

    >>> from synnefo.util.testing import override_settings
    >>> from django.conf import settings
    >>> with override_settings(settings, DEBUG=True):
Ilias Tsitsimpis's avatar
Ilias Tsitsimpis committed
54
    ...     assert settings.DEBUG == True
55
56
57
58
59
60
61

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

    >>> from django.conf import settings
    >>> from django.core import mail
    >>> with override_settings(settings, CONTACT_EMAILS=['kpap@grnet.gr'],
Ilias Tsitsimpis's avatar
Ilias Tsitsimpis committed
62
63
64
65
66
    ...                        prefix='MYAPP_'):
    ...     from django.core.mail import send_mail
    ...     send_mail("hello", "I love you kpap", settings.DEFAULT_FROM_EMAIL,
    ...               settings.MYAPP_CONTACT_EMAILS)
    ...     assert 'kpap@grnet.gr' in mail.mailbox[0].recipients()
67
68
69
70
71
72
73

    If you plan to reuse it

    >>> import functools
    >>> from synnefo.util.testing import override_settings
    >>> from django.conf import settings
    >>> myapp_settings = functools.partial(override_settings, prefix='MYAPP_')
Ilias Tsitsimpis's avatar
Ilias Tsitsimpis committed
74
75
    >>> with myapp_settings(CONTACT_EMAILS=['kpap@grnet.gr']):
    ...     assert settings.MYAPP_CONTACT_EMAILS == ['kpap@grnet.gr']
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118

    """

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

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

    toremove = []
    for key, value in kwargs.iteritems():
        key = prefix(key)
        if not hasattr(settings, key):
            toremove.append(key)
        setattr(settings, key, value)

    yield

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

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

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


def with_settings(settings, prefix='', **override):
    def wrapper(func):
        def inner(*args, **kwargs):
            with override_settings(settings, prefix=prefix, **override):
                ret = func(*args, **kwargs)
            return ret
        return inner
    return wrapper
119

120
121
serial = 0

122
123
124
125
126
127
128
129
130
131
132
133
134

@contextmanager
def astakos_user(user):
    """
    Context manager to mock astakos response.

    usage:
    with astakos_user("user@user.com"):
        .... make api calls ....

    """
    with patch("snf_django.lib.api.get_token") as get_token:
        get_token.return_value = "DummyToken"
135
136
        with patch('astakosclient.AstakosClient.authenticate') as m2:
            m2.return_value = {"access": {
Ilias Tsitsimpis's avatar
Ilias Tsitsimpis committed
137
138
139
140
                "token": {
                    "expires": "2013-06-19T15:23:59.975572+00:00",
                    "id": "DummyToken",
                    "tenant": {
141
                        "id": smart_unicode(user, encoding='utf-8'),
Ilias Tsitsimpis's avatar
Ilias Tsitsimpis committed
142
143
144
145
146
147
                        "name": "Firstname Lastname"
                        }
                    },
                "serviceCatalog": [],
                "user": {
                    "roles_links": [],
148
                    "id": smart_unicode(user, encoding='utf-8'),
Ilias Tsitsimpis's avatar
Ilias Tsitsimpis committed
149
150
151
                    "roles": [{"id": 1, "name": "default"}],
                    "name": "Firstname Lastname"}}
                }
152

153
154
            with patch('astakosclient.AstakosClient.service_get_quotas') as m2:
                m2.return_value = {user: {
155
156
157
158
159
                    "system": {
                        "pithos.diskspace": {
                            "usage": 0,
                            "limit": 1073741824,  # 1GB
                            "pending": 0
160
                            }
161
162
                        }
                    }
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
                }
                issue_fun = \
                    "astakosclient.AstakosClient.issue_one_commission"
                with patch(issue_fun) as m3:
                    serials = []
                    append = serials.append

                    def get_serial(*args, **kwargs):
                        global serial
                        serial += 1
                        append(serial)
                        return serial

                    m3.side_effect = get_serial
                    resolv_fun = \
                        'astakosclient.AstakosClient.resolve_commissions'
                    with patch(resolv_fun) as m4:
                        m4.return_value = {'accepted': serials,
                                           'rejected': [],
                                           'failed': []}
                        users_fun = \
                            'astakosclient.AstakosClient.get_usernames'
                        with patch(users_fun) as m5:

                            def get_usernames(*args, **kwargs):
                                uuids = args[-1]
                                return dict((uuid, uuid) for uuid in uuids)

                            m5.side_effect = get_usernames
                            yield
193
194


195
196
197
serial = 0


198
199
@contextmanager
def mocked_quotaholder(success=True):
200
    with patch("synnefo.quotas.Quotaholder.get") as astakos:
201
        global serial
202
203
204
205
206
207
        serial += 10

        def foo(*args, **kwargs):
            return (len(astakos.return_value.issue_one_commission.mock_calls) +
                    serial)
        astakos.return_value.issue_one_commission.side_effect = foo
208

209
210
211
212
213
214
        def resolve_mock(*args, **kwargs):
            return {"failed": [],
                    "accepted": args[0],
                    "rejected": args[1],
                    }
        astakos.return_value.resolve_commissions.side_effect = resolve_mock
215
        yield astakos.return_value
216

217
218
219
220

class BaseAPITest(TestCase):
    def get(self, url, user='user', *args, **kwargs):
        with astakos_user(user):
221
222
            with mocked_quotaholder():
                response = self.client.get(url, *args, **kwargs)
223
224
        return response

225
226
227
228
229
230
    def head(self, url, user='user', *args, **kwargs):
        with astakos_user(user):
            with mocked_quotaholder():
                response = self.client.head(url, *args, **kwargs)
        return response

231
232
    def delete(self, url, user='user'):
        with astakos_user(user):
233
234
            with mocked_quotaholder() as m:
                self.mocked_quotaholder = m
235
                response = self.client.delete(url)
236
237
238
239
240
241
        return response

    def post(self, url, user='user', params={}, ctype='json', *args, **kwargs):
        if ctype == 'json':
            content_type = 'application/json'
        with astakos_user(user):
242
243
            with mocked_quotaholder() as m:
                self.mocked_quotaholder = m
244
245
246
                response = self.client.post(url, params,
                                            content_type=content_type,
                                            *args, **kwargs)
247
248
249
250
251
252
        return response

    def put(self, url, user='user', params={}, ctype='json', *args, **kwargs):
        if ctype == 'json':
            content_type = 'application/json'
        with astakos_user(user):
253
254
            with mocked_quotaholder() as m:
                self.mocked_quotaholder = m
255
256
257
                response = self.client.put(url, params,
                                           content_type=content_type,
                                           *args, **kwargs)
258
259
260
        return response

    def assertSuccess(self, response):
261
262
        self.assertTrue(response.status_code in [200, 202, 203, 204],
                        msg=response.content)
263

264
    def assertSuccess201(self, response):
265
        self.assertEqual(response.status_code, 201, msg=response.content)
266

267
268
269
    def assertFault(self, response, status_code, name, msg=''):
        self.assertEqual(response.status_code, status_code,
                         msg=msg)
270
271
272
273
        fault = json.loads(response.content)
        self.assertEqual(fault.keys(), [name])

    def assertBadRequest(self, response):
274
        self.assertFault(response, 400, 'badRequest', msg=response.content)
275

276
    def assertConflict(self, response):
277
        self.assertFault(response, 409, 'conflict', msg=response.content)
278

279
    def assertItemNotFound(self, response):
280
        self.assertFault(response, 404, 'itemNotFound', msg=response.content)
281

282
    def assertMethodNotAllowed(self, response):
283
        self.assertFault(response, 405, 'notAllowed', msg=response.content)
284
        self.assertTrue('Allow' in response)
285
286
287
288
        try:
            error = json.loads(response.content)
        except ValueError:
            self.assertTrue(False)
289
        self.assertEqual(error['notAllowed']['message'], 'Method not allowed')
290

291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330

# Imitate unittest assertions new in Python 2.7

class _AssertRaisesContext(object):
    """
    A context manager used to implement TestCase.assertRaises* methods.
    Adapted from unittest2.
    """

    def __init__(self, expected):
        self.expected = expected

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_value, tb):
        if exc_type is None:
            try:
                exc_name = self.expected.__name__
            except AttributeError:
                exc_name = str(self.expected)
            raise AssertionError(
                "%s not raised" % (exc_name,))
        if not issubclass(exc_type, self.expected):
            # let unexpected exceptions pass through
            return False
        self.exception = exc_value  # store for later retrieval
        return True


def assertRaises(excClass):
    return _AssertRaisesContext(excClass)


def assertGreater(x, y):
    assert x > y


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