-
Notifications
You must be signed in to change notification settings - Fork 12
/
environment.py
283 lines (233 loc) · 9.58 KB
/
environment.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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
'''Magically loaded by behave defining helper methods and other things'''
from __future__ import print_function
# define the necessary logging features to write messages to a file
import logging
import os
import re
import sys
from datetime import datetime
import env_setup
if os.getenv("WORKSPACE") is not None:
logdir = os.getenv("WORKSPACE") + "/logs"
else:
logdir = "logs"
if not os.path.exists(logdir):
os.makedirs(logdir)
now_string = datetime.now().strftime('%Y-%b-%d-%H:%M:%S')
logfile = logdir + '/' + now_string + '_behave.log'
file_logger = logging.getLogger()
file_logger.setLevel(logging.INFO)
fh = logging.FileHandler(filename=logfile)
fh.setLevel(logging.INFO)
my_formatter = logging.Formatter('%(asctime)s - %(message)s')
fh.setFormatter(my_formatter)
file_logger.addHandler(fh)
def before_all(context):
'''Behave-specific function that runs before anything else'''
import ConfigParser
import requests
config = ConfigParser.ConfigParser()
config.read('config/uat.cfg')
context.test_cfg = ConfigParser.ConfigParser()
context.test_cfg.read('config/test.cfg')
path = os.path.dirname(sys.modules['env_setup'].__file__)
context.src_dir = os.path.join(path, "resources")
for key, value in context.test_cfg.items("default"):
setattr(context, key, value)
def api(app, path, payload=None, method=None):
'''Generic interface for making application API calls
app: match section name of config file
GET is default
For POST pass in a payload JSON string
For DELETE pass in 'method=delete'
returns JSON results
'''
# TODO: support PUT calls
# TODO: support more auth opts
AUTH = (config.get(app, 'user'), config.get(app, 'pass'))
VERIFY = False
url = '/'.join([config.get(app, 'url'),
config.get(app, 'api_path'), path])
if payload is None:
if method is None:
# GET request
result = requests.get(
url,
auth=AUTH,
verify=VERIFY)
elif method is "delete":
# DELETE request
result = requests.delete(
url,
auth=AUTH,
verify=VERIFY)
else:
# POST request
post_headers = {'content-type': 'application/json'}
result = requests.post(
url,
auth=AUTH,
verify=VERIFY,
headers=post_headers,
data=payload)
if result.raise_for_status():
print('Status %s: %s' % (result.status_code,
result.json()['error']))
return False
if app is "satellite":
if payload is None and method is None:
return result.json()['results']
else:
return result.json()
elif app is "openshiftv2":
print(result.json())
return result.json()
context.api = api
def remote_cmd(cmd, host=None, ignore_rc=False, async=False, **kwargs):
'''Interface to run a command on a remote host using Ansible modules
host: name of host of remote target system in ansible inventory file
or environment variable
cmd: an Ansible module
ignore_rc: occasionally the command is expected to fail. Set this to
True so that the output is retained and can be used
async: run the cmd asynchronous on a remote host.
module_args: module args in the form of "key1=value1 key2=value2"
Returns list of values if all hosts successful, otherwise False'''
import ansible.runner
inventory = None
if context.inventory == "dynamic":
# use custom dynamic hosts script
ansible_config = config.get('ansible', 'dynamic_inventory_script')
else:
# default to static file
ansible_config = config.get('ansible', 'inventory')
inventory = ansible.inventory.Inventory(ansible_config)
# check value of host. if host is not None, we assume the user has
# supplied a host arg to remote_cmd(). otherwise, it is passed
# along in the context object.
if host is not None:
host = host
else:
host = context.target_host
# the 'context' object can basically hold whatever we want.
# if we stash the result from Ansible, we can inspect it or log it
# later
if async:
result = ansible.runner.Runner(module_name=cmd,
inventory=inventory,
pattern=host,
**kwargs
).run_async(context.test_timeout)
context.result = result[0]
poller = result[1]
return poller
else:
context.result = ansible.runner.Runner(module_name=cmd,
inventory=inventory,
pattern=host,
**kwargs
).run()
# TODO support lists of hosts
if context.result['dark']:
print(context.result['dark'])
return False
elif not context.result['contacted']:
print(context.result)
return False
else:
values = []
for key, value in context.result['contacted'].iteritems():
if (ignore_rc is False
and 'rc' in value.keys() and value['rc'] != 0):
return False
else:
values.append(value)
return values
context.remote_cmd = remote_cmd
def get_hosts():
"""
Get host group name and ip pairs from inventory.
:return: the ips for each group in inventory.
:rtype: dictionary
"""
import ansible.runner
if context.inventory == "dynamic":
# use custom dynamic hosts script
host_list = config.get('ansible', 'dynamic_inventory_script')
else:
# default to static file
host_list = config.get('ansible', 'inventory')
inventory = ansible.inventory.Inventory(host_list)
host_groups = {"all": []}
for group in inventory.groups:
group_name = group.name
if group_name != "all":
host_groups[group.name] = []
for host in group.hosts:
host_groups[group.name].append(host.name)
if host.name not in host_groups["all"]:
host_groups["all"].append(host.name)
return host_groups
context.get_hosts = get_hosts
# After each step, we will examine the status and log any results from Ansible
# if they exist
def after_step(context, step):
if (os.getenv("BEHAVE_DEBUG_LOGGING") is not None
and os.getenv("BEHAVE_DEBUG_LOGGING") == "True"):
file_logger.info('Behave Step Name: %s' % step.name)
file_logger.info('Step Error Message: %s' % step.error_message)
if hasattr(context, 'result'):
file_logger.info('Ansible Output: %s' % context.result)
elif step.status == "failed":
file_logger.info('Behave Step Name: %s' % step.name)
file_logger.info('Step Error Message: %s' % step.error_message)
if hasattr(context, 'result'):
file_logger.info('Ansible Output: %s' % context.result)
print('Ansible Output: %s' % context.result)
def before_feature(context, feature):
"""
These run before each feature file is exercised as preparetion steps. It
works with tags marked in each feautre file. Pick up functions from
env_setup.py based on the tags, and the parameters needed is passed by
test_cfg.
"""
feature_sec_name = re.findall("(\w+)\.feature", feature.filename)[0]
if context.test_cfg.has_section(feature_sec_name):
for key, value in context.test_cfg.items(feature_sec_name):
setattr(context, key, value)
for tag in feature.tags:
tag_prepare = "%s_prepare" % tag
if hasattr(env_setup, tag_prepare):
test_tag = tag_prepare
elif hasattr(env_setup, tag):
test_tag = tag
else:
continue
func = getattr(env_setup, test_tag)
try:
func(context)
except Exception, err:
print("%s failed with following error: %s" % (test_tag,
err.message))
def after_feature(context, feature):
"""
These run after each feature file is exercised as clean up steps. It
works with tags marked in each feautre file. Pick up functions from
env_setup.py based on the tags, and the parameters needed is passed by
test_cfg.
"""
feature.tags.reverse()
for tag in feature.tags:
tag_cleanup = "%s_cleanup" % tag
if hasattr(env_setup, tag_cleanup):
test_tag = tag_cleanup
elif hasattr(env_setup, tag):
test_tag = tag
else:
continue
func = getattr(env_setup, test_tag)
try:
func(context)
except Exception, err:
print("%s failed with following error: %s" % (test_tag,
err.message))