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