1 # Unix SMB/CIFS implementation.
2 # Copyright (C) Jelmer Vernooij <jelmer@samba.org> 2011
4 # Loosely based on bzrlib's test_source.py
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.
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.
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/>.
20 """Source level Python tests."""
28 samba.ensure_external_module("pep8", "pep8")
31 from samba.tests import (
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
41 for root, dirs, files in os.walk(library_dir):
44 yield os.path.abspath(os.path.join(root, f))
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):
52 target = os.readlink(p)
53 if os.path.dirname(target).endswith("scripting/bin"):
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):
60 yield os.path.abspath(os.path.join(root, f))
63 def get_source_file_contents():
64 """Iterate over the contents of all python files."""
65 for fname in get_python_source_files():
69 if e.errno == errno.ENOENT:
70 warnings.warn("source file %s broken link?" % fname)
81 class TestSource(TestCase):
83 def test_copyright(self):
84 """Test that all Python files have a valid copyright statement."""
87 copyright_re = re.compile('#\\s*copyright.*(?=\n)', re.I)
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
93 if "wafsamba" in fname:
94 # FIXME: No copyright headers in wafsamba
96 match = copyright_re.search(text)
98 incorrect.append((fname, 'no copyright line found\n'))
102 "Some files have missing or incorrect copyright"
104 for fname, comment in incorrect:
105 help_text.append(fname)
106 help_text.append((' ' * 4) + comment)
108 self.fail('\n'.join(help_text))
111 """Test that all .py files have a GPL disclaimer."""
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.
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.
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/>.
128 gpl_re = re.compile(re.escape(gpl_txt), re.MULTILINE)
130 for fname, text in get_source_file_contents():
131 if "wafsamba" in fname:
132 # FIXME: License to wafsamba hasn't been clarified yet
134 if not gpl_re.search(text):
135 incorrect.append(fname)
138 help_text = ['Some files have missing or incomplete GPL statement',
140 for fname in incorrect:
141 help_text.append((' ' * 4) + fname)
143 self.fail('\n'.join(help_text))
145 def _push_file(self, dict_, fname, line_no):
146 if fname not in dict_:
147 dict_[fname] = [line_no]
149 dict_[fname].append(line_no)
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()]
155 return message + '\n\n %s' % ('\n '.join(files))
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
164 def test_no_tabs(self):
165 """Check that there are no tabs in Python files."""
167 for fname, line_no, line in self._iter_source_files_lines():
169 self._push_file(tabs, fname, line_no)
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:'))
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)
182 self.fail(self._format_message(illegal_newlines,
183 'Non-unix newlines were found in the following source files:'))
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.'))
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():
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:'))
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
235 pep8.process_options()
237 pep8_error_count = {}
239 for fname, text in get_source_file_contents():
240 def report_error(line_number, offset, text, check):
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)
251 pep8_warnings.append(summary)
253 pep8_errors.append(summary)
254 lines = text.splitlines(True)
255 checker = pep8.Checker(fname, lines)
256 checker.report_error = report_error
258 if len(pep8_errors) > 0:
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)))