Statistics
| Branch: | Tag: | Revision:

root / snf-app / synnefo / ui / userdata / tests.py @ 34d1013b

History | View | Annotate | Download (7.5 kB)

1
# Copyright 2011 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 django.test import TransactionTestCase
36
from django.conf import settings
37
from django.test.client import Client
38
from django.core.urlresolvers import clear_url_caches
39
from django.utils import simplejson as json
40
from django.conf import settings
41
from django.core.urlresolvers import reverse
42

    
43
from synnefo.ui.userdata.models import User
44
from synnefo.ui.userdata.models import *
45
from synnefo.db.models import SynnefoUser
46

    
47
class AaiClient(Client):
48

    
49
    def request(self, **request):
50
        request['HTTP_X_AUTH_TOKEN'] = \
51
            settings.BYPASS_AUTHENTICATION_SECRET_TOKEN
52
        return super(AaiClient, self).request(**request)
53

    
54
class TestRestViews(TransactionTestCase):
55

    
56
    fixtures = ['users']
57

    
58
    def setUp(self):
59
        settings.SKIP_SSH_VALIDATION = True
60
        self.client = AaiClient()
61
        self.user = User.objects.get(pk=1)
62
        self.keys_url = reverse('keys_collection')
63

    
64
    def test_keys_collection_get(self):
65
        resp = self.client.get(self.keys_url)
66
        self.assertEqual(resp.content, "[]")
67

    
68
        PublicKeyPair.objects.create(user=self.user, name="key pair 1",
69
                content="content1")
70

    
71
        resp = self.client.get(self.keys_url)
72
        resp_list = json.loads(resp.content);
73
        exp_list = [{"content": "content1", "id": 1,
74
                    "uri": self.keys_url + "/1", "name": "key pair 1",
75
                    "fingerprint": "unknown fingerprint"}]
76
        self.assertEqual(resp_list, exp_list)
77

    
78
        PublicKeyPair.objects.create(user=self.user, name="key pair 2",
79
                content="content2")
80

    
81
        resp = self.client.get(self.keys_url)
82
        resp_list = json.loads(resp.content)
83
        exp_list = [{"content": "content1", "id": 1,
84
                     "uri": self.keys_url + "/1", "name": "key pair 1",
85
                     "fingerprint": "unknown fingerprint"},
86
                    {"content": "content2", "id": 2,
87
                     "uri": self.keys_url + "/2",
88
                     "name": "key pair 2",
89
                     "fingerprint": "unknown fingerprint"}]
90

    
91
        self.assertEqual(resp_list, exp_list)
92

    
93
    def test_keys_resourse_get(self):
94
        resp = self.client.get(self.keys_url + "/1")
95
        self.assertEqual(resp.status_code, 404)
96

    
97
        # create a public key
98
        PublicKeyPair.objects.create(user=self.user, name="key pair 1",
99
                content="content1")
100
        resp = self.client.get(self.keys_url + "/1")
101
        resp_dict = json.loads(resp.content);
102
        exp_dict = {"content": "content1", "id": 1,
103
                    "uri": self.keys_url + "/1", "name": "key pair 1",
104
                    "fingerprint": "unknown fingerprint"}
105
        self.assertEqual(resp_dict, exp_dict)
106

    
107
        # update
108
        resp = self.client.put(self.keys_url + "/1",
109
                               json.dumps({'name':'key pair 1 new name'}),
110
                               content_type='application/json')
111

    
112
        pk = PublicKeyPair.objects.get(pk=1)
113
        self.assertEqual(pk.name, "key pair 1 new name")
114

    
115
        # delete
116
        resp = self.client.delete(self.keys_url + "/1")
117
        self.assertEqual(PublicKeyPair.objects.count(), 0)
118

    
119
        resp = self.client.get(self.keys_url + "/1")
120
        self.assertEqual(resp.status_code, 404)
121

    
122
        resp = self.client.get(self.keys_url)
123
        self.assertEqual(resp.content, "[]")
124

    
125
        # test rest create
126
        resp = self.client.post(self.keys_url,
127
                                json.dumps({'name':'key pair 2',
128
                                            'content':"""key 2 content"""}),
129
                                content_type='application/json')
130
        self.assertEqual(PublicKeyPair.objects.count(), 1)
131
        pk = PublicKeyPair.objects.get(pk=1)
132
        self.assertEqual(pk.name, "key pair 2")
133
        self.assertEqual(pk.content, "key 2 content")
134

    
135
    def test_generate_views(self):
136
        import base64
137

    
138
        # just test that
139
        resp = self.client.post(self.keys_url + "/generate")
140
        self.assertNotEqual(resp, "")
141

    
142
        data = json.loads(resp.content)
143
        self.assertEqual(data.has_key('private'), True)
144
        self.assertEqual(data.has_key('private'), True)
145

    
146
        # public key is base64 encoded
147
        base64.b64decode(data['public'].replace("ssh-rsa ",""))
148

    
149
        # remove header/footer
150
        private = "".join(data['private'].split("\n")[1:-1])
151

    
152
        # private key is base64 encoded
153
        base64.b64decode(private)
154

    
155
        new_key = PublicKeyPair()
156
        new_key.content = data['public']
157
        new_key.name = "new key"
158
        new_key.user = SynnefoUser.objects.all()[0]
159
        new_key.full_clean()
160
        new_key.save()
161

    
162
    def test_invalid_data(self):
163
        resp = self.client.post(self.keys_url,
164
                                json.dumps({'content':"""key 2 content"""}),
165
                                content_type='application/json')
166

    
167
        self.assertEqual(resp.status_code, 500)
168
        self.assertEqual(resp.content, """{"non_field_key": "__all__", "errors": """
169
                                       """{"name": ["This field cannot be blank."]}}""")
170

    
171
        settings.USERDATA_MAX_SSH_KEYS_PER_USER = 2
172

    
173
        # test ssh limit
174
        resp = self.client.post(self.keys_url,
175
                                json.dumps({'name':'key1',
176
                                            'content':"""key 1 content"""}),
177
                                content_type='application/json')
178
        resp = self.client.post(self.keys_url,
179
                                json.dumps({'name':'key1',
180
                                            'content':"""key 1 content"""}),
181
                                content_type='application/json')
182
        resp = self.client.post(self.keys_url,
183
                                json.dumps({'name':'key1',
184
                                            'content':"""key 1 content"""}),
185
                                content_type='application/json')
186
        self.assertEqual(resp.status_code, 500)
187
        self.assertEqual(resp.content, """{"non_field_key": "__all__", "errors": """
188
                                       """{"__all__": ["SSH keys limit exceeded."]}}""")
189