<commit_before>import errno
import imp
import marshal
import os
import py_compile
import random
import stat
import sys
import unittest
import textwrap
import shutil

from test.test_support import (unlink, TESTFN, unload, run_unittest, rmtree,
                               is_jython, check_warnings, EnvironmentVarGuard)
from test import symlink_support
from test import script_helper

def _iter_files(name):
    for f in (name + os.extsep + "py",
              name + os.extsep + "pyc",
              name + os.extsep + "pyo",
              name + os.extsep + "pyw",
              name + "$py.class"):
        yield f

def chmod_files(name):
    for f in _iter_files(name):
        try:
            os.chmod(f, 0600)
        except OSError as exc:
            if exc.errno != errno.ENOENT:
                raise

def remove_files(name):
    for f in _iter_files(name):
        unlink(f)


class ImportTests(unittest.TestCase):

    def tearDown(self):
        unload(TESTFN)
    setUp = tearDown

    def test_case_sensitivity(self):
        # Brief digression to test that import is case-sensitive:  if we got
        # this far, we know for sure that "random" exists.
        try:
            import RAnDoM
        except ImportError:
            pass
        else:
            self.fail("import of RAnDoM should have failed (case mismatch)")

    def test_double_const(self):
        # Another brief digression to test the accuracy of manifest float
        # constants.
        from test import double_const  # don't blink -- that *was* the test

    def test_import(self):
        def test_with_extension(ext):
            # The extension is normally ".py", perhaps ".pyw".
            source = TESTFN + ext
            pyo = TESTFN + os.extsep + "pyo"
            if is_jython:
                pyc = TESTFN + "$py.class"
            else:
                pyc = TESTFN + os.extsep + "pyc"

            with open(source, "w") as f:
                print >> f, ("# This tests Python's ability to import a", ext,
                             "file.")
                a = random.randrange(1000)
                b = random.randrange(1000)
                print >> f, "a =", a
                print >> f, "b =", b

            try:
                mod = __import__(TESTFN)
            except ImportError, err:
                self.fail("import from %s failed: %s" % (ext, err))
            else:
                self.assertEqual(mod.a, a,
                    "module loaded (%s) but contents invalid" % mod)
                self.assertEqual(mod.b, b,
                    "module loaded (%s) but contents invalid" % mod)
            finally:
                unlink(source)

            try:
                imp.reload(mod)
            except ImportError, err:
                self.fail("import from .pyc/.pyo failed: %s" % err)
            finally:
                unlink(pyc)
                unlink(pyo)
                unload(TESTFN)

        sys.path.insert(0, os.curdir)
        try:
            test_with_extension(os.extsep + "py")
            if sys.platform.startswith("win"):
                for ext in [".PY", ".Py", ".pY", ".pyw", ".PYW", ".pYw"]:
                    test_with_extension(ext)
        finally:
            del sys.path[0]

    @unittest.skipUnless(os.name == 'posix', "test meaningful only on posix systems")
    def test_execute_bit_not_copied(self):
        # Issue 6070: under posix .pyc files got their execute bit set if
        # the .py file had the execute bit set, but they aren't executable.
        oldmask = os.umask(022)
        sys.path.insert(0, os.curdir)
        try:
            fname = TESTFN + os.extsep + "py"
            f = open(fname, 'w').close()
            os.chmod(fname, (stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH |
                             stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH))
            __import__(TESTFN)
            fn = fname + 'c'
            if not os.path.exists(fn):
                fn = fname + 'o'
                if not os.path.exists(fn):
                    self.fail("__import__ did not result in creation of "
                              "either a .pyc or .pyo file")
            s = os.stat(fn)
            self.assertEqual(stat.S_IMODE(s.st_mode),
                             stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH)
        finally:
            os.umask(oldmask)
            remove_files(TESTFN)
            unload(TESTFN)
            del sys.path[0]

    def test_rewrite_pyc_with_read_only_source(self):
        # Issue 6074: a long time ago on posix, and more recently on Windows,
        # a read only source file resulted in a read only pyc file, which
        # led to problems with updating it later
        sys.path.insert(0, os.curdir)
        fname = TESTFN + os.extsep + "py"
        try:
            # Write a Python file, make it read-only and import it
            with open(fname, 'w') as f:
                f.write("x = 'original'\n")
            # Tweak the mtime of the source to ensure pyc gets updated later
            s = os.stat(fname)
            os.utime(fname, (s.st_atime, s.st_mtime-100000000))
            os.chmod(fname, 0400)
            m1 = __import__(TESTFN)
            self.assertEqual(m1.x, 'original')
            # Change the file and then reimport it
            os.chmod(fname, 0600)
            with open(fname, 'w') as f:
                f.write("x = 'rewritten'\n")
            unload(TESTFN)
            m2 = __import__(TESTFN)
            self.assertEqual(m2.x, 'rewritten')
            # Now delete the source file and check the pyc was rewritten
            unlink(TESTFN)
            unload(TESTFN)
            m3 = __import__(TESTFN)
            self.assertEqual(m3.x, 'rewritten')
        finally:
            chmod_files(TESTFN)
            remove_files(TESTFN)
            unload(TESTFN)
            del sys.path[0]

    def test_imp_module(self):
        # Verify that the imp module can correctly load and find .py files

        # XXX (ncoghlan): It would be nice to use test_support.CleanImport
        # here, but that breaks because the os module registers some
        # handlers in copy_reg on import. Since CleanImport doesn't<commit_msg>Issue #6074: Actually delete the source file in the test as intended<commit_after>import errno
import imp
import marshal
import os
import py_compile
import random
import stat
import sys
import unittest
import textwrap
import shutil

from test.test_support import (unlink, TESTFN, unload, run_unittest, rmtree,
                               is_jython, check_warnings, EnvironmentVarGuard)
from test import symlink_support
from test import script_helper

def _iter_files(name):
    for f in (name + os.extsep + "py",
              name + os.extsep + "pyc",
              name + os.extsep + "pyo",
              name + os.extsep + "pyw",
              name + "$py.class"):
        yield f

def chmod_files(name):
    for f in _iter_files(name):
        try:
            os.chmod(f, 0600)
        except OSError as exc:
            if exc.errno != errno.ENOENT:
                raise

def remove_files(name):
    for f in _iter_files(name):
        unlink(f)


class ImportTests(unittest.TestCase):

    def tearDown(self):
        unload(TESTFN)
    setUp = tearDown

    def test_case_sensitivity(self):
        # Brief digression to test that import is case-sensitive:  if we got
        # this far, we know for sure that "random" exists.
        try:
            import RAnDoM
        except ImportError:
            pass
        else:
            self.fail("import of RAnDoM should have failed (case mismatch)")

    def test_double_const(self):
        # Another brief digression to test the accuracy of manifest float
        # constants.
        from test import double_const  # don't blink -- that *was* the test

    def test_import(self):
        def test_with_extension(ext):
            # The extension is normally ".py", perhaps ".pyw".
            source = TESTFN + ext
            pyo = TESTFN + os.extsep + "pyo"
            if is_jython:
                pyc = TESTFN + "$py.class"
            else:
                pyc = TESTFN + os.extsep + "pyc"

            with open(source, "w") as f:
                print >> f, ("# This tests Python's ability to import a", ext,
                             "file.")
                a = random.randrange(1000)
                b = random.randrange(1000)
                print >> f, "a =", a
                print >> f, "b =", b

            try:
                mod = __import__(TESTFN)
            except ImportError, err:
                self.fail("import from %s failed: %s" % (ext, err))
            else:
                self.assertEqual(mod.a, a,
                    "module loaded (%s) but contents invalid" % mod)
                self.assertEqual(mod.b, b,
                    "module loaded (%s) but contents invalid" % mod)
            finally:
                unlink(source)

            try:
                imp.reload(mod)
            except ImportError, err:
                self.fail("import from .pyc/.pyo failed: %s" % err)
            finally:
                unlink(pyc)
                unlink(pyo)
                unload(TESTFN)

        sys.path.insert(0, os.curdir)
        try:
            test_with_extension(os.extsep + "py")
            if sys.platform.startswith("win"):
                for ext in [".PY", ".Py", ".pY", ".pyw", ".PYW", ".pYw"]:
                    test_with_extension(ext)
        finally:
            del sys.path[0]

    @unittest.skipUnless(os.name == 'posix', "test meaningful only on posix systems")
    def test_execute_bit_not_copied(self):
        # Issue 6070: under posix .pyc files got their execute bit set if
        # the .py file had the execute bit set, but they aren't executable.
        oldmask = os.umask(022)
        sys.path.insert(0, os.curdir)
        try:
            fname = TESTFN + os.extsep + "py"
            f = open(fname, 'w').close()
            os.chmod(fname, (stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH |
                             stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH))
            __import__(TESTFN)
            fn = fname + 'c'
            if not os.path.exists(fn):
                fn = fname + 'o'
                if not os.path.exists(fn):
                    self.fail("__import__ did not result in creation of "
                              "either a .pyc or .pyo file")
            s = os.stat(fn)
            self.assertEqual(stat.S_IMODE(s.st_mode),
                             stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH)
        finally:
            os.umask(oldmask)
            remove_files(TESTFN)
            unload(TESTFN)
            del sys.path[0]

    def test_rewrite_pyc_with_read_only_source(self):
        # Issue 6074: a long time ago on posix, and more recently on Windows,
        # a read only source file resulted in a read only pyc file, which
        # led to problems with updating it later
        sys.path.insert(0, os.curdir)
        fname = TESTFN + os.extsep + "py"
        try:
            # Write a Python file, make it read-only and import it
            with open(fname, 'w') as f:
                f.write("x = 'original'\n")
            # Tweak the mtime of the source to ensure pyc gets updated later
            s = os.stat(fname)
            os.utime(fname, (s.st_atime, s.st_mtime-100000000))
            os.chmod(fname, 0400)
            m1 = __import__(TESTFN)
            self.assertEqual(m1.x, 'original')
            # Change the file and then reimport it
            os.chmod(fname, 0600)
            with open(fname, 'w') as f:
                f.write("x = 'rewritten'\n")
            unload(TESTFN)
            m2 = __import__(TESTFN)
            self.assertEqual(m2.x, 'rewritten')
            # Now delete the source file and check the pyc was rewritten
            unlink(fname)
            unload(TESTFN)
            m3 = __import__(TESTFN)
            self.assertEqual(m3.x, 'rewritten')
        finally:
            chmod_files(TESTFN)
            remove_files(TESTFN)
            unload(TESTFN)
            del sys.path[0]

    def test_imp_module(self):
        # Verify that the imp module can correctly load and find .py files

        # XXX (ncoghlan): It would be nice to use test_support.CleanImport
        # here, but that breaks because the os module registers some
        # handlers in copy_reg on import. Since CleanImport doesn't
{'fraction_non_alphanumeric': 0.093699774991964, 'fraction_numerical': 0.008678881388621022, 'mean_word_length': 1.5970367278797997, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 15, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 2, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '319276', 'n_tokens_mistral': 3810, 'n_tokens_neox': 3632, 'n_words': 1082}