-
Notifications
You must be signed in to change notification settings - Fork 141
/
Copy pathverify_wrapper.py
261 lines (214 loc) · 8.26 KB
/
verify_wrapper.py
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
"""Wrapper to verify previously created pacts."""
import warnings
from pact.constants import VERIFIER_PATH
import sys
import os
import platform
import subprocess
from os.path import isdir, join, isfile
from os import listdir
def capture_logs(process, verbose):
"""Capture logs from ruby process."""
warnings.warn(
"This function will be deprecated Pact Python v3 "
"(see pact-foundation/pact-python#396)",
PendingDeprecationWarning,
stacklevel=2,
)
result = ''
for line in process.stdout:
result = result + line + '\n'
return result
def path_exists(path):
"""
Determine if a particular path exists.
Can be provided a URL or local path. URLs always result in a True. Local
paths are True only if a file exists at that location.
:param path: The path to check.
:type path: str
:return: True if the path exists and is a file, otherwise False.
:rtype: bool
"""
warnings.warn(
"This function will be deprecated Pact Python v3 "
"(see pact-foundation/pact-python#396)",
PendingDeprecationWarning,
stacklevel=2,
)
if path.startswith('http://') or path.startswith('https://'):
return True
return isfile(path)
def sanitize_logs(process, verbose):
"""
Print the logs from a process while removing Ruby stack traces.
:param process: The Ruby pact verifier process.
:type process: subprocess.Popen
:param verbose: Flag to toggle more verbose logging.
:type verbose: bool
:rtype: None
"""
warnings.warn(
"This function will be deprecated Pact Python v3 "
"(see pact-foundation/pact-python#396)",
PendingDeprecationWarning,
stacklevel=2,
)
for line in process.stdout:
if (not verbose and line.lstrip().startswith('#')
and ('vendor/ruby' in line or 'pact-provider-verifier.rb' in line)):
continue
else:
sys.stdout.write(line)
def expand_directories(paths):
"""
Iterate over paths and expand any that are directories into file paths.
:param paths: A list of file paths to expand.
:type paths: list
:return: A list of file paths with any directory paths replaced with the
JSON files in those directories.
:rtype: list
"""
warnings.warn(
"This function will be deprecated Pact Python v3 "
"(see pact-foundation/pact-python#396)",
PendingDeprecationWarning,
stacklevel=2,
)
paths_ = []
for path in paths:
if path.startswith('http://') or path.startswith('https://'):
paths_.append(path)
elif isdir(path):
paths_.extend(
[join(path, p) for p in listdir(path) if p.endswith('.json')])
else:
paths_.append(path)
# Ruby pact verifier expects forward slashes regardless of OS
return [p.replace('\\', '/') for p in paths_]
def rerun_command():
"""
Create a rerun command template for failed interactions.
:rtype: str
"""
warnings.warn(
"This function will be deprecated Pact Python v3 "
"(see pact-foundation/pact-python#396)",
PendingDeprecationWarning,
stacklevel=2,
)
is_windows = 'windows' in platform.platform().lower()
command = ''
if is_windows:
command = (
'cmd.exe /v /c "'
'set PACT_DESCRIPTION=<PACT_DESCRIPTION>'
'& set PACT_PROVIDER_STATE=<PACT_PROVIDER_STATE>'
'& {command}'
' & set PACT_DESCRIPTION='
' & set PACT_PROVIDER_STATE="'.format(command=' '.join(sys.argv)))
else:
command = ("PACT_DESCRIPTION='<PACT_DESCRIPTION>'"
" PACT_PROVIDER_STATE='<PACT_PROVIDER_STATE>'"
" {command}".format(command=' '.join(sys.argv)))
env = os.environ.copy()
env['PACT_INTERACTION_RERUN_COMMAND'] = command
return env
class PactException(Exception):
"""PactException when input isn't valid.
Args:
Exception ([type]): [description]
Raises:
KeyError: [description]
Exception: [description]
Returns:
[type]: [description]
"""
def __init__(self, *args, **kwargs):
"""Create wrapper."""
warnings.warn(
"This class will be deprecated Pact Python v3 "
"(see pact-foundation/pact-python#396)",
PendingDeprecationWarning,
stacklevel=2,
)
super().__init__(*args, **kwargs)
self.message = args[0]
class VerifyWrapper(object):
"""A Pact Verifier Wrapper."""
def __init__(self):
warnings.warn(
"This class will be deprecated Pact Python v3 "
"(see pact-foundation/pact-python#396)",
PendingDeprecationWarning,
stacklevel=2,
)
def _broker_present(self, **kwargs):
if kwargs.get('broker_url') is None:
return False
return True
def _validate_input(self, pacts, **kwargs):
if len(pacts) == 0 and not self._broker_present(**kwargs):
raise PactException('Pact urls or Pact broker required')
def call_verify(
self, *pacts, provider_base_url, provider, enable_pending=False,
include_wip_pacts_since=None, **kwargs
):
"""Call verify method."""
verbose = kwargs.get('verbose', False)
self._validate_input(pacts, **kwargs)
provider_app_version = kwargs.get('provider_app_version')
provider_version_branch = kwargs.get('provider_version_branch')
options = {
'--provider-base-url': provider_base_url,
'--provider': provider,
'--broker-username': kwargs.get('broker_username', None),
'--broker-password': kwargs.get('broker_password', None),
'--broker-token': kwargs.get('broker_token', None),
'--pact-broker-base-url': kwargs.get('broker_url', None),
'--provider-states-setup-url': kwargs.get('provider_states_setup_url'),
'--log-dir': kwargs.get('log_dir'),
'--log-level': kwargs.get('log_level')
}
command = [VERIFIER_PATH]
all_pact_urls = expand_directories(list(pacts))
command.extend(all_pact_urls)
command.extend(['{}={}'.format(k, v) for k, v in options.items() if v])
if (provider_app_version):
command.extend(["--provider-app-version",
provider_app_version])
if (kwargs.get('publish_verification_results', False) is True):
command.extend(['--publish-verification-results'])
if (kwargs.get('verbose', False) is True):
command.extend(['--verbose'])
if enable_pending:
command.append('--enable-pending')
else:
command.append('--no-enable-pending')
if include_wip_pacts_since:
command.extend(['--include-wip-pacts-since={}'.format(include_wip_pacts_since)])
if provider_version_branch:
command.extend(["--provider-version-branch={}".format(provider_version_branch)])
headers = kwargs.get('custom_provider_headers', [])
for header in headers:
command.extend(['{}={}'.format('--custom-provider-header', header)])
for tag in kwargs.get('consumer_tags', []):
command.extend(["--consumer-version-tag={}".format(tag)])
for tag in kwargs.get('consumer_selectors', []):
command.extend(["--consumer-version-selector={}".format(tag)])
for tag in kwargs.get('provider_tags', []):
command.extend(["--provider-version-tag={}".format(tag)])
env = rerun_command()
result = subprocess.Popen(command, bufsize=1, env=env, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT, universal_newlines=True)
sanitize_logs(result, verbose)
result.wait()
logs = capture_logs(result, verbose)
return result.returncode, logs
def publish_results(self, provider_app_version, command):
"""Publish results to broker."""
if not provider_app_version:
# todo implement
raise Exception('todo')
command.extend(["--provider-app-version",
provider_app_version,
"--publish-verification-results"])