1 # Unix SMB/CIFS implementation.
2 # Copyright © Douglas Bagnall <douglas.bagnall@catalyst.net.nz>
4 # This program is free software; you can redistribute it and/or modify
5 # it under the terms of the GNU General Public License as published by
6 # the Free Software Foundation; either version 3 of the License, or
7 # (at your option) any later version.
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
14 # You should have received a copy of the GNU General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
19 from samba
.tests
import TestCase
, check_help_consistency
23 if 'SRCDIR_ABS' in os
.environ
:
24 BASEDIR
= os
.environ
['SRCDIR_ABS']
26 BASEDIR
= os
.path
.abspath(os
.path
.join(os
.path
.dirname(__file__
),
65 'script/autobuild.py', # defaults to mount /memdisk/
66 'script/bisect-test.py',
67 'ctdb/utils/etcd/ctdb_etcd_lock',
68 'selftest/filter-subunit',
69 'selftest/format-subunit',
70 'bin/gen_output.py', # too much output!
71 'source4/scripting/bin/gen_output.py',
72 'lib/ldb/tests/python/index.py',
73 'lib/ldb/tests/python/api.py',
74 'source4/selftest/tests.py',
76 'selftest/tap2subunit',
77 'script/show_test_time',
78 'source4/scripting/bin/subunitrun',
79 'bin/samba_downgrade_db',
80 'source4/scripting/bin/samba_downgrade_db',
81 'source3/selftest/tests.py',
83 'python/samba/subunit/run.py',
84 'bin/python/samba/subunit/run.py',
85 'lib/compression/tests/scripts/three-byte-hash',
89 'selftest/tap2subunit',
91 'wintest/test-s4-howto.py',
96 'source3/script/tests',
98 'source4/dsdb/tests/python',
100 'bin/python/samba/tests',
101 'bin/python/samba/tests/dcerpc',
102 'bin/python/samba/tests/krb5',
103 'bin/python/samba/tests/ndr',
104 'python/samba/tests',
105 'python/samba/tests/bin',
106 'python/samba/tests/dcerpc',
107 'python/samba/tests/krb5',
108 'python/samba/tests/ndr',
112 def _init_git_file_finder():
113 """Generate a function that quickly answers the question:
114 'is this a git file?'
116 git_file_cache
= set()
117 p
= subprocess
.run(['git',
121 stdout
=subprocess
.PIPE
)
122 if p
.returncode
== 0:
123 for fn
in p
.stdout
.split(b
'\0'):
124 git_file_cache
.add(os
.path
.join(BASEDIR
, fn
.decode('utf-8')))
125 return git_file_cache
.__contains
__
128 is_git_file
= _init_git_file_finder()
131 def script_iterator(d
=BASEDIR
, cache
=None,
133 filename_filter
=None,
138 safename
= re
.compile(r
'\W+').sub
139 for subdir
in subdirs
:
140 sd
= os
.path
.join(d
, subdir
)
141 for root
, dirs
, files
in os
.walk(sd
, followlinks
=False):
145 if fn
.endswith('.inst'):
147 ffn
= os
.path
.join(root
, fn
)
150 except FileNotFoundError
:
152 if not s
.st_mode
& stat
.S_IXUSR
:
154 if not (subdir
== 'bin' or is_git_file(ffn
)):
157 if filename_filter
is not None:
158 if not filename_filter(ffn
):
161 if shebang_filter
is not None:
165 print("could not open %s: %s" % (ffn
, e
))
169 if not shebang_filter(line
):
172 name
= safename('_', fn
)
179 # For ELF we only look at /bin/* top level.
180 def elf_file_name(fn
):
181 fn
= fn
.partition('bin/')[2]
182 return fn
and '/' not in fn
and 'test' not in fn
and 'ldb' in fn
185 return x
[:4] == b
'\x7fELF'
189 return script_iterator(BASEDIR
, elf_cache
,
190 shebang_filter
=elf_shebang
,
191 filename_filter
=elf_file_name
,
195 perl_shebang
= re
.compile(br
'#!.+perl').match
197 perl_script_cache
= {}
198 def perl_script_iterator():
199 return script_iterator(BASEDIR
, perl_script_cache
, perl_shebang
)
202 python_shebang
= re
.compile(br
'#!.+python').match
204 python_script_cache
= {}
205 def python_script_iterator():
206 return script_iterator(BASEDIR
, python_script_cache
, python_shebang
)
209 class PerlScriptUsageTests(TestCase
):
210 """Perl scripts run without arguments should print a usage string,
211 not fail with a traceback.
216 for name
, filename
in perl_script_iterator():
217 print(name
, filename
)
220 class PythonScriptUsageTests(TestCase
):
221 """Python scripts run without arguments should print a usage string,
222 not fail with a traceback.
227 for name
, filename
in python_script_iterator():
228 # We add the actual tests after the class definition so we
229 # can give individual names to them, so we can have a
231 fn
= filename
.replace(BASEDIR
, '').lstrip('/')
233 if fn
in EXCLUDE_USAGE
:
234 print("skipping %s (EXCLUDE_USAGE)" % filename
)
237 if os
.path
.dirname(fn
) in EXCLUDE_DIRS
:
238 print("skipping %s (EXCLUDE_DIRS)" % filename
)
241 def _f(self
, filename
=filename
):
244 p
= subprocess
.Popen(['python3', filename
],
245 stderr
=subprocess
.PIPE
,
246 stdout
=subprocess
.PIPE
)
247 out
, err
= p
.communicate(timeout
=5)
249 self
.fail("Error: %s" % e
)
250 except subprocess
.SubprocessError
as e
:
251 self
.fail("Subprocess error: %s" % e
)
253 err
= err
.decode('utf-8')
254 out
= out
.decode('utf-8')
255 self
.assertNotIn('Traceback', err
)
257 self
.assertIn('usage', out
.lower() + err
.lower(),
258 'stdout:\n%s\nstderr:\n%s' % (out
, err
))
260 attr
= 'test_%s' % name
261 if hasattr(cls
, attr
):
262 raise RuntimeError(f
'Usage test ‘{attr}’ already exists!')
263 setattr(cls
, attr
, _f
)
266 class HelpTestSuper(TestCase
):
267 """Python scripts run with -h or --help should print a help string,
268 and exit with success.
270 check_return_code
= True
271 check_consistency
= True
272 check_contains_usage
= True
273 check_multiline
= True
274 check_merged_out_and_err
= False
281 raise NotImplementedError("Subclass this "
282 "and add an iterator function!")
286 for name
, filename
in cls
.iterator():
287 # We add the actual tests after the class definition so we
288 # can give individual names to them, so we can have a
290 fn
= filename
.replace(BASEDIR
, '').lstrip('/')
292 if fn
in EXCLUDE_HELP
:
293 print("skipping %s (EXCLUDE_HELP)" % filename
)
296 if os
.path
.dirname(fn
) in EXCLUDE_DIRS
:
297 print("skipping %s (EXCLUDE_DIRS)" % filename
)
300 def _f(self
, filename
=filename
):
302 for h
in ('--help', '-h'):
305 cmd
.insert(0, self
.interpreter
)
307 p
= subprocess
.Popen(cmd
,
308 stderr
=subprocess
.PIPE
,
309 stdout
=subprocess
.PIPE
)
310 out
, err
= p
.communicate(timeout
=5)
312 self
.fail("Error: %s" % e
)
313 except subprocess
.SubprocessError
as e
:
314 self
.fail("Subprocess error: %s" % e
)
316 err
= err
.decode('utf-8')
317 out
= out
.decode('utf-8')
318 if self
.check_merged_out_and_err
:
319 out
= "%s\n%s" % (out
, err
)
321 outl
= out
[:500].lower()
323 # These assertions are heuristics, not policy.
324 # If your script fails this test when it shouldn't
325 # just add it to EXCLUDE_HELP above or change the
328 # --help should produce:
329 # * multiple lines of help on stdout (not stderr),
330 # * including a "Usage:" string,
331 # * not contradict itself or repeat options,
332 # * and return success.
333 #print(out.encode('utf8'))
334 #print(err.encode('utf8'))
335 if self
.check_consistency
:
336 errors
= check_help_consistency(out
,
339 if errors
is not None:
342 if self
.check_return_code
:
343 self
.assertEqual(p
.returncode
, 0,
344 "%s %s\nreturncode should not be %d\n"
345 "err:\n%s\nout:\n%s" %
346 (filename
, h
, p
.returncode
, err
, out
))
347 if self
.check_contains_usage
:
348 self
.assertIn('usage', outl
, 'lacks "Usage:"\n')
349 if self
.check_multiline
:
350 self
.assertIn('\n', out
, 'expected multi-line output')
352 attr
= 'test_%s' % name
353 if hasattr(cls
, attr
):
354 raise RuntimeError(f
'Usage test ‘{attr}’ already exists!')
355 setattr(cls
, attr
, _f
)
358 class PythonScriptHelpTests(HelpTestSuper
):
359 """Python scripts run with -h or --help should print a help string,
360 and exit with success.
362 iterator
= python_script_iterator
363 interpreter
= 'python3'
366 class ElfHelpTests(HelpTestSuper
):
367 """ELF binaries run with -h or --help should print a help string,
368 and exit with success.
370 iterator
= elf_iterator
371 check_return_code
= False
372 check_merged_out_and_err
= True
375 PerlScriptUsageTests
.initialise()
376 PythonScriptUsageTests
.initialise()
377 PythonScriptHelpTests
.initialise()
378 ElfHelpTests
.initialise()