15c1af8a51315559c79dcd18ea3e3ef35f074716
[releng.git] / utils / test / scripts / shared_utils.py
1 import json
2
3 import urllib3
4
5 http = urllib3.PoolManager()
6
7
8 def delete_request(url, creds, body=None):
9     headers = urllib3.make_headers(basic_auth=creds)
10     http.request('DELETE', url, headers=headers, body=body)
11
12
13 def publish_json(json_ojb, creds, output_destination):
14     json_dump = json.dumps(json_ojb)
15     if output_destination == 'stdout':
16         print json_dump
17         return 200, None
18     else:
19         headers = urllib3.make_headers(basic_auth=creds)
20         result = http.request('POST', output_destination, headers=headers, body=json_dump)
21         return result.status, result.data
22
23
24 def _get_nr_of_hits(elastic_json):
25     return elastic_json['hits']['total']
26
27
28 def get_elastic_data(elastic_url, creds, body, field='_source'):
29     # 1. get the number of results
30     headers = urllib3.make_headers(basic_auth=creds)
31     elastic_json = json.loads(http.request('GET', elastic_url + '/_search?size=0', headers=headers, body=body).data)
32     nr_of_hits = _get_nr_of_hits(elastic_json)
33
34     # 2. get all results
35     elastic_json = json.loads(http.request('GET', elastic_url + '/_search?size={}'.format(nr_of_hits), headers=headers, body=body).data)
36
37     elastic_data = []
38     for hit in elastic_json['hits']['hits']:
39         elastic_data.append(hit[field])
40     return elastic_data