Fix more pep8 issues in code I touched recently.
[kai/samba-autobuild/.git] / python / samba / tests / source.py
1 # Unix SMB/CIFS implementation.
2 # Copyright (C) Jelmer Vernooij <jelmer@samba.org> 2011
3 #
4 # Loosely based on bzrlib's test_source.py
5 #
6 # This program is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 3 of the License, or
9 # (at your option) any later version.
10 #
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 # GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
18 #
19
20 """Source level Python tests."""
21
22 import errno
23 import os
24 import re
25 import warnings
26
27 import samba
28 samba.ensure_external_module("pep8", "pep8")
29 import pep8
30
31 from samba.tests import (
32     TestCase,
33     )
34
35
36 def get_python_source_files():
37     """Iterate over all Python source files."""
38     library_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..", "samba"))
39     assert os.path.isdir(library_dir), library_dir
40
41     for root, dirs, files in os.walk(library_dir):
42         for f in files:
43             if f.endswith(".py"):
44                 yield os.path.abspath(os.path.join(root, f))
45
46     bindir = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..", "..", "..", "bin"))
47     assert os.path.isdir(bindir), bindir
48     for f in os.listdir(bindir):
49         p = os.path.abspath(os.path.join(bindir, f))
50         if not os.path.islink(p):
51             continue
52         target = os.readlink(p)
53         if os.path.dirname(target).endswith("scripting/bin"):
54             yield p
55     wafsambadir = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..", "..", "..", "buildtools", "wafsamba"))
56     assert os.path.isdir(wafsambadir), wafsambadir
57     for root, dirs, files in os.walk(wafsambadir):
58         for f in files:
59             if f.endswith(".py"):
60                 yield os.path.abspath(os.path.join(root, f))
61
62
63 def get_source_file_contents():
64     """Iterate over the contents of all python files."""
65     for fname in get_python_source_files():
66         try:
67             f = open(fname, 'rb')
68         except IOError, e:
69             if e.errno == errno.ENOENT:
70                 warnings.warn("source file %s broken link?" % fname)
71                 continue
72             else:
73                 raise
74         try:
75             text = f.read()
76         finally:
77             f.close()
78         yield fname, text
79
80
81 class TestSource(TestCase):
82
83     def test_copyright(self):
84         """Test that all Python files have a valid copyright statement."""
85         incorrect = []
86
87         copyright_re = re.compile('#\\s*copyright.*(?=\n)', re.I)
88
89         for fname, text in get_source_file_contents():
90             if fname.endswith("ms_schema.py"):
91                 # FIXME: Not sure who holds copyright on ms_schema.py
92                 continue
93             if "wafsamba" in fname:
94                 # FIXME: No copyright headers in wafsamba
95                 continue
96             match = copyright_re.search(text)
97             if not match:
98                 incorrect.append((fname, 'no copyright line found\n'))
99
100         if incorrect:
101             help_text = [
102                 "Some files have missing or incorrect copyright"
103                 " statements.", ""]
104             for fname, comment in incorrect:
105                 help_text.append(fname)
106                 help_text.append((' ' * 4) + comment)
107
108             self.fail('\n'.join(help_text))
109
110     def test_gpl(self):
111         """Test that all .py files have a GPL disclaimer."""
112         incorrect = []
113
114         gpl_txt = """
115 # This program is free software; you can redistribute it and/or modify
116 # it under the terms of the GNU General Public License as published by
117 # the Free Software Foundation; either version 3 of the License, or
118 # (at your option) any later version.
119 #
120 # This program is distributed in the hope that it will be useful,
121 # but WITHOUT ANY WARRANTY; without even the implied warranty of
122 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
123 # GNU General Public License for more details.
124 #
125 # You should have received a copy of the GNU General Public License
126 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
127 """
128         gpl_re = re.compile(re.escape(gpl_txt), re.MULTILINE)
129
130         for fname, text in get_source_file_contents():
131             if "wafsamba" in fname:
132                 # FIXME: License to wafsamba hasn't been clarified yet
133                 continue
134             if not gpl_re.search(text):
135                 incorrect.append(fname)
136
137         if incorrect:
138             help_text = ['Some files have missing or incomplete GPL statement',
139                          gpl_txt]
140             for fname in incorrect:
141                 help_text.append((' ' * 4) + fname)
142
143             self.fail('\n'.join(help_text))
144
145     def _push_file(self, dict_, fname, line_no):
146         if fname not in dict_:
147             dict_[fname] = [line_no]
148         else:
149             dict_[fname].append(line_no)
150
151     def _format_message(self, dict_, message):
152         files = ["%s: %s" % (f, ', '.join([str(i + 1) for i in lines]))
153                 for f, lines in dict_.items()]
154         files.sort()
155         return message + '\n\n    %s' % ('\n    '.join(files))
156
157     def _iter_source_files_lines(self):
158         for fname, text in get_source_file_contents():
159             lines = text.splitlines(True)
160             last_line_no = len(lines) - 1
161             for line_no, line in enumerate(lines):
162                 yield fname, line_no, line
163
164     def test_no_tabs(self):
165         """Check that there are no tabs in Python files."""
166         tabs = {}
167         for fname, line_no, line in self._iter_source_files_lines():
168             if '\t' in line:
169                 self._push_file(tabs, fname, line_no)
170         if tabs:
171             self.fail(self._format_message(tabs,
172                 'Tab characters were found in the following source files.'
173                 '\nThey should either be replaced by "\\t" or by spaces:'))
174
175     def test_unix_newlines(self):
176         """Check for unix new lines."""
177         illegal_newlines = {}
178         for fname, line_no, line in self._iter_source_files_lines():
179             if not line.endswith('\n') or line.endswith('\r\n'):
180                 self._push_file(illegal_newlines, fname, line_no)
181         if illegal_newlines:
182             self.fail(self._format_message(illegal_newlines,
183                 'Non-unix newlines were found in the following source files:'))
184
185     def test_trailing_whitespace(self):
186         """Check that there is not trailing whitespace in Python files."""
187         trailing_whitespace = {}
188         for fname, line_no, line in self._iter_source_files_lines():
189             if line.rstrip("\n").endswith(" "):
190                 self._push_file(trailing_whitespace, fname, line_no)
191         if trailing_whitespace:
192             self.fail(self._format_message(trailing_whitespace,
193                 'Trailing whitespace was found in the following source files.'))
194
195     def test_shebang_lines(self):
196         """Check that files with shebang lines and only those are executable."""
197         files_with_shebang = {}
198         files_without_shebang= {}
199         for fname, line_no, line in self._iter_source_files_lines():
200             if line_no >= 1:
201                 continue
202             executable = (os.stat(fname).st_mode & 0111)
203             has_shebang = line.startswith("#!")
204             if has_shebang and not executable:
205                 self._push_file(files_with_shebang, fname, line_no)
206             if not has_shebang and executable:
207                 self._push_file(files_without_shebang, fname, line_no)
208         if files_with_shebang:
209             self.fail(self._format_message(files_with_shebang,
210                 'Files with shebang line that are not executable:'))
211         if files_without_shebang:
212             self.fail(self._format_message(files_without_shebang,
213                 'Files without shebang line that are executable:'))
214
215     pep8_ignore = [
216         'E401',      # multiple imports on one line
217         'E501',      # line too long
218         'E251',      # no spaces around keyword / parameter equals
219         'E201',      # whitespace after '['
220         'E202',      # whitespace before ')'
221         'E302',      # expected 2 blank lines, found 1
222         'E231',      # missing whitespace after ','
223         'E225',      # missing whitespace around operator
224         'E111',      # indentation is not a multiple of four
225         'E261',      # at least two spaces before inline comment
226         'E702',      # multiple statements on one line (semicolon)
227         'E221',      # multiple spaces before operator
228         'E303',      # too many blank lines (2)
229         'E203',      # whitespace before ':'
230         'E222',      # multiple spaces after operator
231         'E301',      # expected 1 blank line, found 0
232         ]
233
234     def test_pep8(self):
235         pep8.process_options()
236         pep8_errors = []
237         pep8_error_count = {}
238         pep8_warnings = []
239         for fname, text in get_source_file_contents():
240             def report_error(line_number, offset, text, check):
241                 code = text[:4]
242                 if code not in pep8_error_count:
243                     pep8_error_count[code] = 0
244                 pep8_error_count[code] += 1
245                 if code in self.pep8_ignore:
246                     code = 'W' + code[1:]
247                 text = code + text[4:]
248                 print "%s:%s: %s" % (fname, line_number, text)
249                 summary = (fname, line_number, offset, text, check)
250                 if code[0] == 'W':
251                     pep8_warnings.append(summary)
252                 else:
253                     pep8_errors.append(summary)
254             lines = text.splitlines(True)
255             checker = pep8.Checker(fname, lines)
256             checker.report_error = report_error
257             checker.check_all()
258         if len(pep8_errors) > 0:
259             d = {}
260             for (fname, line_no, offset, text, check) in pep8_errors:
261                 d.setdefault(fname, []).append(line_no - 1)
262             self.fail(self._format_message(
263                 d, 'There were %d PEP8 errors:' % len(pep8_errors)))