1
# Copyright (C) 2005-2011 Canonical Ltd
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
# GNU General Public License for more details.
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17
"""These tests are tests about the source code of breezy itself.
19
They are useful for testing code quality, checking coverage metric etc.
33
from breezy.tests import (
39
# Files which are listed here will be skipped when testing for Copyright (or
41
COPYRIGHT_EXCEPTIONS = [
42
'breezy/_bencode_py.py',
43
'breezy/doc_generate/conf.py',
47
LICENSE_EXCEPTIONS = [
48
'breezy/_bencode_py.py',
49
'breezy/doc_generate/conf.py',
52
# Technically, 'breezy/lsprof.py' should be 'breezy/util/lsprof.py',
53
# (we do not check breezy/util/, since that is code bundled from elsewhere)
54
# but for compatibility with previous releases, we don't want to move it.
56
# sphinx_conf is semi-autogenerated.
59
class TestSourceHelper(TestCase):
61
def source_file_name(self, package):
62
"""Return the path of the .py file for package."""
63
if getattr(sys, "frozen", None) is not None:
64
raise TestSkipped("can't test sources in frozen distributions.")
65
path = package.__file__
72
class TestApiUsage(TestSourceHelper):
74
def find_occurences(self, rule, filename):
75
"""Find the number of occurences of rule in a file."""
77
source = open(filename, 'r')
79
if line.find(rule) > -1:
83
def test_branch_working_tree(self):
84
"""Test that the number of uses of working_tree in branch is stable."""
85
occurences = self.find_occurences('self.working_tree()',
86
self.source_file_name(breezy.branch))
87
# do not even think of increasing this number. If you think you need to
88
# increase it, then you almost certainly are doing something wrong as
89
# the relationship from working_tree to branch is one way.
90
# Note that this is an exact equality so that when the number drops,
91
# it is not given a buffer but rather has this test updated immediately.
92
self.assertEqual(0, occurences)
94
def test_branch_WorkingTree(self):
95
"""Test that the number of uses of working_tree in branch is stable."""
96
occurences = self.find_occurences('WorkingTree',
97
self.source_file_name(breezy.branch))
98
# Do not even think of increasing this number. If you think you need to
99
# increase it, then you almost certainly are doing something wrong as
100
# the relationship from working_tree to branch is one way.
101
# As of 20070809, there are no longer any mentions at all.
102
self.assertEqual(0, occurences)
105
class TestSource(TestSourceHelper):
107
def get_breezy_dir(self):
108
"""Get the path to the root of breezy"""
109
source = self.source_file_name(breezy)
110
source_dir = os.path.dirname(source)
112
# Avoid the case when breezy is packaged in a zip file
113
if not os.path.isdir(source_dir):
115
'Cannot find breezy source directory. Expected %s'
119
def get_source_files(self, extensions=None):
120
"""Yield all source files for bzr and breezy
122
:param our_files_only: If true, exclude files from included libraries
125
breezy_dir = self.get_breezy_dir()
126
if extensions is None:
127
extensions = ('.py',)
129
# This is the front-end 'bzr' script
130
bzr_path = self.get_brz_path()
133
for root, dirs, files in os.walk(breezy_dir):
135
if d.endswith('.tmp'):
138
for extension in extensions:
139
if f.endswith(extension):
142
# Did not match the accepted extensions
144
yield osutils.pathjoin(root, f)
146
def get_source_file_contents(self, extensions=None):
147
for fname in self.get_source_files(extensions=extensions):
148
with open(fname, 'r') as f:
149
yield fname, f.read()
151
def is_our_code(self, fname):
152
"""True if it's a "real" part of breezy rather than external code"""
153
if '/util/' in fname or '/plugins/' in fname:
158
def is_copyright_exception(self, fname):
159
"""Certain files are allowed to be different"""
160
if not self.is_our_code(fname):
162
for exc in COPYRIGHT_EXCEPTIONS:
163
if fname.endswith(exc):
167
def is_license_exception(self, fname):
168
"""Certain files are allowed to be different"""
169
if not self.is_our_code(fname):
171
for exc in LICENSE_EXCEPTIONS:
172
if fname.endswith(exc):
176
def test_tmpdir_not_in_source_files(self):
177
"""When scanning for source files, we don't descend test tempdirs"""
178
for filename in self.get_source_files():
179
if re.search(r'test....\.tmp', filename):
180
self.fail("get_source_file() returned filename %r "
181
"from within a temporary directory"
184
def test_copyright(self):
185
"""Test that all .py and .pyx files have a valid copyright statement"""
188
copyright_re = re.compile('#\\s*copyright.*(?=\n)', re.I)
189
copyright_statement_re = re.compile(
190
r'# Copyright \(C\) ' # Opening "# Copyright (C)"
191
r'(\d+?)((, |-)\d+)*' # followed by a series of dates
192
r' [^ ]*') # and then whoever.
194
for fname, text in self.get_source_file_contents(
195
extensions=('.py', '.pyx')):
196
if self.is_copyright_exception(fname):
198
match = copyright_statement_re.search(text)
200
match = copyright_re.search(text)
202
incorrect.append((fname, 'found: %s' % (match.group(),)))
204
incorrect.append((fname, 'no copyright line found\n'))
206
if 'by Canonical' in match.group():
207
incorrect.append((fname,
208
'should not have: "by Canonical": %s'
212
help_text = ["Some files have missing or incorrect copyright"
215
"Please either add them to the list of"
216
" COPYRIGHT_EXCEPTIONS in"
217
" breezy/tests/test_source.py",
218
# this is broken to prevent a false match
219
"or add '# Copyright (C)"
220
" 2007 Bazaar hackers' to these files:",
223
for fname, comment in incorrect:
224
help_text.append(fname)
225
help_text.append((' ' * 4) + comment)
227
self.fail('\n'.join(help_text))
230
"""Test that all .py and .pyx files have a GPL disclaimer."""
234
# This program is free software; you can redistribute it and/or modify
235
# it under the terms of the GNU General Public License as published by
236
# the Free Software Foundation; either version 2 of the License, or
237
# (at your option) any later version.
239
# This program is distributed in the hope that it will be useful,
240
# but WITHOUT ANY WARRANTY; without even the implied warranty of
241
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
242
# GNU General Public License for more details.
244
# You should have received a copy of the GNU General Public License
245
# along with this program; if not, write to the Free Software
246
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
248
gpl_re = re.compile(re.escape(gpl_txt), re.MULTILINE)
250
for fname, text in self.get_source_file_contents(
251
extensions=('.py', '.pyx')):
252
if self.is_license_exception(fname):
254
if not gpl_re.search(text):
255
incorrect.append(fname)
258
help_text = ['Some files have missing or incomplete GPL statement',
260
"Please either add them to the list of"
261
" LICENSE_EXCEPTIONS in"
262
" breezy/tests/test_source.py",
263
"Or add the following text to the beginning:",
265
for fname in incorrect:
266
help_text.append((' ' * 4) + fname)
268
self.fail('\n'.join(help_text))
270
def _push_file(self, dict_, fname, line_no):
271
if fname not in dict_:
272
dict_[fname] = [line_no]
274
dict_[fname].append(line_no)
276
def _format_message(self, dict_, message):
277
files = sorted(["%s: %s" % (f, ', '.join([str(i + 1) for i in lines]))
278
for f, lines in dict_.items()])
279
return message + '\n\n %s' % ('\n '.join(files))
281
def test_coding_style(self):
282
"""Check if bazaar code conforms to some coding style conventions.
284
Generally we expect PEP8, but we do not generally strictly enforce
285
this, and there are existing files that do not comply. The 'pep8'
286
tool, available separately, will check for more cases.
288
This test only enforces conditions that are globally true at the
289
moment, and that should cause a patch to be rejected: spaces rather
290
than tabs, unix newlines, and a newline at the end of the file.
293
illegal_newlines = {}
294
no_newline_at_eof = []
295
for fname, text in self.get_source_file_contents(
296
extensions=('.py', '.pyx')):
297
if not self.is_our_code(fname):
299
lines = text.splitlines(True)
300
last_line_no = len(lines) - 1
301
for line_no, line in enumerate(lines):
303
self._push_file(tabs, fname, line_no)
304
if not line.endswith('\n') or line.endswith('\r\n'):
305
if line_no != last_line_no: # not no_newline_at_eof
306
self._push_file(illegal_newlines, fname, line_no)
307
if not lines[-1].endswith('\n'):
308
no_newline_at_eof.append(fname)
311
problems.append(self._format_message(tabs,
312
'Tab characters were found in the following source files.'
313
'\nThey should either be replaced by "\\t" or by spaces:'))
315
problems.append(self._format_message(illegal_newlines,
316
'Non-unix newlines were found in the following source files:'))
317
if no_newline_at_eof:
318
no_newline_at_eof.sort()
319
problems.append("The following source files doesn't have a "
320
"newline at the end:"
322
% ('\n '.join(no_newline_at_eof)))
324
self.fail('\n\n'.join(problems))
326
def test_no_asserts(self):
327
"""bzr shouldn't use the 'assert' statement."""
328
# assert causes too much variation between -O and not, and tends to
329
# give bad errors to the user
331
# scan down through x for assert statements, report any problems
332
# this is a bit cheesy; it may get some false positives?
333
if x[0] == symbol.assert_stmt:
335
elif x[0] == token.NAME:
336
# can't search further down
339
if sub and search(sub):
343
assert_re = re.compile(r'\bassert\b')
344
for fname, text in self.get_source_file_contents():
345
if not self.is_our_code(fname):
347
if not assert_re.search(text):
349
st = parser.suite(text)
350
code = parser.st2tuple(st)
352
badfiles.append(fname)
355
"these files contain an assert statement and should not:\n%s"
356
% '\n'.join(badfiles))
358
def test_extension_exceptions(self):
359
"""Extension functions should propagate exceptions.
361
Either they should return an object, have an 'except' clause, or
362
have a "# cannot_raise" to indicate that we've audited them and
363
defined them as not raising exceptions.
365
both_exc_and_no_exc = []
367
common_classes = ('StaticTuple',)
368
class_re = re.compile(r'^(cdef\s+)?(public\s+)?'
369
r'(api\s+)?class (\w+).*:', re.MULTILINE)
370
except_re = re.compile(
371
r'cdef\s+' # start with cdef
372
r'([\w *]*?)\s*' # this is the return signature
373
r'(\w+)\s*\(' # the function name
374
r'[^)]*\)\s*' # parameters
375
r'(.*)\s*:' # the except clause
376
r'\s*(#\s*cannot[- _]raise)?') # cannot raise comment
377
for fname, text in self.get_source_file_contents(
378
extensions=('.pyx',)):
379
known_classes = {m[-1] for m in class_re.findall(text)}
380
known_classes.update(common_classes)
381
cdefs = except_re.findall(text)
382
for sig, func, exc_clause, no_exc_comment in cdefs:
383
if sig.startswith('api '):
385
if not sig or sig in known_classes:
387
if 'nogil' in exc_clause:
388
exc_clause = exc_clause.replace('nogil', '').strip()
389
if exc_clause and no_exc_comment:
390
both_exc_and_no_exc.append((fname, func))
391
if sig != 'object' and not (exc_clause or no_exc_comment):
392
missing_except.append((fname, func))
394
if both_exc_and_no_exc:
396
'The following functions had "cannot raise" comments'
397
' but did have an except clause set:')
398
for fname, func in both_exc_and_no_exc:
399
error_msg.append('%s:%s' % (fname, func))
400
error_msg.extend(('', ''))
403
'The following functions have fixed return types,'
404
' but no except clause.')
406
'Either add an except or append "# cannot_raise".')
407
for fname, func in missing_except:
408
error_msg.append('%s:%s' % (fname, func))
409
error_msg.extend(('', ''))
411
self.fail('\n'.join(error_msg))
413
def test_feature_absolute_import(self):
414
"""Using absolute imports means avoiding unnecesary stat and
417
Make sure that all non-test files have absolute imports enabled.
419
missing_absolute_import = []
420
for fname, text in self.get_source_file_contents(
421
extensions=('.py', '.pyx')):
422
if "/tests/" in fname or "test_" in fname:
423
# We don't really care about tests
425
if "from __future__ import absolute_import" not in text:
426
missing_absolute_import.append(fname)
428
if missing_absolute_import:
430
'The following files do not have absolute_import enabled:\n'
431
'\n' + '\n'.join(missing_absolute_import))