Statistics
| Branch: | Tag: | Revision:

root / snf-cyclades-app / synnefo / api / tests / images.py @ 94537e34

History | View | Annotate | Download (15.7 kB)

1
# Copyright 2012 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
import json
35

    
36
from snf_django.lib.api import faults
37
from snf_django.utils.testing import BaseAPITest
38
from synnefo.lib.services import get_service_path
39
from synnefo.cyclades_settings import cyclades_services
40
from synnefo.lib import join_urls
41

    
42
from mock import patch
43
from functools import wraps
44

    
45

    
46
def assert_backend_closed(func):
47
    """Decorator for ensuring that ImageBackend is returned to pool."""
48
    @wraps(func)
49
    def wrapper(self, backend):
50
        result = func(self, backend)
51
        if backend.called is True:
52
            backend.return_value.close.asssert_called
53
        return result
54
    return wrapper
55

    
56

    
57
class ComputeAPITest(BaseAPITest):
58
    def setUp(self, *args, **kwargs):
59
        super(ComputeAPITest, self).setUp(*args, **kwargs)
60
        self.compute_path = get_service_path(cyclades_services, 'compute',
61
                                             version='v2.0')
62
    def myget(self, path, *args, **kwargs):
63
        path = join_urls(self.compute_path, path)
64
        return self.get(path, *args, **kwargs)
65

    
66
    def myput(self, path, *args, **kwargs):
67
        path = join_urls(self.compute_path, path)
68
        return self.put(path, *args, **kwargs)
69

    
70
    def mypost(self, path, *args, **kwargs):
71
        path = join_urls(self.compute_path, path)
72
        return self.post(path, *args, **kwargs)
73

    
74
    def mydelete(self, path, *args, **kwargs):
75
        path = join_urls(self.compute_path, path)
76
        return self.delete(path, *args, **kwargs)
77

    
78

    
79
@patch('synnefo.plankton.backend.ImageBackend')
80
class ImageAPITest(ComputeAPITest):
81
    @assert_backend_closed
82
    def test_create_image(self, mimage):
83
        """Test that create image is not implemented"""
84
        response = self.mypost('images/', 'user', json.dumps(''), 'json')
85
        self.assertEqual(response.status_code, 501)
86

    
87
    @assert_backend_closed
88
    def test_list_images(self, mimage):
89
        """Test that expected list of images is returned"""
90
        images = [{'id': 1, 'name': 'image-1'},
91
                  {'id': 2, 'name': 'image-2'},
92
                  {'id': 3, 'name': 'image-3'}]
93
        mimage().list_images.return_value = images
94
        response = self.myget('images', 'user')
95
        self.assertSuccess(response)
96
        api_images = json.loads(response.content)['images']
97
        self.assertEqual(images, api_images)
98

    
99
    @assert_backend_closed
100
    def test_list_images_detail(self, mimage):
101
        images = [{'id': 1,
102
                   'name': 'image-1',
103
                   'status':'available',
104
                   'created_at': '2012-11-26 11:52:54',
105
                   'updated_at': '2012-12-26 11:52:54',
106
                   'owner': 'user1',
107
                   'deleted_at': '',
108
                   'properties': {'foo':'bar'}},
109
                  {'id': 2,
110
                   'name': 'image-2',
111
                   'status': 'deleted',
112
                   'created_at': '2012-11-26 11:52:54',
113
                   'updated_at': '2012-12-26 11:52:54',
114
                   'owner': 'user1',
115
                   'deleted_at': '2012-12-27 11:52:54',
116
                   'properties': ''},
117
                  {'id': 3,
118
                   'name': 'image-3',
119
                   'status': 'available',
120
                   'created_at': '2012-11-26 11:52:54',
121
                   'deleted_at': '',
122
                   'updated_at': '2012-12-26 11:52:54',
123
                   'owner': 'user1',
124
                   'properties': ''}]
125
        result_images = [
126
                  {'id': 1,
127
                   'name': 'image-1',
128
                   'status':'ACTIVE',
129
                   'progress': 100,
130
                   'created': '2012-11-26T11:52:54+00:00',
131
                   'updated': '2012-12-26T11:52:54+00:00',
132
                   'user_id': 'user1',
133
                   'tenant_id': 'user1',
134
                   'metadata': {'foo':'bar'}},
135
                  {'id': 2,
136
                   'name': 'image-2',
137
                   'status': 'DELETED',
138
                   'progress': 0,
139
                   'user_id': 'user1',
140
                   'tenant_id': 'user1',
141
                   'created': '2012-11-26T11:52:54+00:00',
142
                   'updated': '2012-12-26T11:52:54+00:00',
143
                   'metadata': {}},
144
                  {'id': 3,
145
                   'name': 'image-3',
146
                   'status': 'ACTIVE',
147
                   'progress': 100,
148
                   'user_id': 'user1',
149
                   'tenant_id': 'user1',
150
                   'created': '2012-11-26T11:52:54+00:00',
151
                   'updated': '2012-12-26T11:52:54+00:00',
152
                   'metadata': {}}]
153
        mimage().list_images.return_value = images
154
        response = self.myget('images/detail', 'user')
155
        self.assertSuccess(response)
156
        api_images = json.loads(response.content)['images']
157
        self.assertEqual(len(result_images), len(api_images))
158
        map(lambda image: image.pop("links"), api_images)
159
        self.assertEqual(result_images, api_images)
160

    
161
    @assert_backend_closed
162
    def test_list_images_detail_since(self, mimage):
163
        from datetime import datetime, timedelta
164
        from time import sleep
165
        old_time = datetime.now()
166
        new_time = old_time + timedelta(seconds=0.1)
167
        sleep(0.1)
168
        images = [
169
                  {'id': 1,
170
                   'name': 'image-1',
171
                   'status':'available',
172
                   'progress': 100,
173
                   'created_at': old_time.isoformat(),
174
                   'deleted_at': '',
175
                   'updated_at': old_time.isoformat(),
176
                   'owner': 'user1',
177
                   'properties': ''},
178
                  {'id': 2,
179
                   'name': 'image-2',
180
                   'status': 'deleted',
181
                   'progress': 0,
182
                   'owner': 'user2',
183
                   'created_at': new_time.isoformat(),
184
                   'updated_at': new_time.isoformat(),
185
                   'deleted_at': new_time.isoformat(),
186
                   'properties': ''}]
187
        mimage().list_images.return_value = images
188
        response =\
189
            self.myget('images/detail?changes-since=%sUTC' % new_time)
190
        self.assertSuccess(response)
191
        api_images = json.loads(response.content)['images']
192
        self.assertEqual(1, len(api_images))
193

    
194
    @assert_backend_closed
195
    def test_get_image_details(self, mimage):
196
        image = {'id': 42,
197
                 'name': 'image-1',
198
                 'status': 'available',
199
                 'created_at': '2012-11-26 11:52:54',
200
                 'updated_at': '2012-12-26 11:52:54',
201
                 'deleted_at': '',
202
                 'owner': 'user1',
203
                 'properties': {'foo': 'bar'}}
204
        result_image = \
205
                  {'id': 42,
206
                   'name': 'image-1',
207
                   'status': 'ACTIVE',
208
                   'progress': 100,
209
                   'created': '2012-11-26T11:52:54+00:00',
210
                   'updated': '2012-12-26T11:52:54+00:00',
211
                   'user_id': 'user1',
212
                   'tenant_id': 'user1',
213
                   'metadata': {'foo': 'bar'}}
214
        mimage.return_value.get_image.return_value = image
215
        response = self.myget('images/42', 'user')
216
        self.assertSuccess(response)
217
        api_image = json.loads(response.content)['image']
218
        api_image.pop("links")
219
        self.assertEqual(api_image, result_image)
220

    
221
    @assert_backend_closed
222
    def test_invalid_image(self, mimage):
223
        mimage.return_value.get_image.side_effect = faults.ItemNotFound('Image not found')
224
        response = self.myget('images/42', 'user')
225
        self.assertItemNotFound(response)
226

    
227
    @assert_backend_closed
228
    def test_delete_image(self, mimage):
229
        response = self.mydelete("images/42", "user")
230
        self.assertEqual(response.status_code, 204)
231
        mimage.return_value.unregister.assert_called_once_with('42')
232
        mimage.return_value._delete.assert_not_called('42')
233

    
234
    @assert_backend_closed
235
    def test_catch_wrong_api_paths(self, *args):
236
        response = self.myget('nonexistent')
237
        self.assertEqual(response.status_code, 400)
238
        try:
239
            error = json.loads(response.content)
240
        except ValueError:
241
            self.assertTrue(False)
242

    
243
    @assert_backend_closed
244
    def test_method_not_allowed(self, *args):
245
        # /images/ allows only POST, GET
246
        response = self.myput('images', '', '')
247
        self.assertMethodNotAllowed(response)
248
        response = self.mydelete('images')
249
        self.assertMethodNotAllowed(response)
250

    
251
        # /images/<imgid>/ allows only GET, DELETE
252
        response = self.mypost("images/42")
253
        self.assertMethodNotAllowed(response)
254
        response = self.myput('images/42', '', '')
255
        self.assertMethodNotAllowed(response)
256

    
257
        # /images/<imgid>/metadata/ allows only POST, GET
258
        response = self.myput('images/42/metadata', '', '')
259
        self.assertMethodNotAllowed(response)
260
        response = self.mydelete('images/42/metadata')
261
        self.assertMethodNotAllowed(response)
262

    
263
        # /images/<imgid>/metadata/ allows only POST, GET
264
        response = self.myput('images/42/metadata', '', '')
265
        self.assertMethodNotAllowed(response)
266
        response = self.mydelete('images/42/metadata')
267
        self.assertMethodNotAllowed(response)
268

    
269
        # /images/<imgid>/metadata/<key> allows only PUT, GET, DELETE
270
        response = self.mypost('images/42/metadata/foo')
271
        self.assertMethodNotAllowed(response)
272

    
273

    
274
@patch('synnefo.plankton.backend.ImageBackend')
275
class ImageMetadataAPITest(ComputeAPITest):
276
    def setUp(self):
277
        self.image = {'id': 42,
278
                 'name': 'image-1',
279
                 'status': 'available',
280
                 'created_at': '2012-11-26 11:52:54',
281
                 'updated_at': '2012-12-26 11:52:54',
282
                 'deleted_at': '',
283
                 'properties': {'foo': 'bar', 'foo2': 'bar2'}}
284
        self.result_image = \
285
                  {'id': 42,
286
                   'name': 'image-1',
287
                   'status': 'ACTIVE',
288
                   'progress': 100,
289
                   'created': '2012-11-26T11:52:54+00:00',
290
                   'updated': '2012-12-26T11:52:54+00:00',
291
                   'metadata': {'foo': 'bar'}}
292
        super(ImageMetadataAPITest, self).setUp()
293

    
294
    @assert_backend_closed
295
    def test_list_metadata(self, backend):
296
        backend.return_value.get_image.return_value = self.image
297
        response = self.myget('images/42/metadata', 'user')
298
        self.assertSuccess(response)
299
        meta = json.loads(response.content)['metadata']
300
        self.assertEqual(meta, self.image['properties'])
301

    
302
    @assert_backend_closed
303
    def test_get_metadata(self, backend):
304
        backend.return_value.get_image.return_value = self.image
305
        response = self.myget('images/42/metadata/foo', 'user')
306
        self.assertSuccess(response)
307
        meta = json.loads(response.content)['meta']
308
        self.assertEqual(meta['foo'], 'bar')
309

    
310
    @assert_backend_closed
311
    def test_get_invalid_metadata(self, backend):
312
        backend.return_value.get_image.return_value = self.image
313
        response = self.myget('images/42/metadata/not_found', 'user')
314
        self.assertItemNotFound(response)
315

    
316
    def test_delete_metadata_item(self, backend):
317
        backend.return_value.get_image.return_value = self.image
318
        response = self.mydelete('images/42/metadata/foo', 'user')
319
        self.assertEqual(response.status_code, 204)
320
        backend.return_value.update_metadata.assert_called_once_with('42', {'properties': {'foo2':
321
                                                    'bar2'}})
322

    
323
    @assert_backend_closed
324
    def test_create_metadata_item(self, backend):
325
        backend.return_value.get_image.return_value = self.image
326
        request = {'meta': {'foo3': 'bar3'}}
327
        response = self.myput('images/42/metadata/foo3', 'user',
328
                              json.dumps(request), 'json')
329
        self.assertEqual(response.status_code, 201)
330
        backend.return_value.update_metadata.assert_called_once_with('42',
331
                {'properties':
332
                    {'foo': 'bar', 'foo2': 'bar2', 'foo3': 'bar3'}})
333

    
334
    @assert_backend_closed
335
    def test_create_metadata_malformed_1(self, backend):
336
        backend.return_value.get_image.return_value = self.image
337
        request = {'met': {'foo3': 'bar3'}}
338
        response = self.myput('images/42/metadata/foo3', 'user',
339
                              json.dumps(request), 'json')
340
        self.assertBadRequest(response)
341

    
342
    @assert_backend_closed
343
    def test_create_metadata_malformed_2(self, backend):
344
        backend.return_value.get_image.return_value = self.image
345
        request = {'metadata': [('foo3', 'bar3')]}
346
        response = self.myput('images/42/metadata/foo3', 'user',
347
                              json.dumps(request), 'json')
348
        self.assertBadRequest(response)
349

    
350
    @assert_backend_closed
351
    def test_create_metadata_malformed_3(self, backend):
352
        backend.return_value.get_image.return_value = self.image
353
        request = {'met': {'foo3': 'bar3', 'foo4': 'bar4'}}
354
        response = self.myput('images/42/metadata/foo3', 'user',
355
                                json.dumps(request), 'json')
356
        self.assertBadRequest(response)
357

    
358
    @assert_backend_closed
359
    def test_create_metadata_malformed_4(self, backend):
360
        backend.return_value.get_image.return_value = self.image
361
        request = {'met': {'foo3': 'bar3'}}
362
        response = self.myput('images/42/metadata/foo4', 'user',
363
                              json.dumps(request), 'json')
364
        self.assertBadRequest(response)
365

    
366
    @assert_backend_closed
367
    def test_update_metadata_item(self, backend):
368
        backend.return_value.get_image.return_value = self.image
369
        request = {'metadata': {'foo': 'bar_new', 'foo4': 'bar4'}}
370
        response = self.mypost('images/42/metadata', 'user',
371
                               json.dumps(request), 'json')
372
        self.assertEqual(response.status_code, 201)
373
        backend.return_value.update_metadata.assert_called_once_with('42',
374
                {'properties':
375
                    {'foo': 'bar_new', 'foo2': 'bar2', 'foo4': 'bar4'}
376
                })
377

    
378
    @assert_backend_closed
379
    def test_update_metadata_malformed(self, backend):
380
        backend.return_value.get_image.return_value = self.image
381
        request = {'meta': {'foo': 'bar_new', 'foo4': 'bar4'}}
382
        response = self.mypost('images/42/metadata', 'user',
383
                               json.dumps(request), 'json')
384
        self.assertBadRequest(response)