File: call_api_tests.py

package info (click to toggle)
python-softlayer 6.2.5-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 7,508 kB
  • sloc: python: 57,195; makefile: 133; xml: 97; sh: 59
file content (324 lines) | stat: -rw-r--r-- 12,903 bytes parent folder | download
1
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
"""
    SoftLayer.tests.CLI.modules.call_api_tests
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    :license: MIT, see LICENSE for more details.
"""
import json

from SoftLayer.CLI import call_api
from SoftLayer.CLI import exceptions
from SoftLayer import SoftLayerAPIError
from SoftLayer import testing

import pytest


def test_filter_empty():
    assert call_api._build_filters([]) == {}


def test_filter_basic():
    result = call_api._build_filters(['property=value'])
    assert result == {'property': {'operation': '_= value'}}


def test_filter_nested():
    result = call_api._build_filters(['nested.property=value'])
    assert result == {'nested': {'property': {'operation': '_= value'}}}


def test_filter_multi():
    result = call_api._build_filters(['prop1=value1', 'prop2=prop2'])
    assert result == {
        'prop1': {'operation': '_= value1'},
        'prop2': {'operation': '_= prop2'},
    }


def test_filter_in():
    result = call_api._build_filters(['prop IN value1,value2'])
    assert result == {
        'prop': {
            'operation': 'in',
            'options': [{'name': 'data', 'value': ['value1', 'value2']}],
        }
    }


def test_filter_in_multi():
    result = call_api._build_filters([
        'prop_a IN a_val1,a_val2',
        'prop_b IN b_val1,b_val2',
    ])
    assert result == {
        'prop_a': {
            'operation': 'in',
            'options': [{'name': 'data', 'value': ['a_val1', 'a_val2']}],
        },
        'prop_b': {
            'operation': 'in',
            'options': [{'name': 'data', 'value': ['b_val1', 'b_val2']}],
        },
    }


def test_filter_in_with_whitespace():
    result = call_api._build_filters(['prop IN value1 ,  value2  '])
    assert result == {
        'prop': {
            'operation': 'in',
            'options': [{'name': 'data', 'value': ['value1', 'value2']}],
        }
    }


def test_filter_invalid_operation():
    with pytest.raises(exceptions.CLIAbort):
        call_api._build_filters(['prop N/A value1'])


def test_filter_only_whitespace():
    with pytest.raises(exceptions.CLIAbort):
        call_api._build_filters([' '])


class CallCliTests(testing.TestCase):

    def test_python_output(self):
        result = self.run_command(['call-api', 'Service', 'method',
                                   '--mask=some.mask',
                                   '--limit=20',
                                   '--offset=40',
                                   '--id=100',
                                   '-f nested.property=5432',
                                   '--output-python'])
        print(f"OUTPUT: \n{result.exception}")
        self.assert_no_fail(result)

        self.assertIsNotNone(result.output, """import SoftLayer

client = SoftLayer.create_client_from_env()
result = client.call(u'Service',
                     u'method',
                     filter={u'nested': {u'property': {'operation': 5432}}},
                     id=u'100',
                     limit=20,
                     mask=u'some.mask',
                     offset=40)
""")
        self.assertEqual(self.calls(), [], "no API calls were made")

    def test_options(self):
        mock = self.set_mock('SoftLayer_Service', 'method')
        mock.return_value = 'test'

        result = self.run_command(['call-api', 'Service', 'method',
                                   '--mask=some.mask',
                                   '--limit=20',
                                   '--offset=40',
                                   '--id=100',
                                   '-f property=1234',
                                   '-f nested.property=5432'])

        self.assert_no_fail(result)
        self.assertEqual(json.loads(result.output), 'test')
        self.assert_called_with('SoftLayer_Service', 'method',
                                mask='mask[some.mask]',
                                limit=20,
                                offset=40,
                                identifier='100',
                                filter={
                                    'property': {'operation': 1234},
                                    'nested': {'property': {'operation': 5432}}
                                })

    def test_object(self):
        mock = self.set_mock('SoftLayer_Service', 'method')
        mock.return_value = {'string': 'string',
                             'int': 10,
                             'float': 1.0,
                             'None': None,
                             'Bool': True}

        result = self.run_command(['call-api', 'Service', 'method'])

        self.assert_no_fail(result)
        self.assertEqual(json.loads(result.output),
                         {'string': 'string',
                          'int': 10,
                          'float': 1.0,
                          'None': None,
                          'Bool': True})

    def test_object_table(self):
        mock = self.set_mock('SoftLayer_Service', 'method')
        mock.return_value = {'string': 'string',
                             'int': 10,
                             'float': 1.0,
                             'None': None,
                             'Bool': True}

        result = self.run_command(['call-api', 'Service', 'method'], fmt='table')

        self.assert_no_fail(result)
        # NOTE(kmcdonald): Order is not guaranteed
        self.assertIn("│   name │ value  │", result.output)
        self.assertIn("│    int │ 10     │", result.output)
        self.assertIn("│   None │ None   │", result.output)
        self.assertIn("│  float │ 1.0    │", result.output)
        self.assertIn("│   Bool │ True   │", result.output)
        self.assertIn("│ string │ string │", result.output)

    def test_object_nested(self):
        mock = self.set_mock('SoftLayer_Service', 'method')
        mock.return_value = {'this': {'is': [{'pretty': 'nested'}]}}

        result = self.run_command(['call-api', 'Service', 'method'])

        self.assert_no_fail(result)
        self.assertEqual(json.loads(result.output),  {'this': {'is': [{'pretty': 'nested'}]}})

    def test_list(self):
        mock = self.set_mock('SoftLayer_Service', 'method')
        mock.return_value = [{'string': 'string',
                              'int': 10,
                              'float': 1.0,
                              'None': None,
                              'Bool': True}]

        result = self.run_command(['call-api', 'Service', 'method'])

        self.assert_no_fail(result)
        self.assertEqual(json.loads(result.output),
                         [{'string': 'string',
                           'int': 10,
                           'float': 1.0,
                           'None': None,
                           'Bool': True}])

    def test_list_table(self):
        mock = self.set_mock('SoftLayer_Service', 'method')
        mock.return_value = [{'string': 'string',
                              'int': 10,
                              'float': 1.0,
                              'None': None,
                              'Bool': True}]

        result = self.run_command(['call-api', 'Service', 'method'], fmt='table')

        self.assert_no_fail(result)
        self.assertEqual(result.output,
                         """┌──────┬──────┬───────┬─────┬────────┐
│ Bool │ None │ float │ int │ string │
├──────┼──────┼───────┼─────┼────────┤
│ True │ None │  1.0  │ 10  │ string │
└──────┴──────┴───────┴─────┴────────┘
""")

    def test_parameters(self):
        mock = self.set_mock('SoftLayer_Service', 'method')
        mock.return_value = {}

        result = self.run_command(['call-api', 'Service', 'method', 'arg1', '1234'])

        self.assert_no_fail(result)
        self.assert_called_with('SoftLayer_Service', 'method', args=('arg1', '1234'))

    def test_fixture_not_implemented(self):
        service = 'SoftLayer_Test'
        method = 'getTest'
        result = self.run_command(['call-api', service, method])
        self.assertEqual(result.exit_code, 1)
        self.assert_called_with(service, method)
        self.assertIsInstance(result.exception, SoftLayerAPIError)
        output = f'{service} fixture is not implemented'
        self.assertIn(output, result.exception.faultString)

    def test_fixture_not_implemented_method(self):
        call_service = 'SoftLayer_Account'
        call_method = 'getTest'
        result = self.run_command(['call-api', call_service, call_method])
        self.assertEqual(result.exit_code, 1)
        self.assert_called_with(call_service, call_method)
        self.assertIsInstance(result.exception, SoftLayerAPIError)
        output = '%s::%s fixture is not implemented' % (call_service, call_method)
        self.assertIn(output, result.exception.faultString)

    def test_fixture_exception(self):
        call_service = 'SoftLayer_Account'
        call_method = 'getTest'
        result = self.run_command(['call-api', call_service, call_method])
        try:
            self.assert_no_fail(result)
        except Exception as ex:
            print(ex)
        self.assertEqual(result.exit_code, 1)
        self.assert_called_with(call_service, call_method)
        self.assertIsInstance(result.exception, SoftLayerAPIError)
        output = '%s::%s fixture is not implemented' % (call_service, call_method)
        self.assertIn(output, result.exception.faultString)

    def test_json_filter_validation(self):
        json_filter = '{"test":"something"}'
        result = call_api._validate_filter(None, None, json_filter)
        self.assertEqual(result['test'], 'something')

        # Valid JSON, but we expect objects, not simple types
        with pytest.raises(exceptions.CLIAbort):
            call_api._validate_filter(None, None, '"test"')

        # Invalid JSON
        with pytest.raises(exceptions.CLIAbort):
            call_api._validate_filter(None, None, 'test')

        # Empty Request
        result = call_api._validate_filter(None, None, None)
        self.assertEqual(None, result)

    def test_json_parameters_validation(self):
        json_params = ('{"test":"something"}', 'String', 1234, '[{"a":"b"}]', '{funky non [ Json')
        result = call_api._validate_parameters(None, None, json_params)
        self.assertEqual(result[0], {"test": "something"})
        self.assertEqual(result[1], "String")
        self.assertEqual(result[2], 1234)
        self.assertEqual(result[3], [{"a": "b"}])
        self.assertEqual(result[4], "{funky non [ Json")

    def test_filter_with_filter(self):
        result = self.run_command(['call-api', 'Account', 'getObject', '--filter=nested.property=5432',
                                   '--json-filter={"test":"something"}'])
        self.assertEqual(2, result.exit_code)
        self.assertEqual(result.exception.message, "--filter and --json-filter cannot be used together.")
        self.assertIsInstance(result.exception, exceptions.CLIAbort)

    def test_json_filter(self):
        result = self.run_command(['call-api', 'Account', 'getObject', '--json-filter={"test":"something"}'])
        self.assert_no_fail(result)
        self.assert_called_with('SoftLayer_Account', 'getObject', filter={"test": "something"})

    def test_call_api_orderBy(self):
        result = self.run_command(['call-api', 'Account', 'getVirtualGuests',
                                   '--orderBy', 'virtualGuests.id=DESC',
                                   '--mask=virtualGuests.typeId,maxCpu',
                                   '-f', 'virtualGuests.typeId=1'])
        self.assert_no_fail(result)
        self.assert_called_with('SoftLayer_Account', 'getVirtualGuests',
                                filter={
                                    'virtualGuests':
                                        {'id':
                                            {
                                                'operation': 'orderBy',
                                                'options': [{
                                                    'name': 'sort',
                                                    'value': ['DESC']}]},
                                            'typeId': {'operation': 1}}
                                })

    def test_very_verbose(self):
        result = self.run_command(['-vvv', 'call-api', 'Account', 'getObject'])
        self.assert_no_fail(result)
        self.assert_called_with('SoftLayer_Account', 'getObject')
        self.assertIn("ORIGIN_PULL", result.output)
        self.assertIn("python_version", result.output)
        self.assertIn("offset", result.output)