summaryrefslogtreecommitdiff
path: root/tools/scan-build-py/tests/unit
diff options
context:
space:
mode:
Diffstat (limited to 'tools/scan-build-py/tests/unit')
-rw-r--r--tools/scan-build-py/tests/unit/__init__.py24
-rw-r--r--tools/scan-build-py/tests/unit/fixtures.py40
-rw-r--r--tools/scan-build-py/tests/unit/test_analyze.py8
-rw-r--r--tools/scan-build-py/tests/unit/test_clang.py41
-rw-r--r--tools/scan-build-py/tests/unit/test_command.py193
-rw-r--r--tools/scan-build-py/tests/unit/test_intercept.py123
-rw-r--r--tools/scan-build-py/tests/unit/test_report.py146
-rw-r--r--tools/scan-build-py/tests/unit/test_runner.py213
-rw-r--r--tools/scan-build-py/tests/unit/test_shell.py42
9 files changed, 830 insertions, 0 deletions
diff --git a/tools/scan-build-py/tests/unit/__init__.py b/tools/scan-build-py/tests/unit/__init__.py
new file mode 100644
index 0000000000000..4fa9edc0fff12
--- /dev/null
+++ b/tools/scan-build-py/tests/unit/__init__.py
@@ -0,0 +1,24 @@
+# -*- coding: utf-8 -*-
+# The LLVM Compiler Infrastructure
+#
+# This file is distributed under the University of Illinois Open Source
+# License. See LICENSE.TXT for details.
+
+from . import test_command
+from . import test_clang
+from . import test_runner
+from . import test_report
+from . import test_analyze
+from . import test_intercept
+from . import test_shell
+
+
+def load_tests(loader, suite, pattern):
+ suite.addTests(loader.loadTestsFromModule(test_command))
+ suite.addTests(loader.loadTestsFromModule(test_clang))
+ suite.addTests(loader.loadTestsFromModule(test_runner))
+ suite.addTests(loader.loadTestsFromModule(test_report))
+ suite.addTests(loader.loadTestsFromModule(test_analyze))
+ suite.addTests(loader.loadTestsFromModule(test_intercept))
+ suite.addTests(loader.loadTestsFromModule(test_shell))
+ return suite
diff --git a/tools/scan-build-py/tests/unit/fixtures.py b/tools/scan-build-py/tests/unit/fixtures.py
new file mode 100644
index 0000000000000..d80f5e64774cc
--- /dev/null
+++ b/tools/scan-build-py/tests/unit/fixtures.py
@@ -0,0 +1,40 @@
+# -*- coding: utf-8 -*-
+# The LLVM Compiler Infrastructure
+#
+# This file is distributed under the University of Illinois Open Source
+# License. See LICENSE.TXT for details.
+
+import contextlib
+import tempfile
+import shutil
+import unittest
+
+
+class Spy(object):
+ def __init__(self):
+ self.arg = None
+ self.success = 0
+
+ def call(self, params):
+ self.arg = params
+ return self.success
+
+
+@contextlib.contextmanager
+def TempDir():
+ name = tempfile.mkdtemp(prefix='scan-build-test-')
+ try:
+ yield name
+ finally:
+ shutil.rmtree(name)
+
+
+class TestCase(unittest.TestCase):
+ def assertIn(self, element, collection):
+ found = False
+ for it in collection:
+ if element == it:
+ found = True
+
+ self.assertTrue(found, '{0} does not have {1}'.format(collection,
+ element))
diff --git a/tools/scan-build-py/tests/unit/test_analyze.py b/tools/scan-build-py/tests/unit/test_analyze.py
new file mode 100644
index 0000000000000..b77db4818024a
--- /dev/null
+++ b/tools/scan-build-py/tests/unit/test_analyze.py
@@ -0,0 +1,8 @@
+# -*- coding: utf-8 -*-
+# The LLVM Compiler Infrastructure
+#
+# This file is distributed under the University of Illinois Open Source
+# License. See LICENSE.TXT for details.
+
+import libscanbuild.analyze as sut
+from . import fixtures
diff --git a/tools/scan-build-py/tests/unit/test_clang.py b/tools/scan-build-py/tests/unit/test_clang.py
new file mode 100644
index 0000000000000..2f1fd79d4a92d
--- /dev/null
+++ b/tools/scan-build-py/tests/unit/test_clang.py
@@ -0,0 +1,41 @@
+# -*- coding: utf-8 -*-
+# The LLVM Compiler Infrastructure
+#
+# This file is distributed under the University of Illinois Open Source
+# License. See LICENSE.TXT for details.
+
+import libscanbuild.clang as sut
+from . import fixtures
+import os.path
+
+
+class GetClangArgumentsTest(fixtures.TestCase):
+ def test_get_clang_arguments(self):
+ with fixtures.TempDir() as tmpdir:
+ filename = os.path.join(tmpdir, 'test.c')
+ with open(filename, 'w') as handle:
+ handle.write('')
+
+ result = sut.get_arguments(
+ ['clang', '-c', filename, '-DNDEBUG', '-Dvar="this is it"'],
+ tmpdir)
+
+ self.assertIn('NDEBUG', result)
+ self.assertIn('var="this is it"', result)
+
+ def test_get_clang_arguments_fails(self):
+ self.assertRaises(
+ Exception, sut.get_arguments,
+ ['clang', '-###', '-fsyntax-only', '-x', 'c', 'notexist.c'], '.')
+
+
+class GetCheckersTest(fixtures.TestCase):
+ def test_get_checkers(self):
+ # this test is only to see is not crashing
+ result = sut.get_checkers('clang', [])
+ self.assertTrue(len(result))
+
+ def test_get_active_checkers(self):
+ # this test is only to see is not crashing
+ result = sut.get_active_checkers('clang', [])
+ self.assertTrue(len(result))
diff --git a/tools/scan-build-py/tests/unit/test_command.py b/tools/scan-build-py/tests/unit/test_command.py
new file mode 100644
index 0000000000000..9a6aae65c6058
--- /dev/null
+++ b/tools/scan-build-py/tests/unit/test_command.py
@@ -0,0 +1,193 @@
+# -*- coding: utf-8 -*-
+# The LLVM Compiler Infrastructure
+#
+# This file is distributed under the University of Illinois Open Source
+# License. See LICENSE.TXT for details.
+
+import libscanbuild.command as sut
+from . import fixtures
+import unittest
+
+
+class ParseTest(unittest.TestCase):
+
+ def test_action(self):
+ def test(expected, cmd):
+ opts = sut.classify_parameters(cmd)
+ self.assertEqual(expected, opts['action'])
+
+ Link = sut.Action.Link
+ test(Link, ['clang', 'source.c'])
+
+ Compile = sut.Action.Compile
+ test(Compile, ['clang', '-c', 'source.c'])
+ test(Compile, ['clang', '-c', 'source.c', '-MF', 'source.d'])
+
+ Preprocess = sut.Action.Ignored
+ test(Preprocess, ['clang', '-E', 'source.c'])
+ test(Preprocess, ['clang', '-c', '-E', 'source.c'])
+ test(Preprocess, ['clang', '-c', '-M', 'source.c'])
+ test(Preprocess, ['clang', '-c', '-MM', 'source.c'])
+
+ def test_optimalizations(self):
+ def test(cmd):
+ opts = sut.classify_parameters(cmd)
+ return opts.get('compile_options', [])
+
+ self.assertEqual(['-O'], test(['clang', '-c', 'source.c', '-O']))
+ self.assertEqual(['-O1'], test(['clang', '-c', 'source.c', '-O1']))
+ self.assertEqual(['-Os'], test(['clang', '-c', 'source.c', '-Os']))
+ self.assertEqual(['-O2'], test(['clang', '-c', 'source.c', '-O2']))
+ self.assertEqual(['-O3'], test(['clang', '-c', 'source.c', '-O3']))
+
+ def test_language(self):
+ def test(cmd):
+ opts = sut.classify_parameters(cmd)
+ return opts.get('language')
+
+ self.assertEqual(None, test(['clang', '-c', 'source.c']))
+ self.assertEqual('c', test(['clang', '-c', 'source.c', '-x', 'c']))
+ self.assertEqual('cpp', test(['clang', '-c', 'source.c', '-x', 'cpp']))
+
+ def test_output(self):
+ def test(cmd):
+ opts = sut.classify_parameters(cmd)
+ return opts.get('output')
+
+ self.assertEqual(None, test(['clang', '-c', 'source.c']))
+ self.assertEqual('source.o',
+ test(['clang', '-c', '-o', 'source.o', 'source.c']))
+
+ def test_arch(self):
+ def test(cmd):
+ opts = sut.classify_parameters(cmd)
+ return opts.get('archs_seen', [])
+
+ eq = self.assertEqual
+
+ eq([], test(['clang', '-c', 'source.c']))
+ eq(['mips'],
+ test(['clang', '-c', 'source.c', '-arch', 'mips']))
+ eq(['mips', 'i386'],
+ test(['clang', '-c', 'source.c', '-arch', 'mips', '-arch', 'i386']))
+
+ def test_input_file(self):
+ def test(cmd):
+ opts = sut.classify_parameters(cmd)
+ return opts.get('files', [])
+
+ eq = self.assertEqual
+
+ eq(['src.c'], test(['clang', 'src.c']))
+ eq(['src.c'], test(['clang', '-c', 'src.c']))
+ eq(['s1.c', 's2.c'], test(['clang', '-c', 's1.c', 's2.c']))
+
+ def test_include(self):
+ def test(cmd):
+ opts = sut.classify_parameters(cmd)
+ return opts.get('compile_options', [])
+
+ eq = self.assertEqual
+
+ eq([], test(['clang', '-c', 'src.c']))
+ eq(['-include', '/usr/local/include'],
+ test(['clang', '-c', 'src.c', '-include', '/usr/local/include']))
+ eq(['-I.'],
+ test(['clang', '-c', 'src.c', '-I.']))
+ eq(['-I', '.'],
+ test(['clang', '-c', 'src.c', '-I', '.']))
+ eq(['-I/usr/local/include'],
+ test(['clang', '-c', 'src.c', '-I/usr/local/include']))
+ eq(['-I', '/usr/local/include'],
+ test(['clang', '-c', 'src.c', '-I', '/usr/local/include']))
+ eq(['-I/opt', '-I', '/opt/otp/include'],
+ test(['clang', '-c', 'src.c', '-I/opt', '-I', '/opt/otp/include']))
+ eq(['-isystem', '/path'],
+ test(['clang', '-c', 'src.c', '-isystem', '/path']))
+ eq(['-isystem=/path'],
+ test(['clang', '-c', 'src.c', '-isystem=/path']))
+
+ def test_define(self):
+ def test(cmd):
+ opts = sut.classify_parameters(cmd)
+ return opts.get('compile_options', [])
+
+ eq = self.assertEqual
+
+ eq([], test(['clang', '-c', 'src.c']))
+ eq(['-DNDEBUG'],
+ test(['clang', '-c', 'src.c', '-DNDEBUG']))
+ eq(['-UNDEBUG'],
+ test(['clang', '-c', 'src.c', '-UNDEBUG']))
+ eq(['-Dvar1=val1', '-Dvar2=val2'],
+ test(['clang', '-c', 'src.c', '-Dvar1=val1', '-Dvar2=val2']))
+ eq(['-Dvar="val ues"'],
+ test(['clang', '-c', 'src.c', '-Dvar="val ues"']))
+
+ def test_ignored_flags(self):
+ def test(flags):
+ cmd = ['clang', 'src.o']
+ opts = sut.classify_parameters(cmd + flags)
+ self.assertEqual(['src.o'], opts.get('compile_options'))
+
+ test([])
+ test(['-lrt', '-L/opt/company/lib'])
+ test(['-static'])
+ test(['-Wnoexcept', '-Wall'])
+ test(['-mtune=i386', '-mcpu=i386'])
+
+ def test_compile_only_flags(self):
+ def test(cmd):
+ opts = sut.classify_parameters(cmd)
+ return opts.get('compile_options', [])
+
+ eq = self.assertEqual
+
+ eq(['-std=C99'],
+ test(['clang', '-c', 'src.c', '-std=C99']))
+ eq(['-nostdinc'],
+ test(['clang', '-c', 'src.c', '-nostdinc']))
+ eq(['-isystem', '/image/debian'],
+ test(['clang', '-c', 'src.c', '-isystem', '/image/debian']))
+ eq(['-iprefix', '/usr/local'],
+ test(['clang', '-c', 'src.c', '-iprefix', '/usr/local']))
+ eq(['-iquote=me'],
+ test(['clang', '-c', 'src.c', '-iquote=me']))
+ eq(['-iquote', 'me'],
+ test(['clang', '-c', 'src.c', '-iquote', 'me']))
+
+ def test_compile_and_link_flags(self):
+ def test(cmd):
+ opts = sut.classify_parameters(cmd)
+ return opts.get('compile_options', [])
+
+ eq = self.assertEqual
+
+ eq(['-fsinged-char'],
+ test(['clang', '-c', 'src.c', '-fsinged-char']))
+ eq(['-fPIC'],
+ test(['clang', '-c', 'src.c', '-fPIC']))
+ eq(['-stdlib=libc++'],
+ test(['clang', '-c', 'src.c', '-stdlib=libc++']))
+ eq(['--sysroot', '/'],
+ test(['clang', '-c', 'src.c', '--sysroot', '/']))
+ eq(['-isysroot', '/'],
+ test(['clang', '-c', 'src.c', '-isysroot', '/']))
+ eq([],
+ test(['clang', '-c', 'src.c', '-fsyntax-only']))
+ eq([],
+ test(['clang', '-c', 'src.c', '-sectorder', 'a', 'b', 'c']))
+
+ def test_detect_cxx_from_compiler_name(self):
+ def test(cmd):
+ opts = sut.classify_parameters(cmd)
+ return opts.get('c++')
+
+ eq = self.assertEqual
+
+ eq(False, test(['cc', '-c', 'src.c']))
+ eq(True, test(['c++', '-c', 'src.c']))
+ eq(False, test(['clang', '-c', 'src.c']))
+ eq(True, test(['clang++', '-c', 'src.c']))
+ eq(False, test(['gcc', '-c', 'src.c']))
+ eq(True, test(['g++', '-c', 'src.c']))
diff --git a/tools/scan-build-py/tests/unit/test_intercept.py b/tools/scan-build-py/tests/unit/test_intercept.py
new file mode 100644
index 0000000000000..b6f01f36eeb3f
--- /dev/null
+++ b/tools/scan-build-py/tests/unit/test_intercept.py
@@ -0,0 +1,123 @@
+# -*- coding: utf-8 -*-
+# The LLVM Compiler Infrastructure
+#
+# This file is distributed under the University of Illinois Open Source
+# License. See LICENSE.TXT for details.
+
+import libscanbuild.intercept as sut
+from . import fixtures
+import os.path
+
+
+class InterceptUtilTest(fixtures.TestCase):
+
+ def test_is_compiler_call_filter(self):
+ def test(command):
+ return sut.is_compiler_call({'command': [command]})
+
+ self.assertTrue(test('clang'))
+ self.assertTrue(test('clang-3.6'))
+ self.assertTrue(test('clang++'))
+ self.assertTrue(test('clang++-3.5.1'))
+ self.assertTrue(test('cc'))
+ self.assertTrue(test('c++'))
+ self.assertTrue(test('gcc'))
+ self.assertTrue(test('g++'))
+ self.assertTrue(test('/usr/local/bin/gcc'))
+ self.assertTrue(test('/usr/local/bin/g++'))
+ self.assertTrue(test('/usr/local/bin/clang'))
+ self.assertTrue(test('armv7_neno-linux-gnueabi-g++'))
+
+ self.assertFalse(test(''))
+ self.assertFalse(test('ld'))
+ self.assertFalse(test('as'))
+ self.assertFalse(test('/usr/local/bin/compiler'))
+
+ def test_format_entry_filters_action(self):
+ def test(command):
+ return list(sut.format_entry(
+ {'command': command, 'directory': '/opt/src/project'}))
+
+ self.assertTrue(test(['cc', '-c', 'file.c', '-o', 'file.o']))
+ self.assertFalse(test(['cc', '-E', 'file.c']))
+ self.assertFalse(test(['cc', '-MM', 'file.c']))
+ self.assertFalse(test(['cc', 'this.o', 'that.o', '-o', 'a.out']))
+ self.assertFalse(test(['cc', '-print-prog-name']))
+
+ def test_format_entry_normalize_filename(self):
+ directory = os.path.join(os.sep, 'home', 'me', 'project')
+
+ def test(command):
+ result = list(sut.format_entry(
+ {'command': command, 'directory': directory}))
+ return result[0]['file']
+
+ self.assertEqual(test(['cc', '-c', 'file.c']),
+ os.path.join(directory, 'file.c'))
+ self.assertEqual(test(['cc', '-c', './file.c']),
+ os.path.join(directory, 'file.c'))
+ self.assertEqual(test(['cc', '-c', '../file.c']),
+ os.path.join(os.path.dirname(directory), 'file.c'))
+ self.assertEqual(test(['cc', '-c', '/opt/file.c']),
+ '/opt/file.c')
+
+ def test_sip(self):
+ def create_status_report(filename, message):
+ content = """#!/usr/bin/env sh
+ echo 'sa-la-la-la'
+ echo 'la-la-la'
+ echo '{0}'
+ echo 'sa-la-la-la'
+ echo 'la-la-la'
+ """.format(message)
+ lines = [line.strip() for line in content.split('\n')]
+ with open(filename, 'w') as handle:
+ handle.write('\n'.join(lines))
+ handle.close()
+ os.chmod(filename, 0x1ff)
+
+ def create_csrutil(dest_dir, status):
+ filename = os.path.join(dest_dir, 'csrutil')
+ message = 'System Integrity Protection status: {0}'.format(status)
+ return create_status_report(filename, message)
+
+ def create_sestatus(dest_dir, status):
+ filename = os.path.join(dest_dir, 'sestatus')
+ message = 'SELinux status:\t{0}'.format(status)
+ return create_status_report(filename, message)
+
+ ENABLED = 'enabled'
+ DISABLED = 'disabled'
+
+ OSX = 'darwin'
+ LINUX = 'linux'
+
+ with fixtures.TempDir() as tmpdir:
+ try:
+ saved = os.environ['PATH']
+ os.environ['PATH'] = tmpdir + ':' + saved
+
+ create_csrutil(tmpdir, ENABLED)
+ self.assertTrue(sut.is_preload_disabled(OSX))
+
+ create_csrutil(tmpdir, DISABLED)
+ self.assertFalse(sut.is_preload_disabled(OSX))
+
+ create_sestatus(tmpdir, ENABLED)
+ self.assertTrue(sut.is_preload_disabled(LINUX))
+
+ create_sestatus(tmpdir, DISABLED)
+ self.assertFalse(sut.is_preload_disabled(LINUX))
+ finally:
+ os.environ['PATH'] = saved
+
+ try:
+ saved = os.environ['PATH']
+ os.environ['PATH'] = ''
+ # shall be false when it's not in the path
+ self.assertFalse(sut.is_preload_disabled(OSX))
+ self.assertFalse(sut.is_preload_disabled(LINUX))
+
+ self.assertFalse(sut.is_preload_disabled('unix'))
+ finally:
+ os.environ['PATH'] = saved
diff --git a/tools/scan-build-py/tests/unit/test_report.py b/tools/scan-build-py/tests/unit/test_report.py
new file mode 100644
index 0000000000000..d505afc20a891
--- /dev/null
+++ b/tools/scan-build-py/tests/unit/test_report.py
@@ -0,0 +1,146 @@
+# -*- coding: utf-8 -*-
+# The LLVM Compiler Infrastructure
+#
+# This file is distributed under the University of Illinois Open Source
+# License. See LICENSE.TXT for details.
+
+import libscanbuild.report as sut
+from . import fixtures
+import unittest
+import os
+import os.path
+
+
+def run_bug_parse(content):
+ with fixtures.TempDir() as tmpdir:
+ file_name = os.path.join(tmpdir, 'test.html')
+ with open(file_name, 'w') as handle:
+ handle.writelines(content)
+ for bug in sut.parse_bug_html(file_name):
+ return bug
+
+
+def run_crash_parse(content, preproc):
+ with fixtures.TempDir() as tmpdir:
+ file_name = os.path.join(tmpdir, preproc + '.info.txt')
+ with open(file_name, 'w') as handle:
+ handle.writelines(content)
+ return sut.parse_crash(file_name)
+
+
+class ParseFileTest(unittest.TestCase):
+
+ def test_parse_bug(self):
+ content = [
+ "some header\n",
+ "<!-- BUGDESC Division by zero -->\n",
+ "<!-- BUGTYPE Division by zero -->\n",
+ "<!-- BUGCATEGORY Logic error -->\n",
+ "<!-- BUGFILE xx -->\n",
+ "<!-- BUGLINE 5 -->\n",
+ "<!-- BUGCOLUMN 22 -->\n",
+ "<!-- BUGPATHLENGTH 4 -->\n",
+ "<!-- BUGMETAEND -->\n",
+ "<!-- REPORTHEADER -->\n",
+ "some tails\n"]
+ result = run_bug_parse(content)
+ self.assertEqual(result['bug_category'], 'Logic error')
+ self.assertEqual(result['bug_path_length'], 4)
+ self.assertEqual(result['bug_line'], 5)
+ self.assertEqual(result['bug_description'], 'Division by zero')
+ self.assertEqual(result['bug_type'], 'Division by zero')
+ self.assertEqual(result['bug_file'], 'xx')
+
+ def test_parse_bug_empty(self):
+ content = []
+ result = run_bug_parse(content)
+ self.assertEqual(result['bug_category'], 'Other')
+ self.assertEqual(result['bug_path_length'], 1)
+ self.assertEqual(result['bug_line'], 0)
+
+ def test_parse_crash(self):
+ content = [
+ "/some/path/file.c\n",
+ "Some very serious Error\n",
+ "bla\n",
+ "bla-bla\n"]
+ result = run_crash_parse(content, 'file.i')
+ self.assertEqual(result['source'], content[0].rstrip())
+ self.assertEqual(result['problem'], content[1].rstrip())
+ self.assertEqual(os.path.basename(result['file']),
+ 'file.i')
+ self.assertEqual(os.path.basename(result['info']),
+ 'file.i.info.txt')
+ self.assertEqual(os.path.basename(result['stderr']),
+ 'file.i.stderr.txt')
+
+ def test_parse_real_crash(self):
+ import libscanbuild.runner as sut2
+ import re
+ with fixtures.TempDir() as tmpdir:
+ filename = os.path.join(tmpdir, 'test.c')
+ with open(filename, 'w') as handle:
+ handle.write('int main() { return 0')
+ # produce failure report
+ opts = {'directory': os.getcwd(),
+ 'clang': 'clang',
+ 'file': filename,
+ 'report': ['-fsyntax-only', '-E', filename],
+ 'language': 'c',
+ 'output_dir': tmpdir,
+ 'error_type': 'other_error',
+ 'error_output': 'some output',
+ 'exit_code': 13}
+ sut2.report_failure(opts)
+ # find the info file
+ pp_file = None
+ for root, _, files in os.walk(tmpdir):
+ keys = [os.path.join(root, name) for name in files]
+ for key in keys:
+ if re.match(r'^(.*/)+clang(.*)\.i$', key):
+ pp_file = key
+ self.assertIsNot(pp_file, None)
+ # read the failure report back
+ result = sut.parse_crash(pp_file + '.info.txt')
+ self.assertEqual(result['source'], filename)
+ self.assertEqual(result['problem'], 'Other Error')
+ self.assertEqual(result['file'], pp_file)
+ self.assertEqual(result['info'], pp_file + '.info.txt')
+ self.assertEqual(result['stderr'], pp_file + '.stderr.txt')
+
+
+class ReportMethodTest(unittest.TestCase):
+
+ def test_chop(self):
+ self.assertEqual('file', sut.chop('/prefix', '/prefix/file'))
+ self.assertEqual('file', sut.chop('/prefix/', '/prefix/file'))
+ self.assertEqual('lib/file', sut.chop('/prefix/', '/prefix/lib/file'))
+ self.assertEqual('/prefix/file', sut.chop('', '/prefix/file'))
+
+ def test_chop_when_cwd(self):
+ self.assertEqual('../src/file', sut.chop('/cwd', '/src/file'))
+ self.assertEqual('../src/file', sut.chop('/prefix/cwd',
+ '/prefix/src/file'))
+
+
+class GetPrefixFromCompilationDatabaseTest(fixtures.TestCase):
+
+ def test_with_different_filenames(self):
+ self.assertEqual(
+ sut.commonprefix(['/tmp/a.c', '/tmp/b.c']), '/tmp')
+
+ def test_with_different_dirnames(self):
+ self.assertEqual(
+ sut.commonprefix(['/tmp/abs/a.c', '/tmp/ack/b.c']), '/tmp')
+
+ def test_no_common_prefix(self):
+ self.assertEqual(
+ sut.commonprefix(['/tmp/abs/a.c', '/usr/ack/b.c']), '/')
+
+ def test_with_single_file(self):
+ self.assertEqual(
+ sut.commonprefix(['/tmp/a.c']), '/tmp')
+
+ def test_empty(self):
+ self.assertEqual(
+ sut.commonprefix([]), '')
diff --git a/tools/scan-build-py/tests/unit/test_runner.py b/tools/scan-build-py/tests/unit/test_runner.py
new file mode 100644
index 0000000000000..ea10051d8506f
--- /dev/null
+++ b/tools/scan-build-py/tests/unit/test_runner.py
@@ -0,0 +1,213 @@
+# -*- coding: utf-8 -*-
+# The LLVM Compiler Infrastructure
+#
+# This file is distributed under the University of Illinois Open Source
+# License. See LICENSE.TXT for details.
+
+import libscanbuild.runner as sut
+from . import fixtures
+import unittest
+import re
+import os
+import os.path
+
+
+def run_analyzer(content, opts):
+ with fixtures.TempDir() as tmpdir:
+ filename = os.path.join(tmpdir, 'test.cpp')
+ with open(filename, 'w') as handle:
+ handle.write(content)
+
+ opts.update({
+ 'directory': os.getcwd(),
+ 'clang': 'clang',
+ 'file': filename,
+ 'language': 'c++',
+ 'analyze': ['--analyze', '-x', 'c++', filename],
+ 'output': ['-o', tmpdir]})
+ spy = fixtures.Spy()
+ result = sut.run_analyzer(opts, spy.call)
+ return (result, spy.arg)
+
+
+class RunAnalyzerTest(unittest.TestCase):
+
+ def test_run_analyzer(self):
+ content = "int div(int n, int d) { return n / d; }"
+ (result, fwds) = run_analyzer(content, dict())
+ self.assertEqual(None, fwds)
+ self.assertEqual(0, result['exit_code'])
+
+ def test_run_analyzer_crash(self):
+ content = "int div(int n, int d) { return n / d }"
+ (result, fwds) = run_analyzer(content, dict())
+ self.assertEqual(None, fwds)
+ self.assertEqual(1, result['exit_code'])
+
+ def test_run_analyzer_crash_and_forwarded(self):
+ content = "int div(int n, int d) { return n / d }"
+ (_, fwds) = run_analyzer(content, {'output_failures': True})
+ self.assertEqual('crash', fwds['error_type'])
+ self.assertEqual(1, fwds['exit_code'])
+ self.assertTrue(len(fwds['error_output']) > 0)
+
+
+class SetAnalyzerOutputTest(fixtures.TestCase):
+
+ def test_not_defined(self):
+ with fixtures.TempDir() as tmpdir:
+ opts = {'output_dir': tmpdir}
+ spy = fixtures.Spy()
+ sut.set_analyzer_output(opts, spy.call)
+ self.assertTrue(os.path.exists(spy.arg['output'][1]))
+ self.assertTrue(os.path.isdir(spy.arg['output'][1]))
+
+ def test_html(self):
+ with fixtures.TempDir() as tmpdir:
+ opts = {'output_dir': tmpdir, 'output_format': 'html'}
+ spy = fixtures.Spy()
+ sut.set_analyzer_output(opts, spy.call)
+ self.assertTrue(os.path.exists(spy.arg['output'][1]))
+ self.assertTrue(os.path.isdir(spy.arg['output'][1]))
+
+ def test_plist_html(self):
+ with fixtures.TempDir() as tmpdir:
+ opts = {'output_dir': tmpdir, 'output_format': 'plist-html'}
+ spy = fixtures.Spy()
+ sut.set_analyzer_output(opts, spy.call)
+ self.assertTrue(os.path.exists(spy.arg['output'][1]))
+ self.assertTrue(os.path.isfile(spy.arg['output'][1]))
+
+ def test_plist(self):
+ with fixtures.TempDir() as tmpdir:
+ opts = {'output_dir': tmpdir, 'output_format': 'plist'}
+ spy = fixtures.Spy()
+ sut.set_analyzer_output(opts, spy.call)
+ self.assertTrue(os.path.exists(spy.arg['output'][1]))
+ self.assertTrue(os.path.isfile(spy.arg['output'][1]))
+
+
+class ReportFailureTest(fixtures.TestCase):
+
+ def assertUnderFailures(self, path):
+ self.assertEqual('failures', os.path.basename(os.path.dirname(path)))
+
+ def test_report_failure_create_files(self):
+ with fixtures.TempDir() as tmpdir:
+ # create input file
+ filename = os.path.join(tmpdir, 'test.c')
+ with open(filename, 'w') as handle:
+ handle.write('int main() { return 0')
+ uname_msg = ' '.join(os.uname()) + os.linesep
+ error_msg = 'this is my error output'
+ # execute test
+ opts = {'directory': os.getcwd(),
+ 'clang': 'clang',
+ 'file': filename,
+ 'report': ['-fsyntax-only', '-E', filename],
+ 'language': 'c',
+ 'output_dir': tmpdir,
+ 'error_type': 'other_error',
+ 'error_output': error_msg,
+ 'exit_code': 13}
+ sut.report_failure(opts)
+ # verify the result
+ result = dict()
+ pp_file = None
+ for root, _, files in os.walk(tmpdir):
+ keys = [os.path.join(root, name) for name in files]
+ for key in keys:
+ with open(key, 'r') as handle:
+ result[key] = handle.readlines()
+ if re.match(r'^(.*/)+clang(.*)\.i$', key):
+ pp_file = key
+
+ # prepocessor file generated
+ self.assertUnderFailures(pp_file)
+ # info file generated and content dumped
+ info_file = pp_file + '.info.txt'
+ self.assertIn(info_file, result)
+ self.assertEqual('Other Error\n', result[info_file][1])
+ self.assertEqual(uname_msg, result[info_file][3])
+ # error file generated and content dumped
+ error_file = pp_file + '.stderr.txt'
+ self.assertIn(error_file, result)
+ self.assertEqual([error_msg], result[error_file])
+
+
+class AnalyzerTest(unittest.TestCase):
+
+ def test_set_language(self):
+ def test(expected, input):
+ spy = fixtures.Spy()
+ self.assertEqual(spy.success, sut.language_check(input, spy.call))
+ self.assertEqual(expected, spy.arg['language'])
+
+ l = 'language'
+ f = 'file'
+ i = 'c++'
+ test('c', {f: 'file.c', l: 'c', i: False})
+ test('c++', {f: 'file.c', l: 'c++', i: False})
+ test('c++', {f: 'file.c', i: True})
+ test('c', {f: 'file.c', i: False})
+ test('c++', {f: 'file.cxx', i: False})
+ test('c-cpp-output', {f: 'file.i', i: False})
+ test('c++-cpp-output', {f: 'file.i', i: True})
+ test('c-cpp-output', {f: 'f.i', l: 'c-cpp-output', i: True})
+
+ def test_arch_loop(self):
+ def test(input):
+ spy = fixtures.Spy()
+ sut.arch_check(input, spy.call)
+ return spy.arg
+
+ input = {'key': 'value'}
+ self.assertEqual(input, test(input))
+
+ input = {'archs_seen': ['i386']}
+ self.assertEqual({'arch': 'i386'}, test(input))
+
+ input = {'archs_seen': ['ppc']}
+ self.assertEqual(None, test(input))
+
+ input = {'archs_seen': ['i386', 'ppc']}
+ self.assertEqual({'arch': 'i386'}, test(input))
+
+ input = {'archs_seen': ['i386', 'sparc']}
+ result = test(input)
+ self.assertTrue(result == {'arch': 'i386'} or
+ result == {'arch': 'sparc'})
+
+
+@sut.require([])
+def method_without_expecteds(opts):
+ return 0
+
+
+@sut.require(['this', 'that'])
+def method_with_expecteds(opts):
+ return 0
+
+
+@sut.require([])
+def method_exception_from_inside(opts):
+ raise Exception('here is one')
+
+
+class RequireDecoratorTest(unittest.TestCase):
+
+ def test_method_without_expecteds(self):
+ self.assertEqual(method_without_expecteds(dict()), 0)
+ self.assertEqual(method_without_expecteds({}), 0)
+ self.assertEqual(method_without_expecteds({'this': 2}), 0)
+ self.assertEqual(method_without_expecteds({'that': 3}), 0)
+
+ def test_method_with_expecteds(self):
+ self.assertRaises(KeyError, method_with_expecteds, dict())
+ self.assertRaises(KeyError, method_with_expecteds, {})
+ self.assertRaises(KeyError, method_with_expecteds, {'this': 2})
+ self.assertRaises(KeyError, method_with_expecteds, {'that': 3})
+ self.assertEqual(method_with_expecteds({'this': 0, 'that': 3}), 0)
+
+ def test_method_exception_not_caught(self):
+ self.assertRaises(Exception, method_exception_from_inside, dict())
diff --git a/tools/scan-build-py/tests/unit/test_shell.py b/tools/scan-build-py/tests/unit/test_shell.py
new file mode 100644
index 0000000000000..a2904b07f5bcf
--- /dev/null
+++ b/tools/scan-build-py/tests/unit/test_shell.py
@@ -0,0 +1,42 @@
+# -*- coding: utf-8 -*-
+# The LLVM Compiler Infrastructure
+#
+# This file is distributed under the University of Illinois Open Source
+# License. See LICENSE.TXT for details.
+
+import libscanbuild.shell as sut
+import unittest
+
+
+class ShellTest(unittest.TestCase):
+
+ def test_encode_decode_are_same(self):
+ def test(value):
+ self.assertEqual(sut.encode(sut.decode(value)), value)
+
+ test("")
+ test("clang")
+ test("clang this and that")
+
+ def test_decode_encode_are_same(self):
+ def test(value):
+ self.assertEqual(sut.decode(sut.encode(value)), value)
+
+ test([])
+ test(['clang'])
+ test(['clang', 'this', 'and', 'that'])
+ test(['clang', 'this and', 'that'])
+ test(['clang', "it's me", 'again'])
+ test(['clang', 'some "words" are', 'quoted'])
+
+ def test_encode(self):
+ self.assertEqual(sut.encode(['clang', "it's me", 'again']),
+ 'clang "it\'s me" again')
+ self.assertEqual(sut.encode(['clang', "it(s me", 'again)']),
+ 'clang "it(s me" "again)"')
+ self.assertEqual(sut.encode(['clang', 'redirect > it']),
+ 'clang "redirect > it"')
+ self.assertEqual(sut.encode(['clang', '-DKEY="VALUE"']),
+ 'clang -DKEY=\\"VALUE\\"')
+ self.assertEqual(sut.encode(['clang', '-DKEY="value with spaces"']),
+ 'clang -DKEY=\\"value with spaces\\"')