test.py 9.06 KB
Newer Older
1
# Copyright 2013 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
#
# 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.

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


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

77
astakos_pkg = 'kamaki.clients.astakos'
78
79


80
class AstakosClient(TestCase):
81

82
83
    cached = False

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

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

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

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

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

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

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

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

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

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

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

172
    def test_item(self):
173
174
        if not self.cached:
            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
187
        self.assertTrue(len(r) == 1)
        self.assertEqual(r[0]['auth_token'], self.token)
188

189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
    @patch(
        '%s.SynnefoAstakosClient.get_usernames' % astakos_pkg,
        return_value={42: 'username42', 43: 'username43'})
    def test_uuids2usernames(self, get_usernames):
        from astakosclient import AstakosClientException
        self.assertRaises(
            AstakosClientException, self.client.uuids2usernames, [42, 43])
        with patch(
                '%s.SynnefoAstakosClient.__init__' % astakos_pkg,
                return_value=None) as sac:
            with patch(
                    '%s.SynnefoAstakosClient.get_endpoints' % astakos_pkg,
                    return_value=example) as get_endpoints:
                r = self.client.uuids2usernames([42, 43])
                self.assert_dicts_are_equal(
                    r, {42: 'username42', 43: 'username43'})
                self.assertEqual(sac.mock_calls[-1], call(
                    self.token, self.url, logger=getLogger('astakosclient')))
                self.assertEqual(get_endpoints.mock_calls[-1], call())
                self.assertEqual(get_usernames.mock_calls[-1], call([42, 43]))

    @patch(
        '%s.SynnefoAstakosClient.get_uuids' % astakos_pkg,
        return_value={'username42': 42, 'username43': 43})
    def test_usernames2uuids(self, get_uuids):
        from astakosclient import AstakosClientException
        self.assertRaises(
            AstakosClientException, self.client.usernames2uuids, ['u1', 'u2'])
        with patch(
                '%s.SynnefoAstakosClient.__init__' % astakos_pkg,
                return_value=None) as sac:
            with patch(
                    '%s.SynnefoAstakosClient.get_endpoints' % astakos_pkg,
                    return_value=example) as get_endpoints:
                r = self.client.usernames2uuids(['u1', 'u2'])
                self.assert_dicts_are_equal(
                    r, {'username42': 42, 'username43': 43})
                self.assertEqual(sac.mock_calls[-1], call(
                    self.token, self.url, logger=getLogger('astakosclient')))
                self.assertEqual(get_endpoints.mock_calls[-1], call())
                self.assertEqual(get_uuids.mock_calls[-1], call(['u1', 'u2']))


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