1'''Test Tools/scripts/fixcid.py.''' 2 3from io import StringIO 4import os, os.path 5import runpy 6import sys 7from test import support 8from test.support import os_helper 9from test.test_tools import skip_if_missing, scriptsdir 10import unittest 11 12skip_if_missing() 13 14class Test(unittest.TestCase): 15 def test_parse_strings(self): 16 old1 = 'int xx = "xx\\"xx"[xx];\n' 17 old2 = "int xx = 'x\\'xx' + xx;\n" 18 output = self.run_script(old1 + old2) 19 new1 = 'int yy = "xx\\"xx"[yy];\n' 20 new2 = "int yy = 'x\\'xx' + yy;\n" 21 self.assertMultiLineEqual(output, 22 "1\n" 23 "< {old1}" 24 "> {new1}" 25 "{new1}" 26 "2\n" 27 "< {old2}" 28 "> {new2}" 29 "{new2}".format(old1=old1, old2=old2, new1=new1, new2=new2) 30 ) 31 32 def test_alter_comments(self): 33 output = self.run_script( 34 substfile= 35 "xx yy\n" 36 "*aa bb\n", 37 args=("-c", "-",), 38 input= 39 "/* xx altered */\n" 40 "int xx;\n" 41 "/* aa unaltered */\n" 42 "int aa;\n", 43 ) 44 self.assertMultiLineEqual(output, 45 "1\n" 46 "< /* xx altered */\n" 47 "> /* yy altered */\n" 48 "/* yy altered */\n" 49 "2\n" 50 "< int xx;\n" 51 "> int yy;\n" 52 "int yy;\n" 53 "/* aa unaltered */\n" 54 "4\n" 55 "< int aa;\n" 56 "> int bb;\n" 57 "int bb;\n" 58 ) 59 60 def test_directory(self): 61 os.mkdir(os_helper.TESTFN) 62 self.addCleanup(os_helper.rmtree, os_helper.TESTFN) 63 c_filename = os.path.join(os_helper.TESTFN, "file.c") 64 with open(c_filename, "w") as file: 65 file.write("int xx;\n") 66 with open(os.path.join(os_helper.TESTFN, "file.py"), "w") as file: 67 file.write("xx = 'unaltered'\n") 68 script = os.path.join(scriptsdir, "fixcid.py") 69 output = self.run_script(args=(os_helper.TESTFN,)) 70 self.assertMultiLineEqual(output, 71 "{}:\n" 72 "1\n" 73 '< int xx;\n' 74 '> int yy;\n'.format(c_filename) 75 ) 76 77 def run_script(self, input="", *, args=("-",), substfile="xx yy\n"): 78 substfilename = os_helper.TESTFN + ".subst" 79 with open(substfilename, "w") as file: 80 file.write(substfile) 81 self.addCleanup(os_helper.unlink, substfilename) 82 83 argv = ["fixcid.py", "-s", substfilename] + list(args) 84 script = os.path.join(scriptsdir, "fixcid.py") 85 with support.swap_attr(sys, "argv", argv), \ 86 support.swap_attr(sys, "stdin", StringIO(input)), \ 87 support.captured_stdout() as output, \ 88 support.captured_stderr(): 89 try: 90 runpy.run_path(script, run_name="__main__") 91 except SystemExit as exit: 92 self.assertEqual(exit.code, 0) 93 return output.getvalue() 94