python (3.12.0)
1 """Support code for test_*.py files"""
2 # Author: Collin Winter
3
4 # Python imports
5 import unittest
6 import os
7 import os.path
8 from textwrap import dedent
9
10 # Local imports
11 import lib2to3
12 from lib2to3 import pytree, refactor
13 from lib2to3.pgen2 import driver as pgen2_driver
14
15 lib2to3_dir = os.path.dirname(lib2to3.__file__)
16 test_dir = os.path.dirname(__file__)
17 proj_dir = os.path.normpath(os.path.join(test_dir, ".."))
18 grammar_path = os.path.join(lib2to3_dir, "Grammar.txt")
19 grammar = pgen2_driver.load_grammar(grammar_path)
20 grammar_no_print_statement = pgen2_driver.load_grammar(grammar_path)
21 del grammar_no_print_statement.keywords["print"]
22 driver = pgen2_driver.Driver(grammar, convert=pytree.convert)
23 driver_no_print_statement = pgen2_driver.Driver(
24 grammar_no_print_statement,
25 convert=pytree.convert
26 )
27
28 def parse_string(string):
29 return driver.parse_string(reformat(string), debug=True)
30
31 def run_all_tests(test_mod=None, tests=None):
32 if tests is None:
33 tests = unittest.TestLoader().loadTestsFromModule(test_mod)
34 unittest.TextTestRunner(verbosity=2).run(tests)
35
36 def reformat(string):
37 return dedent(string) + "\n\n"
38
39 def get_refactorer(fixer_pkg="lib2to3", fixers=None, options=None):
40 """
41 A convenience function for creating a RefactoringTool for tests.
42
43 fixers is a list of fixers for the RefactoringTool to use. By default
44 "lib2to3.fixes.*" is used. options is an optional dictionary of options to
45 be passed to the RefactoringTool.
46 """
47 if fixers is not None:
48 fixers = [fixer_pkg + ".fixes.fix_" + fix for fix in fixers]
49 else:
50 fixers = refactor.get_fixers_from_package(fixer_pkg + ".fixes")
51 options = options or {}
52 return refactor.RefactoringTool(fixers, options, explicit=True)
53
54 def _all_project_files(root, files):
55 for dirpath, dirnames, filenames in os.walk(root):
56 for filename in filenames:
57 if not filename.endswith(".py"):
58 continue
59 files.append(os.path.join(dirpath, filename))
60
61 def all_project_files():
62 files = []
63 _all_project_files(lib2to3_dir, files)
64 _all_project_files(test_dir, files)
65 # Sort to get more reproducible tests
66 files.sort()
67 return files
68
69 TestCase = unittest.TestCase