testtransform.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. """Identity AST transform test cases"""
  2. from __future__ import annotations
  3. from mypy import build
  4. from mypy.errors import CompileError
  5. from mypy.modulefinder import BuildSource
  6. from mypy.options import TYPE_VAR_TUPLE, UNPACK
  7. from mypy.test.config import test_temp_dir
  8. from mypy.test.data import DataDrivenTestCase, DataSuite
  9. from mypy.test.helpers import assert_string_arrays_equal, normalize_error_messages, parse_options
  10. from mypy.test.visitors import TypeAssertTransformVisitor
  11. class TransformSuite(DataSuite):
  12. required_out_section = True
  13. # Reuse semantic analysis test cases.
  14. files = [
  15. "semanal-basic.test",
  16. "semanal-expressions.test",
  17. "semanal-classes.test",
  18. "semanal-types.test",
  19. "semanal-modules.test",
  20. "semanal-statements.test",
  21. "semanal-abstractclasses.test",
  22. ]
  23. native_sep = True
  24. def run_case(self, testcase: DataDrivenTestCase) -> None:
  25. test_transform(testcase)
  26. def test_transform(testcase: DataDrivenTestCase) -> None:
  27. """Perform an identity transform test case."""
  28. try:
  29. src = "\n".join(testcase.input)
  30. options = parse_options(src, testcase, 1)
  31. options.use_builtins_fixtures = True
  32. options.semantic_analysis_only = True
  33. options.enable_incomplete_feature = [TYPE_VAR_TUPLE, UNPACK]
  34. options.show_traceback = True
  35. options.force_uppercase_builtins = True
  36. result = build.build(
  37. sources=[BuildSource("main", None, src)], options=options, alt_lib_path=test_temp_dir
  38. )
  39. a = result.errors
  40. if a:
  41. raise CompileError(a)
  42. # Include string representations of the source files in the actual
  43. # output.
  44. for module in sorted(result.files.keys()):
  45. if module in testcase.test_modules:
  46. t = TypeAssertTransformVisitor()
  47. t.test_only = True
  48. file = t.mypyfile(result.files[module])
  49. a += file.str_with_options(options).split("\n")
  50. except CompileError as e:
  51. a = e.messages
  52. if testcase.normalize_output:
  53. a = normalize_error_messages(a)
  54. assert_string_arrays_equal(
  55. testcase.output,
  56. a,
  57. f"Invalid semantic analyzer output ({testcase.file}, line {testcase.line})",
  58. )