blob: 528424a486f01dd772d836784acfc619989aeae2 [file] [log] [blame]
Matthew Treinish8b372892012-12-07 17:13:16 -05001#!/usr/bin/env python
2# vim: tabstop=4 shiftwidth=4 softtabstop=4
3
4# Copyright (c) 2012, Cloudscaling
5# All Rights Reserved.
6#
7# Licensed under the Apache License, Version 2.0 (the "License"); you may
8# not use this file except in compliance with the License. You may obtain
9# a copy of the License at
10#
11# http://www.apache.org/licenses/LICENSE-2.0
12#
13# Unless required by applicable law or agreed to in writing, software
14# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
15# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
16# License for the specific language governing permissions and limitations
17# under the License.
18
19"""tempest HACKING file compliance testing
20
21built on top of pep8.py
22"""
23
24import fnmatch
25import inspect
26import logging
27import os
28import re
29import subprocess
30import sys
31import tokenize
32import warnings
33
34import pep8
35
36# Don't need this for testing
37logging.disable('LOG')
38
Sean Dagued18cfe52013-01-04 14:53:00 -050039#T1xx comments
40#T2xx except
41#T3xx imports
42#T4xx docstrings
43#T5xx dictionaries/lists
44#T6xx calling methods
45#T7xx localization
Matthew Treinish8b372892012-12-07 17:13:16 -050046#N8xx git commit messages
47
48IMPORT_EXCEPTIONS = ['sqlalchemy', 'migrate']
49DOCSTRING_TRIPLE = ['"""', "'''"]
50VERBOSE_MISSING_IMPORT = os.getenv('HACKING_VERBOSE_MISSING_IMPORT', 'False')
51
52
53# Monkey patch broken excluded filter in pep8
54# See https://github.com/jcrocholl/pep8/pull/111
55def excluded(self, filename):
56 """
57 Check if options.exclude contains a pattern that matches filename.
58 """
59 basename = os.path.basename(filename)
60 return any((pep8.filename_match(filename, self.options.exclude,
61 default=False),
62 pep8.filename_match(basename, self.options.exclude,
63 default=False)))
64
65
66def input_dir(self, dirname):
67 """Check all files in this directory and all subdirectories."""
68 dirname = dirname.rstrip('/')
69 if self.excluded(dirname):
70 return 0
71 counters = self.options.report.counters
72 verbose = self.options.verbose
73 filepatterns = self.options.filename
74 runner = self.runner
75 for root, dirs, files in os.walk(dirname):
76 if verbose:
77 print('directory ' + root)
78 counters['directories'] += 1
79 for subdir in sorted(dirs):
80 if self.excluded(os.path.join(root, subdir)):
81 dirs.remove(subdir)
82 for filename in sorted(files):
83 # contain a pattern that matches?
84 if ((pep8.filename_match(filename, filepatterns) and
85 not self.excluded(filename))):
86 runner(os.path.join(root, filename))
87
88
89def is_import_exception(mod):
90 return (mod in IMPORT_EXCEPTIONS or
91 any(mod.startswith(m + '.') for m in IMPORT_EXCEPTIONS))
92
93
94def import_normalize(line):
95 # convert "from x import y" to "import x.y"
96 # handle "from x import y as z" to "import x.y as z"
97 split_line = line.split()
98 if ("import" in line and line.startswith("from ") and "," not in line and
99 split_line[2] == "import" and split_line[3] != "*" and
100 split_line[1] != "__future__" and
101 (len(split_line) == 4 or
102 (len(split_line) == 6 and split_line[4] == "as"))):
103 return "import %s.%s" % (split_line[1], split_line[3])
104 else:
105 return line
106
107
108def tempest_todo_format(physical_line):
109 """Check for 'TODO()'.
110
111 tempest HACKING guide recommendation for TODO:
112 Include your name with TODOs as in "#TODO(termie)"
Sean Dagued18cfe52013-01-04 14:53:00 -0500113 T101
Matthew Treinish8b372892012-12-07 17:13:16 -0500114 """
115 pos = physical_line.find('TODO')
116 pos1 = physical_line.find('TODO(')
117 pos2 = physical_line.find('#') # make sure it's a comment
118 if (pos != pos1 and pos2 >= 0 and pos2 < pos):
Sean Dagued18cfe52013-01-04 14:53:00 -0500119 return pos, "T101: Use TODO(NAME)"
Matthew Treinish8b372892012-12-07 17:13:16 -0500120
121
122def tempest_except_format(logical_line):
123 """Check for 'except:'.
124
125 tempest HACKING guide recommends not using except:
126 Do not write "except:", use "except Exception:" at the very least
Sean Dagued18cfe52013-01-04 14:53:00 -0500127 T201
Matthew Treinish8b372892012-12-07 17:13:16 -0500128 """
129 if logical_line.startswith("except:"):
Sean Dagued18cfe52013-01-04 14:53:00 -0500130 yield 6, "T201: no 'except:' at least use 'except Exception:'"
Matthew Treinish8b372892012-12-07 17:13:16 -0500131
132
133def tempest_except_format_assert(logical_line):
134 """Check for 'assertRaises(Exception'.
135
136 tempest HACKING guide recommends not using assertRaises(Exception...):
137 Do not use overly broad Exception type
Sean Dagued18cfe52013-01-04 14:53:00 -0500138 T202
Matthew Treinish8b372892012-12-07 17:13:16 -0500139 """
140 if logical_line.startswith("self.assertRaises(Exception"):
Sean Dagued18cfe52013-01-04 14:53:00 -0500141 yield 1, "T202: assertRaises Exception too broad"
Matthew Treinish8b372892012-12-07 17:13:16 -0500142
143
144def tempest_one_import_per_line(logical_line):
145 """Check for import format.
146
147 tempest HACKING guide recommends one import per line:
148 Do not import more than one module per line
149
150 Examples:
151 BAD: from tempest.common.rest_client import RestClient, RestClientXML
Sean Dagued18cfe52013-01-04 14:53:00 -0500152 T301
Matthew Treinish8b372892012-12-07 17:13:16 -0500153 """
154 pos = logical_line.find(',')
155 parts = logical_line.split()
156 if (pos > -1 and (parts[0] == "import" or
157 parts[0] == "from" and parts[2] == "import") and
158 not is_import_exception(parts[1])):
Sean Dagued18cfe52013-01-04 14:53:00 -0500159 yield pos, "T301: one import per line"
Matthew Treinish8b372892012-12-07 17:13:16 -0500160
161_missingImport = set([])
162
163
164def tempest_import_module_only(logical_line):
165 """Check for import module only.
166
167 tempest HACKING guide recommends importing only modules:
168 Do not import objects, only modules
Sean Dagued18cfe52013-01-04 14:53:00 -0500169 T302 import only modules
170 T303 Invalid Import
171 T304 Relative Import
Matthew Treinish8b372892012-12-07 17:13:16 -0500172 """
173 def importModuleCheck(mod, parent=None, added=False):
174 """
175 If can't find module on first try, recursively check for relative
176 imports
177 """
178 current_path = os.path.dirname(pep8.current_file)
179 try:
180 with warnings.catch_warnings():
181 warnings.simplefilter('ignore', DeprecationWarning)
182 valid = True
183 if parent:
184 if is_import_exception(parent):
185 return
186 parent_mod = __import__(parent, globals(), locals(),
187 [mod], -1)
188 valid = inspect.ismodule(getattr(parent_mod, mod))
189 else:
190 __import__(mod, globals(), locals(), [], -1)
191 valid = inspect.ismodule(sys.modules[mod])
192 if not valid:
193 if added:
194 sys.path.pop()
195 added = False
Sean Dagued18cfe52013-01-04 14:53:00 -0500196 return logical_line.find(mod), ("T304: No "
Matthew Treinish8b372892012-12-07 17:13:16 -0500197 "relative imports. "
198 "'%s' is a relative "
199 "import"
200 % logical_line)
Sean Dagued18cfe52013-01-04 14:53:00 -0500201 return logical_line.find(mod), ("T302: import only"
Matthew Treinish8b372892012-12-07 17:13:16 -0500202 " modules. '%s' does not "
203 "import a module"
204 % logical_line)
205
206 except (ImportError, NameError) as exc:
207 if not added:
208 added = True
209 sys.path.append(current_path)
210 return importModuleCheck(mod, parent, added)
211 else:
212 name = logical_line.split()[1]
213 if name not in _missingImport:
214 if VERBOSE_MISSING_IMPORT != 'False':
215 print >> sys.stderr, ("ERROR: import '%s' in %s "
216 "failed: %s" %
217 (name, pep8.current_file, exc))
218 _missingImport.add(name)
219 added = False
220 sys.path.pop()
221 return
222
223 except AttributeError:
224 # Invalid import
Sean Dagued18cfe52013-01-04 14:53:00 -0500225 return logical_line.find(mod), ("T303: Invalid import, "
Matthew Treinish8b372892012-12-07 17:13:16 -0500226 "AttributeError raised")
227
228 # convert "from x import y" to " import x.y"
229 # convert "from x import y as z" to " import x.y"
230 import_normalize(logical_line)
231 split_line = logical_line.split()
232
233 if (logical_line.startswith("import ") and "," not in logical_line and
234 (len(split_line) == 2 or
235 (len(split_line) == 4 and split_line[2] == "as"))):
236 mod = split_line[1]
237 rval = importModuleCheck(mod)
238 if rval is not None:
239 yield rval
240
241 # TODO(jogo) handle "from x import *"
242
Sean Dagued18cfe52013-01-04 14:53:00 -0500243#TODO(jogo): import template: T305
Matthew Treinish8b372892012-12-07 17:13:16 -0500244
245
246def tempest_import_alphabetical(logical_line, line_number, lines):
247 """Check for imports in alphabetical order.
248
249 Tempest HACKING guide recommendation for imports:
250 imports in human alphabetical order
Sean Dagued18cfe52013-01-04 14:53:00 -0500251 T306
Matthew Treinish8b372892012-12-07 17:13:16 -0500252 """
253 # handle import x
254 # use .lower since capitalization shouldn't dictate order
255 split_line = import_normalize(logical_line.strip()).lower().split()
256 split_previous = import_normalize(lines[
257 line_number - 2]).strip().lower().split()
258 # with or without "as y"
259 length = [2, 4]
260 if (len(split_line) in length and len(split_previous) in length and
261 split_line[0] == "import" and split_previous[0] == "import"):
262 if split_line[1] < split_previous[1]:
Sean Dagued18cfe52013-01-04 14:53:00 -0500263 yield (0, "T306: imports not in alphabetical order"
Matthew Treinish8b372892012-12-07 17:13:16 -0500264 " (%s, %s)"
265 % (split_previous[1], split_line[1]))
266
267
268def tempest_docstring_start_space(physical_line):
269 """Check for docstring not start with space.
270
271 tempest HACKING guide recommendation for docstring:
272 Docstring should not start with space
Sean Dagued18cfe52013-01-04 14:53:00 -0500273 T401
Matthew Treinish8b372892012-12-07 17:13:16 -0500274 """
275 pos = max([physical_line.find(i) for i in DOCSTRING_TRIPLE]) # start
Sean Daguef237ccb2013-01-04 15:19:14 -0500276 end = max([physical_line[-4:-1] == i for i in DOCSTRING_TRIPLE]) # end
277 if (pos != -1 and end and len(physical_line) > pos + 4):
Matthew Treinish8b372892012-12-07 17:13:16 -0500278 if (physical_line[pos + 3] == ' '):
Sean Dagued18cfe52013-01-04 14:53:00 -0500279 return (pos, "T401: one line docstring should not start"
Matthew Treinish8b372892012-12-07 17:13:16 -0500280 " with a space")
281
282
283def tempest_docstring_one_line(physical_line):
284 """Check one line docstring end.
285
286 tempest HACKING guide recommendation for one line docstring:
287 A one line docstring looks like this and ends in a period.
Sean Dagued18cfe52013-01-04 14:53:00 -0500288 T402
Matthew Treinish8b372892012-12-07 17:13:16 -0500289 """
290 pos = max([physical_line.find(i) for i in DOCSTRING_TRIPLE]) # start
291 end = max([physical_line[-4:-1] == i for i in DOCSTRING_TRIPLE]) # end
292 if (pos != -1 and end and len(physical_line) > pos + 4):
293 if (physical_line[-5] != '.'):
Sean Dagued18cfe52013-01-04 14:53:00 -0500294 return pos, "T402: one line docstring needs a period"
Matthew Treinish8b372892012-12-07 17:13:16 -0500295
296
297def tempest_docstring_multiline_end(physical_line):
298 """Check multi line docstring end.
299
300 Tempest HACKING guide recommendation for docstring:
301 Docstring should end on a new line
Sean Dagued18cfe52013-01-04 14:53:00 -0500302 T403
Matthew Treinish8b372892012-12-07 17:13:16 -0500303 """
304 pos = max([physical_line.find(i) for i in DOCSTRING_TRIPLE]) # start
305 if (pos != -1 and len(physical_line) == pos):
306 if (physical_line[pos + 3] == ' '):
Sean Dagued18cfe52013-01-04 14:53:00 -0500307 return (pos, "T403: multi line docstring end on new line")
Matthew Treinish8b372892012-12-07 17:13:16 -0500308
309
Sean Dague97449cc2013-01-04 14:38:26 -0500310def tempest_no_test_docstring(physical_line, previous_logical, filename):
311 """Check that test_ functions don't have docstrings
312
313 This ensure we get better results out of tempest, instead
314 of them being hidden behind generic descriptions of the
315 functions.
316
Sean Dagued18cfe52013-01-04 14:53:00 -0500317 T404
Sean Dague97449cc2013-01-04 14:38:26 -0500318 """
319 if "tempest/test" in filename:
320 pos = max([physical_line.find(i) for i in DOCSTRING_TRIPLE])
321 if pos != -1:
322 if previous_logical.startswith("def test_"):
Sean Dagued18cfe52013-01-04 14:53:00 -0500323 return (pos, "T404: test functions must "
Sean Dague97449cc2013-01-04 14:38:26 -0500324 "not have doc strings")
325
Matthew Treinish997da922013-03-19 11:44:12 -0400326SKIP_DECORATOR = '@testtools.skip('
327
328
329def tempest_skip_bugs(physical_line):
330 """Check skip lines for proper bug entries
331
332 T601: Bug not in skip line
333 T602: Bug in message formatted incorrectly
334 """
335
336 pos = physical_line.find(SKIP_DECORATOR)
337
338 skip_re = re.compile(r'^\s*@testtools.skip.*')
339
340 if pos != -1 and skip_re.match(physical_line):
341 bug = re.compile(r'^.*\bbug\b.*', re.IGNORECASE)
342 if bug.match(physical_line) is None:
343 return (pos, 'T601: skips must have an associated bug')
344
345 bug_re = re.compile(r'.*skip\(.*Bug\s\#\d+', re.IGNORECASE)
346
347 if bug_re.match(physical_line) is None:
348 return (pos, 'T602: Bug number formatted incorrectly')
349
Sean Dague97449cc2013-01-04 14:38:26 -0500350
Matthew Treinish8b372892012-12-07 17:13:16 -0500351FORMAT_RE = re.compile("%(?:"
352 "%|" # Ignore plain percents
353 "(\(\w+\))?" # mapping key
354 "([#0 +-]?" # flag
355 "(?:\d+|\*)?" # width
356 "(?:\.\d+)?" # precision
357 "[hlL]?" # length mod
358 "\w))") # type
359
360
361class LocalizationError(Exception):
362 pass
363
364
365def check_i18n():
366 """Generator that checks token stream for localization errors.
367
368 Expects tokens to be ``send``ed one by one.
369 Raises LocalizationError if some error is found.
370 """
371 while True:
372 try:
373 token_type, text, _, _, line = yield
374 except GeneratorExit:
375 return
376 if (token_type == tokenize.NAME and text == "_" and
377 not line.startswith('def _(msg):')):
378
379 while True:
380 token_type, text, start, _, _ = yield
381 if token_type != tokenize.NL:
382 break
383 if token_type != tokenize.OP or text != "(":
384 continue # not a localization call
385
386 format_string = ''
387 while True:
388 token_type, text, start, _, _ = yield
389 if token_type == tokenize.STRING:
390 format_string += eval(text)
391 elif token_type == tokenize.NL:
392 pass
393 else:
394 break
395
396 if not format_string:
397 raise LocalizationError(start,
Sean Dagued18cfe52013-01-04 14:53:00 -0500398 "T701: Empty localization "
Matthew Treinish8b372892012-12-07 17:13:16 -0500399 "string")
400 if token_type != tokenize.OP:
401 raise LocalizationError(start,
Sean Dagued18cfe52013-01-04 14:53:00 -0500402 "T701: Invalid localization "
Matthew Treinish8b372892012-12-07 17:13:16 -0500403 "call")
404 if text != ")":
405 if text == "%":
406 raise LocalizationError(start,
Sean Dagued18cfe52013-01-04 14:53:00 -0500407 "T702: Formatting "
Matthew Treinish8b372892012-12-07 17:13:16 -0500408 "operation should be outside"
409 " of localization method call")
410 elif text == "+":
411 raise LocalizationError(start,
Sean Dagued18cfe52013-01-04 14:53:00 -0500412 "T702: Use bare string "
Matthew Treinish8b372892012-12-07 17:13:16 -0500413 "concatenation instead of +")
414 else:
415 raise LocalizationError(start,
Sean Dagued18cfe52013-01-04 14:53:00 -0500416 "T702: Argument to _ must"
Matthew Treinish8b372892012-12-07 17:13:16 -0500417 " be just a string")
418
419 format_specs = FORMAT_RE.findall(format_string)
420 positional_specs = [(key, spec) for key, spec in format_specs
421 if not key and spec]
422 # not spec means %%, key means %(smth)s
423 if len(positional_specs) > 1:
424 raise LocalizationError(start,
Sean Dagued18cfe52013-01-04 14:53:00 -0500425 "T703: Multiple positional "
Matthew Treinish8b372892012-12-07 17:13:16 -0500426 "placeholders")
427
428
429def tempest_localization_strings(logical_line, tokens):
430 """Check localization in line.
431
Sean Dagued18cfe52013-01-04 14:53:00 -0500432 T701: bad localization call
433 T702: complex expression instead of string as argument to _()
434 T703: multiple positional placeholders
Matthew Treinish8b372892012-12-07 17:13:16 -0500435 """
436
437 gen = check_i18n()
438 next(gen)
439 try:
440 map(gen.send, tokens)
441 gen.close()
442 except LocalizationError as e:
443 yield e.args
444
445#TODO(jogo) Dict and list objects
446
447current_file = ""
448
449
450def readlines(filename):
451 """Record the current file being tested."""
452 pep8.current_file = filename
453 return open(filename).readlines()
454
455
456def add_tempest():
457 """Monkey patch in tempest guidelines.
458
459 Look for functions that start with tempest_ and have arguments
460 and add them to pep8 module
461 Assumes you know how to write pep8.py checks
462 """
463 for name, function in globals().items():
464 if not inspect.isfunction(function):
465 continue
466 args = inspect.getargspec(function)[0]
467 if args and name.startswith("tempest"):
468 exec("pep8.%s = %s" % (name, name))
469
470
471def once_git_check_commit_title():
472 """Check git commit messages.
473
474 tempest HACKING recommends not referencing a bug or blueprint
475 in first line, it should provide an accurate description of the change
Sean Dagued18cfe52013-01-04 14:53:00 -0500476 T801
477 T802 Title limited to 50 chars
Matthew Treinish8b372892012-12-07 17:13:16 -0500478 """
479 #Get title of most recent commit
480
481 subp = subprocess.Popen(['git', 'log', '--no-merges', '--pretty=%s', '-1'],
482 stdout=subprocess.PIPE)
483 title = subp.communicate()[0]
484 if subp.returncode:
485 raise Exception("git log failed with code %s" % subp.returncode)
486
487 #From https://github.com/openstack/openstack-ci-puppet
488 # /blob/master/modules/gerrit/manifests/init.pp#L74
489 #Changeid|bug|blueprint
490 git_keywords = (r'(I[0-9a-f]{8,40})|'
491 '([Bb]ug|[Ll][Pp])[\s\#:]*(\d+)|'
492 '([Bb]lue[Pp]rint|[Bb][Pp])[\s\#:]*([A-Za-z0-9\\-]+)')
493 GIT_REGEX = re.compile(git_keywords)
494
495 error = False
496 #NOTE(jogo) if match regex but over 3 words, acceptable title
497 if GIT_REGEX.search(title) is not None and len(title.split()) <= 3:
Sean Dagued18cfe52013-01-04 14:53:00 -0500498 print ("T801: git commit title ('%s') should provide an accurate "
Matthew Treinish8b372892012-12-07 17:13:16 -0500499 "description of the change, not just a reference to a bug "
500 "or blueprint" % title.strip())
501 error = True
502 if len(title.decode('utf-8')) > 72:
Sean Dagued18cfe52013-01-04 14:53:00 -0500503 print ("T802: git commit title ('%s') should be under 50 chars"
Matthew Treinish8b372892012-12-07 17:13:16 -0500504 % title.strip())
505 error = True
506 return error
507
508if __name__ == "__main__":
509 #include tempest path
510 sys.path.append(os.getcwd())
511 #Run once tests (not per line)
512 once_error = once_git_check_commit_title()
Sean Dagued18cfe52013-01-04 14:53:00 -0500513 #TEMPEST error codes start with a T
514 pep8.ERRORCODE_REGEX = re.compile(r'[EWT]\d{3}')
Matthew Treinish8b372892012-12-07 17:13:16 -0500515 add_tempest()
516 pep8.current_file = current_file
517 pep8.readlines = readlines
518 pep8.StyleGuide.excluded = excluded
519 pep8.StyleGuide.input_dir = input_dir
520 try:
521 pep8._main()
522 sys.exit(once_error)
523 finally:
524 if len(_missingImport) > 0:
525 print >> sys.stderr, ("%i imports missing in this test environment"
526 % len(_missingImport))