~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_source.py

  • Committer: INADA Naoki
  • Date: 2011-05-05 09:15:34 UTC
  • mto: (5830.3.3 i18n-msgfmt)
  • mto: This revision was merged to the branch mainline in revision 5873.
  • Revision ID: songofacandy@gmail.com-20110505091534-7sv835xpofwrmpt4
Add update-pot command to Makefile and tools/bzrgettext script that
extracts help text from bzr commands.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005, 2006 Canonical Ltd
2
 
#   Authors: Robert Collins <robert.collins@canonical.com>
 
1
# Copyright (C) 2005-2010 Canonical Ltd
3
2
#
4
3
# This program is free software; you can redistribute it and/or modify
5
4
# it under the terms of the GNU General Public License as published by
13
12
#
14
13
# You should have received a copy of the GNU General Public License
15
14
# along with this program; if not, write to the Free Software
16
 
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17
16
 
18
17
"""These tests are tests about the source code of bzrlib itself.
19
18
 
22
21
 
23
22
# import system imports here
24
23
import os
 
24
import parser
25
25
import re
 
26
import symbol
26
27
import sys
 
28
import token
27
29
 
28
30
#import bzrlib specific imports here
29
31
from bzrlib import (
30
32
    osutils,
31
33
    )
32
34
import bzrlib.branch
33
 
from bzrlib.tests import TestCase, TestSkipped
 
35
from bzrlib.tests import (
 
36
    TestCase,
 
37
    TestSkipped,
 
38
    )
34
39
 
35
40
 
36
41
# Files which are listed here will be skipped when testing for Copyright (or
37
42
# GPL) statements.
38
 
COPYRIGHT_EXCEPTIONS = ['bzrlib/lsprof.py']
 
43
COPYRIGHT_EXCEPTIONS = [
 
44
    'bzrlib/_bencode_py.py',
 
45
    'bzrlib/doc_generate/conf.py',
 
46
    'bzrlib/lsprof.py',
 
47
    ]
39
48
 
40
 
LICENSE_EXCEPTIONS = ['bzrlib/lsprof.py']
 
49
LICENSE_EXCEPTIONS = [
 
50
    'bzrlib/_bencode_py.py',
 
51
    'bzrlib/doc_generate/conf.py',
 
52
    'bzrlib/lsprof.py',
 
53
    ]
41
54
# Technically, 'bzrlib/lsprof.py' should be 'bzrlib/util/lsprof.py',
42
55
# (we do not check bzrlib/util/, since that is code bundled from elsewhere)
43
56
# but for compatibility with previous releases, we don't want to move it.
 
57
#
 
58
# sphinx_conf is semi-autogenerated.
44
59
 
45
60
 
46
61
class TestSourceHelper(TestCase):
47
62
 
48
63
    def source_file_name(self, package):
49
64
        """Return the path of the .py file for package."""
 
65
        if getattr(sys, "frozen", None) is not None:
 
66
            raise TestSkipped("can't test sources in frozen distributions.")
50
67
        path = package.__file__
51
68
        if path[-1] in 'co':
52
69
            return path[:-1]
72
89
        # do not even think of increasing this number. If you think you need to
73
90
        # increase it, then you almost certainly are doing something wrong as
74
91
        # the relationship from working_tree to branch is one way.
75
 
        # Note that this is an exact equality so that when the number drops, 
 
92
        # Note that this is an exact equality so that when the number drops,
76
93
        #it is not given a buffer but rather has this test updated immediately.
77
94
        self.assertEqual(0, occurences)
78
95
 
80
97
        """Test that the number of uses of working_tree in branch is stable."""
81
98
        occurences = self.find_occurences('WorkingTree',
82
99
                                          self.source_file_name(bzrlib.branch))
83
 
        # do not even think of increasing this number. If you think you need to
 
100
        # Do not even think of increasing this number. If you think you need to
84
101
        # increase it, then you almost certainly are doing something wrong as
85
102
        # the relationship from working_tree to branch is one way.
86
 
        # This number should be 4 (import NoWorkingTree and WorkingTree, 
87
 
        # raise NoWorkingTree from working_tree(), and construct a working tree
88
 
        # there) but a merge that regressed this was done before this test was
89
 
        # written. Note that this is an exact equality so that when the number
90
 
        # drops, it is not given a buffer but rather this test updated
91
 
        # immediately.
92
 
        self.assertEqual(2, occurences)
 
103
        # As of 20070809, there are no longer any mentions at all.
 
104
        self.assertEqual(0, occurences)
93
105
 
94
106
 
95
107
class TestSource(TestSourceHelper):
105
117
                              % source_dir)
106
118
        return source_dir
107
119
 
108
 
    def get_source_files(self):
109
 
        """yield all source files for bzr and bzrlib"""
 
120
    def get_source_files(self, extensions=None):
 
121
        """Yield all source files for bzr and bzrlib
 
122
 
 
123
        :param our_files_only: If true, exclude files from included libraries
 
124
            or plugins.
 
125
        """
110
126
        bzrlib_dir = self.get_bzrlib_dir()
 
127
        if extensions is None:
 
128
            extensions = ('.py',)
111
129
 
112
130
        # This is the front-end 'bzr' script
113
131
        bzr_path = self.get_bzr_path()
118
136
                if d.endswith('.tmp'):
119
137
                    dirs.remove(d)
120
138
            for f in files:
121
 
                if not f.endswith('.py'):
 
139
                for extension in extensions:
 
140
                    if f.endswith(extension):
 
141
                        break
 
142
                else:
 
143
                    # Did not match the accepted extensions
122
144
                    continue
123
145
                yield osutils.pathjoin(root, f)
124
146
 
125
 
    def get_source_file_contents(self):
126
 
        for fname in self.get_source_files():
 
147
    def get_source_file_contents(self, extensions=None):
 
148
        for fname in self.get_source_files(extensions=extensions):
127
149
            f = open(fname, 'rb')
128
150
            try:
129
151
                text = f.read()
131
153
                f.close()
132
154
            yield fname, text
133
155
 
 
156
    def is_our_code(self, fname):
 
157
        """Return true if it's a "real" part of bzrlib rather than external code"""
 
158
        if '/util/' in fname or '/plugins/' in fname:
 
159
            return False
 
160
        else:
 
161
            return True
 
162
 
134
163
    def is_copyright_exception(self, fname):
135
164
        """Certain files are allowed to be different"""
136
 
        if '/util/' in fname or '/plugins/' in fname:
 
165
        if not self.is_our_code(fname):
137
166
            # We don't ask that external utilities or plugins be
138
167
            # (C) Canonical Ltd
139
168
            return True
140
 
 
141
169
        for exc in COPYRIGHT_EXCEPTIONS:
142
170
            if fname.endswith(exc):
143
171
                return True
144
 
 
145
172
        return False
146
173
 
147
174
    def is_license_exception(self, fname):
148
175
        """Certain files are allowed to be different"""
149
 
        if '/util/' in fname or '/plugins/' in fname:
150
 
            # We don't ask that external utilities or plugins be
151
 
            # (C) Canonical Ltd
 
176
        if not self.is_our_code(fname):
152
177
            return True
153
 
 
154
178
        for exc in LICENSE_EXCEPTIONS:
155
179
            if fname.endswith(exc):
156
180
                return True
157
 
 
158
181
        return False
159
182
 
160
183
    def test_tmpdir_not_in_source_files(self):
166
189
                          % filename)
167
190
 
168
191
    def test_copyright(self):
169
 
        """Test that all .py files have a valid copyright statement"""
170
 
        # These are files which contain a different copyright statement
171
 
        # and that is okay.
 
192
        """Test that all .py and .pyx files have a valid copyright statement"""
172
193
        incorrect = []
173
194
 
174
195
        copyright_re = re.compile('#\\s*copyright.*(?=\n)', re.I)
178
199
            r'.*Canonical Ltd' # And containing 'Canonical Ltd'
179
200
            )
180
201
 
181
 
        for fname, text in self.get_source_file_contents():
 
202
        for fname, text in self.get_source_file_contents(
 
203
                extensions=('.py', '.pyx')):
182
204
            if self.is_copyright_exception(fname):
183
205
                continue
184
206
            match = copyright_canonical_re.search(text)
203
225
                         " bzrlib/tests/test_source.py",
204
226
                         # this is broken to prevent a false match
205
227
                         "or add '# Copyright (C)"
206
 
                         " 2006 Canonical Ltd' to these files:",
 
228
                         " 2007 Canonical Ltd' to these files:",
207
229
                         "",
208
230
                        ]
209
231
            for fname, comment in incorrect:
213
235
            self.fail('\n'.join(help_text))
214
236
 
215
237
    def test_gpl(self):
216
 
        """Test that all .py files have a GPL disclaimer"""
 
238
        """Test that all .py and .pyx files have a GPL disclaimer."""
217
239
        incorrect = []
218
240
 
219
241
        gpl_txt = """
229
251
#
230
252
# You should have received a copy of the GNU General Public License
231
253
# along with this program; if not, write to the Free Software
232
 
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
254
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
233
255
"""
234
256
        gpl_re = re.compile(re.escape(gpl_txt), re.MULTILINE)
235
257
 
236
 
        for fname, text in self.get_source_file_contents():
 
258
        for fname, text in self.get_source_file_contents(
 
259
                extensions=('.py', '.pyx')):
237
260
            if self.is_license_exception(fname):
238
261
                continue
239
262
            if not gpl_re.search(text):
253
276
 
254
277
            self.fail('\n'.join(help_text))
255
278
 
256
 
    def test_no_tabs(self):
257
 
        """bzrlib source files should not contain any tab characters."""
258
 
        incorrect = []
259
 
 
 
279
    def _push_file(self, dict_, fname, line_no):
 
280
        if fname not in dict_:
 
281
            dict_[fname] = [line_no]
 
282
        else:
 
283
            dict_[fname].append(line_no)
 
284
 
 
285
    def _format_message(self, dict_, message):
 
286
        files = ["%s: %s" % (f, ', '.join([str(i+1) for i in lines]))
 
287
                for f, lines in dict_.items()]
 
288
        files.sort()
 
289
        return message + '\n\n    %s' % ('\n    '.join(files))
 
290
 
 
291
    def test_coding_style(self):
 
292
        """Check if bazaar code conforms to some coding style conventions.
 
293
 
 
294
        Currently we assert that the following is not present:
 
295
         * any tab characters
 
296
         * non-unix newlines
 
297
         * no newline at end of files
 
298
 
 
299
        Print how many files have
 
300
         * trailing white space
 
301
         * lines longer than 79 chars
 
302
        """
 
303
        tabs = {}
 
304
        trailing_ws = {}
 
305
        illegal_newlines = {}
 
306
        long_lines = {}
 
307
        no_newline_at_eof = []
 
308
        for fname, text in self.get_source_file_contents(
 
309
                extensions=('.py', '.pyx')):
 
310
            if not self.is_our_code(fname):
 
311
                continue
 
312
            lines = text.splitlines(True)
 
313
            last_line_no = len(lines) - 1
 
314
            for line_no, line in enumerate(lines):
 
315
                if '\t' in line:
 
316
                    self._push_file(tabs, fname, line_no)
 
317
                if not line.endswith('\n') or line.endswith('\r\n'):
 
318
                    if line_no != last_line_no: # not no_newline_at_eof
 
319
                        self._push_file(illegal_newlines, fname, line_no)
 
320
                if line.endswith(' \n'):
 
321
                    self._push_file(trailing_ws, fname, line_no)
 
322
                if len(line) > 80:
 
323
                    self._push_file(long_lines, fname, line_no)
 
324
            if not lines[-1].endswith('\n'):
 
325
                no_newline_at_eof.append(fname)
 
326
        problems = []
 
327
        if tabs:
 
328
            problems.append(self._format_message(tabs,
 
329
                'Tab characters were found in the following source files.'
 
330
                '\nThey should either be replaced by "\\t" or by spaces:'))
 
331
        if trailing_ws:
 
332
            print ("There are %i lines with trailing white space in %i files."
 
333
                % (sum([len(lines) for f, lines in trailing_ws.items()]),
 
334
                    len(trailing_ws)))
 
335
        if illegal_newlines:
 
336
            problems.append(self._format_message(illegal_newlines,
 
337
                'Non-unix newlines were found in the following source files:'))
 
338
        if long_lines:
 
339
            print ("There are %i lines longer than 79 characters in %i files."
 
340
                % (sum([len(lines) for f, lines in long_lines.items()]),
 
341
                    len(long_lines)))
 
342
        if no_newline_at_eof:
 
343
            no_newline_at_eof.sort()
 
344
            problems.append("The following source files doesn't have a "
 
345
                "newline at the end:"
 
346
               '\n\n    %s'
 
347
               % ('\n    '.join(no_newline_at_eof)))
 
348
        if problems:
 
349
            self.fail('\n\n'.join(problems))
 
350
 
 
351
    def test_no_asserts(self):
 
352
        """bzr shouldn't use the 'assert' statement."""
 
353
        # assert causes too much variation between -O and not, and tends to
 
354
        # give bad errors to the user
 
355
        def search(x):
 
356
            # scan down through x for assert statements, report any problems
 
357
            # this is a bit cheesy; it may get some false positives?
 
358
            if x[0] == symbol.assert_stmt:
 
359
                return True
 
360
            elif x[0] == token.NAME:
 
361
                # can't search further down
 
362
                return False
 
363
            for sub in x[1:]:
 
364
                if sub and search(sub):
 
365
                    return True
 
366
            return False
 
367
        badfiles = []
 
368
        assert_re = re.compile(r'\bassert\b')
260
369
        for fname, text in self.get_source_file_contents():
261
 
            if '/util/' in fname or '/plugins/' in fname:
262
 
                continue
263
 
            if '\t' in text:
264
 
                incorrect.append(fname)
265
 
 
266
 
        if incorrect:
267
 
            self.fail('Tab characters were found in the following source files.'
268
 
              '\nThey should either be replaced by "\\t" or by spaces:'
269
 
              '\n\n    %s'
270
 
              % ('\n    '.join(incorrect)))
 
370
            if not self.is_our_code(fname):
 
371
                continue
 
372
            if not assert_re.search(text):
 
373
                continue
 
374
            ast = parser.ast2tuple(parser.suite(text))
 
375
            if search(ast):
 
376
                badfiles.append(fname)
 
377
        if badfiles:
 
378
            self.fail(
 
379
                "these files contain an assert statement and should not:\n%s"
 
380
                % '\n'.join(badfiles))
 
381
 
 
382
    def test_extension_exceptions(self):
 
383
        """Extension functions should propagate exceptions.
 
384
 
 
385
        Either they should return an object, have an 'except' clause, or have a
 
386
        "# cannot_raise" to indicate that we've audited them and defined them as not
 
387
        raising exceptions.
 
388
        """
 
389
        both_exc_and_no_exc = []
 
390
        missing_except = []
 
391
        class_re = re.compile(r'^(cdef\s+)?(public\s+)?'
 
392
                              r'(api\s+)?class (\w+).*:', re.MULTILINE)
 
393
        extern_class_re = re.compile(r'## extern cdef class (\w+)',
 
394
                                     re.MULTILINE)
 
395
        except_re = re.compile(r'cdef\s+' # start with cdef
 
396
                               r'([\w *]*?)\s*' # this is the return signature
 
397
                               r'(\w+)\s*\(' # the function name
 
398
                               r'[^)]*\)\s*' # parameters
 
399
                               r'(.*)\s*:' # the except clause
 
400
                               r'\s*(#\s*cannot[- _]raise)?' # cannot raise comment
 
401
                              )
 
402
        for fname, text in self.get_source_file_contents(
 
403
                extensions=('.pyx',)):
 
404
            known_classes = set([m[-1] for m in class_re.findall(text)])
 
405
            known_classes.update(extern_class_re.findall(text))
 
406
            cdefs = except_re.findall(text)
 
407
            for sig, func, exc_clause, no_exc_comment in cdefs:
 
408
                if sig.startswith('api '):
 
409
                    sig = sig[4:]
 
410
                if not sig or sig in known_classes:
 
411
                    sig = 'object'
 
412
                if 'nogil' in exc_clause:
 
413
                    exc_clause = exc_clause.replace('nogil', '').strip()
 
414
                if exc_clause and no_exc_comment:
 
415
                    both_exc_and_no_exc.append((fname, func))
 
416
                if sig != 'object' and not (exc_clause or no_exc_comment):
 
417
                    missing_except.append((fname, func))
 
418
        error_msg = []
 
419
        if both_exc_and_no_exc:
 
420
            error_msg.append('The following functions had "cannot raise" comments'
 
421
                             ' but did have an except clause set:')
 
422
            for fname, func in both_exc_and_no_exc:
 
423
                error_msg.append('%s:%s' % (fname, func))
 
424
            error_msg.extend(('', ''))
 
425
        if missing_except:
 
426
            error_msg.append('The following functions have fixed return types,'
 
427
                             ' but no except clause.')
 
428
            error_msg.append('Either add an except or append "# cannot_raise".')
 
429
            for fname, func in missing_except:
 
430
                error_msg.append('%s:%s' % (fname, func))
 
431
            error_msg.extend(('', ''))
 
432
        if error_msg:
 
433
            self.fail('\n'.join(error_msg))