Imported Upstream version 6.10.0.49

Former-commit-id: 1d6753294b2993e1fbf92de9366bb9544db4189b
This commit is contained in:
Xamarin Public Jenkins (auto-signing)
2020-01-16 16:38:04 +00:00
parent d94e79959b
commit 468663ddbb
48518 changed files with 2789335 additions and 61176 deletions

View File

@@ -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_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

View File

@@ -0,0 +1,335 @@
# -*- 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 libear
import libscanbuild.analyze as sut
import unittest
import re
import os
import os.path
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())

View File

@@ -0,0 +1,94 @@
# -*- 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 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'))

View File

@@ -0,0 +1,122 @@
# -*- 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.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))

View File

@@ -0,0 +1,90 @@
# -*- 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 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

View File

@@ -0,0 +1,30 @@
# -*- 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 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))

View File

@@ -0,0 +1,148 @@
# -*- 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 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([]), '')

View File

@@ -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\\"')