diff options
Diffstat (limited to 'gnu/llvm/clang/tools/scan-build-py/tests/unit')
8 files changed, 969 insertions, 0 deletions
diff --git a/gnu/llvm/clang/tools/scan-build-py/tests/unit/__init__.py b/gnu/llvm/clang/tools/scan-build-py/tests/unit/__init__.py new file mode 100644 index 00000000000..83a04743e6a --- /dev/null +++ b/gnu/llvm/clang/tools/scan-build-py/tests/unit/__init__.py @@ -0,0 +1,23 @@ +# -*- coding: utf-8 -*- +# Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +# See https://llvm.org/LICENSE.txt for license information. +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +from . import test_libear +from . import test_compilation +from . import test_clang +from . import test_report +from . import test_analyze +from . import test_intercept +from . import test_shell + + +def load_tests(loader, suite, _): + suite.addTests(loader.loadTestsFromModule(test_libear)) + suite.addTests(loader.loadTestsFromModule(test_compilation)) + suite.addTests(loader.loadTestsFromModule(test_clang)) + 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/gnu/llvm/clang/tools/scan-build-py/tests/unit/test_analyze.py b/gnu/llvm/clang/tools/scan-build-py/tests/unit/test_analyze.py new file mode 100644 index 00000000000..4b6f5d05211 --- /dev/null +++ b/gnu/llvm/clang/tools/scan-build-py/tests/unit/test_analyze.py @@ -0,0 +1,414 @@ +# -*- coding: utf-8 -*- +# Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +# See https://llvm.org/LICENSE.txt for license information. +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +import unittest +import re +import os +import os.path +import libear +import libscanbuild.analyze as sut + + +class ReportDirectoryTest(unittest.TestCase): + + # Test that successive report directory names ascend in lexicographic + # order. This is required so that report directories from two runs of + # scan-build can be easily matched up to compare results. + def test_directory_name_comparison(self): + with libear.TemporaryDirectory() as tmpdir, \ + sut.report_directory(tmpdir, False) as report_dir1, \ + sut.report_directory(tmpdir, False) as report_dir2, \ + sut.report_directory(tmpdir, False) as report_dir3: + self.assertLess(report_dir1, report_dir2) + self.assertLess(report_dir2, report_dir3) + + +class FilteringFlagsTest(unittest.TestCase): + + def test_language_captured(self): + def test(flags): + cmd = ['clang', '-c', 'source.c'] + flags + opts = sut.classify_parameters(cmd) + return opts['language'] + + self.assertEqual(None, test([])) + self.assertEqual('c', test(['-x', 'c'])) + self.assertEqual('cpp', test(['-x', 'cpp'])) + + def test_arch(self): + def test(flags): + cmd = ['clang', '-c', 'source.c'] + flags + opts = sut.classify_parameters(cmd) + return opts['arch_list'] + + self.assertEqual([], test([])) + self.assertEqual(['mips'], test(['-arch', 'mips'])) + self.assertEqual(['mips', 'i386'], + test(['-arch', 'mips', '-arch', 'i386'])) + + def assertFlagsChanged(self, expected, flags): + cmd = ['clang', '-c', 'source.c'] + flags + opts = sut.classify_parameters(cmd) + self.assertEqual(expected, opts['flags']) + + def assertFlagsUnchanged(self, flags): + self.assertFlagsChanged(flags, flags) + + def assertFlagsFiltered(self, flags): + self.assertFlagsChanged([], flags) + + def test_optimalizations_pass(self): + self.assertFlagsUnchanged(['-O']) + self.assertFlagsUnchanged(['-O1']) + self.assertFlagsUnchanged(['-Os']) + self.assertFlagsUnchanged(['-O2']) + self.assertFlagsUnchanged(['-O3']) + + def test_include_pass(self): + self.assertFlagsUnchanged([]) + self.assertFlagsUnchanged(['-include', '/usr/local/include']) + self.assertFlagsUnchanged(['-I.']) + self.assertFlagsUnchanged(['-I', '.']) + self.assertFlagsUnchanged(['-I/usr/local/include']) + self.assertFlagsUnchanged(['-I', '/usr/local/include']) + self.assertFlagsUnchanged(['-I/opt', '-I', '/opt/otp/include']) + self.assertFlagsUnchanged(['-isystem', '/path']) + self.assertFlagsUnchanged(['-isystem=/path']) + + def test_define_pass(self): + self.assertFlagsUnchanged(['-DNDEBUG']) + self.assertFlagsUnchanged(['-UNDEBUG']) + self.assertFlagsUnchanged(['-Dvar1=val1', '-Dvar2=val2']) + self.assertFlagsUnchanged(['-Dvar="val ues"']) + + def test_output_filtered(self): + self.assertFlagsFiltered(['-o', 'source.o']) + + def test_some_warning_filtered(self): + self.assertFlagsFiltered(['-Wall']) + self.assertFlagsFiltered(['-Wnoexcept']) + self.assertFlagsFiltered(['-Wreorder', '-Wunused', '-Wundef']) + self.assertFlagsUnchanged(['-Wno-reorder', '-Wno-unused']) + + def test_compile_only_flags_pass(self): + self.assertFlagsUnchanged(['-std=C99']) + self.assertFlagsUnchanged(['-nostdinc']) + self.assertFlagsUnchanged(['-isystem', '/image/debian']) + self.assertFlagsUnchanged(['-iprefix', '/usr/local']) + self.assertFlagsUnchanged(['-iquote=me']) + self.assertFlagsUnchanged(['-iquote', 'me']) + + def test_compile_and_link_flags_pass(self): + self.assertFlagsUnchanged(['-fsinged-char']) + self.assertFlagsUnchanged(['-fPIC']) + self.assertFlagsUnchanged(['-stdlib=libc++']) + self.assertFlagsUnchanged(['--sysroot', '/']) + self.assertFlagsUnchanged(['-isysroot', '/']) + + def test_some_flags_filtered(self): + self.assertFlagsFiltered(['-g']) + self.assertFlagsFiltered(['-fsyntax-only']) + self.assertFlagsFiltered(['-save-temps']) + self.assertFlagsFiltered(['-init', 'my_init']) + self.assertFlagsFiltered(['-sectorder', 'a', 'b', 'c']) + + +class Spy(object): + def __init__(self): + self.arg = None + self.success = 0 + + def call(self, params): + self.arg = params + return self.success + + +class RunAnalyzerTest(unittest.TestCase): + + @staticmethod + def run_analyzer(content, failures_report): + with libear.TemporaryDirectory() as tmpdir: + filename = os.path.join(tmpdir, 'test.cpp') + with open(filename, 'w') as handle: + handle.write(content) + + opts = { + 'clang': 'clang', + 'directory': os.getcwd(), + 'flags': [], + 'direct_args': [], + 'file': filename, + 'output_dir': tmpdir, + 'output_format': 'plist', + 'output_failures': failures_report + } + spy = Spy() + result = sut.run_analyzer(opts, spy.call) + return (result, spy.arg) + + def test_run_analyzer(self): + content = "int div(int n, int d) { return n / d; }" + (result, fwds) = RunAnalyzerTest.run_analyzer(content, False) + 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) = RunAnalyzerTest.run_analyzer(content, False) + 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) = RunAnalyzerTest.run_analyzer(content, True) + self.assertEqual(1, fwds['exit_code']) + self.assertTrue(len(fwds['error_output']) > 0) + + +class ReportFailureTest(unittest.TestCase): + + def assertUnderFailures(self, path): + self.assertEqual('failures', os.path.basename(os.path.dirname(path))) + + def test_report_failure_create_files(self): + with libear.TemporaryDirectory() 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 = { + 'clang': 'clang', + 'directory': os.getcwd(), + 'flags': [], + 'file': filename, + 'output_dir': tmpdir, + 'language': 'c', + '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.assertTrue(info_file in 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.assertTrue(error_file in result) + self.assertEqual([error_msg], result[error_file]) + + +class AnalyzerTest(unittest.TestCase): + + def test_nodebug_macros_appended(self): + def test(flags): + spy = Spy() + opts = {'flags': flags, 'force_debug': True} + self.assertEqual(spy.success, + sut.filter_debug_flags(opts, spy.call)) + return spy.arg['flags'] + + self.assertEqual(['-UNDEBUG'], test([])) + self.assertEqual(['-DNDEBUG', '-UNDEBUG'], test(['-DNDEBUG'])) + self.assertEqual(['-DSomething', '-UNDEBUG'], test(['-DSomething'])) + + def test_set_language_fall_through(self): + def language(expected, input): + spy = Spy() + input.update({'compiler': 'c', 'file': 'test.c'}) + self.assertEqual(spy.success, sut.language_check(input, spy.call)) + self.assertEqual(expected, spy.arg['language']) + + language('c', {'language': 'c', 'flags': []}) + language('c++', {'language': 'c++', 'flags': []}) + + def test_set_language_stops_on_not_supported(self): + spy = Spy() + input = { + 'compiler': 'c', + 'flags': [], + 'file': 'test.java', + 'language': 'java' + } + self.assertIsNone(sut.language_check(input, spy.call)) + self.assertIsNone(spy.arg) + + def test_set_language_sets_flags(self): + def flags(expected, input): + spy = Spy() + input.update({'compiler': 'c', 'file': 'test.c'}) + self.assertEqual(spy.success, sut.language_check(input, spy.call)) + self.assertEqual(expected, spy.arg['flags']) + + flags(['-x', 'c'], {'language': 'c', 'flags': []}) + flags(['-x', 'c++'], {'language': 'c++', 'flags': []}) + + def test_set_language_from_filename(self): + def language(expected, input): + spy = Spy() + input.update({'language': None, 'flags': []}) + self.assertEqual(spy.success, sut.language_check(input, spy.call)) + self.assertEqual(expected, spy.arg['language']) + + language('c', {'file': 'file.c', 'compiler': 'c'}) + language('c++', {'file': 'file.c', 'compiler': 'c++'}) + language('c++', {'file': 'file.cxx', 'compiler': 'c'}) + language('c++', {'file': 'file.cxx', 'compiler': 'c++'}) + language('c++', {'file': 'file.cpp', 'compiler': 'c++'}) + language('c-cpp-output', {'file': 'file.i', 'compiler': 'c'}) + language('c++-cpp-output', {'file': 'file.i', 'compiler': 'c++'}) + + def test_arch_loop_sets_flags(self): + def flags(archs): + spy = Spy() + input = {'flags': [], 'arch_list': archs} + sut.arch_check(input, spy.call) + return spy.arg['flags'] + + self.assertEqual([], flags([])) + self.assertEqual(['-arch', 'i386'], flags(['i386'])) + self.assertEqual(['-arch', 'i386'], flags(['i386', 'ppc'])) + self.assertEqual(['-arch', 'sparc'], flags(['i386', 'sparc'])) + + def test_arch_loop_stops_on_not_supported(self): + def stop(archs): + spy = Spy() + input = {'flags': [], 'arch_list': archs} + self.assertIsNone(sut.arch_check(input, spy.call)) + self.assertIsNone(spy.arg) + + stop(['ppc']) + stop(['ppc64']) + + +@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()) + + +class PrefixWithTest(unittest.TestCase): + + def test_gives_empty_on_empty(self): + res = sut.prefix_with(0, []) + self.assertFalse(res) + + def test_interleaves_prefix(self): + res = sut.prefix_with(0, [1, 2, 3]) + self.assertListEqual([0, 1, 0, 2, 0, 3], res) + + +class MergeCtuMapTest(unittest.TestCase): + + def test_no_map_gives_empty(self): + pairs = sut.create_global_ctu_extdef_map([]) + self.assertFalse(pairs) + + def test_multiple_maps_merged(self): + concat_map = ['c:@F@fun1#I# ast/fun1.c.ast', + 'c:@F@fun2#I# ast/fun2.c.ast', + 'c:@F@fun3#I# ast/fun3.c.ast'] + pairs = sut.create_global_ctu_extdef_map(concat_map) + self.assertTrue(('c:@F@fun1#I#', 'ast/fun1.c.ast') in pairs) + self.assertTrue(('c:@F@fun2#I#', 'ast/fun2.c.ast') in pairs) + self.assertTrue(('c:@F@fun3#I#', 'ast/fun3.c.ast') in pairs) + self.assertEqual(3, len(pairs)) + + def test_not_unique_func_left_out(self): + concat_map = ['c:@F@fun1#I# ast/fun1.c.ast', + 'c:@F@fun2#I# ast/fun2.c.ast', + 'c:@F@fun1#I# ast/fun7.c.ast'] + pairs = sut.create_global_ctu_extdef_map(concat_map) + self.assertFalse(('c:@F@fun1#I#', 'ast/fun1.c.ast') in pairs) + self.assertFalse(('c:@F@fun1#I#', 'ast/fun7.c.ast') in pairs) + self.assertTrue(('c:@F@fun2#I#', 'ast/fun2.c.ast') in pairs) + self.assertEqual(1, len(pairs)) + + def test_duplicates_are_kept(self): + concat_map = ['c:@F@fun1#I# ast/fun1.c.ast', + 'c:@F@fun2#I# ast/fun2.c.ast', + 'c:@F@fun1#I# ast/fun1.c.ast'] + pairs = sut.create_global_ctu_extdef_map(concat_map) + self.assertTrue(('c:@F@fun1#I#', 'ast/fun1.c.ast') in pairs) + self.assertTrue(('c:@F@fun2#I#', 'ast/fun2.c.ast') in pairs) + self.assertEqual(2, len(pairs)) + + def test_space_handled_in_source(self): + concat_map = ['c:@F@fun1#I# ast/f un.c.ast'] + pairs = sut.create_global_ctu_extdef_map(concat_map) + self.assertTrue(('c:@F@fun1#I#', 'ast/f un.c.ast') in pairs) + self.assertEqual(1, len(pairs)) + + +class ExtdefMapSrcToAstTest(unittest.TestCase): + + def test_empty_gives_empty(self): + fun_ast_lst = sut.extdef_map_list_src_to_ast([]) + self.assertFalse(fun_ast_lst) + + def test_sources_to_asts(self): + fun_src_lst = ['c:@F@f1#I# ' + os.path.join(os.sep + 'path', 'f1.c'), + 'c:@F@f2#I# ' + os.path.join(os.sep + 'path', 'f2.c')] + fun_ast_lst = sut.extdef_map_list_src_to_ast(fun_src_lst) + self.assertTrue('c:@F@f1#I# ' + + os.path.join('ast', 'path', 'f1.c.ast') + in fun_ast_lst) + self.assertTrue('c:@F@f2#I# ' + + os.path.join('ast', 'path', 'f2.c.ast') + in fun_ast_lst) + self.assertEqual(2, len(fun_ast_lst)) + + def test_spaces_handled(self): + fun_src_lst = ['c:@F@f1#I# ' + os.path.join(os.sep + 'path', 'f 1.c')] + fun_ast_lst = sut.extdef_map_list_src_to_ast(fun_src_lst) + self.assertTrue('c:@F@f1#I# ' + + os.path.join('ast', 'path', 'f 1.c.ast') + in fun_ast_lst) + self.assertEqual(1, len(fun_ast_lst)) diff --git a/gnu/llvm/clang/tools/scan-build-py/tests/unit/test_clang.py b/gnu/llvm/clang/tools/scan-build-py/tests/unit/test_clang.py new file mode 100644 index 00000000000..80ce61a1fab --- /dev/null +++ b/gnu/llvm/clang/tools/scan-build-py/tests/unit/test_clang.py @@ -0,0 +1,105 @@ +# -*- coding: utf-8 -*- +# Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +# See https://llvm.org/LICENSE.txt for license information. +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +import libear +import libscanbuild.clang as sut +import unittest +import os.path +import sys + + +class ClangGetVersion(unittest.TestCase): + def test_get_version_is_not_empty(self): + self.assertTrue(sut.get_version('clang')) + + def test_get_version_throws(self): + with self.assertRaises(OSError): + sut.get_version('notexists') + + +class ClangGetArgumentsTest(unittest.TestCase): + def test_get_clang_arguments(self): + with libear.TemporaryDirectory() 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.assertTrue('NDEBUG' in result) + self.assertTrue('var="this is it"' in result) + + def test_get_clang_arguments_fails(self): + with self.assertRaises(Exception): + sut.get_arguments(['clang', '-x', 'c', 'notexist.c'], '.') + + def test_get_clang_arguments_fails_badly(self): + with self.assertRaises(OSError): + sut.get_arguments(['notexist'], '.') + + +class ClangGetCheckersTest(unittest.TestCase): + def test_get_checkers(self): + # this test is only to see is not crashing + result = sut.get_checkers('clang', []) + self.assertTrue(len(result)) + # do check result types + string_type = unicode if sys.version_info < (3,) else str + for key, value in result.items(): + self.assertEqual(string_type, type(key)) + self.assertEqual(string_type, type(value[0])) + self.assertEqual(bool, type(value[1])) + + 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)) + # do check result types + for value in result: + self.assertEqual(str, type(value)) + + def test_is_active(self): + test = sut.is_active(['a', 'b.b', 'c.c.c']) + + self.assertTrue(test('a')) + self.assertTrue(test('a.b')) + self.assertTrue(test('b.b')) + self.assertTrue(test('b.b.c')) + self.assertTrue(test('c.c.c.p')) + + self.assertFalse(test('ab')) + self.assertFalse(test('ba')) + self.assertFalse(test('bb')) + self.assertFalse(test('c.c')) + self.assertFalse(test('b')) + self.assertFalse(test('d')) + + def test_parse_checkers(self): + lines = [ + 'OVERVIEW: Clang Static Analyzer Checkers List', + '', + 'CHECKERS:', + ' checker.one Checker One description', + ' checker.two', + ' Checker Two description'] + result = dict(sut.parse_checkers(lines)) + self.assertTrue('checker.one' in result) + self.assertEqual('Checker One description', result.get('checker.one')) + self.assertTrue('checker.two' in result) + self.assertEqual('Checker Two description', result.get('checker.two')) + + +class ClangIsCtuCapableTest(unittest.TestCase): + def test_ctu_not_found(self): + is_ctu = sut.is_ctu_capable('not-found-clang-extdef-mapping') + self.assertFalse(is_ctu) + + +class ClangGetTripleArchTest(unittest.TestCase): + def test_arch_is_not_empty(self): + arch = sut.get_triple_arch(['clang', '-E', '-'], '.') + self.assertTrue(len(arch) > 0) diff --git a/gnu/llvm/clang/tools/scan-build-py/tests/unit/test_compilation.py b/gnu/llvm/clang/tools/scan-build-py/tests/unit/test_compilation.py new file mode 100644 index 00000000000..e8ad3d8c99f --- /dev/null +++ b/gnu/llvm/clang/tools/scan-build-py/tests/unit/test_compilation.py @@ -0,0 +1,121 @@ +# -*- coding: utf-8 -*- +# Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +# See https://llvm.org/LICENSE.txt for license information. +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +import libscanbuild.compilation as sut +import unittest + + +class CompilerTest(unittest.TestCase): + + def test_is_compiler_call(self): + self.assertIsNotNone(sut.compiler_language(['clang'])) + self.assertIsNotNone(sut.compiler_language(['clang-3.6'])) + self.assertIsNotNone(sut.compiler_language(['clang++'])) + self.assertIsNotNone(sut.compiler_language(['clang++-3.5.1'])) + self.assertIsNotNone(sut.compiler_language(['cc'])) + self.assertIsNotNone(sut.compiler_language(['c++'])) + self.assertIsNotNone(sut.compiler_language(['gcc'])) + self.assertIsNotNone(sut.compiler_language(['g++'])) + self.assertIsNotNone(sut.compiler_language(['/usr/local/bin/gcc'])) + self.assertIsNotNone(sut.compiler_language(['/usr/local/bin/g++'])) + self.assertIsNotNone(sut.compiler_language(['/usr/local/bin/clang'])) + self.assertIsNotNone( + sut.compiler_language(['armv7_neno-linux-gnueabi-g++'])) + + self.assertIsNone(sut.compiler_language([])) + self.assertIsNone(sut.compiler_language([''])) + self.assertIsNone(sut.compiler_language(['ld'])) + self.assertIsNone(sut.compiler_language(['as'])) + self.assertIsNone(sut.compiler_language(['/usr/local/bin/compiler'])) + + +class SplitTest(unittest.TestCase): + + def test_detect_cxx_from_compiler_name(self): + def test(cmd): + result = sut.split_command([cmd, '-c', 'src.c']) + self.assertIsNotNone(result, "wrong input for test") + return result.compiler == 'c++' + + self.assertFalse(test('cc')) + self.assertFalse(test('gcc')) + self.assertFalse(test('clang')) + + self.assertTrue(test('c++')) + self.assertTrue(test('g++')) + self.assertTrue(test('g++-5.3.1')) + self.assertTrue(test('clang++')) + self.assertTrue(test('clang++-3.7.1')) + self.assertTrue(test('armv7_neno-linux-gnueabi-g++')) + + def test_action(self): + self.assertIsNotNone(sut.split_command(['clang', 'source.c'])) + self.assertIsNotNone(sut.split_command(['clang', '-c', 'source.c'])) + self.assertIsNotNone(sut.split_command(['clang', '-c', 'source.c', + '-MF', 'a.d'])) + + self.assertIsNone(sut.split_command(['clang', '-E', 'source.c'])) + self.assertIsNone(sut.split_command(['clang', '-c', '-E', 'source.c'])) + self.assertIsNone(sut.split_command(['clang', '-c', '-M', 'source.c'])) + self.assertIsNone( + sut.split_command(['clang', '-c', '-MM', 'source.c'])) + + def test_source_file(self): + def test(expected, cmd): + self.assertEqual(expected, sut.split_command(cmd).files) + + test(['src.c'], ['clang', 'src.c']) + test(['src.c'], ['clang', '-c', 'src.c']) + test(['src.C'], ['clang', '-x', 'c', 'src.C']) + test(['src.cpp'], ['clang++', '-c', 'src.cpp']) + test(['s1.c', 's2.c'], ['clang', '-c', 's1.c', 's2.c']) + test(['s1.c', 's2.c'], ['cc', 's1.c', 's2.c', '-ldep', '-o', 'a.out']) + test(['src.c'], ['clang', '-c', '-I', './include', 'src.c']) + test(['src.c'], ['clang', '-c', '-I', '/opt/me/include', 'src.c']) + test(['src.c'], ['clang', '-c', '-D', 'config=file.c', 'src.c']) + + self.assertIsNone( + sut.split_command(['cc', 'this.o', 'that.o', '-o', 'a.out'])) + self.assertIsNone( + sut.split_command(['cc', 'this.o', '-lthat', '-o', 'a.out'])) + + def test_filter_flags(self): + def test(expected, flags): + command = ['clang', '-c', 'src.c'] + flags + self.assertEqual(expected, sut.split_command(command).flags) + + def same(expected): + test(expected, expected) + + def filtered(flags): + test([], flags) + + same([]) + same(['-I', '/opt/me/include', '-DNDEBUG', '-ULIMITS']) + same(['-O', '-O2']) + same(['-m32', '-mmms']) + same(['-Wall', '-Wno-unused', '-g', '-funroll-loops']) + + filtered([]) + filtered(['-lclien', '-L/opt/me/lib', '-L', '/opt/you/lib']) + filtered(['-static']) + filtered(['-MD', '-MT', 'something']) + filtered(['-MMD', '-MF', 'something']) + + +class SourceClassifierTest(unittest.TestCase): + + def test_sources(self): + self.assertIsNone(sut.classify_source('file.o')) + self.assertIsNone(sut.classify_source('file.exe')) + self.assertIsNone(sut.classify_source('/path/file.o')) + self.assertIsNone(sut.classify_source('clang')) + + self.assertEqual('c', sut.classify_source('file.c')) + self.assertEqual('c', sut.classify_source('./file.c')) + self.assertEqual('c', sut.classify_source('/path/file.c')) + self.assertEqual('c++', sut.classify_source('file.c', False)) + self.assertEqual('c++', sut.classify_source('./file.c', False)) + self.assertEqual('c++', sut.classify_source('/path/file.c', False)) diff --git a/gnu/llvm/clang/tools/scan-build-py/tests/unit/test_intercept.py b/gnu/llvm/clang/tools/scan-build-py/tests/unit/test_intercept.py new file mode 100644 index 00000000000..5473b88d833 --- /dev/null +++ b/gnu/llvm/clang/tools/scan-build-py/tests/unit/test_intercept.py @@ -0,0 +1,89 @@ +# -*- coding: utf-8 -*- +# Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +# See https://llvm.org/LICENSE.txt for license information. +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +import libear +import libscanbuild.intercept as sut +import unittest +import os.path + + +class InterceptUtilTest(unittest.TestCase): + + def test_format_entry_filters_action(self): + def test(command): + trace = {'command': command, 'directory': '/opt/src/project'} + return list(sut.format_entry(trace)) + + 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'])) + + def test_format_entry_normalize_filename(self): + parent = os.path.join(os.sep, 'home', 'me') + current = os.path.join(parent, 'project') + + def test(filename): + trace = {'directory': current, 'command': ['cc', '-c', filename]} + return list(sut.format_entry(trace))[0]['file'] + + self.assertEqual(os.path.join(current, 'file.c'), test('file.c')) + self.assertEqual(os.path.join(current, 'file.c'), test('./file.c')) + self.assertEqual(os.path.join(parent, 'file.c'), test('../file.c')) + self.assertEqual(os.path.join(current, 'file.c'), + test(os.path.join(current, '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' + + with libear.TemporaryDirectory() as tmpdir: + saved = os.environ['PATH'] + try: + 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)) + finally: + os.environ['PATH'] = saved + + saved = os.environ['PATH'] + try: + 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('unix')) + finally: + os.environ['PATH'] = saved diff --git a/gnu/llvm/clang/tools/scan-build-py/tests/unit/test_libear.py b/gnu/llvm/clang/tools/scan-build-py/tests/unit/test_libear.py new file mode 100644 index 00000000000..933da50242f --- /dev/null +++ b/gnu/llvm/clang/tools/scan-build-py/tests/unit/test_libear.py @@ -0,0 +1,29 @@ +# -*- coding: utf-8 -*- +# Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +# See https://llvm.org/LICENSE.txt for license information. +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +import libear as sut +import unittest +import os.path + + +class TemporaryDirectoryTest(unittest.TestCase): + def test_creates_directory(self): + dirname = None + with sut.TemporaryDirectory() as tmpdir: + self.assertTrue(os.path.isdir(tmpdir)) + dirname = tmpdir + self.assertIsNotNone(dirname) + self.assertFalse(os.path.exists(dirname)) + + def test_removes_directory_when_exception(self): + dirname = None + try: + with sut.TemporaryDirectory() as tmpdir: + self.assertTrue(os.path.isdir(tmpdir)) + dirname = tmpdir + raise RuntimeError('message') + except: + self.assertIsNotNone(dirname) + self.assertFalse(os.path.exists(dirname)) diff --git a/gnu/llvm/clang/tools/scan-build-py/tests/unit/test_report.py b/gnu/llvm/clang/tools/scan-build-py/tests/unit/test_report.py new file mode 100644 index 00000000000..60ec0d855ff --- /dev/null +++ b/gnu/llvm/clang/tools/scan-build-py/tests/unit/test_report.py @@ -0,0 +1,147 @@ +# -*- coding: utf-8 -*- +# Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +# See https://llvm.org/LICENSE.txt for license information. +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +import libear +import libscanbuild.report as sut +import unittest +import os +import os.path + + +def run_bug_parse(content): + with libear.TemporaryDirectory() 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 libear.TemporaryDirectory() 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.analyze as sut2 + import re + with libear.TemporaryDirectory() 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 = { + 'clang': 'clang', + 'directory': os.getcwd(), + 'flags': [], + 'file': filename, + 'output_dir': tmpdir, + 'language': 'c', + '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(unittest.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/gnu/llvm/clang/tools/scan-build-py/tests/unit/test_shell.py b/gnu/llvm/clang/tools/scan-build-py/tests/unit/test_shell.py new file mode 100644 index 00000000000..6ffbb8782a9 --- /dev/null +++ b/gnu/llvm/clang/tools/scan-build-py/tests/unit/test_shell.py @@ -0,0 +1,41 @@ +# -*- coding: utf-8 -*- +# Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +# See https://llvm.org/LICENSE.txt for license information. +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +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\\"') |