-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathbehave.py
399 lines (334 loc) · 14.7 KB
/
behave.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
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
# -*- coding: utf-8 -*-
#
# Containers Testing Framework command line interface
# Copyright (C) 2015 Red Hat, Inc.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import os
import shutil
import glob
from subprocess import check_call, call, CalledProcessError
from six.moves.configparser import ConfigParser, NoSectionError, NoOptionError
from ctf_cli.logger import logger
from ctf_cli.exceptions import CTFCliError
from ctf_cli.config import CTFCliConfig
class BehaveTestsConfig(object):
"""
Configuration parser for tests configuration
"""
STEPS_OPTION = 'Steps'
FEATURES_OPTION = "Features"
def __init__(self, conf_path):
self._config = ConfigParser()
self._config_path = conf_path
try:
self._config.read(self._config_path)[0]
except IndexError:
logger.warning("Tests configuration '%s' can not be read!", conf_path)
else:
logger.debug("Using Tests configuration from '%s'.", conf_path)
def __getattr__(self, name):
"""
Forward all ConfigParser attributes to ConfigParser object
:param name: name of the attribute
:return: returns the selected attribute
"""
try:
return getattr(self._config, name)
except AttributeError:
return object.__getattribute__(self, name)
def get_tests(self):
return self._config.sections()
def get_test_steps(self, test_name):
return self._config.get(test_name, self.STEPS_OPTION)
def get_test_features(self, test_name):
return self._config.get(test_name, self.FEATURES_OPTION)
class BehaveWorkingDirectory(object):
"""
Class representing the Behave working directory
"""
def __init__(self, working_dir, cli_conf=None):
self._working_dir = working_dir
self._cli_conf = cli_conf
self._execution_dir = os.path.dirname(self._working_dir)
self._exec_type_conf_path = None
if os.path.isdir(os.path.join(self._execution_dir, 'test')):
self._project_tests_dir = os.path.join(self._execution_dir, 'test')
elif os.path.isdir(os.path.join(self._execution_dir, 'tests')):
self._project_tests_dir = os.path.join(self._execution_dir, 'tests')
else:
# Use the execution dir if we don't have any better option
self._project_tests_dir = self._execution_dir
self._features_dir = os.path.join(self._working_dir, 'features')
self._steps_dir = os.path.join(self._working_dir, 'steps')
self._tests_conf_path = self.find_tests_config(self._project_tests_dir)
try:
tests_conf_path = self._cli_conf.get(CTFCliConfig.GLOBAL_SECTION_NAME,
CTFCliConfig.CONFIG_TESTS_CONFIG_PATH)
assert tests_conf_path
self._tests_conf_path = tests_conf_path
except Exception:
pass
if self._tests_conf_path is not None:
# keep the cli_conf object Up-To-Date
if tests_conf_path is None:
self._cli_conf.set(CTFCliConfig.GLOBAL_SECTION_NAME,
CTFCliConfig.CONFIG_TESTS_CONFIG_PATH,
self._tests_conf_path)
self._tests_conf = BehaveTestsConfig(self._tests_conf_path)
else:
self._tests_conf = None
def path(self):
return self._working_dir
def exec_type_conf_path(self):
return self._exec_type_conf_path
def setup(self):
"""
Setup the working directory
:return:
"""
self._check_working_dir()
if self._cli_conf.get(CTFCliConfig.GLOBAL_SECTION_NAME,
CTFCliConfig.CONFIG_EXEC_TYPE) == 'ansible':
self._create_ansible_config()
self._add_project_specific_features()
self._add_project_specific_steps()
self._add_project_specific_environment_py()
if self._tests_conf:
self._add_remote_features()
self._add_remote_steps()
@staticmethod
def find_tests_config(tests_path):
"""
Find a tests config in the tests directory
:param tests_path: path to tests/ directory containing Features and Steps
:return: path to a config file or None if not found
"""
logger.debug("Looking for tests configuration inside '%s'", tests_path)
f = glob.glob(os.path.join(tests_path, 'test*.ini'))
if not f:
f = glob.glob(os.path.join(tests_path, 'test*.conf'))
if not f:
logger.debug("Didn't find any tests configuration file!")
return None
else:
logger.debug("Found configuration file: %s", str(f))
return os.path.join(tests_path, f[0])
def _create_ansible_config(self):
"""
Create ansible configuration file
:return: None
"""
script = None
method = None
host = None
user = None
try:
script = self._cli_conf.get(CTFCliConfig.ANSIBLE_SECTION_NAME,
CTFCliConfig.CONFIG_ANSIBLE_DYNAMIC_SCRIPT)
except NoSectionError:
raise CTFCliError("No configuration for 'ansible' provided!")
except NoOptionError:
logger.debug("No dynamic provision script found")
script = None
if not script:
try:
method = self._cli_conf.get(CTFCliConfig.ANSIBLE_SECTION_NAME,
CTFCliConfig.CONFIG_ANSIBLE_METHOD)
host = self._cli_conf.get(CTFCliConfig.ANSIBLE_SECTION_NAME,
CTFCliConfig.CONFIG_ANSIBLE_HOST)
user = self._cli_conf.get(CTFCliConfig.ANSIBLE_SECTION_NAME,
CTFCliConfig.CONFIG_ANSIBLE_USER)
except NoOptionError:
logger.debug("No dynamic provision script found")
# Optional parameters
try:
sudo = self._cli_conf.get(CTFCliConfig.ANSIBLE_SECTION_NAME,
CTFCliConfig.CONFIG_ANSIBLE_SUDO)
except NoOptionError:
sudo = False
ansible_conf_path = None
if script:
ansible_conf_path = os.path.join(self._working_dir, script)
shutil.copy(os.path.abspath(script), self._working_dir)
logger.debug("Using ansible dynamic configuration from '%s'", ansible_conf_path)
else:
ansible_conf_path = os.path.join(self._working_dir, 'ansible.conf')
ansible_conf_content = "[ctf]\n{host} ansible_connection={method} ansible_ssh_user={user} ansible_sudo={sudo}\n".format(
host=host, method=method, user=user, sudo=sudo
)
logger.debug("Writing ansible configuration to '%s'\n%s",
ansible_conf_path, ansible_conf_content)
with open(ansible_conf_path, 'w') as f:
f.write(ansible_conf_content)
self._exec_type_conf_path = ansible_conf_path
def _check_working_dir(self):
"""
Check if working directory exists.
Remove it if it exists and then recreate.
Create it if it does not exist
"""
if os.path.exists(self._working_dir):
logger.debug("Working directory '%s' exists. Removing it!", self._working_dir)
shutil.rmtree(self._working_dir)
logger.debug("Creating working directory '%s'.", self._working_dir)
os.mkdir(self._working_dir)
def _add_project_specific_steps(self):
"""
Adds project specific steps from execution_dir/test/steps into the
steps in working directory.
:return:
"""
project_steps_dir = os.path.join(self._project_tests_dir, 'steps')
if os.path.exists(project_steps_dir):
logger.info("Using project specific Steps from '%s'",
project_steps_dir.replace(self._execution_dir + os.sep, ''))
shutil.copytree(project_steps_dir, self._steps_dir)
else:
logger.warning("Not using project specific Steps. '%s' does not exist!",
project_steps_dir)
def _add_project_specific_features(self):
"""
Adds project specific features from execution_dir/test/features into the
features in working directory
:return:
"""
project_features_dir = os.path.join(self._project_tests_dir, 'features')
if os.path.exists(project_features_dir):
logger.info("Using project specific Features from '%s'",
project_features_dir.replace(self._execution_dir + os.sep, ''))
shutil.copytree(project_features_dir, self._features_dir)
else:
logger.warning("Not using project specific Features. '%s' does not exist!", project_features_dir)
def _add_project_specific_environment_py(self):
"""
Adds project specific environment.py from execution_dir/test/ into the
working directory. It is renamed and included in the common environment.py
:return:
"""
project_environment_py = os.path.join(self._project_tests_dir, 'environment.py')
if os.path.exists(project_environment_py):
logger.info("Using project specific environment.py from '%s'", project_environment_py.replace(
self._execution_dir + os.sep, ''))
shutil.copy(project_environment_py, self._working_dir)
else:
logger.warning("Not using project specific environment.py. '%s' does not exist!", project_environment_py)
def _add_remote_steps(self):
"""
Add all remote steps
:return:
"""
for test in self._tests_conf.get_tests():
remote_repo = self._tests_conf.get_test_steps(test)
local_dir = os.path.join(self._steps_dir, '{0}_steps'.format(test).replace('-', '_'))
logger.info("Using remote Steps from '%s'", remote_repo)
logger.debug("Cloning remote test Steps from '%s' to '%s'", remote_repo, local_dir)
try:
check_call(['git', 'clone', '-q', remote_repo, local_dir])
except CalledProcessError as e:
raise CTFCliError("Cloning of {0} failed!\n{1}".format(remote_repo, str(e)))
def _add_remote_features(self):
"""
Add all remote features
:return:
"""
for test in self._tests_conf.get_tests():
remote_repo = self._tests_conf.get_test_features(test)
local_dir = os.path.join(self._features_dir, '{0}_features'.format(test).replace('-', '_'))
logger.info("Using remote Features from '%s'", remote_repo)
logger.debug("Cloning remote test Features from '%s' to '%s'", remote_repo, local_dir)
try:
check_call(['git', 'clone', '-q', remote_repo, local_dir])
except CalledProcessError as e:
raise CTFCliError("Cloning of {0} failed!\n{1}".format(remote_repo, str(e)))
class BehaveRunner(object):
"""
Class wrapping the process of running behave inside the working directory
"""
def __init__(self, working_dir, cli_config):
"""
Constructor
:param working_dir: The BehaveWorkingDirectory instance
:param cli_config: The CTFCliConf instance
:return: None
"""
self._working_dir_obj = working_dir
self._cli_conf_obj = cli_config
def run(self):
"""
Run Behave and pass some runtime arguments
:return:
"""
behave_data = None
try:
behave_data = self._cli_conf_obj.get(CTFCliConfig.GLOBAL_SECTION_NAME, CTFCliConfig.CONFIG_BEHAVE_DATA)
except Exception:
pass
behave_tags = None
try:
behave_tags = self._cli_conf_obj.get(CTFCliConfig.GLOBAL_SECTION_NAME, CTFCliConfig.CONFIG_BEHAVE_TAGS)
except Exception:
pass
junit = None
try:
junit = self._cli_conf_obj.get(CTFCliConfig.GLOBAL_SECTION_NAME, CTFCliConfig.CONFIG_JUNIT)
except Exception:
pass
behave_opts = None
try:
behave_opts = self._cli_conf_obj.get(CTFCliConfig.GLOBAL_SECTION_NAME, CTFCliConfig.CONFIG_BEHAVE_OPTS)
except Exception:
pass
verbose = None
try:
verbose = self._cli_conf_obj.get(CTFCliConfig.GLOBAL_SECTION_NAME, CTFCliConfig.CONFIG_VERBOSE)
except Exception:
pass
# configuration file for ansible
ansible_conf = None
try:
if self._cli_conf_obj.get(CTFCliConfig.GLOBAL_SECTION_NAME, CTFCliConfig.CONFIG_EXEC_TYPE) == 'ansible':
ansible_conf = self._working_dir_obj.exec_type_conf_path()
except Exception:
pass
command = [
'behave'
]
if verbose == "yes":
command.append('-v')
if junit:
command.append('--junit')
command.append('--junit-directory={0}'.format(junit))
if behave_data:
#FIXME hacky otherwise it return string - seems like wierd buig in config.py
if type(behave_data) is str:
behave_data = behave_data.split('\n')
for userdata in behave_data:
command.extend(['-D', '{0}'.format(userdata)])
if behave_tags:
#FIXME hacky otherwise it return string - seems like wierd buig in config.py
if type(behave_tags) is str:
behave_tags = behave_tags.split('\n')
for tag in behave_tags:
command.extend(['-t', '{0}'.format(tag)])
if verbose != "yes":
command.append('--no-skipped')
if behave_opts:
if type(behave_opts) is str:
behave_opts = behave_opts.split()
command.extend(behave_opts)
if ansible_conf:
command.extend(['-D', 'ANSIBLE={0}'.format(ansible_conf)])
logger.info("Running behave inside working directory '%s'", ' '.join(command))
return call(command, cwd=self._working_dir_obj.path())