testit-python-commons 4.2.8__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. api_client_syncstorage/__init__.py +27 -0
  2. api_client_syncstorage/api/__init__.py +3 -0
  3. api_client_syncstorage/api/completion_api.py +302 -0
  4. api_client_syncstorage/api/health_api.py +158 -0
  5. api_client_syncstorage/api/system_api.py +158 -0
  6. api_client_syncstorage/api/test_results_api.py +182 -0
  7. api_client_syncstorage/api/workers_api.py +308 -0
  8. api_client_syncstorage/api_client.py +898 -0
  9. api_client_syncstorage/apis/__init__.py +21 -0
  10. api_client_syncstorage/configuration.py +450 -0
  11. api_client_syncstorage/exceptions.py +158 -0
  12. api_client_syncstorage/model/__init__.py +5 -0
  13. api_client_syncstorage/model/completion_response.py +267 -0
  14. api_client_syncstorage/model/health_status_response.py +267 -0
  15. api_client_syncstorage/model/register_request.py +275 -0
  16. api_client_syncstorage/model/register_response.py +279 -0
  17. api_client_syncstorage/model/set_worker_status_request.py +271 -0
  18. api_client_syncstorage/model/set_worker_status_response.py +267 -0
  19. api_client_syncstorage/model/shutdown_response.py +267 -0
  20. api_client_syncstorage/model/test_result_cut_api_model.py +279 -0
  21. api_client_syncstorage/model/test_result_save_response.py +267 -0
  22. api_client_syncstorage/model_utils.py +2058 -0
  23. api_client_syncstorage/models/__init__.py +20 -0
  24. api_client_syncstorage/rest.py +356 -0
  25. testit.py +69 -0
  26. testit_python_commons/__init__.py +0 -0
  27. testit_python_commons/app_properties.py +257 -0
  28. testit_python_commons/client/__init__.py +9 -0
  29. testit_python_commons/client/api_client.py +560 -0
  30. testit_python_commons/client/client_configuration.py +74 -0
  31. testit_python_commons/client/converter.py +618 -0
  32. testit_python_commons/client/helpers/__init__.py +0 -0
  33. testit_python_commons/client/helpers/bulk_autotest_helper.py +246 -0
  34. testit_python_commons/client/helpers/threads_manager.py +86 -0
  35. testit_python_commons/client/models/__init__.py +8 -0
  36. testit_python_commons/client/models/threads_for_create_and_result.py +35 -0
  37. testit_python_commons/client/models/threads_for_update_and_result.py +45 -0
  38. testit_python_commons/configurations/__init__.py +0 -0
  39. testit_python_commons/configurations/properties_names.py +51 -0
  40. testit_python_commons/decorators.py +221 -0
  41. testit_python_commons/dynamic_methods.py +237 -0
  42. testit_python_commons/models/__init__.py +5 -0
  43. testit_python_commons/models/adapter_mode.py +4 -0
  44. testit_python_commons/models/fixture.py +24 -0
  45. testit_python_commons/models/link.py +53 -0
  46. testit_python_commons/models/link_type.py +10 -0
  47. testit_python_commons/models/outcome_type.py +5 -0
  48. testit_python_commons/models/status_type.py +6 -0
  49. testit_python_commons/models/step_result.py +90 -0
  50. testit_python_commons/models/test_result.py +297 -0
  51. testit_python_commons/models/test_result_with_all_fixture_step_results_model.py +28 -0
  52. testit_python_commons/services/__init__.py +41 -0
  53. testit_python_commons/services/adapter_manager.py +318 -0
  54. testit_python_commons/services/adapter_manager_configuration.py +42 -0
  55. testit_python_commons/services/fixture_manager.py +60 -0
  56. testit_python_commons/services/fixture_storage.py +40 -0
  57. testit_python_commons/services/logger.py +32 -0
  58. testit_python_commons/services/plugin_manager.py +101 -0
  59. testit_python_commons/services/retry.py +92 -0
  60. testit_python_commons/services/step_manager.py +36 -0
  61. testit_python_commons/services/step_result_storage.py +26 -0
  62. testit_python_commons/services/sync_storage/__init__.py +9 -0
  63. testit_python_commons/services/sync_storage/sync_storage_runner.py +589 -0
  64. testit_python_commons/services/utils.py +132 -0
  65. testit_python_commons/step.py +101 -0
  66. testit_python_commons/utils/__init__.py +3 -0
  67. testit_python_commons/utils/html_escape_utils.py +219 -0
  68. testit_python_commons-4.2.8.dist-info/METADATA +52 -0
  69. testit_python_commons-4.2.8.dist-info/RECORD +71 -0
  70. testit_python_commons-4.2.8.dist-info/WHEEL +5 -0
  71. testit_python_commons-4.2.8.dist-info/top_level.txt +3 -0
@@ -0,0 +1,898 @@
1
+ """
2
+ Sync Storage Service API
3
+
4
+ This is a sync storage service for coordinating test workers. # noqa: E501
5
+
6
+ The version of the OpenAPI document: 1.0
7
+ Generated by: https://openapi-generator.tech
8
+ """
9
+
10
+
11
+ import json
12
+ import atexit
13
+ import mimetypes
14
+ from multiprocessing.pool import ThreadPool
15
+ import io
16
+ import os
17
+ import re
18
+ import typing
19
+ from urllib.parse import quote
20
+ from urllib3.fields import RequestField
21
+
22
+
23
+ from api_client_syncstorage import rest
24
+ from api_client_syncstorage.configuration import Configuration
25
+ from api_client_syncstorage.exceptions import ApiTypeError, ApiValueError, ApiException
26
+ from api_client_syncstorage.model_utils import (
27
+ ModelNormal,
28
+ ModelSimple,
29
+ ModelComposed,
30
+ check_allowed_values,
31
+ check_validations,
32
+ date,
33
+ datetime,
34
+ deserialize_file,
35
+ file_type,
36
+ model_to_dict,
37
+ none_type,
38
+ validate_and_convert_types
39
+ )
40
+
41
+
42
+ class ApiClient(object):
43
+ """Generic API client for OpenAPI client library builds.
44
+
45
+ OpenAPI generic API client. This client handles the client-
46
+ server communication, and is invariant across implementations. Specifics of
47
+ the methods and models for each application are generated from the OpenAPI
48
+ templates.
49
+
50
+ NOTE: This class is auto generated by OpenAPI Generator.
51
+ Ref: https://openapi-generator.tech
52
+ Do not edit the class manually.
53
+
54
+ :param configuration: .Configuration object for this client
55
+ :param header_name: a header to pass when making calls to the API.
56
+ :param header_value: a header value to pass when making calls to
57
+ the API.
58
+ :param cookie: a cookie to include in the header when making calls
59
+ to the API
60
+ :param pool_threads: The number of threads to use for async requests
61
+ to the API. More threads means more concurrent API requests.
62
+ """
63
+
64
+ _pool = None
65
+
66
+ def __init__(self, configuration=None, header_name=None, header_value=None,
67
+ cookie=None, pool_threads=1):
68
+ if configuration is None:
69
+ configuration = Configuration.get_default_copy()
70
+ self.configuration = configuration
71
+ self.pool_threads = pool_threads
72
+
73
+ self.rest_client = rest.RESTClientObject(configuration)
74
+ self.default_headers = {}
75
+ if header_name is not None:
76
+ self.default_headers[header_name] = header_value
77
+ self.cookie = cookie
78
+ # Set default User-Agent.
79
+ self.user_agent = 'OpenAPI-Generator/1.0.0/python'
80
+
81
+ def __enter__(self):
82
+ return self
83
+
84
+ def __exit__(self, exc_type, exc_value, traceback):
85
+ self.close()
86
+
87
+ def close(self):
88
+ if self._pool:
89
+ self._pool.close()
90
+ self._pool.join()
91
+ self._pool = None
92
+ if hasattr(atexit, 'unregister'):
93
+ atexit.unregister(self.close)
94
+
95
+ @property
96
+ def pool(self):
97
+ """Create thread pool on first request
98
+ avoids instantiating unused threadpool for blocking clients.
99
+ """
100
+ if self._pool is None:
101
+ atexit.register(self.close)
102
+ self._pool = ThreadPool(self.pool_threads)
103
+ return self._pool
104
+
105
+ @property
106
+ def user_agent(self):
107
+ """User agent for this API client"""
108
+ return self.default_headers['User-Agent']
109
+
110
+ @user_agent.setter
111
+ def user_agent(self, value):
112
+ self.default_headers['User-Agent'] = value
113
+
114
+ def set_default_header(self, header_name, header_value):
115
+ self.default_headers[header_name] = header_value
116
+
117
+ def __call_api(
118
+ self,
119
+ resource_path: str,
120
+ method: str,
121
+ path_params: typing.Optional[typing.Dict[str, typing.Any]] = None,
122
+ query_params: typing.Optional[typing.List[typing.Tuple[str, typing.Any]]] = None,
123
+ header_params: typing.Optional[typing.Dict[str, typing.Any]] = None,
124
+ body: typing.Optional[typing.Any] = None,
125
+ post_params: typing.Optional[typing.List[typing.Tuple[str, typing.Any]]] = None,
126
+ files: typing.Optional[typing.Dict[str, typing.List[io.IOBase]]] = None,
127
+ response_type: typing.Optional[typing.Tuple[typing.Any]] = None,
128
+ auth_settings: typing.Optional[typing.List[str]] = None,
129
+ _return_http_data_only: typing.Optional[bool] = None,
130
+ collection_formats: typing.Optional[typing.Dict[str, str]] = None,
131
+ _preload_content: bool = True,
132
+ _request_timeout: typing.Optional[typing.Union[int, float, typing.Tuple]] = None,
133
+ _host: typing.Optional[str] = None,
134
+ _check_type: typing.Optional[bool] = None,
135
+ _content_type: typing.Optional[str] = None,
136
+ _request_auths: typing.Optional[typing.List[typing.Dict[str, typing.Any]]] = None
137
+ ):
138
+
139
+ config = self.configuration
140
+
141
+ # header parameters
142
+ header_params = header_params or {}
143
+ header_params.update(self.default_headers)
144
+ if self.cookie:
145
+ header_params['Cookie'] = self.cookie
146
+ if header_params:
147
+ header_params = self.sanitize_for_serialization(header_params)
148
+ header_params = dict(self.parameters_to_tuples(header_params,
149
+ collection_formats))
150
+
151
+ # path parameters
152
+ if path_params:
153
+ path_params = self.sanitize_for_serialization(path_params)
154
+ path_params = self.parameters_to_tuples(path_params,
155
+ collection_formats)
156
+ for k, v in path_params:
157
+ # specified safe chars, encode everything
158
+ resource_path = resource_path.replace(
159
+ '{%s}' % k,
160
+ quote(str(v), safe=config.safe_chars_for_path_param)
161
+ )
162
+
163
+ # query parameters
164
+ if query_params:
165
+ query_params = self.sanitize_for_serialization(query_params)
166
+ query_params = self.parameters_to_tuples(query_params,
167
+ collection_formats)
168
+
169
+ # post parameters
170
+ if post_params or files:
171
+ post_params = post_params if post_params else []
172
+ post_params = self.sanitize_for_serialization(post_params)
173
+ post_params = self.parameters_to_tuples(post_params,
174
+ collection_formats)
175
+ post_params.extend(self.files_parameters(files))
176
+ if header_params['Content-Type'].startswith("multipart"):
177
+ post_params = self.parameters_to_multipart(post_params,
178
+ (dict))
179
+
180
+ # body
181
+ if body:
182
+ body = self.sanitize_for_serialization(body)
183
+
184
+ # auth setting
185
+ self.update_params_for_auth(header_params, query_params,
186
+ auth_settings, resource_path, method, body,
187
+ request_auths=_request_auths)
188
+
189
+ # request url
190
+ if _host is None:
191
+ url = self.configuration.host + resource_path
192
+ else:
193
+ # use server/host defined in path or operation instead
194
+ url = _host + resource_path
195
+
196
+ try:
197
+ # perform request and return response
198
+ response_data = self.request(
199
+ method, url, query_params=query_params, headers=header_params,
200
+ post_params=post_params, body=body,
201
+ _preload_content=_preload_content,
202
+ _request_timeout=_request_timeout)
203
+ except ApiException as e:
204
+ e.body = e.body.decode('utf-8')
205
+ raise e
206
+
207
+ self.last_response = response_data
208
+
209
+ return_data = response_data
210
+
211
+ if not _preload_content:
212
+ return (return_data)
213
+ return return_data
214
+
215
+ # deserialize response data
216
+ if response_type:
217
+ if response_type != (file_type,):
218
+ encoding = "utf-8"
219
+ content_type = response_data.getheader('content-type')
220
+ if content_type is not None:
221
+ match = re.search(r"charset=([a-zA-Z\-\d]+)[\s\;]?", content_type)
222
+ if match:
223
+ encoding = match.group(1)
224
+ response_data.data = response_data.data.decode(encoding)
225
+
226
+ return_data = self.deserialize(
227
+ response_data,
228
+ response_type,
229
+ _check_type
230
+ )
231
+ else:
232
+ return_data = None
233
+
234
+ if _return_http_data_only:
235
+ return (return_data)
236
+ else:
237
+ return (return_data, response_data.status,
238
+ response_data.getheaders())
239
+
240
+ def parameters_to_multipart(self, params, collection_types):
241
+ """Get parameters as list of tuples, formatting as json if value is collection_types
242
+
243
+ :param params: Parameters as list of two-tuples
244
+ :param dict collection_types: Parameter collection types
245
+ :return: Parameters as list of tuple or urllib3.fields.RequestField
246
+ """
247
+ new_params = []
248
+ if collection_types is None:
249
+ collection_types = (dict)
250
+ for k, v in params.items() if isinstance(params, dict) else params: # noqa: E501
251
+ if isinstance(
252
+ v, collection_types): # v is instance of collection_type, formatting as application/json
253
+ v = json.dumps(v, ensure_ascii=False).encode("utf-8")
254
+ field = RequestField(k, v)
255
+ field.make_multipart(content_type="application/json; charset=utf-8")
256
+ new_params.append(field)
257
+ else:
258
+ new_params.append((k, v))
259
+ return new_params
260
+
261
+ @classmethod
262
+ def sanitize_for_serialization(cls, obj):
263
+ """Prepares data for transmission before it is sent with the rest client
264
+ If obj is None, return None.
265
+ If obj is str, int, long, float, bool, return directly.
266
+ If obj is datetime.datetime, datetime.date
267
+ convert to string in iso8601 format.
268
+ If obj is list, sanitize each element in the list.
269
+ If obj is dict, return the dict.
270
+ If obj is OpenAPI model, return the properties dict.
271
+ If obj is io.IOBase, return the bytes
272
+ :param obj: The data to serialize.
273
+ :return: The serialized form of data.
274
+ """
275
+ if isinstance(obj, (ModelNormal, ModelComposed)):
276
+ return {
277
+ key: cls.sanitize_for_serialization(val) for key,
278
+ val in model_to_dict(
279
+ obj,
280
+ serialize=True).items()}
281
+ elif isinstance(obj, io.IOBase):
282
+ return cls.get_file_data_and_close_file(obj)
283
+ elif isinstance(obj, (str, int, float, none_type, bool)):
284
+ return obj
285
+ elif isinstance(obj, (datetime, date)):
286
+ return obj.isoformat()
287
+ elif isinstance(obj, ModelSimple):
288
+ return cls.sanitize_for_serialization(obj.value)
289
+ elif isinstance(obj, list):
290
+ return [cls.sanitize_for_serialization(item) for item in obj]
291
+ elif isinstance(obj, tuple):
292
+ return tuple(cls.sanitize_for_serialization(item) for item in obj)
293
+ if isinstance(obj, dict):
294
+ return {key: cls.sanitize_for_serialization(val) for key, val in obj.items()}
295
+ raise ApiValueError(
296
+ 'Unable to prepare type {} for serialization'.format(
297
+ obj.__class__.__name__))
298
+
299
+ def deserialize(self, response, response_type, _check_type):
300
+ """Deserializes response into an object.
301
+
302
+ :param response: RESTResponse object to be deserialized.
303
+ :param response_type: For the response, a tuple containing:
304
+ valid classes
305
+ a list containing valid classes (for list schemas)
306
+ a dict containing a tuple of valid classes as the value
307
+ Example values:
308
+ (str,)
309
+ (Pet,)
310
+ (float, none_type)
311
+ ([int, none_type],)
312
+ ({str: (bool, str, int, float, date, datetime, str, none_type)},)
313
+ :param _check_type: boolean, whether to check the types of the data
314
+ received from the server
315
+ :type _check_type: bool
316
+
317
+ :return: deserialized object.
318
+ """
319
+ # handle file downloading
320
+ # save response body into a tmp file and return the instance
321
+ if response_type == (file_type,):
322
+ content_disposition = response.getheader("Content-Disposition")
323
+ return deserialize_file(response.data, self.configuration,
324
+ content_disposition=content_disposition)
325
+
326
+ # fetch data from response object
327
+ try:
328
+ received_data = json.loads(response.data)
329
+ except ValueError:
330
+ received_data = response.data
331
+
332
+ # store our data under the key of 'received_data' so users have some
333
+ # context if they are deserializing a string and the data type is wrong
334
+ deserialized_data = validate_and_convert_types(
335
+ received_data,
336
+ response_type,
337
+ ['received_data'],
338
+ True,
339
+ _check_type,
340
+ configuration=self.configuration
341
+ )
342
+ return deserialized_data
343
+
344
+ def call_api(
345
+ self,
346
+ resource_path: str,
347
+ method: str,
348
+ path_params: typing.Optional[typing.Dict[str, typing.Any]] = None,
349
+ query_params: typing.Optional[typing.List[typing.Tuple[str, typing.Any]]] = None,
350
+ header_params: typing.Optional[typing.Dict[str, typing.Any]] = None,
351
+ body: typing.Optional[typing.Any] = None,
352
+ post_params: typing.Optional[typing.List[typing.Tuple[str, typing.Any]]] = None,
353
+ files: typing.Optional[typing.Dict[str, typing.List[io.IOBase]]] = None,
354
+ response_type: typing.Optional[typing.Tuple[typing.Any]] = None,
355
+ auth_settings: typing.Optional[typing.List[str]] = None,
356
+ async_req: typing.Optional[bool] = None,
357
+ _return_http_data_only: typing.Optional[bool] = None,
358
+ collection_formats: typing.Optional[typing.Dict[str, str]] = None,
359
+ _preload_content: bool = True,
360
+ _request_timeout: typing.Optional[typing.Union[int, float, typing.Tuple]] = None,
361
+ _host: typing.Optional[str] = None,
362
+ _check_type: typing.Optional[bool] = None,
363
+ _request_auths: typing.Optional[typing.List[typing.Dict[str, typing.Any]]] = None
364
+ ):
365
+ """Makes the HTTP request (synchronous) and returns deserialized data.
366
+
367
+ To make an async_req request, set the async_req parameter.
368
+
369
+ :param resource_path: Path to method endpoint.
370
+ :param method: Method to call.
371
+ :param path_params: Path parameters in the url.
372
+ :param query_params: Query parameters in the url.
373
+ :param header_params: Header parameters to be
374
+ placed in the request header.
375
+ :param body: Request body.
376
+ :param post_params dict: Request post form parameters,
377
+ for `application/x-www-form-urlencoded`, `multipart/form-data`.
378
+ :param auth_settings list: Auth Settings names for the request.
379
+ :param response_type: For the response, a tuple containing:
380
+ valid classes
381
+ a list containing valid classes (for list schemas)
382
+ a dict containing a tuple of valid classes as the value
383
+ Example values:
384
+ (str,)
385
+ (Pet,)
386
+ (float, none_type)
387
+ ([int, none_type],)
388
+ ({str: (bool, str, int, float, date, datetime, str, none_type)},)
389
+ :param files: key -> field name, value -> a list of open file
390
+ objects for `multipart/form-data`.
391
+ :type files: dict
392
+ :param async_req bool: execute request asynchronously
393
+ :type async_req: bool, optional
394
+ :param _return_http_data_only: response data without head status code
395
+ and headers
396
+ :type _return_http_data_only: bool, optional
397
+ :param collection_formats: dict of collection formats for path, query,
398
+ header, and post parameters.
399
+ :type collection_formats: dict, optional
400
+ :param _preload_content: if False, the urllib3.HTTPResponse object will
401
+ be returned without reading/decoding response
402
+ data. Default is True.
403
+ :type _preload_content: bool, optional
404
+ :param _request_timeout: timeout setting for this request. If one
405
+ number provided, it will be total request
406
+ timeout. It can also be a pair (tuple) of
407
+ (connection, read) timeouts.
408
+ :param _check_type: boolean describing if the data back from the server
409
+ should have its type checked.
410
+ :type _check_type: bool, optional
411
+ :param _request_auths: set to override the auth_settings for an a single
412
+ request; this effectively ignores the authentication
413
+ in the spec for a single request.
414
+ :type _request_auths: list, optional
415
+ :return:
416
+ If async_req parameter is True,
417
+ the request will be called asynchronously.
418
+ The method will return the request thread.
419
+ If parameter async_req is False or missing,
420
+ then the method will return the response directly.
421
+ """
422
+ if not async_req:
423
+ return self.__call_api(resource_path, method,
424
+ path_params, query_params, header_params,
425
+ body, post_params, files,
426
+ response_type, auth_settings,
427
+ _return_http_data_only, collection_formats,
428
+ _preload_content, _request_timeout, _host,
429
+ _check_type, _request_auths=_request_auths)
430
+
431
+ return self.pool.apply_async(self.__call_api, (resource_path,
432
+ method, path_params,
433
+ query_params,
434
+ header_params, body,
435
+ post_params, files,
436
+ response_type,
437
+ auth_settings,
438
+ _return_http_data_only,
439
+ collection_formats,
440
+ _preload_content,
441
+ _request_timeout,
442
+ _host, _check_type, None, _request_auths))
443
+
444
+ def request(self, method, url, query_params=None, headers=None,
445
+ post_params=None, body=None, _preload_content=True,
446
+ _request_timeout=None):
447
+ """Makes the HTTP request using RESTClient."""
448
+ if method == "GET":
449
+ return self.rest_client.GET(url,
450
+ query_params=query_params,
451
+ _preload_content=_preload_content,
452
+ _request_timeout=_request_timeout,
453
+ headers=headers)
454
+ elif method == "HEAD":
455
+ return self.rest_client.HEAD(url,
456
+ query_params=query_params,
457
+ _preload_content=_preload_content,
458
+ _request_timeout=_request_timeout,
459
+ headers=headers)
460
+ elif method == "OPTIONS":
461
+ return self.rest_client.OPTIONS(url,
462
+ query_params=query_params,
463
+ headers=headers,
464
+ post_params=post_params,
465
+ _preload_content=_preload_content,
466
+ _request_timeout=_request_timeout,
467
+ body=body)
468
+ elif method == "POST":
469
+ return self.rest_client.POST(url,
470
+ query_params=query_params,
471
+ headers=headers,
472
+ post_params=post_params,
473
+ _preload_content=_preload_content,
474
+ _request_timeout=_request_timeout,
475
+ body=body)
476
+ elif method == "PUT":
477
+ return self.rest_client.PUT(url,
478
+ query_params=query_params,
479
+ headers=headers,
480
+ post_params=post_params,
481
+ _preload_content=_preload_content,
482
+ _request_timeout=_request_timeout,
483
+ body=body)
484
+ elif method == "PATCH":
485
+ return self.rest_client.PATCH(url,
486
+ query_params=query_params,
487
+ headers=headers,
488
+ post_params=post_params,
489
+ _preload_content=_preload_content,
490
+ _request_timeout=_request_timeout,
491
+ body=body)
492
+ elif method == "DELETE":
493
+ return self.rest_client.DELETE(url,
494
+ query_params=query_params,
495
+ headers=headers,
496
+ _preload_content=_preload_content,
497
+ _request_timeout=_request_timeout,
498
+ body=body)
499
+ else:
500
+ raise ApiValueError(
501
+ "http method must be `GET`, `HEAD`, `OPTIONS`,"
502
+ " `POST`, `PATCH`, `PUT` or `DELETE`."
503
+ )
504
+
505
+ def parameters_to_tuples(self, params, collection_formats):
506
+ """Get parameters as list of tuples, formatting collections.
507
+
508
+ :param params: Parameters as dict or list of two-tuples
509
+ :param dict collection_formats: Parameter collection formats
510
+ :return: Parameters as list of tuples, collections formatted
511
+ """
512
+ new_params = []
513
+ if collection_formats is None:
514
+ collection_formats = {}
515
+ for k, v in params.items() if isinstance(params, dict) else params: # noqa: E501
516
+ if k in collection_formats:
517
+ collection_format = collection_formats[k]
518
+ if collection_format == 'multi':
519
+ new_params.extend((k, value) for value in v)
520
+ else:
521
+ if collection_format == 'ssv':
522
+ delimiter = ' '
523
+ elif collection_format == 'tsv':
524
+ delimiter = '\t'
525
+ elif collection_format == 'pipes':
526
+ delimiter = '|'
527
+ else: # csv is the default
528
+ delimiter = ','
529
+ new_params.append(
530
+ (k, delimiter.join(str(value) for value in v)))
531
+ else:
532
+ new_params.append((k, v))
533
+ return new_params
534
+
535
+ @staticmethod
536
+ def get_file_data_and_close_file(file_instance: io.IOBase) -> bytes:
537
+ file_data = file_instance.read()
538
+ file_instance.close()
539
+ return file_data
540
+
541
+ def files_parameters(self,
542
+ files: typing.Optional[typing.Dict[str,
543
+ typing.List[io.IOBase]]] = None):
544
+ """Builds form parameters.
545
+
546
+ :param files: None or a dict with key=param_name and
547
+ value is a list of open file objects
548
+ :return: List of tuples of form parameters with file data
549
+ """
550
+ if files is None:
551
+ return []
552
+
553
+ params = []
554
+ for param_name, file_instances in files.items():
555
+ if file_instances is None:
556
+ # if the file field is nullable, skip None values
557
+ continue
558
+ for file_instance in file_instances:
559
+ if file_instance is None:
560
+ # if the file field is nullable, skip None values
561
+ continue
562
+ if file_instance.closed is True:
563
+ raise ApiValueError(
564
+ "Cannot read a closed file. The passed in file_type "
565
+ "for %s must be open." % param_name
566
+ )
567
+ filename = os.path.basename(file_instance.name)
568
+ filedata = self.get_file_data_and_close_file(file_instance)
569
+ mimetype = (mimetypes.guess_type(filename)[0] or
570
+ 'application/octet-stream')
571
+ params.append(
572
+ tuple([param_name, tuple([filename, filedata, mimetype])]))
573
+
574
+ return params
575
+
576
+ def select_header_accept(self, accepts):
577
+ """Returns `Accept` based on an array of accepts provided.
578
+
579
+ :param accepts: List of headers.
580
+ :return: Accept (e.g. application/json).
581
+ """
582
+ if not accepts:
583
+ return
584
+
585
+ accepts = [x.lower() for x in accepts]
586
+
587
+ if 'application/json' in accepts:
588
+ return 'application/json'
589
+ else:
590
+ return ', '.join(accepts)
591
+
592
+ def select_header_content_type(self, content_types, method=None, body=None):
593
+ """Returns `Content-Type` based on an array of content_types provided.
594
+
595
+ :param content_types: List of content-types.
596
+ :param method: http method (e.g. POST, PATCH).
597
+ :param body: http body to send.
598
+ :return: Content-Type (e.g. application/json).
599
+ """
600
+ if not content_types:
601
+ return None
602
+
603
+ content_types = [x.lower() for x in content_types]
604
+
605
+ if (method == 'PATCH' and
606
+ 'application/json-patch+json' in content_types and
607
+ isinstance(body, list)):
608
+ return 'application/json-patch+json'
609
+
610
+ if 'application/json' in content_types or '*/*' in content_types:
611
+ return 'application/json'
612
+ else:
613
+ return content_types[0]
614
+
615
+ def update_params_for_auth(self, headers, queries, auth_settings,
616
+ resource_path, method, body, request_auths=None):
617
+ """Updates header and query params based on authentication setting.
618
+
619
+ :param headers: Header parameters dict to be updated.
620
+ :param queries: Query parameters tuple list to be updated.
621
+ :param auth_settings: Authentication setting identifiers list.
622
+ :param resource_path: A string representation of the HTTP request resource path.
623
+ :param method: A string representation of the HTTP request method.
624
+ :param body: A object representing the body of the HTTP request.
625
+ The object type is the return value of _encoder.default().
626
+ :param request_auths: if set, the provided settings will
627
+ override the token in the configuration.
628
+ """
629
+ if not auth_settings:
630
+ return
631
+
632
+ if request_auths:
633
+ for auth_setting in request_auths:
634
+ self._apply_auth_params(
635
+ headers, queries, resource_path, method, body, auth_setting)
636
+ return
637
+
638
+ for auth in auth_settings:
639
+ auth_setting = self.configuration.auth_settings().get(auth)
640
+ if auth_setting:
641
+ self._apply_auth_params(
642
+ headers, queries, resource_path, method, body, auth_setting)
643
+
644
+ def _apply_auth_params(self, headers, queries, resource_path, method, body, auth_setting):
645
+ if auth_setting['in'] == 'cookie':
646
+ headers['Cookie'] = auth_setting['key'] + "=" + auth_setting['value']
647
+ elif auth_setting['in'] == 'header':
648
+ if auth_setting['type'] != 'http-signature':
649
+ headers[auth_setting['key']] = auth_setting['value']
650
+ elif auth_setting['in'] == 'query':
651
+ queries.append((auth_setting['key'], auth_setting['value']))
652
+ else:
653
+ raise ApiValueError(
654
+ 'Authentication token must be in `query` or `header`'
655
+ )
656
+
657
+
658
+ class Endpoint(object):
659
+ def __init__(self, settings=None, params_map=None, root_map=None,
660
+ headers_map=None, api_client=None, callable=None):
661
+ """Creates an endpoint
662
+
663
+ Args:
664
+ settings (dict): see below key value pairs
665
+ 'response_type' (tuple/None): response type
666
+ 'auth' (list): a list of auth type keys
667
+ 'endpoint_path' (str): the endpoint path
668
+ 'operation_id' (str): endpoint string identifier
669
+ 'http_method' (str): POST/PUT/PATCH/GET etc
670
+ 'servers' (list): list of str servers that this endpoint is at
671
+ params_map (dict): see below key value pairs
672
+ 'all' (list): list of str endpoint parameter names
673
+ 'required' (list): list of required parameter names
674
+ 'nullable' (list): list of nullable parameter names
675
+ 'enum' (list): list of parameters with enum values
676
+ 'validation' (list): list of parameters with validations
677
+ root_map
678
+ 'validations' (dict): the dict mapping endpoint parameter tuple
679
+ paths to their validation dictionaries
680
+ 'allowed_values' (dict): the dict mapping endpoint parameter
681
+ tuple paths to their allowed_values (enum) dictionaries
682
+ 'openapi_types' (dict): param_name to openapi type
683
+ 'attribute_map' (dict): param_name to camelCase name
684
+ 'location_map' (dict): param_name to 'body', 'file', 'form',
685
+ 'header', 'path', 'query'
686
+ collection_format_map (dict): param_name to `csv` etc.
687
+ headers_map (dict): see below key value pairs
688
+ 'accept' (list): list of Accept header strings
689
+ 'content_type' (list): list of Content-Type header strings
690
+ api_client (ApiClient) api client instance
691
+ callable (function): the function which is invoked when the
692
+ Endpoint is called
693
+ """
694
+ self.settings = settings
695
+ self.params_map = params_map
696
+ self.params_map['all'].extend([
697
+ 'async_req',
698
+ '_host_index',
699
+ '_preload_content',
700
+ '_request_timeout',
701
+ '_return_http_data_only',
702
+ '_check_input_type',
703
+ '_check_return_type',
704
+ '_content_type',
705
+ '_spec_property_naming',
706
+ '_request_auths'
707
+ ])
708
+ self.params_map['nullable'].extend(['_request_timeout'])
709
+ self.validations = root_map['validations']
710
+ self.allowed_values = root_map['allowed_values']
711
+ self.openapi_types = root_map['openapi_types']
712
+ extra_types = {
713
+ 'async_req': (bool,),
714
+ '_host_index': (none_type, int),
715
+ '_preload_content': (bool,),
716
+ '_request_timeout': (none_type, float, (float,), [float], int, (int,), [int]),
717
+ '_return_http_data_only': (bool,),
718
+ '_check_input_type': (bool,),
719
+ '_check_return_type': (bool,),
720
+ '_spec_property_naming': (bool,),
721
+ '_content_type': (none_type, str),
722
+ '_request_auths': (none_type, list)
723
+ }
724
+ self.openapi_types.update(extra_types)
725
+ self.attribute_map = root_map['attribute_map']
726
+ self.location_map = root_map['location_map']
727
+ self.collection_format_map = root_map['collection_format_map']
728
+ self.headers_map = headers_map
729
+ self.api_client = api_client
730
+ self.callable = callable
731
+
732
+ def __validate_inputs(self, kwargs):
733
+ for param in self.params_map['enum']:
734
+ if param in kwargs:
735
+ check_allowed_values(
736
+ self.allowed_values,
737
+ (param,),
738
+ kwargs[param]
739
+ )
740
+
741
+ for param in self.params_map['validation']:
742
+ if param in kwargs:
743
+ check_validations(
744
+ self.validations,
745
+ (param,),
746
+ kwargs[param],
747
+ configuration=self.api_client.configuration
748
+ )
749
+
750
+ if kwargs['_check_input_type'] is False:
751
+ return
752
+
753
+ for key, value in kwargs.items():
754
+ fixed_val = validate_and_convert_types(
755
+ value,
756
+ self.openapi_types[key],
757
+ [key],
758
+ kwargs['_spec_property_naming'],
759
+ kwargs['_check_input_type'],
760
+ configuration=self.api_client.configuration
761
+ )
762
+ kwargs[key] = fixed_val
763
+
764
+ def __gather_params(self, kwargs):
765
+ params = {
766
+ 'body': None,
767
+ 'collection_format': {},
768
+ 'file': {},
769
+ 'form': [],
770
+ 'header': {},
771
+ 'path': {},
772
+ 'query': []
773
+ }
774
+
775
+ for param_name, param_value in kwargs.items():
776
+ param_location = self.location_map.get(param_name)
777
+ if param_location is None:
778
+ continue
779
+ if param_location:
780
+ if param_location == 'body':
781
+ params['body'] = param_value
782
+ continue
783
+ base_name = self.attribute_map[param_name]
784
+ if (param_location == 'form' and
785
+ self.openapi_types[param_name] == (file_type,)):
786
+ params['file'][base_name] = [param_value]
787
+ elif (param_location == 'form' and
788
+ self.openapi_types[param_name] == ([file_type],)):
789
+ # param_value is already a list
790
+ params['file'][base_name] = param_value
791
+ elif param_location in {'form', 'query'}:
792
+ param_value_full = (base_name, param_value)
793
+ params[param_location].append(param_value_full)
794
+ if param_location not in {'form', 'query'}:
795
+ params[param_location][base_name] = param_value
796
+ collection_format = self.collection_format_map.get(param_name)
797
+ if collection_format:
798
+ params['collection_format'][base_name] = collection_format
799
+
800
+ return params
801
+
802
+ def __call__(self, *args, **kwargs):
803
+ """ This method is invoked when endpoints are called
804
+ Example:
805
+
806
+ api_instance = CompletionApi()
807
+ api_instance.force_completion_get # this is an instance of the class Endpoint
808
+ api_instance.force_completion_get() # this invokes api_instance.force_completion_get.__call__()
809
+ which then invokes the callable functions stored in that endpoint at
810
+ api_instance.force_completion_get.callable or self.callable in this class
811
+
812
+ """
813
+ return self.callable(self, *args, **kwargs)
814
+
815
+ def call_with_http_info(self, **kwargs):
816
+
817
+ try:
818
+ index = self.api_client.configuration.server_operation_index.get(
819
+ self.settings['operation_id'], self.api_client.configuration.server_index
820
+ ) if kwargs['_host_index'] is None else kwargs['_host_index']
821
+ server_variables = self.api_client.configuration.server_operation_variables.get(
822
+ self.settings['operation_id'], self.api_client.configuration.server_variables
823
+ )
824
+ _host = self.api_client.configuration.get_host_from_settings(
825
+ index, variables=server_variables, servers=self.settings['servers']
826
+ )
827
+ except IndexError:
828
+ if self.settings['servers']:
829
+ raise ApiValueError(
830
+ "Invalid host index. Must be 0 <= index < %s" %
831
+ len(self.settings['servers'])
832
+ )
833
+ _host = None
834
+
835
+ for key, value in kwargs.items():
836
+ if key not in self.params_map['all']:
837
+ raise ApiTypeError(
838
+ "Got an unexpected parameter '%s'"
839
+ " to method `%s`" %
840
+ (key, self.settings['operation_id'])
841
+ )
842
+ # only throw this nullable ApiValueError if _check_input_type
843
+ # is False, if _check_input_type==True we catch this case
844
+ # in self.__validate_inputs
845
+ if (key not in self.params_map['nullable'] and value is None
846
+ and kwargs['_check_input_type'] is False):
847
+ raise ApiValueError(
848
+ "Value may not be None for non-nullable parameter `%s`"
849
+ " when calling `%s`" %
850
+ (key, self.settings['operation_id'])
851
+ )
852
+
853
+ for key in self.params_map['required']:
854
+ if key not in kwargs.keys():
855
+ raise ApiValueError(
856
+ "Missing the required parameter `%s` when calling "
857
+ "`%s`" % (key, self.settings['operation_id'])
858
+ )
859
+
860
+ self.__validate_inputs(kwargs)
861
+
862
+ params = self.__gather_params(kwargs)
863
+
864
+ accept_headers_list = self.headers_map['accept']
865
+ if accept_headers_list:
866
+ params['header']['Accept'] = self.api_client.select_header_accept(
867
+ accept_headers_list)
868
+
869
+ if kwargs.get('_content_type'):
870
+ params['header']['Content-Type'] = kwargs['_content_type']
871
+ else:
872
+ content_type_headers_list = self.headers_map['content_type']
873
+ if content_type_headers_list:
874
+ if params['body'] != "":
875
+ content_types_list = self.api_client.select_header_content_type(
876
+ content_type_headers_list, self.settings['http_method'],
877
+ params['body'])
878
+ if content_types_list:
879
+ params['header']['Content-Type'] = content_types_list
880
+
881
+ return self.api_client.call_api(
882
+ self.settings['endpoint_path'], self.settings['http_method'],
883
+ params['path'],
884
+ params['query'],
885
+ params['header'],
886
+ body=params['body'],
887
+ post_params=params['form'],
888
+ files=params['file'],
889
+ response_type=self.settings['response_type'],
890
+ auth_settings=self.settings['auth'],
891
+ async_req=kwargs['async_req'],
892
+ _check_type=kwargs['_check_return_type'],
893
+ _return_http_data_only=kwargs['_return_http_data_only'],
894
+ _preload_content=kwargs['_preload_content'],
895
+ _request_timeout=kwargs['_request_timeout'],
896
+ _host=_host,
897
+ _request_auths=kwargs['_request_auths'],
898
+ collection_formats=params['collection_format'])