1# -*- coding: utf-8 -*- 2# Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 3# See https://llvm.org/LICENSE.txt for license information. 4# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 5 6import unittest 7import re 8import os 9import os.path 10import libear 11import libscanbuild.analyze as sut 12 13 14class ReportDirectoryTest(unittest.TestCase): 15 16 # Test that successive report directory names ascend in lexicographic 17 # order. This is required so that report directories from two runs of 18 # scan-build can be easily matched up to compare results. 19 def test_directory_name_comparison(self): 20 with libear.TemporaryDirectory() as tmpdir, \ 21 sut.report_directory(tmpdir, False) as report_dir1, \ 22 sut.report_directory(tmpdir, False) as report_dir2, \ 23 sut.report_directory(tmpdir, False) as report_dir3: 24 self.assertLess(report_dir1, report_dir2) 25 self.assertLess(report_dir2, report_dir3) 26 27 28class FilteringFlagsTest(unittest.TestCase): 29 30 def test_language_captured(self): 31 def test(flags): 32 cmd = ['clang', '-c', 'source.c'] + flags 33 opts = sut.classify_parameters(cmd) 34 return opts['language'] 35 36 self.assertEqual(None, test([])) 37 self.assertEqual('c', test(['-x', 'c'])) 38 self.assertEqual('cpp', test(['-x', 'cpp'])) 39 40 def test_arch(self): 41 def test(flags): 42 cmd = ['clang', '-c', 'source.c'] + flags 43 opts = sut.classify_parameters(cmd) 44 return opts['arch_list'] 45 46 self.assertEqual([], test([])) 47 self.assertEqual(['mips'], test(['-arch', 'mips'])) 48 self.assertEqual(['mips', 'i386'], 49 test(['-arch', 'mips', '-arch', 'i386'])) 50 51 def assertFlagsChanged(self, expected, flags): 52 cmd = ['clang', '-c', 'source.c'] + flags 53 opts = sut.classify_parameters(cmd) 54 self.assertEqual(expected, opts['flags']) 55 56 def assertFlagsUnchanged(self, flags): 57 self.assertFlagsChanged(flags, flags) 58 59 def assertFlagsFiltered(self, flags): 60 self.assertFlagsChanged([], flags) 61 62 def test_optimalizations_pass(self): 63 self.assertFlagsUnchanged(['-O']) 64 self.assertFlagsUnchanged(['-O1']) 65 self.assertFlagsUnchanged(['-Os']) 66 self.assertFlagsUnchanged(['-O2']) 67 self.assertFlagsUnchanged(['-O3']) 68 69 def test_include_pass(self): 70 self.assertFlagsUnchanged([]) 71 self.assertFlagsUnchanged(['-include', '/usr/local/include']) 72 self.assertFlagsUnchanged(['-I.']) 73 self.assertFlagsUnchanged(['-I', '.']) 74 self.assertFlagsUnchanged(['-I/usr/local/include']) 75 self.assertFlagsUnchanged(['-I', '/usr/local/include']) 76 self.assertFlagsUnchanged(['-I/opt', '-I', '/opt/otp/include']) 77 self.assertFlagsUnchanged(['-isystem', '/path']) 78 self.assertFlagsUnchanged(['-isystem=/path']) 79 80 def test_define_pass(self): 81 self.assertFlagsUnchanged(['-DNDEBUG']) 82 self.assertFlagsUnchanged(['-UNDEBUG']) 83 self.assertFlagsUnchanged(['-Dvar1=val1', '-Dvar2=val2']) 84 self.assertFlagsUnchanged(['-Dvar="val ues"']) 85 86 def test_output_filtered(self): 87 self.assertFlagsFiltered(['-o', 'source.o']) 88 89 def test_some_warning_filtered(self): 90 self.assertFlagsFiltered(['-Wall']) 91 self.assertFlagsFiltered(['-Wnoexcept']) 92 self.assertFlagsFiltered(['-Wreorder', '-Wunused', '-Wundef']) 93 self.assertFlagsUnchanged(['-Wno-reorder', '-Wno-unused']) 94 95 def test_compile_only_flags_pass(self): 96 self.assertFlagsUnchanged(['-std=C99']) 97 self.assertFlagsUnchanged(['-nostdinc']) 98 self.assertFlagsUnchanged(['-isystem', '/image/debian']) 99 self.assertFlagsUnchanged(['-iprefix', '/usr/local']) 100 self.assertFlagsUnchanged(['-iquote=me']) 101 self.assertFlagsUnchanged(['-iquote', 'me']) 102 103 def test_compile_and_link_flags_pass(self): 104 self.assertFlagsUnchanged(['-fsinged-char']) 105 self.assertFlagsUnchanged(['-fPIC']) 106 self.assertFlagsUnchanged(['-stdlib=libc++']) 107 self.assertFlagsUnchanged(['--sysroot', '/']) 108 self.assertFlagsUnchanged(['-isysroot', '/']) 109 110 def test_some_flags_filtered(self): 111 self.assertFlagsFiltered(['-g']) 112 self.assertFlagsFiltered(['-fsyntax-only']) 113 self.assertFlagsFiltered(['-save-temps']) 114 self.assertFlagsFiltered(['-init', 'my_init']) 115 self.assertFlagsFiltered(['-sectorder', 'a', 'b', 'c']) 116 117 118class Spy(object): 119 def __init__(self): 120 self.arg = None 121 self.success = 0 122 123 def call(self, params): 124 self.arg = params 125 return self.success 126 127 128class RunAnalyzerTest(unittest.TestCase): 129 130 @staticmethod 131 def run_analyzer(content, failures_report): 132 with libear.TemporaryDirectory() as tmpdir: 133 filename = os.path.join(tmpdir, 'test.cpp') 134 with open(filename, 'w') as handle: 135 handle.write(content) 136 137 opts = { 138 'clang': 'clang', 139 'directory': os.getcwd(), 140 'flags': [], 141 'direct_args': [], 142 'file': filename, 143 'output_dir': tmpdir, 144 'output_format': 'plist', 145 'output_failures': failures_report 146 } 147 spy = Spy() 148 result = sut.run_analyzer(opts, spy.call) 149 return (result, spy.arg) 150 151 def test_run_analyzer(self): 152 content = "int div(int n, int d) { return n / d; }" 153 (result, fwds) = RunAnalyzerTest.run_analyzer(content, False) 154 self.assertEqual(None, fwds) 155 self.assertEqual(0, result['exit_code']) 156 157 def test_run_analyzer_crash(self): 158 content = "int div(int n, int d) { return n / d }" 159 (result, fwds) = RunAnalyzerTest.run_analyzer(content, False) 160 self.assertEqual(None, fwds) 161 self.assertEqual(1, result['exit_code']) 162 163 def test_run_analyzer_crash_and_forwarded(self): 164 content = "int div(int n, int d) { return n / d }" 165 (_, fwds) = RunAnalyzerTest.run_analyzer(content, True) 166 self.assertEqual(1, fwds['exit_code']) 167 self.assertTrue(len(fwds['error_output']) > 0) 168 169 170class ReportFailureTest(unittest.TestCase): 171 172 def assertUnderFailures(self, path): 173 self.assertEqual('failures', os.path.basename(os.path.dirname(path))) 174 175 def test_report_failure_create_files(self): 176 with libear.TemporaryDirectory() as tmpdir: 177 # create input file 178 filename = os.path.join(tmpdir, 'test.c') 179 with open(filename, 'w') as handle: 180 handle.write('int main() { return 0') 181 uname_msg = ' '.join(os.uname()) + os.linesep 182 error_msg = 'this is my error output' 183 # execute test 184 opts = { 185 'clang': 'clang', 186 'directory': os.getcwd(), 187 'flags': [], 188 'file': filename, 189 'output_dir': tmpdir, 190 'language': 'c', 191 'error_type': 'other_error', 192 'error_output': error_msg, 193 'exit_code': 13 194 } 195 sut.report_failure(opts) 196 # verify the result 197 result = dict() 198 pp_file = None 199 for root, _, files in os.walk(tmpdir): 200 keys = [os.path.join(root, name) for name in files] 201 for key in keys: 202 with open(key, 'r') as handle: 203 result[key] = handle.readlines() 204 if re.match(r'^(.*/)+clang(.*)\.i$', key): 205 pp_file = key 206 207 # prepocessor file generated 208 self.assertUnderFailures(pp_file) 209 # info file generated and content dumped 210 info_file = pp_file + '.info.txt' 211 self.assertTrue(info_file in result) 212 self.assertEqual('Other Error\n', result[info_file][1]) 213 self.assertEqual(uname_msg, result[info_file][3]) 214 # error file generated and content dumped 215 error_file = pp_file + '.stderr.txt' 216 self.assertTrue(error_file in result) 217 self.assertEqual([error_msg], result[error_file]) 218 219 220class AnalyzerTest(unittest.TestCase): 221 222 def test_nodebug_macros_appended(self): 223 def test(flags): 224 spy = Spy() 225 opts = {'flags': flags, 'force_debug': True} 226 self.assertEqual(spy.success, 227 sut.filter_debug_flags(opts, spy.call)) 228 return spy.arg['flags'] 229 230 self.assertEqual(['-UNDEBUG'], test([])) 231 self.assertEqual(['-DNDEBUG', '-UNDEBUG'], test(['-DNDEBUG'])) 232 self.assertEqual(['-DSomething', '-UNDEBUG'], test(['-DSomething'])) 233 234 def test_set_language_fall_through(self): 235 def language(expected, input): 236 spy = Spy() 237 input.update({'compiler': 'c', 'file': 'test.c'}) 238 self.assertEqual(spy.success, sut.language_check(input, spy.call)) 239 self.assertEqual(expected, spy.arg['language']) 240 241 language('c', {'language': 'c', 'flags': []}) 242 language('c++', {'language': 'c++', 'flags': []}) 243 244 def test_set_language_stops_on_not_supported(self): 245 spy = Spy() 246 input = { 247 'compiler': 'c', 248 'flags': [], 249 'file': 'test.java', 250 'language': 'java' 251 } 252 self.assertIsNone(sut.language_check(input, spy.call)) 253 self.assertIsNone(spy.arg) 254 255 def test_set_language_sets_flags(self): 256 def flags(expected, input): 257 spy = Spy() 258 input.update({'compiler': 'c', 'file': 'test.c'}) 259 self.assertEqual(spy.success, sut.language_check(input, spy.call)) 260 self.assertEqual(expected, spy.arg['flags']) 261 262 flags(['-x', 'c'], {'language': 'c', 'flags': []}) 263 flags(['-x', 'c++'], {'language': 'c++', 'flags': []}) 264 265 def test_set_language_from_filename(self): 266 def language(expected, input): 267 spy = Spy() 268 input.update({'language': None, 'flags': []}) 269 self.assertEqual(spy.success, sut.language_check(input, spy.call)) 270 self.assertEqual(expected, spy.arg['language']) 271 272 language('c', {'file': 'file.c', 'compiler': 'c'}) 273 language('c++', {'file': 'file.c', 'compiler': 'c++'}) 274 language('c++', {'file': 'file.cxx', 'compiler': 'c'}) 275 language('c++', {'file': 'file.cxx', 'compiler': 'c++'}) 276 language('c++', {'file': 'file.cpp', 'compiler': 'c++'}) 277 language('c-cpp-output', {'file': 'file.i', 'compiler': 'c'}) 278 language('c++-cpp-output', {'file': 'file.i', 'compiler': 'c++'}) 279 280 def test_arch_loop_sets_flags(self): 281 def flags(archs): 282 spy = Spy() 283 input = {'flags': [], 'arch_list': archs} 284 sut.arch_check(input, spy.call) 285 return spy.arg['flags'] 286 287 self.assertEqual([], flags([])) 288 self.assertEqual(['-arch', 'i386'], flags(['i386'])) 289 self.assertEqual(['-arch', 'i386'], flags(['i386', 'ppc'])) 290 self.assertEqual(['-arch', 'sparc'], flags(['i386', 'sparc'])) 291 292 def test_arch_loop_stops_on_not_supported(self): 293 def stop(archs): 294 spy = Spy() 295 input = {'flags': [], 'arch_list': archs} 296 self.assertIsNone(sut.arch_check(input, spy.call)) 297 self.assertIsNone(spy.arg) 298 299 stop(['ppc']) 300 stop(['ppc64']) 301 302 303@sut.require([]) 304def method_without_expecteds(opts): 305 return 0 306 307 308@sut.require(['this', 'that']) 309def method_with_expecteds(opts): 310 return 0 311 312 313@sut.require([]) 314def method_exception_from_inside(opts): 315 raise Exception('here is one') 316 317 318class RequireDecoratorTest(unittest.TestCase): 319 320 def test_method_without_expecteds(self): 321 self.assertEqual(method_without_expecteds(dict()), 0) 322 self.assertEqual(method_without_expecteds({}), 0) 323 self.assertEqual(method_without_expecteds({'this': 2}), 0) 324 self.assertEqual(method_without_expecteds({'that': 3}), 0) 325 326 def test_method_with_expecteds(self): 327 self.assertRaises(KeyError, method_with_expecteds, dict()) 328 self.assertRaises(KeyError, method_with_expecteds, {}) 329 self.assertRaises(KeyError, method_with_expecteds, {'this': 2}) 330 self.assertRaises(KeyError, method_with_expecteds, {'that': 3}) 331 self.assertEqual(method_with_expecteds({'this': 0, 'that': 3}), 0) 332 333 def test_method_exception_not_caught(self): 334 self.assertRaises(Exception, method_exception_from_inside, dict()) 335 336 337class PrefixWithTest(unittest.TestCase): 338 339 def test_gives_empty_on_empty(self): 340 res = sut.prefix_with(0, []) 341 self.assertFalse(res) 342 343 def test_interleaves_prefix(self): 344 res = sut.prefix_with(0, [1, 2, 3]) 345 self.assertListEqual([0, 1, 0, 2, 0, 3], res) 346 347 348class MergeCtuMapTest(unittest.TestCase): 349 350 def test_no_map_gives_empty(self): 351 pairs = sut.create_global_ctu_extdef_map([]) 352 self.assertFalse(pairs) 353 354 def test_multiple_maps_merged(self): 355 concat_map = ['c:@F@fun1#I# ast/fun1.c.ast', 356 'c:@F@fun2#I# ast/fun2.c.ast', 357 'c:@F@fun3#I# ast/fun3.c.ast'] 358 pairs = sut.create_global_ctu_extdef_map(concat_map) 359 self.assertTrue(('c:@F@fun1#I#', 'ast/fun1.c.ast') in pairs) 360 self.assertTrue(('c:@F@fun2#I#', 'ast/fun2.c.ast') in pairs) 361 self.assertTrue(('c:@F@fun3#I#', 'ast/fun3.c.ast') in pairs) 362 self.assertEqual(3, len(pairs)) 363 364 def test_not_unique_func_left_out(self): 365 concat_map = ['c:@F@fun1#I# ast/fun1.c.ast', 366 'c:@F@fun2#I# ast/fun2.c.ast', 367 'c:@F@fun1#I# ast/fun7.c.ast'] 368 pairs = sut.create_global_ctu_extdef_map(concat_map) 369 self.assertFalse(('c:@F@fun1#I#', 'ast/fun1.c.ast') in pairs) 370 self.assertFalse(('c:@F@fun1#I#', 'ast/fun7.c.ast') in pairs) 371 self.assertTrue(('c:@F@fun2#I#', 'ast/fun2.c.ast') in pairs) 372 self.assertEqual(1, len(pairs)) 373 374 def test_duplicates_are_kept(self): 375 concat_map = ['c:@F@fun1#I# ast/fun1.c.ast', 376 'c:@F@fun2#I# ast/fun2.c.ast', 377 'c:@F@fun1#I# ast/fun1.c.ast'] 378 pairs = sut.create_global_ctu_extdef_map(concat_map) 379 self.assertTrue(('c:@F@fun1#I#', 'ast/fun1.c.ast') in pairs) 380 self.assertTrue(('c:@F@fun2#I#', 'ast/fun2.c.ast') in pairs) 381 self.assertEqual(2, len(pairs)) 382 383 def test_space_handled_in_source(self): 384 concat_map = ['c:@F@fun1#I# ast/f un.c.ast'] 385 pairs = sut.create_global_ctu_extdef_map(concat_map) 386 self.assertTrue(('c:@F@fun1#I#', 'ast/f un.c.ast') in pairs) 387 self.assertEqual(1, len(pairs)) 388 389 390class ExtdefMapSrcToAstTest(unittest.TestCase): 391 392 def test_empty_gives_empty(self): 393 fun_ast_lst = sut.extdef_map_list_src_to_ast([]) 394 self.assertFalse(fun_ast_lst) 395 396 def test_sources_to_asts(self): 397 fun_src_lst = ['c:@F@f1#I# ' + os.path.join(os.sep + 'path', 'f1.c'), 398 'c:@F@f2#I# ' + os.path.join(os.sep + 'path', 'f2.c')] 399 fun_ast_lst = sut.extdef_map_list_src_to_ast(fun_src_lst) 400 self.assertTrue('c:@F@f1#I# ' + 401 os.path.join('ast', 'path', 'f1.c.ast') 402 in fun_ast_lst) 403 self.assertTrue('c:@F@f2#I# ' + 404 os.path.join('ast', 'path', 'f2.c.ast') 405 in fun_ast_lst) 406 self.assertEqual(2, len(fun_ast_lst)) 407 408 def test_spaces_handled(self): 409 fun_src_lst = ['c:@F@f1#I# ' + os.path.join(os.sep + 'path', 'f 1.c')] 410 fun_ast_lst = sut.extdef_map_list_src_to_ast(fun_src_lst) 411 self.assertTrue('c:@F@f1#I# ' + 412 os.path.join('ast', 'path', 'f 1.c.ast') 413 in fun_ast_lst) 414 self.assertEqual(1, len(fun_ast_lst)) 415