def run_level36(): f = """\ 4 2 1 1 2 3 3 3 . . 2 3 3 . 4 . . 2 . 2 4 3 2 2 2 . . . 2 4 3 4 . . 3 2 3 3 """ order = DESCENDING strategy = Done.FIRST_STRATEGY output = StringIO() solve_file(f, strategy, order, output) expected = """\ 3 4 3 2 3 4 4 . 3 2 . . 3 4 3 2 . 1 . 3 . 2 3 3 . 2 . 2 3 . 2 . 2 2 2 . 1 """ if output.getvalue() != expected: raise AssertionError("got a wrong answer:\n%s" % output.getvalue())
def test_normalize_partition_tags_bad_vendor_deps(self): """Check whether normalize_partition_tags() hides the dependencies from the system partition to the vendor partition if the dependencies are not SP-HAL libraries.""" gb = GraphBuilder() libfwk = gb.add_lib32(PT_SYSTEM, 'libfwk', dt_needed=['libvnd.so']) libvnd = gb.add_lib32(PT_VENDOR, 'libvnd') gb.resolve() self.assertIn(libvnd, libfwk.deps_needed) self.assertIn(libfwk, libvnd.users_needed) stderr = StringIO() with patch('sys.stderr', stderr): gb.graph.normalize_partition_tags(set(), None) self.assertRegexpMatches( stderr.getvalue(), 'error: .*: system exe/lib must not depend on vendor lib .*. ' 'Assume such dependency does not exist.') self.assertNotIn(libvnd, libfwk.deps_needed) self.assertNotIn(libfwk, libvnd.users_needed) self.assertIn(libvnd, libfwk.deps_needed_hidden) self.assertIn(libfwk, libvnd.users_needed_hidden) self.assertIn(libvnd, libfwk.deps_all) self.assertIn(libvnd, libfwk.deps_needed_all) self.assertNotIn(libvnd, libfwk.deps_good) self.assertIn(libfwk, libvnd.users_all) self.assertIn(libfwk, libvnd.users_needed_all) self.assertNotIn(libfwk, libvnd.users_good)
def test_dump(self): elf = ELF(ELF.ELFCLASS32, ELF.ELFDATA2LSB, 183, ['a'], ['b'], ['libc.so', 'libm.so'], {'hello', 'world'}, {'d', 'e'}) f = StringIO() elf.dump(f) actual_output = f.getvalue() self.assertEqual('EI_CLASS\t32\n' 'EI_DATA\t\tLittle-Endian\n' 'E_MACHINE\tEM_AARCH64\n' 'FILE_SIZE\t0\n' 'RO_SEG_FILE_SIZE\t0\n' 'RO_SEG_MEM_SIZE\t0\n' 'RW_SEG_FILE_SIZE\t0\n' 'RW_SEG_MEM_SIZE\t0\n' 'DT_RPATH\ta\n' 'DT_RUNPATH\tb\n' 'DT_NEEDED\tlibc.so\n' 'DT_NEEDED\tlibm.so\n' 'EXP_SYMBOL\thello\n' 'EXP_SYMBOL\tworld\n' 'IMP_SYMBOL\td\n' 'IMP_SYMBOL\te\n', actual_output)
def test_dump(self): elf = ELF(ELF.ELFCLASS32, ELF.ELFDATA2LSB, 183, ['a'], ['b'], ['libc.so', 'libm.so'], {'hello', 'world'}, {'d', 'e'}) f = StringIO() elf.dump(f) actual_output = f.getvalue() self.assertEqual( 'EI_CLASS\t32\n' 'EI_DATA\t\tLittle-Endian\n' 'E_MACHINE\tEM_AARCH64\n' 'FILE_SIZE\t0\n' 'RO_SEG_FILE_SIZE\t0\n' 'RO_SEG_MEM_SIZE\t0\n' 'RW_SEG_FILE_SIZE\t0\n' 'RW_SEG_MEM_SIZE\t0\n' 'DT_RPATH\ta\n' 'DT_RUNPATH\tb\n' 'DT_NEEDED\tlibc.so\n' 'DT_NEEDED\tlibm.so\n' 'EXP_SYMBOL\thello\n' 'EXP_SYMBOL\tworld\n' 'IMP_SYMBOL\td\n' 'IMP_SYMBOL\te\n', actual_output)
def test_normalize_partition_tags_bad_vendor_deps(self): """Check whether normalize_partition_tags() hides the dependencies from the system partition to the vendor partition if the dependencies are not SP-HAL libraries.""" gb = GraphBuilder() libfwk = gb.add_lib32(PT_SYSTEM, 'libfwk', dt_needed=['libvnd.so']) libvnd = gb.add_lib32(PT_VENDOR, 'libvnd') gb.resolve() self.assertIn(libvnd, libfwk.deps_needed) self.assertIn(libfwk, libvnd.users_needed) stderr = StringIO() with patch('sys.stderr', stderr): gb.graph.normalize_partition_tags(set(), None) self.assertRegex( stderr.getvalue(), 'error: .*: system exe/lib must not depend on vendor lib .*. ' 'Assume such dependency does not exist.') self.assertNotIn(libvnd, libfwk.deps_needed) self.assertNotIn(libfwk, libvnd.users_needed) self.assertIn(libvnd, libfwk.deps_needed_hidden) self.assertIn(libfwk, libvnd.users_needed_hidden) self.assertIn(libvnd, libfwk.deps_all) self.assertIn(libvnd, libfwk.deps_needed_all) self.assertNotIn(libvnd, libfwk.deps_good) self.assertIn(libfwk, libvnd.users_all) self.assertIn(libfwk, libvnd.users_needed_all) self.assertNotIn(libfwk, libvnd.users_good)
def test_shouldReportParseErrors(self): output = StringIO() report_parse_error(output, path.join(pardir, 'foo', 'myprog.py'), ParseError('the message')) self.assertEqual(output.getvalue(), 'myprog: parse error: the message\n')
def test_dump_exported_symbols(self): elf = ELF(ELF.ELFCLASS32, ELF.ELFDATA2LSB, 183, ['a'], ['b'], ['libc.so', 'libm.so'], {'hello', 'world'}) f = StringIO() elf.dump_exported_symbols(f) actual_output = f.getvalue() self.assertEqual('hello\nworld\n', actual_output)
def runcode(self, code_obj): fake_stdout = StringIO() sys.stdout = fake_stdout sys.stderr = fake_stdout try: code.InteractiveConsole.runcode(self, code_obj) finally: sys.stdout = sys.__stdout__ sys.stderr = sys.__stderr__ self.write(fake_stdout.getvalue())
def test_add_dlopen_deps_error(self): gb = GraphBuilder() liba = gb.add_lib32(PT_SYSTEM, 'liba') libb = gb.add_lib32(PT_SYSTEM, 'libb') gb.resolve() with tempfile.NamedTemporaryFile(mode='w') as tmp_file: tmp_file.write('/system/lib/libc.so: /system/lib/libd.so') tmp_file.seek(0) stderr = StringIO() with patch('sys.stderr', stderr): gb.graph.add_dlopen_deps(tmp_file.name) self.assertRegexpMatches( stderr.getvalue(), 'error:' + re.escape(tmp_file.name) + ':1: ' + 'Failed to add dlopen dependency from .* to .*\\.\n')
def test_add_dlopen_deps_error(self): gb = GraphBuilder() liba = gb.add_lib32(PT_SYSTEM, 'liba') libb = gb.add_lib32(PT_SYSTEM, 'libb') gb.resolve() with tempfile.NamedTemporaryFile(mode='w') as tmp_file: tmp_file.write('/system/lib/libc.so: /system/lib/libd.so') tmp_file.seek(0) stderr = StringIO() with patch('sys.stderr', stderr): gb.graph.add_dlopen_deps(tmp_file.name) self.assertRegexpMatches( stderr.getvalue(), 'error: Failed to add dlopen dependency from .* to .*\\.\n')
def test_add_dlopen_deps_regex(self): gb = GraphBuilder() liba = gb.add_lib32(PT_SYSTEM, 'liba') libb = gb.add_lib32(PT_SYSTEM, 'libb') gb.resolve() with tempfile.NamedTemporaryFile(mode='w') as tmp_file: tmp_file.write('[regex].*libb\\.so: [regex].*/${LIB}/liba\\.so') tmp_file.seek(0) stderr = StringIO() with patch('sys.stderr', stderr): gb.graph.add_dlopen_deps(tmp_file.name) self.assertEqual('', stderr.getvalue()) self.assertIn(liba, libb.deps_dlopen) self.assertIn(libb, liba.users_dlopen)
class MockHeaderWriterTests(TestCase): def setUp(self): self.hBuffer = StringIO() def test_shouldWriteHeader(self): # Given mockpaths = MagicMock() mockpaths.headerrelpath = "mockable.h" mockpaths.guardmacro = "MOCK_MOCKABLE_H" mockgen = MagicMock() mockgen.mocks = [ MockInfo(mockname="mock_func1", funcname="", prototype="", return_text="", return_hint="", args_info=[]), MockInfo(mockname="mock_func2", funcname="", prototype="", return_text="", return_hint="", args_info=[]) ] mock_h_writer = MockHeaderWriter(mockpaths, mockgen) # When mock_h_writer.write_header(self.hBuffer) # Then self.assertEqual( self.hBuffer.getvalue(), """#ifndef MOCK_MOCKABLE_H #define MOCK_MOCKABLE_H #include "mockable.h" #include "pfstest-mock.h" pfstest_mock_declare(mock_func1); pfstest_mock_declare(mock_func2); #endif /* !defined(MOCK_MOCKABLE_H) */ """)
def test_add_dlopen_deps_lib_subset_single_bitness(self): gb = GraphBuilder() liba_32, liba_64 = gb.add_multilib(PT_SYSTEM, 'liba') libb_32 = gb.add_lib32(PT_SYSTEM, 'libb') gb.resolve() with tempfile.NamedTemporaryFile(mode='w') as tmp_file: tmp_file.write('/system/${LIB}/libb.so: /system/${LIB}/liba.so') tmp_file.seek(0) stderr = StringIO() with patch('sys.stderr', stderr): gb.graph.add_dlopen_deps(tmp_file.name) self.assertEqual('', stderr.getvalue()) self.assertIn(liba_32, libb_32.deps_dlopen) self.assertIn(libb_32, liba_32.users_dlopen) self.assertEqual(0, len(liba_64.users_dlopen))
def prepare_lines(ih): sio = StringIO() ih.dump(sio) dump = sio.getvalue() lines = dump.splitlines() return lines
def _extract_error(self, type, err, tb): file = StringIO() traceback.print_exception(type, err, tb, None, file) return file.getvalue()
def assertASTShows(self, ast, string): showbuf = StringIO() ast.show(buf=showbuf, nodenames=True, attrnames=True) self.assertEqual(showbuf.getvalue(), string)
class MockImplementationWriterTests(TestCase): def setUp(self): self.maxDiff = None self.cBuffer = StringIO() self.mockpaths = MagicMock() self.mockpaths.mockheaderrelpath = "mock-mockable.h" def test_shouldWriteImplementation(self): # Given mockgen = MagicMock() mockgen.mocks = [ MockInfo(mockname = "mock_func1", funcname = "func1", prototype = "void func1(void)", return_text = "void", return_hint = ReturnHint.VOID, args_info = []) ] mock_c_writer = MockImplementationWriter(self.mockpaths, mockgen) # When mock_c_writer.write_implementation(self.cBuffer) # Then self.assertEqual( self.cBuffer.getvalue(), '#include "mock-mockable.h"\n' + boilerplate_includes + """pfstest_mock_define(mock_func1, "func1", 0); void func1(void) { pfstest_value_t *__pfstest_return_value = pfstest_mock_invoke(mock_func1, NULL); (void)__pfstest_return_value; } """ ) def test_shouldWriteMultipleFunctions(self): # Given mockgen = MagicMock() mockgen.mocks = [ MockInfo(mockname = "mock_func1", funcname = "func1", prototype = "void func1(void)", return_text = "void", return_hint = ReturnHint.VOID, args_info = []), MockInfo(mockname = "mock_func2", funcname = "func2", prototype = "void func2(void)", return_text = "void", return_hint = ReturnHint.VOID, args_info = []), ] mock_c_writer = MockImplementationWriter(self.mockpaths, mockgen) # When mock_c_writer.write_implementation(self.cBuffer) # Then self.assertEqual( self.cBuffer.getvalue(), '#include "mock-mockable.h"\n' + boilerplate_includes + """pfstest_mock_define(mock_func1, "func1", 0); void func1(void) { pfstest_value_t *__pfstest_return_value = pfstest_mock_invoke(mock_func1, NULL); (void)__pfstest_return_value; } pfstest_mock_define(mock_func2, "func2", 0); void func2(void) { pfstest_value_t *__pfstest_return_value = pfstest_mock_invoke(mock_func2, NULL); (void)__pfstest_return_value; } """ ) def test_shouldHandlePrimitiveReturnTypes(self): # Given mockgen = MagicMock() mockgen.mocks = [ MockInfo(mockname = "mock_func1", funcname = "func1", prototype = "int func1(void)", return_text = "int", return_hint = ReturnHint.PRIMITIVE, args_info = []) ] mock_c_writer = MockImplementationWriter(self.mockpaths, mockgen) # When mock_c_writer.write_implementation(self.cBuffer) # Then self.assertEqual( self.cBuffer.getvalue(), '#include "mock-mockable.h"\n' + boilerplate_includes + """pfstest_mock_define(mock_func1, "func1", 0); int func1(void) { int __pfstest_default_return = 0; pfstest_value_t *__pfstest_return_value = pfstest_mock_invoke(mock_func1, pfstest_the_memory( &__pfstest_default_return, sizeof(__pfstest_default_return))); return *(int *)pfstest_value_data(__pfstest_return_value); } """ ) def test_shouldHandlePointerReturnTypes(self): # Given mockgen = MagicMock() mockgen.mocks = [ MockInfo(mockname = "mock_func1", funcname = "func1", prototype = "char *func1(void)", return_text = "char *", return_hint = ReturnHint.POINTER, args_info = []) ] mock_c_writer = MockImplementationWriter(self.mockpaths, mockgen) # When mock_c_writer.write_implementation(self.cBuffer) # Then self.assertEqual( self.cBuffer.getvalue(), '#include "mock-mockable.h"\n' + boilerplate_includes + """pfstest_mock_define(mock_func1, "func1", 0); char *func1(void) { char * __pfstest_default_return = NULL; pfstest_value_t *__pfstest_return_value = pfstest_mock_invoke(mock_func1, pfstest_the_pointer(__pfstest_default_return)); return (char *)pfstest_value_data(__pfstest_return_value); } """ ) def test_shouldHandleStructReturnTypes(self): # Given mockgen = MagicMock() mockgen.mocks = [ MockInfo(mockname = "mock_func1", funcname = "func1", prototype = "struct foo func1(void)", return_text = "struct foo", return_hint = ReturnHint.BLOB, args_info = []) ] mock_c_writer = MockImplementationWriter(self.mockpaths, mockgen) # When mock_c_writer.write_implementation(self.cBuffer) # Then self.assertEqual( self.cBuffer.getvalue(), '#include "mock-mockable.h"\n' + boilerplate_includes + """pfstest_mock_define(mock_func1, "func1", 0); struct foo func1(void) { struct foo __pfstest_default_return; memset(&__pfstest_default_return, 0, sizeof(__pfstest_default_return)); pfstest_value_t *__pfstest_return_value = pfstest_mock_invoke(mock_func1, pfstest_the_memory( &__pfstest_default_return, sizeof(__pfstest_default_return))); return *(struct foo *)pfstest_value_data(__pfstest_return_value); } """ ) def test_shouldWriteBlobParameter(self): # Given mockgen = MagicMock() mockgen.mocks = [ MockInfo(mockname = "mock_func1", funcname = "func1", prototype = "void func1(int __pfstest_arg_0)", return_text = "void", return_hint = ReturnHint.VOID, args_info = [ArgInfo('__pfstest_arg_0', ArgHint.BLOB)] )] mock_c_writer = MockImplementationWriter(self.mockpaths, mockgen) # When mock_c_writer.write_implementation(self.cBuffer) # Then self.assertEqual( self.cBuffer.getvalue(), '#include "mock-mockable.h"\n' + boilerplate_includes + """pfstest_mock_define(mock_func1, "func1", 1); void func1(int __pfstest_arg_0) { pfstest_value_t *__pfstest_return_value = pfstest_mock_invoke(mock_func1, NULL, pfstest_the_memory(&__pfstest_arg_0, sizeof(__pfstest_arg_0))); (void)__pfstest_return_value; } """ ) def test_shouldWritePointerParameter(self): # Given mockgen = MagicMock() mockgen.mocks = [ MockInfo(mockname = "mock_func1", funcname = "func1", prototype = "void func1(char *__pfstest_arg_0)", return_text = "void", return_hint = ReturnHint.VOID, args_info = [ArgInfo('__pfstest_arg_0', ArgHint.POINTER)] )] mock_c_writer = MockImplementationWriter(self.mockpaths, mockgen) # When mock_c_writer.write_implementation(self.cBuffer) # Then self.assertEqual( self.cBuffer.getvalue(), '#include "mock-mockable.h"\n' + boilerplate_includes + """pfstest_mock_define(mock_func1, "func1", 1); void func1(char *__pfstest_arg_0) { pfstest_value_t *__pfstest_return_value = pfstest_mock_invoke(mock_func1, NULL, pfstest_the_pointer(__pfstest_arg_0)); (void)__pfstest_return_value; } """ ) def test_shouldWriteMultipleParameters(self): # Given mockgen = MagicMock() mockgen.mocks = [ MockInfo(mockname = "mock_func1", funcname = "func1", prototype = "void func1(int __pfstest_arg_0, " + "char *__pfstest_arg_1)", return_text = "void", return_hint = ReturnHint.VOID, args_info = [ArgInfo('__pfstest_arg_0', ArgHint.BLOB), ArgInfo('__pfstest_arg_1', ArgHint.POINTER)] )] mock_c_writer = MockImplementationWriter(self.mockpaths, mockgen) # When mock_c_writer.write_implementation(self.cBuffer) # Then self.assertEqual( self.cBuffer.getvalue(), '#include "mock-mockable.h"\n' + boilerplate_includes + """pfstest_mock_define(mock_func1, "func1", 2); void func1(int __pfstest_arg_0, char *__pfstest_arg_1) { pfstest_value_t *__pfstest_return_value = pfstest_mock_invoke(mock_func1, NULL, pfstest_the_memory(&__pfstest_arg_0, sizeof(__pfstest_arg_0)), pfstest_the_pointer(__pfstest_arg_1)); (void)__pfstest_return_value; } """ )
def make_editor_icons_action(target, source, env): dst = target[0] svg_icons = source icons_string = StringIO() for f in svg_icons: fname = str(f) icons_string.write('\t"') with open(fname, 'rb') as svgf: b = svgf.read(1) while (len(b) == 1): icons_string.write("\\" + str(hex(ord(b)))[1:]) b = svgf.read(1) icons_string.write('"') if fname != svg_icons[-1]: icons_string.write(",") icons_string.write('\n') s = StringIO() s.write("/* THIS FILE IS GENERATED DO NOT EDIT */\n") s.write("#ifndef _EDITOR_ICONS_H\n") s.write("#define _EDITOR_ICONS_H\n") s.write("static const int editor_icons_count = {};\n".format( len(svg_icons))) s.write("static const char *editor_icons_sources[] = {\n") s.write(icons_string.getvalue()) s.write('};\n\n') s.write("static const char *editor_icons_names[] = {\n") # this is used to store the indices of thumbnail icons thumb_medium_indices = [] thumb_big_indices = [] index = 0 for f in svg_icons: fname = str(f) # Trim the `.svg` extension from the string. icon_name = os.path.basename(fname)[:-4] # some special cases if icon_name.endswith( "MediumThumb"): # don't know a better way to handle this thumb_medium_indices.append(str(index)) if icon_name.endswith( "BigThumb"): # don't know a better way to handle this thumb_big_indices.append(str(index)) s.write('\t"{0}"'.format(icon_name)) if fname != svg_icons[-1]: s.write(",") s.write('\n') index += 1 s.write('};\n') if thumb_medium_indices: s.write("\n\n") s.write("static const int editor_md_thumbs_count = {};\n".format( len(thumb_medium_indices))) s.write("static const int editor_md_thumbs_indices[] = {") s.write(", ".join(thumb_medium_indices)) s.write("};\n") if thumb_big_indices: s.write("\n\n") s.write("static const int editor_bg_thumbs_count = {};\n".format( len(thumb_big_indices))) s.write("static const int editor_bg_thumbs_indices[] = {") s.write(", ".join(thumb_big_indices)) s.write("};\n") s.write("#endif\n") with open(dst, "w") as f: f.write(s.getvalue()) s.close() icons_string.close()
def make_editor_icons_action(target, source, env): dst = target[0] svg_icons = source icons_string = StringIO() for f in svg_icons: fname = str(f) icons_string.write('\t"') with open(fname, 'rb') as svgf: b = svgf.read(1) while(len(b) == 1): icons_string.write("\\" + str(hex(ord(b)))[1:]) b = svgf.read(1) icons_string.write('"') if fname != svg_icons[-1]: icons_string.write(",") icons_string.write('\n') s = StringIO() s.write("/* THIS FILE IS GENERATED DO NOT EDIT */\n") s.write("#ifndef _EDITOR_ICONS_H\n") s.write("#define _EDITOR_ICONS_H\n") s.write("static const int editor_icons_count = {};\n".format(len(svg_icons))) s.write("static const char *editor_icons_sources[] = {\n") s.write(icons_string.getvalue()) s.write('};\n\n') s.write("static const char *editor_icons_names[] = {\n") # this is used to store the indices of thumbnail icons thumb_medium_indices = []; thumb_big_indices = []; index = 0 for f in svg_icons: fname = str(f) icon_name = os.path.basename(fname)[5:-4].title().replace("_", "") # some special cases if icon_name in ['Int', 'Bool', 'Float']: icon_name = icon_name.lower() if icon_name.endswith("MediumThumb"): # don't know a better way to handle this thumb_medium_indices.append(str(index)) if icon_name.endswith("BigThumb"): # don't know a better way to handle this thumb_big_indices.append(str(index)) s.write('\t"{0}"'.format(icon_name)) if fname != svg_icons[-1]: s.write(",") s.write('\n') index += 1 s.write('};\n') if thumb_medium_indices: s.write("\n\n") s.write("static const int editor_md_thumbs_count = {};\n".format(len(thumb_medium_indices))) s.write("static const int editor_md_thumbs_indices[] = {") s.write(", ".join(thumb_medium_indices)) s.write("};\n") if thumb_big_indices: s.write("\n\n") s.write("static const int editor_bg_thumbs_count = {};\n".format(len(thumb_big_indices))) s.write("static const int editor_bg_thumbs_indices[] = {") s.write(", ".join(thumb_big_indices)) s.write("};\n") s.write("#endif\n") with open(dst, "w") as f: f.write(s.getvalue()) s.close() icons_string.close()