blob: a71ad39c9288218da976815045a2f181d261bd54 [file] [log] [blame]
Marc Koderer07a5a6f2015-03-16 15:14:37 +01001#!/usr/bin/env python
2
Chris Hoge296558c2015-02-19 00:29:49 -06003# Copyright 2014 Mirantis, Inc.
4#
5# Licensed under the Apache License, Version 2.0 (the "License"); you may
6# not use this file except in compliance with the License. You may obtain
7# a copy of the License at
8#
9# http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
13# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
14# License for the specific language governing permissions and limitations
15# under the License.
16
17import argparse
18import ast
19import importlib
20import inspect
21import os
22import sys
23import unittest
24import urllib
25import uuid
26
27DECORATOR_MODULE = 'test'
28DECORATOR_NAME = 'idempotent_id'
29DECORATOR_IMPORT = 'tempest.%s' % DECORATOR_MODULE
30IMPORT_LINE = 'from tempest import %s' % DECORATOR_MODULE
31DECORATOR_TEMPLATE = "@%s.%s('%%s')" % (DECORATOR_MODULE,
32 DECORATOR_NAME)
Chris Hoge7579c1a2015-02-26 14:12:15 -080033UNIT_TESTS_EXCLUDE = 'tempest.tests'
Chris Hoge296558c2015-02-19 00:29:49 -060034
35
36class SourcePatcher(object):
37
38 """"Lazy patcher for python source files"""
39
40 def __init__(self):
41 self.source_files = None
42 self.patches = None
43 self.clear()
44
45 def clear(self):
46 """Clear inner state"""
47 self.source_files = {}
48 self.patches = {}
49
50 @staticmethod
51 def _quote(s):
52 return urllib.quote(s)
53
54 @staticmethod
55 def _unquote(s):
56 return urllib.unquote(s)
57
58 def add_patch(self, filename, patch, line_no):
59 """Add lazy patch"""
60 if filename not in self.source_files:
61 with open(filename) as f:
62 self.source_files[filename] = self._quote(f.read())
63 patch_id = str(uuid.uuid4())
64 if not patch.endswith('\n'):
65 patch += '\n'
66 self.patches[patch_id] = self._quote(patch)
67 lines = self.source_files[filename].split(self._quote('\n'))
68 lines[line_no - 1] = ''.join(('{%s:s}' % patch_id, lines[line_no - 1]))
69 self.source_files[filename] = self._quote('\n').join(lines)
70
71 def _save_changes(self, filename, source):
72 print('%s fixed' % filename)
73 with open(filename, 'w') as f:
74 f.write(source)
75
76 def apply_patches(self):
77 """Apply all patches"""
78 for filename in self.source_files:
79 patched_source = self._unquote(
80 self.source_files[filename].format(**self.patches)
81 )
82 self._save_changes(filename, patched_source)
83 self.clear()
84
85
86class TestChecker(object):
87
88 def __init__(self, package):
89 self.package = package
90 self.base_path = os.path.abspath(os.path.dirname(package.__file__))
91
92 def _path_to_package(self, path):
93 relative_path = path[len(self.base_path) + 1:]
94 if relative_path:
95 return '.'.join((self.package.__name__,) +
96 tuple(relative_path.split('/')))
97 else:
98 return self.package.__name__
99
100 def _modules_search(self):
101 """Recursive search for python modules in base package"""
102 modules = []
103 for root, dirs, files in os.walk(self.base_path):
104 if not os.path.exists(os.path.join(root, '__init__.py')):
105 continue
106 root_package = self._path_to_package(root)
107 for item in files:
108 if item.endswith('.py'):
Chris Hoge7579c1a2015-02-26 14:12:15 -0800109 module_name = '.'.join((root_package,
110 os.path.splitext(item)[0]))
111 if not module_name.startswith(UNIT_TESTS_EXCLUDE):
112 modules.append(module_name)
Chris Hoge296558c2015-02-19 00:29:49 -0600113 return modules
114
115 @staticmethod
116 def _get_idempotent_id(test_node):
Ken'ichi Ohmichi7616d192015-11-17 13:12:55 +0000117 # Return key-value dict with all metadata from @test.idempotent_id
118 # decorators for test method
Chris Hoge296558c2015-02-19 00:29:49 -0600119 idempotent_id = None
120 for decorator in test_node.decorator_list:
121 if (hasattr(decorator, 'func') and
Marc Kodererfb199c02015-03-16 11:53:44 +0100122 hasattr(decorator.func, 'attr') and
123 decorator.func.attr == DECORATOR_NAME and
124 hasattr(decorator.func, 'value') and
125 decorator.func.value.id == DECORATOR_MODULE):
Chris Hoge296558c2015-02-19 00:29:49 -0600126 for arg in decorator.args:
127 idempotent_id = ast.literal_eval(arg)
128 return idempotent_id
129
130 @staticmethod
131 def _is_decorator(line):
132 return line.strip().startswith('@')
133
134 @staticmethod
135 def _is_def(line):
136 return line.strip().startswith('def ')
137
138 def _add_uuid_to_test(self, patcher, test_node, source_path):
139 with open(source_path) as src:
140 src_lines = src.read().split('\n')
141 lineno = test_node.lineno
142 insert_position = lineno
143 while True:
144 if (self._is_def(src_lines[lineno - 1]) or
145 (self._is_decorator(src_lines[lineno - 1]) and
146 (DECORATOR_TEMPLATE.split('(')[0] <=
147 src_lines[lineno - 1].strip().split('(')[0]))):
148 insert_position = lineno
149 break
150 lineno += 1
151 patcher.add_patch(
152 source_path,
153 ' ' * test_node.col_offset + DECORATOR_TEMPLATE % uuid.uuid4(),
154 insert_position
155 )
156
157 @staticmethod
158 def _is_test_case(module, node):
159 if (node.__class__ is ast.ClassDef and
160 hasattr(module, node.name) and
161 inspect.isclass(getattr(module, node.name))):
162 return issubclass(getattr(module, node.name), unittest.TestCase)
163
164 @staticmethod
165 def _is_test_method(node):
166 return (node.__class__ is ast.FunctionDef
167 and node.name.startswith('test_'))
168
169 @staticmethod
170 def _next_node(body, node):
171 if body.index(node) < len(body):
172 return body[body.index(node) + 1]
173
174 @staticmethod
175 def _import_name(node):
176 if type(node) == ast.Import:
177 return node.names[0].name
178 elif type(node) == ast.ImportFrom:
179 return '%s.%s' % (node.module, node.names[0].name)
180
181 def _add_import_for_test_uuid(self, patcher, src_parsed, source_path):
182 with open(source_path) as f:
183 src_lines = f.read().split('\n')
184 line_no = 0
185 tempest_imports = [node for node in src_parsed.body
186 if self._import_name(node) and
187 'tempest.' in self._import_name(node)]
188 if not tempest_imports:
189 import_snippet = '\n'.join(('', IMPORT_LINE, ''))
190 else:
191 for node in tempest_imports:
192 if self._import_name(node) < DECORATOR_IMPORT:
193 continue
194 else:
195 line_no = node.lineno
196 import_snippet = IMPORT_LINE
197 break
198 else:
199 line_no = tempest_imports[-1].lineno
200 while True:
201 if (not src_lines[line_no - 1] or
202 getattr(self._next_node(src_parsed.body,
203 tempest_imports[-1]),
204 'lineno') == line_no or
205 line_no == len(src_lines)):
206 break
207 line_no += 1
208 import_snippet = '\n'.join((IMPORT_LINE, ''))
209 patcher.add_patch(source_path, import_snippet, line_no)
210
211 def get_tests(self):
212 """Get test methods with sources from base package with metadata"""
213 tests = {}
214 for module_name in self._modules_search():
215 tests[module_name] = {}
216 module = importlib.import_module(module_name)
217 source_path = '.'.join(
218 (os.path.splitext(module.__file__)[0], 'py')
219 )
220 with open(source_path, 'r') as f:
221 source = f.read()
222 tests[module_name]['source_path'] = source_path
223 tests[module_name]['tests'] = {}
224 source_parsed = ast.parse(source)
225 tests[module_name]['ast'] = source_parsed
226 tests[module_name]['import_valid'] = (
227 hasattr(module, DECORATOR_MODULE) and
228 inspect.ismodule(getattr(module, DECORATOR_MODULE))
229 )
230 test_cases = (node for node in source_parsed.body
231 if self._is_test_case(module, node))
232 for node in test_cases:
233 for subnode in filter(self._is_test_method, node.body):
234 test_name = '%s.%s' % (node.name, subnode.name)
235 tests[module_name]['tests'][test_name] = subnode
236 return tests
237
238 @staticmethod
239 def _filter_tests(function, tests):
240 """Filter tests with condition 'function(test_node) == True'"""
241 result = {}
242 for module_name in tests:
243 for test_name in tests[module_name]['tests']:
244 if function(module_name, test_name, tests):
245 if module_name not in result:
246 result[module_name] = {
247 'ast': tests[module_name]['ast'],
248 'source_path': tests[module_name]['source_path'],
249 'import_valid': tests[module_name]['import_valid'],
250 'tests': {}
251 }
252 result[module_name]['tests'][test_name] = \
253 tests[module_name]['tests'][test_name]
254 return result
255
256 def find_untagged(self, tests):
257 """Filter all tests without uuid in metadata"""
258 def check_uuid_in_meta(module_name, test_name, tests):
259 idempotent_id = self._get_idempotent_id(
260 tests[module_name]['tests'][test_name])
261 return not idempotent_id
262 return self._filter_tests(check_uuid_in_meta, tests)
263
264 def report_collisions(self, tests):
Ken'ichi Ohmichi7616d192015-11-17 13:12:55 +0000265 """Reports collisions if there are any.
266
267 Returns true if collisions exist.
Chris Hoge296558c2015-02-19 00:29:49 -0600268 """
269 uuids = {}
270
271 def report(module_name, test_name, tests):
272 test_uuid = self._get_idempotent_id(
273 tests[module_name]['tests'][test_name])
274 if not test_uuid:
275 return
276 if test_uuid in uuids:
Joe Gordon4f10e452015-03-27 11:49:57 -0400277 error_str = "%s:%s\n uuid %s collision: %s<->%s\n%s:%s" % (
Chris Hoge296558c2015-02-19 00:29:49 -0600278 tests[module_name]['source_path'],
279 tests[module_name]['tests'][test_name].lineno,
280 test_uuid,
281 test_name,
282 uuids[test_uuid]['test_name'],
283 uuids[test_uuid]['source_path'],
284 uuids[test_uuid]['test_node'].lineno,
285 )
286 print(error_str)
Joe Gordon4f10e452015-03-27 11:49:57 -0400287 print("cannot automatically resolve the collision, please "
288 "manually remove the duplicate value on the new test.")
Chris Hoge296558c2015-02-19 00:29:49 -0600289 return True
290 else:
291 uuids[test_uuid] = {
292 'module': module_name,
293 'test_name': test_name,
294 'test_node': tests[module_name]['tests'][test_name],
295 'source_path': tests[module_name]['source_path']
296 }
297 return bool(self._filter_tests(report, tests))
298
299 def report_untagged(self, tests):
Ken'ichi Ohmichi7616d192015-11-17 13:12:55 +0000300 """Reports untagged tests if there are any.
301
302 Returns true if untagged tests exist.
Chris Hoge296558c2015-02-19 00:29:49 -0600303 """
304 def report(module_name, test_name, tests):
305 error_str = "%s:%s\nmissing @test.idempotent_id('...')\n%s\n" % (
306 tests[module_name]['source_path'],
307 tests[module_name]['tests'][test_name].lineno,
308 test_name
309 )
310 print(error_str)
311 return True
312 return bool(self._filter_tests(report, tests))
313
314 def fix_tests(self, tests):
Ken'ichi Ohmichi7616d192015-11-17 13:12:55 +0000315 """Add uuids to all tests specified in tests and fix it"""
Chris Hoge296558c2015-02-19 00:29:49 -0600316 patcher = SourcePatcher()
317 for module_name in tests:
318 add_import_once = True
319 for test_name in tests[module_name]['tests']:
320 if not tests[module_name]['import_valid'] and add_import_once:
321 self._add_import_for_test_uuid(
322 patcher,
323 tests[module_name]['ast'],
324 tests[module_name]['source_path']
325 )
326 add_import_once = False
327 self._add_uuid_to_test(
328 patcher, tests[module_name]['tests'][test_name],
329 tests[module_name]['source_path'])
330 patcher.apply_patches()
331
332
333def run():
334 parser = argparse.ArgumentParser()
335 parser.add_argument('--package', action='store', dest='package',
336 default='tempest', type=str,
337 help='Package with tests')
338 parser.add_argument('--fix', action='store_true', dest='fix_tests',
339 help='Attempt to fix tests without UUIDs')
340 args = parser.parse_args()
341 sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
342 pkg = importlib.import_module(args.package)
343 checker = TestChecker(pkg)
344 errors = False
345 tests = checker.get_tests()
346 untagged = checker.find_untagged(tests)
347 errors = checker.report_collisions(tests) or errors
348 if args.fix_tests and untagged:
349 checker.fix_tests(untagged)
350 else:
351 errors = checker.report_untagged(untagged) or errors
352 if errors:
Chris Hoge7579c1a2015-02-26 14:12:15 -0800353 sys.exit("@test.idempotent_id existence and uniqueness checks failed\n"
354 "Run 'tox -v -euuidgen' to automatically fix tests with\n"
355 "missing @test.idempotent_id decorators.")
Chris Hoge296558c2015-02-19 00:29:49 -0600356
357if __name__ == '__main__':
358 run()