Debian Codegraph @

ansible_collections/theforeman/foreman/tests/vcr_python_wrapper.py

raw symbols SCIP
1 #!/usr/bin/env python
2
3 import os
4 import re
5 import sys
6 import json
7 try:
8 from urlparse import urlparse, urlunparse
9 except ImportError:
10 from urllib.parse import urlparse, urlunparse
11
12 FILTER_REQUEST_HEADERS = ['Authorization', 'Cookie']
13 FILTER_RESPONSE_HEADERS = ['Apipie-Checksum', 'Date', 'ETag', 'Server', 'Set-Cookie', 'Via', 'X-Powered-By', 'X-Request-Id', 'X-Runtime']
14
15
16 def safe_method_matcher(r1, r2):
17 assert r1.method not in ['POST', 'PUT', 'PATCH', 'DELETE'], 'Method {0} not allowed in check_mode'.format(r1.method)
18 assert r1.method == r2.method
19
20
21 # We need our own json level2 matcher, because, python2 and python3 do not save
22 # dictionaries in the same order
23 def body_json_l2_matcher(r1, r2):
24 if r1.headers.get('content-type') == r2.headers.get('content-type') == 'application/json':
25 if r1.body is None or r2.body is None:
26 assert r1.body == r2.body, "{} != {}".format(r1.body, r2.body)
27 body1 = json.loads(r1.body.decode('utf8'))
28 body2 = json.loads(r2.body.decode('utf8'))
29 if 'common_parameter' in body1 and 'common_parameter' in body2:
30 if (body1['common_parameter'].get('parameter_type') == body2['common_parameter'].get('parameter_type')
31 and body1['common_parameter'].get('parameter_type') in ['hash', 'json', 'yaml']):
32 body1['common_parameter']['value'] = json.loads(body1['common_parameter'].get('value'))
33 body2['common_parameter']['value'] = json.loads(body2['common_parameter'].get('value'))
34 assert body1 == body2, "{} != {}".format(body1, body2)
35 elif (r1.headers.get('content-type') == r2.headers.get('content-type')
36 and r1.headers.get('content-type') in ['multipart/form-data', 'application/x-www-form-urlencoded']):
37 if r1.body is None or r2.body is None:
38 assert r1.body == r2.body, "{} != {}".format(r1.body, r2.body)
39 body1 = sorted(r1.body.replace(b'~', b'%7E').split(b'&'))
40 body2 = sorted(r2.body.replace(b'~', b'%7E').split(b'&'))
41 assert len(body1) == len(body2), "the body lengths don't match"
42 for i, v in enumerate(body1):
43 assert body1[i] == body2[i], "body contents at position {} dont't match: '{}' vs '{}'".format(i, body1[i], body2[i]) # pylint:disable=all
44 else:
45 assert r1.body == r2.body, "{} != {}".format(r1.body, r2.body)
46
47
48 def _query_without_search_matcher(r1, r2, path):
49 if r1.path == r2.path == path:
50 query1 = [q for q in r1.query if q[0] != 'search']
51 query2 = [q for q in r2.query if q[0] != 'search']
52 assert query1 == query2, "{} != {}".format(query1, query2)
53 else:
54 vcr.matchers.query(r1, r2)
55
56
57 def snapshot_query_matcher(r1, r2):
58 _query_without_search_matcher(r1, r2, '/api/hosts')
59
60
61 def query_matcher_ignore_proxy(r1, r2):
62 _query_without_search_matcher(r1, r2, '/api/smart_proxies')
63
64
65 def subscription_manifest_body_matcher(r1, r2):
66 if r1.path.endswith('/subscriptions/upload') and r2.path.endswith('/subscriptions/upload'):
67 if r1.headers.get('content-type').startswith('multipart/form-data') and r2.headers.get('content-type').startswith('multipart/form-data'):
68 r1_copy = vcr.request.Request(r1.method, r1.uri, r1.body, r1.headers)
69 r2_copy = vcr.request.Request(r2.method, r2.uri, r2.body, r2.headers)
70 # the body is a huge binary blob, which seems to differ on every run, so we just ignore it
71 body1 = body2 = {}
72 r1_copy.body = json.dumps(body1)
73 r2_copy.body = json.dumps(body2)
74 return body_json_l2_matcher(r1_copy, r2_copy)
75 return body_json_l2_matcher(r1, r2)
76
77
78 def host_body_matcher(r1, r2):
79 if r1.headers.get('content-type') == r2.headers.get('content-type') == 'application/json':
80 if r1.path == r2.path == '/api/v2/hostgroups':
81 r1_copy = vcr.request.Request(r1.method, r1.uri, r1.body, r1.headers)
82 r2_copy = vcr.request.Request(r2.method, r2.uri, r2.body, r2.headers)
83 body1 = json.loads(r1_copy.body.decode('utf8'))
84 body2 = json.loads(r2_copy.body.decode('utf8'))
85 body1['search'] = 'name="test_group"'
86 body2['search'] = 'name="test_group"'
87 r1_copy.body = json.dumps(body1)
88 r2_copy.body = json.dumps(body2)
89 return body_json_l2_matcher(r1_copy, r2_copy)
90 return body_json_l2_matcher(r1, r2)
91
92
93 def job_invocation_body_matcher(r1, r2):
94 if r1.path == r2.path == '/api/job_invocations':
95 r1_copy = vcr.request.Request(r1.method, r1.uri, r1.body, r1.headers)
96 r2_copy = vcr.request.Request(r2.method, r2.uri, r2.body, r2.headers)
97 body1 = json.loads(r1_copy.body.decode('utf8'))
98 body2 = json.loads(r2_copy.body.decode('utf8'))
99 if 'search_query' in body1['job_invocation']:
100 body1['job_invocation']['search_query'] = body2['job_invocation']['search_query']
101 r1_copy.body = json.dumps(body1)
102 return body_json_l2_matcher(r1_copy, r2_copy)
103 return body_json_l2_matcher(r1, r2)
104
105
106 def filter_response(response):
107 response = filter_response_headers(response)
108 response = filter_response_body(response)
109 return response
110
111
112 def filter_response_headers(response):
113 for header in FILTER_RESPONSE_HEADERS:
114 # headers should be case insensitive, but for some reason they weren't for me
115 response['headers'].pop(header.lower(), None)
116 response['headers'].pop(header, None)
117 return response
118
119
120 def filter_response_body(response):
121 if 'body' in response and 'string' in response['body']:
122 body_string = response['body']['string'].decode('utf8')
123 if 'Authorization:' in body_string and 'Bearer' in body_string:
124 body_string = re.sub(r'Bearer [0-9a-zA-Z._-]+', 'Bearer INVALID', body_string)
125 if test_params['hostname'] in body_string:
126 body_string = body_string.replace(test_params['hostname'], 'foreman.example.org')
127 response['body']['string'] = body_string.encode('utf8')
128 return response
129
130
131 def filter_request_uri(request):
132 uri = urlparse(request.uri)
133 if uri.hostname != 'subscription.rhsm.redhat.com':
134 uri = uri._replace(netloc="foreman.example.org")
135 if uri.hostname == 'subscription.rhsm.redhat.com' and re.match('/subscription/users/[^/]+/owners', uri.path):
136 uri = uri._replace(path='/subscription/users/john-smith/owners')
137 request.uri = urlunparse(uri)
138 return request
139
140
141 def filter_request_manifest(request):
142 if request.method == 'POST' and request.path.endswith('/subscriptions/upload'):
143 request.body = 'FAKE_MANIFEST'
144 return request
145
146
147 def filter_request(request):
148 request = filter_request_uri(request)
149 request = filter_request_manifest(request)
150 return request
151
152
153 VCR_PARAMS_FILE = os.environ.get('FAM_TEST_VCR_PARAMS_FILE')
154
155 # Remove the name of the wrapper from argv
156 # (to make it look like the module had been called directly)
157 sys.argv.pop(0)
158
159 if VCR_PARAMS_FILE is None:
160 # Run the program as if nothing had happened
161 with open(sys.argv[0]) as f:
162 code = compile(f.read(), sys.argv[0], 'exec')
163 exec(code)
164 else:
165 import vcr
166 # Run the program wrapped within vcr cassette recorder
167 # Load recording parameters from file
168 with open(VCR_PARAMS_FILE, 'r') as params_file:
169 test_params = json.load(params_file)
170 cassette_file = 'fixtures/{}-{}.yml'.format(test_params['test_name'], test_params['serial'])
171 # Increase serial and dump back to file
172 test_params['serial'] += 1
173 with open(VCR_PARAMS_FILE, 'w') as params_file:
174 json.dump(test_params, params_file)
175
176 # Call the original python script with vcr-cassette in place
177 fam_vcr = vcr.VCR()
178
179 method_matcher = 'method'
180 if test_params['check_mode']:
181 fam_vcr.register_matcher('safe_method_matcher', safe_method_matcher)
182 method_matcher = 'safe_method_matcher'
183
184 query_matcher = 'query'
185 if test_params['test_name'] in ['domain', 'hostgroup', 'katello_hostgroup', 'luna_hostgroup', 'realm',
186 'subnet', 'puppetclasses_import', 'smart_proxy_refresh']:
187 fam_vcr.register_matcher('query_ignore_proxy', query_matcher_ignore_proxy)
188 query_matcher = 'query_ignore_proxy'
189 elif test_params['test_name'] in ['snapshot', 'snapshot_info']:
190 fam_vcr.register_matcher('snapshot_query', snapshot_query_matcher)
191 query_matcher = 'snapshot_query'
192
193 fam_vcr.register_matcher('body_json_l2', body_json_l2_matcher)
194
195 body_matcher = 'body_json_l2'
196 if test_params['test_name'] == 'host':
197 fam_vcr.register_matcher('host_body', host_body_matcher)
198 body_matcher = 'host_body'
199 elif test_params['test_name'] in ['subscription_manifest', 'manifest_role', 'content_rhel_role']:
200 fam_vcr.register_matcher('subscription_manifest_body', subscription_manifest_body_matcher)
201 body_matcher = 'subscription_manifest_body'
202 elif test_params['test_name'] == 'job_invocation':
203 fam_vcr.register_matcher('job_invocation_body', job_invocation_body_matcher)
204 body_matcher = 'job_invocation_body'
205
206 with fam_vcr.use_cassette(cassette_file,
207 record_mode=test_params['record_mode'],
208 match_on=[method_matcher, 'path', query_matcher, body_matcher],
209 filter_headers=FILTER_REQUEST_HEADERS,
210 before_record_request=filter_request,
211 before_record_response=filter_response,
212 decode_compressed_response=True,
213 ):
214 with open(sys.argv[0]) as f:
215 code = compile(f.read(), sys.argv[0], 'exec')
216 exec(code)