support.py 1.9 KB

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