コード例 #1
0
 def test_pyc_always_writable(self):
     # Initially read-only .pyc files on Windows used to cause problems
     # with later updates, see issue #6074 for details
     with _ready_to_import() as (name, path):
         # Write a Python file, make it read-only and import it
         with open(path, 'w') as f:
             f.write("x = 'original'\n")
         # Tweak the mtime of the source to ensure pyc gets updated later
         s = os.stat(path)
         os.utime(path, (s.st_atime, s.st_mtime-100000000))
         os.chmod(path, 0o400)
         m = __import__(name)
         self.assertEqual(m.x, 'original')
         # Change the file and then reimport it
         os.chmod(path, 0o600)
         with open(path, 'w') as f:
             f.write("x = 'rewritten'\n")
         unload(name)
         importlib.invalidate_caches()
         m = __import__(name)
         self.assertEqual(m.x, 'rewritten')
         # Now delete the source file and check the pyc was rewritten
         unlink(path)
         unload(name)
         importlib.invalidate_caches()
         bytecode_only = path + "c"
         os.rename(importlib.util.cache_from_source(path), bytecode_only)
         m = __import__(name)
         self.assertEqual(m.x, 'rewritten')
コード例 #2
0
 def test_UNC_path(self):
     with open(os.path.join(self.path, 'test_unc_path.py'), 'w') as f:
         f.write("testdata = 'test_unc_path'")
     importlib.invalidate_caches()
     # Create the UNC path, like \\myhost\c$\foo\bar.
     path = os.path.abspath(self.path)
     import socket
     hn = socket.gethostname()
     drive = path[0]
     unc = "\\\\%s\\%s$"%(hn, drive)
     unc += path[2:]
     try:
         os.listdir(unc)
     except OSError as e:
         if e.errno in (errno.EPERM, errno.EACCES, errno.ENOENT):
             # See issue #15338
             self.skipTest("cannot access administrative share %r" % (unc,))
         raise
     sys.path.insert(0, unc)
     try:
         mod = __import__("test_unc_path")
     except ImportError as e:
         self.fail("could not import 'test_unc_path' from %r: %r"
                   % (unc, e))
     self.assertEqual(mod.testdata, 'test_unc_path')
     self.assertTrue(mod.__file__.startswith(unc), mod.__file__)
     unload("test_unc_path")
コード例 #3
0
 def test_package___cached___from_pyc(self):
     # Like test___cached__ but ensuring __cached__ when imported from a
     # PEP 3147 pyc file.
     def cleanup():
         rmtree('pep3147')
         unload('pep3147.foo')
         unload('pep3147')
     os.mkdir('pep3147')
     self.addCleanup(cleanup)
     # Touch the __init__.py
     with open(os.path.join('pep3147', '__init__.py'), 'w'):
         pass
     with open(os.path.join('pep3147', 'foo.py'), 'w'):
         pass
     importlib.invalidate_caches()
     m = __import__('pep3147.foo')
     unload('pep3147.foo')
     unload('pep3147')
     importlib.invalidate_caches()
     m = __import__('pep3147.foo')
     init_pyc = importlib.util.cache_from_source(
         os.path.join('pep3147', '__init__.py'))
     self.assertEqual(m.__cached__, os.path.join(os.curdir, init_pyc))
     foo_pyc = importlib.util.cache_from_source(os.path.join('pep3147', 'foo.py'))
     self.assertEqual(sys.modules['pep3147.foo'].__cached__,
                      os.path.join(os.curdir, foo_pyc))
コード例 #4
0
 def test_trailing_slash(self):
     with open(os.path.join(self.path, 'test_trailing_slash.py'), 'w') as f:
         f.write("testdata = 'test_trailing_slash'")
     sys.path.append(self.path+'/')
     mod = __import__("test_trailing_slash")
     self.assertEqual(mod.testdata, 'test_trailing_slash')
     unload("test_trailing_slash")
コード例 #5
0
 def test_recompute_pyc_same_second(self):
     # Even when the source file doesn't change timestamp, a change in
     # source size is enough to trigger recomputation of the pyc file.
     __import__(TESTFN)
     unload(TESTFN)
     with open(self.source, 'a') as fp:
         print("x = 5", file=fp)
     m = __import__(TESTFN)
     self.assertEqual(m.x, 5)
コード例 #6
0
def runtest_inner(ns, test, display_failure=True):
    support.unload(test)

    test_time = 0.0
    refleak = False  # True if the test leaked references.
    try:
        abstest = get_abs_module(ns, test)
        clear_caches()
        with saved_test_environment(test, ns.verbose, ns.quiet, pgo=ns.pgo) as environment:
            start_time = time.time()
            the_module = importlib.import_module(abstest)
            # If the test has a test_main, that will run the appropriate
            # tests.  If not, use normal unittest test loading.
            test_runner = getattr(the_module, "test_main", None)
            if test_runner is None:
                def test_runner():
                    loader = unittest.TestLoader()
                    tests = loader.loadTestsFromModule(the_module)
                    for error in loader.errors:
                        print(error, file=sys.stderr)
                    if loader.errors:
                        raise Exception("errors while loading tests")
                    support.run_unittest(tests)
            test_runner()
            if ns.huntrleaks:
                refleak = dash_R(the_module, test, test_runner, ns.huntrleaks)
            test_time = time.time() - start_time
    except support.ResourceDenied as msg:
        if not ns.quiet and not ns.pgo:
            print(test, "skipped --", msg, flush=True)
        return RESOURCE_DENIED, test_time
    except unittest.SkipTest as msg:
        if not ns.quiet and not ns.pgo:
            print(test, "skipped --", msg, flush=True)
        return SKIPPED, test_time
    except KeyboardInterrupt:
        raise
    except support.TestFailed as msg:
        if not ns.pgo:
            if display_failure:
                print("test", test, "failed --", msg, file=sys.stderr,
                      flush=True)
            else:
                print("test", test, "failed", file=sys.stderr, flush=True)
        return FAILED, test_time
    except:
        msg = traceback.format_exc()
        if not ns.pgo:
            print("test", test, "crashed --", msg, file=sys.stderr,
                  flush=True)
        return FAILED, test_time
    else:
        if refleak:
            return FAILED, test_time
        if environment.changed:
            return ENV_CHANGED, test_time
        return PASSED, test_time
コード例 #7
0
 def tearDown(self):
     sys.path[:] = self.sys_path
     if self.orig_module is not None:
         sys.modules[self.module_name] = self.orig_module
     else:
         unload(self.module_name)
     unlink(self.file_name)
     unlink(self.compiled_name)
     rmtree(self.dir_name)
コード例 #8
0
 def tearDown(self):
     # Get everything back to normal
     support.unload('xx')
     sys.path = self.sys_path[0]
     sys.path[:] = self.sys_path[1]
     import site
     site.USER_BASE = self.old_user_base
     from distutils.command import build_ext
     build_ext.USER_BASE = self.old_user_base
     super(BuildExtTestCase, self).tearDown()
コード例 #9
0
 def test_stacklevel_import(self):
     # Issue #24305: With stacklevel=2, module-level warnings should work.
     support.unload('test.test_warnings.data.import_warning')
     with warnings_state(self.module):
         with original_warnings.catch_warnings(record=True,
                                               module=self.module) as w:
             self.module.simplefilter('always')
             import sql_mode.test_warnings.data.import_warning
             self.assertEqual(len(w), 1)
             self.assertEqual(w[0].filename, __file__)
コード例 #10
0
 def test___cached___legacy_pyc(self):
     # Like test___cached__() except that for backward compatibility,
     # when the pyc file lives where the py file would have been (and named
     # without the tag), it is importable.  The __cached__ of the imported
     # module is the pyc location.
     __import__(TESTFN)
     # pyc_file gets removed in _clean() via tearDown().
     pyc_file = make_legacy_pyc(self.source)
     os.remove(self.source)
     unload(TESTFN)
     importlib.invalidate_caches()
     m = __import__(TESTFN)
     self.assertEqual(m.__cached__,
                      os.path.join(os.curdir, os.path.relpath(pyc_file)))
    def test_file_parse(self):
        # issue1134: all encodings outside latin-1 and utf-8 fail on
        # multiline strings and long lines (>512 columns)
        unload(TESTFN)
        filename = TESTFN + ".py"
        f = open(filename, "w", encoding="cp1252")
        sys.path.insert(0, os.curdir)
        try:
            with f:
                f.write("# -*- coding: cp1252 -*-\n")
                f.write("'''A short string\n")
                f.write("'''\n")
                f.write("'A very long string %s'\n" % ("X" * 1000))

            importlib.invalidate_caches()
            __import__(TESTFN)
        finally:
            del sys.path[0]
            unlink(filename)
            unlink(filename + "c")
            unlink(filename + "o")
            unload(TESTFN)
            rmtree('__pycache__')
コード例 #12
0
    def test_failing_reload(self):
        # A failing reload should leave the module object in sys.modules.
        source = TESTFN + os.extsep + "py"
        with open(source, "w") as f:
            f.write("a = 1\nb=2\n")

        sys.path.insert(0, os.curdir)
        try:
            mod = __import__(TESTFN)
            self.assertIn(TESTFN, sys.modules)
            self.assertEqual(mod.a, 1, "module has wrong attribute values")
            self.assertEqual(mod.b, 2, "module has wrong attribute values")

            # On WinXP, just replacing the .py file wasn't enough to
            # convince reload() to reparse it.  Maybe the timestamp didn't
            # move enough.  We force it to get reparsed by removing the
            # compiled file too.
            remove_files(TESTFN)

            # Now damage the module.
            with open(source, "w") as f:
                f.write("a = 10\nb=20//0\n")

            self.assertRaises(ZeroDivisionError, importlib.reload, mod)
            # But we still expect the module to be in sys.modules.
            mod = sys.modules.get(TESTFN)
            self.assertIsNotNone(mod, "expected module to be in sys.modules")

            # We should have replaced a w/ 10, but the old b value should
            # stick.
            self.assertEqual(mod.a, 10, "module has wrong attribute values")
            self.assertEqual(mod.b, 2, "module has wrong attribute values")

        finally:
            del sys.path[0]
            remove_files(TESTFN)
            unload(TESTFN)
コード例 #13
0
 def cleanup():
     rmtree('pep3147')
     unload('pep3147.foo')
     unload('pep3147')
コード例 #14
0
 def test_unload(self):
     import sched
     self.assertIn("sched", sys.modules)
     support.unload("sched")
     self.assertNotIn("sched", sys.modules)
コード例 #15
0
 def tearDown(self):
     unload("test.relimport")
コード例 #16
0
 def setUp(self):
     support.unload(self.module_name)
     self.addCleanup(support.unload, self.module_name)
コード例 #17
0
    def run_tests_sequential(self):
        if self.ns.trace:
            import trace
            self.tracer = trace.Trace(trace=False, count=True)

        save_modules = sys.modules.keys()

        print("Run tests sequentially")

        previous_test = None
        for test_index, test in enumerate(self.tests, 1):
            start_time = time.monotonic()

            text = test
            if previous_test:
                text = '%s -- %s' % (text, previous_test)
            self.display_progress(test_index, text)

            if self.tracer:
                # If we're tracing code coverage, then we don't exit with status
                # if on a false return value from main.
                cmd = ('result = runtest(self.ns, test); '
                       'self.accumulate_result(test, result)')
                ns = dict(locals())
                self.tracer.runctx(cmd, globals=globals(), locals=ns)
                result = ns['result']
            else:
                try:
                    result = runtest(self.ns, test)
                except KeyboardInterrupt:
                    self.interrupted = True
                    self.accumulate_result(test, (INTERRUPTED, None))
                    break
                else:
                    self.accumulate_result(test, result)

            previous_test = format_test_result(test, result[0])
            test_time = time.monotonic() - start_time
            if test_time >= PROGRESS_MIN_TIME:
                previous_test = "%s in %s" % (previous_test,
                                              format_duration(test_time))
            elif result[0] == PASSED:
                # be quiet: say nothing if the test passed shortly
                previous_test = None

            if self.ns.findleaks:
                gc.collect()
                if gc.garbage:
                    print("Warning: test created", len(gc.garbage), end=' ')
                    print("uncollectable object(s).")
                    # move the uncollectable objects somewhere so we don't see
                    # them again
                    self.found_garbage.extend(gc.garbage)
                    del gc.garbage[:]

            # Unload the newly imported modules (best effort finalization)
            for module in sys.modules.keys():
                if module not in save_modules and module.startswith("test."):
                    support.unload(module)

        if previous_test:
            print(previous_test)
コード例 #18
0
 def tearDown(self):
     unload(TESTFN)