Revision d2b8ec7b

b/snf-astakos-app/astakos/im/tests.py
36 36
import datetime
37 37
import functools
38 38

  
39
from synnefo.util.testing import with_settings, override_settings
39
from snf_django.utils.testing import with_settings, override_settings
40 40

  
41 41
from django.test import TestCase, Client
42 42
from django.core import mail
/dev/null
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

  
37

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

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

  
47
    >>> from synnefo.util.testing import override_settings
48
    >>> from django.conf import settings
49
    >>> with override_settings(settings, DEBUG=True):
50
    >>>     assert settings.DEBUG == True
51

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

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

  
64
    If you plan to reuse it
65

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

  
73
    """
74

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

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

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

  
88
    yield
89

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

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

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

  
106

  
107
def with_settings(settings, prefix='', **override):
108
    def wrapper(func):
109
        def inner(*args, **kwargs):
110
            with override_settings(settings, prefix=prefix, **override):
111
                ret = func(*args, **kwargs)
112
            return ret
113
        return inner
114
    return wrapper
b/snf-cyclades-app/synnefo/api/test/flavors.py
33 33

  
34 34
import json
35 35

  
36
from synnefo.api.tests import BaseAPITest
36
from snf_django.utils.testing import BaseAPITest
37 37
from synnefo.db.models import Flavor
38 38
from synnefo.db.models_factory import FlavorFactory
39 39

  
b/snf-cyclades-app/synnefo/api/test/images.py
34 34
import json
35 35

  
36 36
from snf_django.lib.api import faults
37
from synnefo.api.tests import BaseAPITest
37
from snf_django.utils.testing import BaseAPITest
38 38

  
39 39
from mock import patch
40 40
from functools import wraps
b/snf-cyclades-app/synnefo/api/test/networks.py
34 34
import json
35 35
from mock import patch
36 36

  
37
from synnefo.api.tests import BaseAPITest
37
from snf_django.utils.testing import BaseAPITest
38 38
from synnefo.db.models import Network, NetworkInterface
39 39
from synnefo.db import models_factory as mfactory
40 40

  
b/snf-cyclades-app/synnefo/api/test/servers.py
33 33

  
34 34
import json
35 35

  
36
from synnefo.api.tests import  BaseAPITest
36
from snf_django.utils.testing import BaseAPITest
37 37
from synnefo.db.models import VirtualMachine, VirtualMachineMetadata
38 38
from synnefo.db import models_factory as mfactory
39 39
from synnefo.logic.utils import get_rsapi_state
b/snf-cyclades-app/synnefo/api/test/versions.py
1
# Copyright 2012-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
from django.utils import simplejson as json
35
from django.test import TestCase
36
from snf_django.utils.testing import astakos_user
37

  
38
class APITest(TestCase):
39
    def test_api_version(self):
40
        """Check API version."""
41
        with astakos_user('user'):
42
            response = self.client.get('/api/v1.1/')
43
        self.assertEqual(response.status_code, 200)
44
        api_version = json.loads(response.content)['version']
45
        self.assertEqual(api_version['id'], 'v1.1')
46
        self.assertEqual(api_version['status'], 'CURRENT')
b/snf-cyclades-app/synnefo/api/tests.py
31 31
# interpreted as representing official policies, either expressed
32 32
# or implied, of GRNET S.A.
33 33

  
34
from __future__ import with_statement
35

  
36
from django.utils import simplejson as json
37
from django.test import TestCase
38

  
39
from mock import patch
40
from contextlib import contextmanager
41

  
42

  
43
@contextmanager
44
def astakos_user(user):
45
    """
46
    Context manager to mock astakos response.
47

  
48
    usage:
49
    with astakos_user("user@user.com"):
50
        .... make api calls ....
51

  
52
    """
53
    with patch("snf_django.lib.api.get_token") as get_token:
54
        get_token.return_value = "DummyToken"
55
        with patch('astakosclient.AstakosClient.get_user_info') as m:
56
            m.return_value = {"uuid": user}
57
            yield
58

  
59

  
60
class BaseAPITest(TestCase):
61
    def get(self, url, user='user', *args, **kwargs):
62
        with astakos_user(user):
63
            response = self.client.get(url, *args, **kwargs)
64
        return response
65

  
66
    def delete(self, url, user='user'):
67
        with astakos_user(user):
68
            response = self.client.delete(url)
69
        return response
70

  
71
    def post(self, url, user='user', params={}, ctype='json', *args, **kwargs):
72
        if ctype == 'json':
73
            content_type = 'application/json'
74
        with astakos_user(user):
75
            response = self.client.post(url, params, content_type=content_type,
76
                                        *args, **kwargs)
77
        return response
78

  
79
    def put(self, url, user='user', params={}, ctype='json', *args, **kwargs):
80
        if ctype == 'json':
81
            content_type = 'application/json'
82
        with astakos_user(user):
83
            response = self.client.put(url, params, content_type=content_type,
84
                                       *args, **kwargs)
85
        return response
86

  
87
    def assertSuccess(self, response):
88
        self.assertTrue(response.status_code in [200, 203, 204])
89

  
90
    def assertFault(self, response, status_code, name):
91
        self.assertEqual(response.status_code, status_code)
92
        fault = json.loads(response.content)
93
        self.assertEqual(fault.keys(), [name])
94

  
95
    def assertBadRequest(self, response):
96
        self.assertFault(response, 400, 'badRequest')
97

  
98
    def assertItemNotFound(self, response):
99
        self.assertFault(response, 404, 'itemNotFound')
100

  
101

  
102
class APITest(TestCase):
103
    def test_api_version(self):
104
        """Check API version."""
105
        with astakos_user('user'):
106
            response = self.client.get('/api/v1.1/')
107
        self.assertEqual(response.status_code, 200)
108
        api_version = json.loads(response.content)['version']
109
        self.assertEqual(api_version['id'], 'v1.1')
110
        self.assertEqual(api_version['status'], 'CURRENT')
111

  
112

  
113 34
# Import TestCases
114 35
from synnefo.api.test.servers import *
115 36
from synnefo.api.test.networks import *
116 37
from synnefo.api.test.flavors import *
117 38
from synnefo.api.test.images import *
39
from synnefo.api.test.versions import *
b/snf-cyclades-app/synnefo/plankton/tests.py
39 39
from mock import patch
40 40
from functools import wraps
41 41
from copy import deepcopy
42
from snf_django.utils.testing import astakos_user, BaseAPITest
42 43

  
43 44

  
44 45
FILTERS = ('name', 'container_format', 'disk_format', 'status', 'size_min',
......
58 59
                 'owner', 'properties', 'status')
59 60

  
60 61

  
61
@contextmanager
62
def astakos_user(user):
63
    """
64
    Context manager to mock astakos response.
65

  
66
    usage:
67
    with astakos_user("user@user.com"):
68
        .... make api calls ....
69

  
70
    """
71
    with patch("snf_django.lib.api.get_token") as get_token:
72
        get_token.return_value = "DummyToken"
73
        with patch('astakosclient.AstakosClient.get_user_info') as m:
74
            m.return_value = {"uuid": user}
75
            yield
76

  
77

  
78
class BaseAPITest(TestCase):
79
    def get(self, url, user='user', *args, **kwargs):
80
        with astakos_user(user):
81
            response = self.client.get(url, *args, **kwargs)
82
        return response
83

  
84
    def delete(self, url, user='user'):
85
        with astakos_user(user):
86
            response = self.client.delete(url)
87
        return response
88

  
89
    def post(self, url, user='user', params={}, ctype='json', *args, **kwargs):
90
        if ctype == 'json':
91
            content_type = 'application/json'
92
        with astakos_user(user):
93
            response = self.client.post(url, params, content_type=content_type,
94
                                        *args, **kwargs)
95
        return response
96

  
97
    def put(self, url, user='user', params={}, ctype='json', *args, **kwargs):
98
        if ctype == 'json':
99
            content_type = 'application/json'
100
        with astakos_user(user):
101
            response = self.client.put(url, params, content_type=content_type,
102
                                       *args, **kwargs)
103
        return response
104

  
105
    def assertSuccess(self, response):
106
        self.assertTrue(response.status_code in [200, 203, 204])
107

  
108
    def assertFault(self, response, status_code, name):
109
        self.assertEqual(response.status_code, status_code)
110
        fault = response.content
111
        self.assertEqual(fault, name)
112

  
113
    def assertBadRequest(self, response):
114
        self.assertFault(response, 400, '400 Bad Request')
115

  
116
    def assertItemNotFound(self, response):
117
        self.assertFault(response, 404, 'itemNotFound')
118

  
119

  
120 62
DummyImages = {
121 63
 '0786a349-9725-48ec-8b86-8598eefc4043':
122 64
 {'checksum': u'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855',
b/snf-cyclades-app/synnefo/plankton/views.py
38 38
from urllib import unquote
39 39

  
40 40
from django.conf import settings
41
from django.http import (HttpResponse, HttpResponseNotFound,
42
                         HttpResponseBadRequest)
41
from django.http import HttpResponse
43 42

  
44 43
from snf_django.lib import api
44
from snf_django.lib.api import faults
45 45
from synnefo.plankton.utils import plankton_method
46 46

  
47 47

  
......
233 233

  
234 234
    image = request.backend.get_image(image_id)
235 235
    if not image:
236
        return HttpResponseNotFound()
236
        raise faults.ItemNotFound()
237 237
    return _create_image_response(image)
238 238

  
239 239

  
......
285 285
        try:
286 286
            filters['size_max'] = int(filters['size_max'])
287 287
        except ValueError:
288
            return HttpResponseBadRequest('400 Bad Request')
288
            raise faults.BadRequest("Malformed request.")
289 289

  
290 290
    if 'size_min' in filters:
291 291
        try:
292 292
            filters['size_min'] = int(filters['size_min'])
293 293
        except ValueError:
294
            return HttpResponseBadRequest('400 Bad Request')
294
            raise faults.BadRequest("Malformed request.")
295 295

  
296 296
    images = request.backend.list(filters, params)
297 297

  
b/snf-django-lib/snf_django/utils/testing.py
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')

Also available in: Unified diff