Example #1
0
def main(toplevels, is_main_module=True):
  """The main method for tests subclassing one of the above classes.

  This function should be called unconditionally, and typically as follows:

    main(globals(), __name__ == "__main__")

  This enables one to run the tests using the 'python -m unittest ...' command,
  which does run the main test module as the main interpreter module.
  Call to unittest.main is made only if |is_main_module| is true.

  Arguments:
    toplevels: The toplevels defined in the main test module.
    is_main_module: True if the main test module is the main module in the
                    interpreter.
  """
  # In Python 3.5, some tests shouldn't run.
  tests_to_delete_35 = []
  # We set a python_version attribute on every test class.
  python_versions = {}
  # For tests that we want to run under multiple target Python versions, we
  # create a subclass for each additional version.
  new_tests = {}
  for name, tp in toplevels.items():
    if not isinstance(tp, type) or not issubclass(tp, BaseTest):
      continue
    if sys.version_info.minor < 6 and issubclass(tp, TargetPython3FeatureTest):
      # Many of our Python 3 feature tests are Python 3.6+, since they use
      # PEP 526-style variable annotations.
      tests_to_delete_35.append(name)
      continue
    if hasattr(tp, "PY_MAJOR_VERSIONS"):
      versions = sorted(tp.PY_MAJOR_VERSIONS, reverse=True)
    else:
      versions = [3]
    assert versions, "Must specify at least one Python major version"
    assert not hasattr(tp, "python_version"), (
        "Do not set python_version directly; use PY_MAJOR_VERSIONS")
    # We can't set python_version yet, since that would cause the assertion that
    # python_version is not defined to fail on subclasses of tp.
    python_versions[tp] = utils.full_version_from_major(versions[0])
    for version in versions[1:]:
      name = "%sPy%d" % (name, version)
      subtest = type(name, (tp,),
                     {"python_version": utils.full_version_from_major(version)})
      new_tests[name] = subtest
  for name in tests_to_delete_35:
    del toplevels[name]
  for tp, version in python_versions.items():
    setattr(tp, "python_version", version)
  toplevels.update(new_tests)
  if is_main_module:
    unittest.main()
Example #2
0
  def _store_python_version(self, python_version):
    """Configure the python version."""
    if python_version:
      if isinstance(python_version, str):
        self.output_options.python_version = utils.version_from_string(
            python_version)
      elif isinstance(python_version, int):
        self.output_options.python_version = utils.full_version_from_major(
            python_version)
      else:
        self.output_options.python_version = python_version
    else:
      self.output_options.python_version = sys.version_info[:2]
    if len(self.output_options.python_version) != 2:
      self.error(
          "--python_version must be <major>.<minor>: %r" % python_version)
    # Check that we have a version supported by pytype.
    utils.validate_version(self.output_options.python_version)

    if utils.can_compile_bytecode_natively(self.output_options.python_version):
      # pytype does not need an exe for bytecode compilation. Abort early to
      # avoid extracting a large unused exe into /tmp.
      self.output_options.python_exe = (None, None)
      return

    python_exe, flags = utils.get_python_exe(self.output_options.python_version)
    python_exe_version = utils.get_python_exe_version(python_exe)
    if python_exe_version != self.output_options.python_version:
      self.error("Need a valid python%d.%d executable in $PATH" %
                 self.output_options.python_version)
    self.output_options.python_exe = (python_exe, flags)
Example #3
0
class Python3Test(unittest.TestCase):
    """Tests for load_pytd.py on (target) Python 3."""

    python_version = utils.full_version_from_major(3)

    def setUp(self):
        super(Python3Test, self).setUp()
        self.options = config.Options.create(
            python_version=self.python_version)

    def test_python3_builtins(self):
        # Test that we read python3 builtins from builtin.pytd if we pass a python3
        # version to the loader.
        with file_utils.Tempdir() as d:
            d.create_file(
                "a.pyi", """
          from typing import AsyncContextManager
          class A(AsyncContextManager[str]): ...""")
            loader = load_pytd.Loader("base",
                                      python_version=self.python_version,
                                      pythonpath=[d.path])
            a = loader.import_name("a")
            cls = a.Lookup("a.A")
            self.assertEqual("AsyncContextManager[str]",
                             pytd_utils.Print(cls.parents[0]))
Example #4
0
 def test_generate_builtins_py3(self):
     self.pytype_args["--generate-builtins"] = self._tmp_path("builtins.py")
     self.pytype_args["--python_version"] = utils.format_version(
         utils.full_version_from_major(3))
     self._run_pytype(self.pytype_args)
     self.assertOutputStateMatches(stdout=False,
                                   stderr=False,
                                   returncode=False)
Example #5
0
 def _store_python_version(self, python_version):
     """Configure the python version."""
     if python_version:
         if isinstance(python_version, str):
             self.output_options.python_version = utils.version_from_string(
                 python_version)
         elif isinstance(python_version, int):
             self.output_options.python_version = utils.full_version_from_major(
                 python_version)
         else:
             self.output_options.python_version = python_version
     else:
         self.output_options.python_version = sys.version_info[:2]
     if len(self.output_options.python_version) != 2:
         self.error("--python_version must be <major>.<minor>: %r" %
                    python_version)
     # Check that we have a version supported by pytype.
     utils.validate_version(self.output_options.python_version)
Example #6
0
 def test_full_version_from_major3(self):
   major, _ = utils.full_version_from_major(3)
   self.assertEqual(major, 3)
Example #7
0
 def test_full_version_from_major2(self):
   self.assertEqual(utils.full_version_from_major(2), (2, 7))
Example #8
0
class UnitTest(unittest.TestCase):
    """Base class for tests that specify a target Python version."""

    python_version = utils.full_version_from_major(3)
Example #9
0
 def test_builtins_determinism3(self):
     f1, f2 = self._generate_builtins_twice(
         utils.format_version(utils.full_version_from_major(3)))
     self.assertBuiltinsPickleEqual(f1, f2)