~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_source.py

  • Committer: John Arbash Meinel
  • Date: 2007-07-13 02:23:34 UTC
  • mfrom: (2592 +trunk) (2612 +trunk)
  • mto: This revision was merged to the branch mainline in revision 2614.
  • Revision ID: john@arbash-meinel.com-20070713022334-qb6ewgo6v4251yd9
[merge] bzr.dev 2612

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005, 2006, 2008 Canonical Ltd
 
1
# Copyright (C) 2005, 2006 Canonical Ltd
2
2
#   Authors: Robert Collins <robert.collins@canonical.com>
3
 
#            and others
4
3
#
5
4
# This program is free software; you can redistribute it and/or modify
6
5
# it under the terms of the GNU General Public License as published by
14
13
#
15
14
# You should have received a copy of the GNU General Public License
16
15
# along with this program; if not, write to the Free Software
17
 
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
16
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18
17
 
19
18
"""These tests are tests about the source code of bzrlib itself.
20
19
 
23
22
 
24
23
# import system imports here
25
24
import os
26
 
import parser
27
25
import re
28
 
import symbol
29
26
import sys
30
 
import token
31
27
 
32
28
#import bzrlib specific imports here
33
29
from bzrlib import (
34
30
    osutils,
35
31
    )
36
32
import bzrlib.branch
37
 
from bzrlib.tests import (
38
 
    KnownFailure,
39
 
    TestCase,
40
 
    TestSkipped,
41
 
    )
 
33
from bzrlib.tests import TestCase, TestSkipped
42
34
 
43
35
 
44
36
# Files which are listed here will be skipped when testing for Copyright (or
55
47
 
56
48
    def source_file_name(self, package):
57
49
        """Return the path of the .py file for package."""
58
 
        if getattr(sys, "frozen", None) is not None:
59
 
            raise TestSkipped("can't test sources in frozen distributions.")
60
50
        path = package.__file__
61
51
        if path[-1] in 'co':
62
52
            return path[:-1]
82
72
        # do not even think of increasing this number. If you think you need to
83
73
        # increase it, then you almost certainly are doing something wrong as
84
74
        # the relationship from working_tree to branch is one way.
85
 
        # Note that this is an exact equality so that when the number drops,
 
75
        # Note that this is an exact equality so that when the number drops, 
86
76
        #it is not given a buffer but rather has this test updated immediately.
87
77
        self.assertEqual(0, occurences)
88
78
 
90
80
        """Test that the number of uses of working_tree in branch is stable."""
91
81
        occurences = self.find_occurences('WorkingTree',
92
82
                                          self.source_file_name(bzrlib.branch))
93
 
        # Do not even think of increasing this number. If you think you need to
 
83
        # do not even think of increasing this number. If you think you need to
94
84
        # increase it, then you almost certainly are doing something wrong as
95
85
        # the relationship from working_tree to branch is one way.
96
 
        # As of 20070809, there are no longer any mentions at all.
97
 
        self.assertEqual(0, occurences)
 
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)
98
93
 
99
94
 
100
95
class TestSource(TestSourceHelper):
110
105
                              % source_dir)
111
106
        return source_dir
112
107
 
113
 
    def get_source_files(self, extensions=None):
114
 
        """Yield all source files for bzr and bzrlib
115
 
 
116
 
        :param our_files_only: If true, exclude files from included libraries
117
 
            or plugins.
118
 
        """
 
108
    def get_source_files(self):
 
109
        """yield all source files for bzr and bzrlib"""
119
110
        bzrlib_dir = self.get_bzrlib_dir()
120
 
        if extensions is None:
121
 
            extensions = ('.py',)
122
111
 
123
112
        # This is the front-end 'bzr' script
124
113
        bzr_path = self.get_bzr_path()
129
118
                if d.endswith('.tmp'):
130
119
                    dirs.remove(d)
131
120
            for f in files:
132
 
                for extension in extensions:
133
 
                    if f.endswith(extension):
134
 
                        break
135
 
                else:
136
 
                    # Did not match the accepted extensions
 
121
                if not f.endswith('.py'):
137
122
                    continue
138
123
                yield osutils.pathjoin(root, f)
139
124
 
140
 
    def get_source_file_contents(self, extensions=None):
141
 
        for fname in self.get_source_files(extensions=extensions):
 
125
    def get_source_file_contents(self):
 
126
        for fname in self.get_source_files():
142
127
            f = open(fname, 'rb')
143
128
            try:
144
129
                text = f.read()
146
131
                f.close()
147
132
            yield fname, text
148
133
 
149
 
    def is_our_code(self, fname):
150
 
        """Return true if it's a "real" part of bzrlib rather than external code"""
151
 
        if '/util/' in fname or '/plugins/' in fname:
152
 
            return False
153
 
        else:
154
 
            return True
155
 
 
156
134
    def is_copyright_exception(self, fname):
157
135
        """Certain files are allowed to be different"""
158
 
        if not self.is_our_code(fname):
 
136
        if '/util/' in fname or '/plugins/' in fname:
159
137
            # We don't ask that external utilities or plugins be
160
138
            # (C) Canonical Ltd
161
139
            return True
 
140
 
162
141
        for exc in COPYRIGHT_EXCEPTIONS:
163
142
            if fname.endswith(exc):
164
143
                return True
 
144
 
165
145
        return False
166
146
 
167
147
    def is_license_exception(self, fname):
168
148
        """Certain files are allowed to be different"""
169
 
        if not self.is_our_code(fname):
 
149
        if '/util/' in fname or '/plugins/' in fname:
 
150
            # We don't ask that external utilities or plugins be
 
151
            # (C) Canonical Ltd
170
152
            return True
 
153
 
171
154
        for exc in LICENSE_EXCEPTIONS:
172
155
            if fname.endswith(exc):
173
156
                return True
 
157
 
174
158
        return False
175
159
 
176
160
    def test_tmpdir_not_in_source_files(self):
182
166
                          % filename)
183
167
 
184
168
    def test_copyright(self):
185
 
        """Test that all .py and .pyx files have a valid copyright statement"""
 
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.
186
172
        incorrect = []
187
173
 
188
174
        copyright_re = re.compile('#\\s*copyright.*(?=\n)', re.I)
192
178
            r'.*Canonical Ltd' # And containing 'Canonical Ltd'
193
179
            )
194
180
 
195
 
        for fname, text in self.get_source_file_contents(
196
 
                extensions=('.py', '.pyx')):
 
181
        for fname, text in self.get_source_file_contents():
197
182
            if self.is_copyright_exception(fname):
198
183
                continue
199
184
            match = copyright_canonical_re.search(text)
218
203
                         " bzrlib/tests/test_source.py",
219
204
                         # this is broken to prevent a false match
220
205
                         "or add '# Copyright (C)"
221
 
                         " 2007 Canonical Ltd' to these files:",
 
206
                         " 2006 Canonical Ltd' to these files:",
222
207
                         "",
223
208
                        ]
224
209
            for fname, comment in incorrect:
228
213
            self.fail('\n'.join(help_text))
229
214
 
230
215
    def test_gpl(self):
231
 
        """Test that all .py and .pyx files have a GPL disclaimer."""
 
216
        """Test that all .py files have a GPL disclaimer"""
232
217
        incorrect = []
233
218
 
234
219
        gpl_txt = """
244
229
#
245
230
# You should have received a copy of the GNU General Public License
246
231
# along with this program; if not, write to the Free Software
247
 
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
232
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
248
233
"""
249
234
        gpl_re = re.compile(re.escape(gpl_txt), re.MULTILINE)
250
235
 
251
 
        for fname, text in self.get_source_file_contents(
252
 
                extensions=('.py', '.pyx')):
 
236
        for fname, text in self.get_source_file_contents():
253
237
            if self.is_license_exception(fname):
254
238
                continue
255
239
            if not gpl_re.search(text):
269
253
 
270
254
            self.fail('\n'.join(help_text))
271
255
 
272
 
    def _push_file(self, dict_, fname, line_no):
273
 
        if fname not in dict_:
274
 
            dict_[fname] = [line_no]
275
 
        else:
276
 
            dict_[fname].append(line_no)
277
 
 
278
 
    def _format_message(self, dict_, message):
279
 
        files = ["%s: %s" % (f, ', '.join([str(i+1) for i in lines]))
280
 
                for f, lines in dict_.items()]
281
 
        files.sort()
282
 
        return message + '\n\n    %s' % ('\n    '.join(files))
283
 
 
284
 
    def test_coding_style(self):
285
 
        """Check if bazaar code conforms to some coding style conventions.
286
 
 
287
 
        Currently we check for:
288
 
         * any tab characters
289
 
         * trailing white space
290
 
         * non-unix newlines
291
 
         * no newline at end of files
292
 
         * lines longer than 79 chars
293
 
           (only print how many files and lines are in violation)
294
 
        """
295
 
        tabs = {}
296
 
        trailing_ws = {}
297
 
        illegal_newlines = {}
298
 
        long_lines = {}
299
 
        no_newline_at_eof = []
300
 
        for fname, text in self.get_source_file_contents(
301
 
                extensions=('.py', '.pyx')):
302
 
            if not self.is_our_code(fname):
303
 
                continue
304
 
            lines = text.splitlines(True)
305
 
            last_line_no = len(lines) - 1
306
 
            for line_no, line in enumerate(lines):
307
 
                if '\t' in line:
308
 
                    self._push_file(tabs, fname, line_no)
309
 
                if not line.endswith('\n') or line.endswith('\r\n'):
310
 
                    if line_no != last_line_no: # not no_newline_at_eof
311
 
                        self._push_file(illegal_newlines, fname, line_no)
312
 
                if line.endswith(' \n'):
313
 
                    self._push_file(trailing_ws, fname, line_no)
314
 
                if len(line) > 80:
315
 
                    self._push_file(long_lines, fname, line_no)
316
 
            if not lines[-1].endswith('\n'):
317
 
                no_newline_at_eof.append(fname)
318
 
        problems = []
319
 
        if tabs:
320
 
            problems.append(self._format_message(tabs,
321
 
                'Tab characters were found in the following source files.'
322
 
                '\nThey should either be replaced by "\\t" or by spaces:'))
323
 
        if trailing_ws:
324
 
            problems.append(self._format_message(trailing_ws,
325
 
                'Trailing white space was found in the following source files:'
326
 
                ))
327
 
        if illegal_newlines:
328
 
            problems.append(self._format_message(illegal_newlines,
329
 
                'Non-unix newlines were found in the following source files:'))
330
 
        if long_lines:
331
 
            print ("There are %i lines longer than 79 characters in %i files."
332
 
                % (sum([len(lines) for f, lines in long_lines.items()]),
333
 
                    len(long_lines)))
334
 
        if no_newline_at_eof:
335
 
            no_newline_at_eof.sort()
336
 
            problems.append("The following source files doesn't have a "
337
 
                "newline at the end:"
338
 
               '\n\n    %s'
339
 
               % ('\n    '.join(no_newline_at_eof)))
340
 
        if problems:
341
 
            raise KnownFailure("test_coding_style has failed")
342
 
            self.fail('\n\n'.join(problems))
343
 
 
344
 
    def test_no_asserts(self):
345
 
        """bzr shouldn't use the 'assert' statement."""
346
 
        # assert causes too much variation between -O and not, and tends to
347
 
        # give bad errors to the user
348
 
        def search(x):
349
 
            # scan down through x for assert statements, report any problems
350
 
            # this is a bit cheesy; it may get some false positives?
351
 
            if x[0] == symbol.assert_stmt:
352
 
                return True
353
 
            elif x[0] == token.NAME:
354
 
                # can't search further down
355
 
                return False
356
 
            for sub in x[1:]:
357
 
                if sub and search(sub):
358
 
                    return True
359
 
            return False
360
 
        badfiles = []
 
256
    def test_no_tabs(self):
 
257
        """bzrlib source files should not contain any tab characters."""
 
258
        incorrect = []
 
259
 
361
260
        for fname, text in self.get_source_file_contents():
362
 
            if not self.is_our_code(fname):
 
261
            if '/util/' in fname or '/plugins/' in fname:
363
262
                continue
364
 
            ast = parser.ast2tuple(parser.suite(''.join(text)))
365
 
            if search(ast):
366
 
                badfiles.append(fname)
367
 
        if badfiles:
368
 
            self.fail(
369
 
                "these files contain an assert statement and should not:\n%s"
370
 
                % '\n'.join(badfiles))
 
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)))