Statistics
| Branch: | Tag: | Revision:

root / kamaki / clients / astakos / test.py @ 058ee9a8

History | View | Annotate | Download (9.1 kB)

1
# Copyright 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 mock import patch, call
35
from logging import getLogger
36
from unittest import TestCase
37

    
38
from kamaki.clients import ClientError
39

    
40

    
41
example = dict(
42
    access=dict(
43
         token=dict(
44
            expires="2013-07-14T10:07:42.481134+00:00",
45
            id="ast@k0sT0k3n==",
46
            tenant=dict(
47
                id="42",
48
                name="Simple Name 0")
49
        ),
50
        serviceCatalog=[
51
            dict(name='service name 1', type='compute', endpoints=[
52
                dict(versionId='v1', publicUrl='http://1.1.1.1/v1'),
53
                dict(versionId='v2', publicUrl='http://1.1.1.1/v2')]),
54
            dict(name='service name 3', type='object-storage', endpoints=[
55
                dict(versionId='v2', publicUrl='http://1.1.1.1/v2'),
56
                dict(versionId='v2.1', publicUrl='http://1.1.1.1/v2/xtra')])
57
            ],
58
        user=dict(
59
            name='Simple Name 0',
60
            username='User Full Name 0',
61
            auth_token_expires='1362585796000',
62
            auth_token_created='1359931796000',
63
            email=['user0@example.gr'],
64
            id=42,
65
            uuid='aus3r-uu1d-507-73s71ng-as7ak0s')
66
        )
67
    )
68

    
69

    
70
class FR(object):
71
    json = example
72
    headers = {}
73
    content = json
74
    status = None
75
    status_code = 200
76

    
77
astakos_pkg = 'kamaki.clients.astakos'
78

    
79

    
80
class AstakosClient(TestCase):
81

    
82
    cached = False
83

    
84
    def assert_dicts_are_equal(self, d1, d2):
85
        for k, v in d1.items():
86
            self.assertTrue(k in d2)
87
            if isinstance(v, dict):
88
                self.assert_dicts_are_equal(v, d2[k])
89
            else:
90
                self.assertEqual(unicode(v), unicode(d2[k]))
91

    
92
    def setUp(self):
93
        self.url = 'https://astakos.example.com'
94
        self.token = 'ast@k0sT0k3n=='
95
        from kamaki.clients.astakos import AstakosClient as AC
96
        self.client = AC(self.url, self.token)
97

    
98
    def tearDown(self):
99
        FR.json = example
100

    
101
    @patch(
102
        '%s.SynnefoAstakosClient.__init__' % astakos_pkg, return_value=None)
103
    @patch(
104
        '%s.SynnefoAstakosClient.get_endpoints' % astakos_pkg,
105
        return_value=example)
106
    def _authenticate(self, get_endpoints, sac):
107
        r = self.client.authenticate()
108
        self.assertEqual(
109
            sac.mock_calls[-1], call(self.token, self.url,
110
                logger=getLogger('astakosclient')))
111
        self.assertEqual(get_endpoints.mock_calls[-1], call())
112
        return r
113

    
114
    def test_authenticate(self):
115
        r = self._authenticate()
116
        self.assert_dicts_are_equal(r, example)
117
        uuid = example['access']['user']['id']
118
        self.assert_dicts_are_equal(self.client._uuids, {self.token: uuid})
119
        self.assert_dicts_are_equal(self.client._cache, {uuid: r})
120
        from astakosclient import AstakosClient as SAC
121
        self.assertTrue(isinstance(self.client._astakos[uuid], SAC))
122
        self.assert_dicts_are_equal(self.client._uuids2usernames, {uuid: {}})
123
        self.assert_dicts_are_equal(self.client._usernames2uuids, {uuid: {}})
124

    
125
    def test_get_client(self):
126
        if not self.cached:
127
            self._authenticate()
128
        from astakosclient import AstakosClient as SNFAC
129
        self.assertTrue(self.client.get_client(), SNFAC)
130

    
131
    def test_get_token(self):
132
        self._authenticate()
133
        uuid = self.client._uuids.values()[0]
134
        self.assertEqual(self.client.get_token(uuid), self.token)
135

    
136
    def test_get_services(self):
137
        if not self.cached:
138
            self._authenticate()
139
        slist = self.client.get_services()
140
        self.assertEqual(slist, example['access']['serviceCatalog'])
141

    
142
    def test_get_service_details(self):
143
        if not self.cached:
144
            self._authenticate()
145
        stype = '#FAIL'
146
        self.assertRaises(ClientError, self.client.get_service_details, stype)
147
        stype = 'compute'
148
        expected = [s for s in example['access']['serviceCatalog'] if (
149
            s['type'] == stype)]
150
        self.assert_dicts_are_equal(
151
            self.client.get_service_details(stype), expected[0])
152

    
153
    def test_get_service_endpoints(self):
154
        if not self.cached:
155
            self._authenticate()
156
        stype, version = 'compute', 'V2'
157
        self.assertRaises(
158
            ClientError, self.client.get_service_endpoints, stype)
159
        expected = [s for s in example['access']['serviceCatalog'] if (
160
            s['type'] == stype)]
161
        expected = [e for e in expected[0]['endpoints'] if (
162
            e['versionId'] == version.lower())]
163
        self.assert_dicts_are_equal(
164
            self.client.get_service_endpoints(stype, version), expected[0])
165

    
166
    def test_user_info(self):
167
        if not self.cached:
168
            self._authenticate()
169
        self.assertTrue(set(example['access']['user'].keys()).issubset(
170
            self.client.user_info().keys()))
171

    
172
    def test_item(self):
173
        if not self.cached:
174
            self._authenticate()
175
        for term, val in example['access']['user'].items():
176
            self.assertEqual(self.client.term(term, self.token), val)
177
        self.assertTrue(
178
            example['access']['user']['email'][0] in self.client.term('email'))
179

    
180
    def test_list_users(self):
181
        if not self.cached:
182
            self._authenticate()
183
        FR.json = example
184
        self._authenticate()
185
        r = self.client.list_users()
186
        self.assertTrue(len(r) == 1)
187
        self.assertEqual(r[0]['auth_token'], self.token)
188

    
189
    @patch(
190
        '%s.SynnefoAstakosClient.get_usernames' % astakos_pkg,
191
        return_value={42: 'username42', 43: 'username43'})
192
    def test_uuids2usernames(self, get_usernames):
193
        from astakosclient import AstakosClientException
194
        self.assertRaises(
195
            AstakosClientException, self.client.uuids2usernames, [42, 43])
196
        with patch(
197
                '%s.SynnefoAstakosClient.__init__' % astakos_pkg,
198
                return_value=None) as sac:
199
            with patch(
200
                    '%s.SynnefoAstakosClient.get_endpoints' % astakos_pkg,
201
                    return_value=example) as get_endpoints:
202
                r = self.client.uuids2usernames([42, 43])
203
                self.assert_dicts_are_equal(
204
                    r, {42: 'username42', 43: 'username43'})
205
                self.assertEqual(sac.mock_calls[-1], call(
206
                    self.token, self.url, logger=getLogger('astakosclient')))
207
                self.assertEqual(get_endpoints.mock_calls[-1], call())
208
                self.assertEqual(get_usernames.mock_calls[-1], call([42, 43]))
209

    
210
    @patch(
211
        '%s.SynnefoAstakosClient.get_uuids' % astakos_pkg,
212
        return_value={'username42': 42, 'username43': 43})
213
    def test_usernames2uuids(self, get_uuids):
214
        from astakosclient import AstakosClientException
215
        self.assertRaises(
216
            AstakosClientException, self.client.usernames2uuids, ['u1', 'u2'])
217
        with patch(
218
                '%s.SynnefoAstakosClient.__init__' % astakos_pkg,
219
                return_value=None) as sac:
220
            with patch(
221
                    '%s.SynnefoAstakosClient.get_endpoints' % astakos_pkg,
222
                    return_value=example) as get_endpoints:
223
                r = self.client.usernames2uuids(['u1', 'u2'])
224
                self.assert_dicts_are_equal(
225
                    r, {'username42': 42, 'username43': 43})
226
                self.assertEqual(sac.mock_calls[-1], call(
227
                    self.token, self.url, logger=getLogger('astakosclient')))
228
                self.assertEqual(get_endpoints.mock_calls[-1], call())
229
                self.assertEqual(get_uuids.mock_calls[-1], call(['u1', 'u2']))
230

    
231

    
232
if __name__ == '__main__':
233
    from sys import argv
234
    from kamaki.clients.test import runTestCase
235
    runTestCase(AstakosClient, 'AstakosClient', argv[1:])