Ejemplo n.º 1
0
 def tearDown(self):
     for db in self._db:
         db.close()
     self._db = []
     if not self._in_mem:
         for f in glob.glob(self.fn+"*"):
             support.unlink(f)
Ejemplo n.º 2
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, 0o400)
         m1 = __import__(TESTFN)
         self.assertEqual(m1.x, 'original')
         # Change the file and then reimport it
         os.chmod(fname, 0o600)
         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]
Ejemplo n.º 3
0
 def test_realpath_basic(self):
     # Basic operation.
     try:
         os.symlink(ABSTFN+"1", ABSTFN)
         self.assertEqual(realpath(ABSTFN), ABSTFN+"1")
     finally:
         support.unlink(ABSTFN)
Ejemplo n.º 4
0
    def test_execfile(self):
        globals = {'a': 1, 'b': 2}
        locals = {'b': 200, 'c': 300}

        class M:
            "Test mapping interface versus possible calls from execfile()."
            def __init__(self):
                self.z = 10
            def __getitem__(self, key):
                if key == 'z':
                    return self.z
                raise KeyError
            def __setitem__(self, key, value):
                if key == 'z':
                    self.z = value
                    return
                raise KeyError

        locals = M()
        locals['z'] = 0
        exec(compile(open(TESTFN).read(), TESTFN, 'exec'), globals, locals)
        self.assertEqual(locals['z'], 2)

        self.assertRaises(TypeError, execfile)
        self.assertRaises(TypeError, execfile, TESTFN, {}, ())
        unlink(TESTFN)
Ejemplo n.º 5
0
    def test_realpath_resolve_before_normalizing(self):
        # Bug #990669: Symbolic links should be resolved before we
        # normalize the path. E.g.: if we have directories 'a', 'k' and 'y'
        # in the following hierarchy:
        # a/k/y
        #
        # and a symbolic link 'link-y' pointing to 'y' in directory 'a',
        # then realpath("link-y/..") should return 'k', not 'a'.
        try:
            os.mkdir(ABSTFN)
            os.mkdir(ABSTFN + "/k")
            os.mkdir(ABSTFN + "/k/y")
            os.symlink(ABSTFN + "/k/y", ABSTFN + "/link-y")

            # Absolute path.
            self.assertEqual(realpath(ABSTFN + "/link-y/.."), ABSTFN + "/k")
            # Relative path.
            with support.change_cwd(dirname(ABSTFN)):
                self.assertEqual(realpath(basename(ABSTFN) + "/link-y/.."),
                                 ABSTFN + "/k")
        finally:
            support.unlink(ABSTFN + "/link-y")
            safe_rmdir(ABSTFN + "/k/y")
            safe_rmdir(ABSTFN + "/k")
            safe_rmdir(ABSTFN)
Ejemplo n.º 6
0
    def test_encode(self):
        fin = fout = None
        try:
            support.unlink(self.tmpin)
            fin = open(self.tmpin, 'wb')
            fin.write(plaintext)
            fin.close()

            fin = open(self.tmpin, 'rb')
            fout = open(self.tmpout, 'wb')
            uu.encode(fin, fout, self.tmpin, mode=0o644)
            fin.close()
            fout.close()

            fout = open(self.tmpout, 'rb')
            s = fout.read()
            fout.close()
            self.assertEqual(s, encodedtextwrapped(0o644, self.tmpin))

            # in_file and out_file as filenames
            uu.encode(self.tmpin, self.tmpout, self.tmpin, mode=0o644)
            fout = open(self.tmpout, 'rb')
            s = fout.read()
            fout.close()
            self.assertEqual(s, encodedtextwrapped(0o644, self.tmpin))

        finally:
            self._kill(fin)
            self._kill(fout)
Ejemplo n.º 7
0
    def try_one(self, s):
        # Write s + "\n" + s to file, then open it and ensure that successive
        # .readline()s deliver what we wrote.

        # Ensure we can open TESTFN for writing.
        support.unlink(support.TESTFN)

        # Since C doesn't guarantee we can write/read arbitrary bytes in text
        # files, use binary mode.
        f = self.open(support.TESTFN, "wb")
        try:
            # write once with \n and once without
            f.write(s)
            f.write(b"\n")
            f.write(s)
            f.close()
            f = open(support.TESTFN, "rb")
            line = f.readline()
            self.assertEqual(line, s + b"\n")
            line = f.readline()
            self.assertEqual(line, s)
            line = f.readline()
            self.assertTrue(not line)  # Must be at EOF
            f.close()
        finally:
            support.unlink(support.TESTFN)
Ejemplo n.º 8
0
    def test_builtin_map(self):
        self.assertEqual(list(map(lambda x: x+1, SequenceClass(5))),
                         list(range(1, 6)))

        d = {"one": 1, "two": 2, "three": 3}
        self.assertEqual(list(map(lambda k, d=d: (k, d[k]), d)),
                         list(d.items()))
        dkeys = list(d.keys())
        expected = [(i < len(d) and dkeys[i] or None,
                     i,
                     i < len(d) and dkeys[i] or None)
                    for i in range(3)]

        f = open(TESTFN, "w")
        try:
            for i in range(10):
                f.write("xy" * i + "\n") # line i has len 2*i+1
        finally:
            f.close()
        f = open(TESTFN, "r")
        try:
            self.assertEqual(list(map(len, f)), list(range(1, 21, 2)))
        finally:
            f.close()
            try:
                unlink(TESTFN)
            except OSError:
                pass
Ejemplo n.º 9
0
    def test_countOf(self):
        from operator import countOf
        self.assertEqual(countOf([1,2,2,3,2,5], 2), 3)
        self.assertEqual(countOf((1,2,2,3,2,5), 2), 3)
        self.assertEqual(countOf("122325", "2"), 3)
        self.assertEqual(countOf("122325", "6"), 0)

        self.assertRaises(TypeError, countOf, 42, 1)
        self.assertRaises(TypeError, countOf, countOf, countOf)

        d = {"one": 3, "two": 3, "three": 3, 1j: 2j}
        for k in d:
            self.assertEqual(countOf(d, k), 1)
        self.assertEqual(countOf(d.values(), 3), 3)
        self.assertEqual(countOf(d.values(), 2j), 1)
        self.assertEqual(countOf(d.values(), 1j), 0)

        f = open(TESTFN, "w")
        try:
            f.write("a\n" "b\n" "c\n" "b\n")
        finally:
            f.close()
        f = open(TESTFN, "r")
        try:
            for letter, count in ("a", 1), ("b", 2), ("c", 1), ("d", 0):
                f.seek(0, 0)
                self.assertEqual(countOf(f, letter + "\n"), count)
        finally:
            f.close()
            try:
                unlink(TESTFN)
            except OSError:
                pass
Ejemplo n.º 10
0
    def test_builtin_tuple(self):
        self.assertEqual(tuple(SequenceClass(5)), (0, 1, 2, 3, 4))
        self.assertEqual(tuple(SequenceClass(0)), ())
        self.assertEqual(tuple([]), ())
        self.assertEqual(tuple(()), ())
        self.assertEqual(tuple("abc"), ("a", "b", "c"))

        d = {"one": 1, "two": 2, "three": 3}
        self.assertEqual(tuple(d), tuple(d.keys()))

        self.assertRaises(TypeError, tuple, list)
        self.assertRaises(TypeError, tuple, 42)

        f = open(TESTFN, "w")
        try:
            for i in range(5):
                f.write("%d\n" % i)
        finally:
            f.close()
        f = open(TESTFN, "r")
        try:
            self.assertEqual(tuple(f), ("0\n", "1\n", "2\n", "3\n", "4\n"))
            f.seek(0, 0)
            self.assertEqual(tuple(f),
                             ("0\n", "1\n", "2\n", "3\n", "4\n"))
        finally:
            f.close()
            try:
                unlink(TESTFN)
            except OSError:
                pass
Ejemplo n.º 11
0
    def test_builtin_max_min(self):
        self.assertEqual(max(SequenceClass(5)), 4)
        self.assertEqual(min(SequenceClass(5)), 0)
        self.assertEqual(max(8, -1), 8)
        self.assertEqual(min(8, -1), -1)

        d = {"one": 1, "two": 2, "three": 3}
        self.assertEqual(max(d), "two")
        self.assertEqual(min(d), "one")
        self.assertEqual(max(d.values()), 3)
        self.assertEqual(min(iter(d.values())), 1)

        f = open(TESTFN, "w")
        try:
            f.write("medium line\n")
            f.write("xtra large line\n")
            f.write("itty-bitty line\n")
        finally:
            f.close()
        f = open(TESTFN, "r")
        try:
            self.assertEqual(min(f), "itty-bitty line\n")
            f.seek(0, 0)
            self.assertEqual(max(f), "xtra large line\n")
        finally:
            f.close()
            try:
                unlink(TESTFN)
            except OSError:
                pass
Ejemplo n.º 12
0
    def _test_open(self, do_open_close_reader, do_open_close_writer):
        filename = support.TESTFN

        # Use a fifo: until the child opens it for reading, the parent will
        # block when trying to open it for writing.
        support.unlink(filename)
        os.mkfifo(filename)
        self.addCleanup(support.unlink, filename)

        code = '\n'.join((
            'import os, time',
            '',
            'path = %a' % filename,
            'sleep_time = %r' % self.sleep_time,
            '',
            '# let the parent block',
            'time.sleep(sleep_time)',
            '',
            do_open_close_reader,
        ))

        proc = self.subprocess(code)
        with kill_on_error(proc):
            do_open_close_writer(filename)
            self.assertEqual(proc.wait(), 0)
Ejemplo n.º 13
0
    def test_builtin_list(self):
        self.assertEqual(list(SequenceClass(5)), list(range(5)))
        self.assertEqual(list(SequenceClass(0)), [])
        self.assertEqual(list(()), [])

        d = {"one": 1, "two": 2, "three": 3}
        self.assertEqual(list(d), list(d.keys()))

        self.assertRaises(TypeError, list, list)
        self.assertRaises(TypeError, list, 42)

        f = open(TESTFN, "w")
        try:
            for i in range(5):
                f.write("%d\n" % i)
        finally:
            f.close()
        f = open(TESTFN, "r")
        try:
            self.assertEqual(list(f), ["0\n", "1\n", "2\n", "3\n", "4\n"])
            f.seek(0, 0)
            self.assertEqual(list(f),
                             ["0\n", "1\n", "2\n", "3\n", "4\n"])
        finally:
            f.close()
            try:
                unlink(TESTFN)
            except OSError:
                pass
Ejemplo n.º 14
0
    def test_implicit_binary_modes(self):
        # Test implicit binary modes (no "b" or "t" in mode string).
        uncompressed = data1 * 50

        with gzip.open(self.filename, "w") as f:
            f.write(uncompressed)
        with open(self.filename, "rb") as f:
            file_data = gzip.decompress(f.read())
            self.assertEqual(file_data, uncompressed)

        with gzip.open(self.filename, "r") as f:
            self.assertEqual(f.read(), uncompressed)

        with gzip.open(self.filename, "a") as f:
            f.write(uncompressed)
        with open(self.filename, "rb") as f:
            file_data = gzip.decompress(f.read())
            self.assertEqual(file_data, uncompressed * 2)

        with self.assertRaises(FileExistsError):
            gzip.open(self.filename, "x")
        support.unlink(self.filename)
        with gzip.open(self.filename, "x") as f:
            f.write(uncompressed)
        with open(self.filename, "rb") as f:
            file_data = gzip.decompress(f.read())
            self.assertEqual(file_data, uncompressed)
    def _testBogusZipFile(self):
        support.unlink(TESTMOD)
        fp = open(TESTMOD, 'w+')
        fp.write(struct.pack('=I', 0x06054B50))
        fp.write('a' * 18)
        fp.close()
        z = zipimport.zipimporter(TESTMOD)

        try:
            self.assertRaises(TypeError, z.find_module, None)
            self.assertRaises(TypeError, z.load_module, None)
            self.assertRaises(TypeError, z.is_package, None)
            self.assertRaises(TypeError, z.get_code, None)
            self.assertRaises(TypeError, z.get_data, None)
            self.assertRaises(TypeError, z.get_source, None)

            error = zipimport.ZipImportError
            self.assertEqual(z.find_module('abc'), None)

            self.assertRaises(error, z.load_module, 'abc')
            self.assertRaises(error, z.get_code, 'abc')
            self.assertRaises(IOError, z.get_data, 'abc')
            self.assertRaises(error, z.get_source, 'abc')
            self.assertRaises(error, z.is_package, 'abc')
        finally:
            zipimport._zip_directory_cache.clear()
Ejemplo n.º 16
0
 def test_mode(self):
     self.test_write()
     with gzip.GzipFile(self.filename, 'r') as f:
         self.assertEqual(f.myfileobj.mode, 'rb')
     support.unlink(self.filename)
     with gzip.GzipFile(self.filename, 'x') as f:
         self.assertEqual(f.myfileobj.mode, 'xb')
Ejemplo n.º 17
0
    def test_binary_modes(self):
        uncompressed = data1 * 50

        with gzip.open(self.filename, "wb") as f:
            f.write(uncompressed)
        with open(self.filename, "rb") as f:
            file_data = gzip.decompress(f.read())
            self.assertEqual(file_data, uncompressed)

        with gzip.open(self.filename, "rb") as f:
            self.assertEqual(f.read(), uncompressed)

        with gzip.open(self.filename, "ab") as f:
            f.write(uncompressed)
        with open(self.filename, "rb") as f:
            file_data = gzip.decompress(f.read())
            self.assertEqual(file_data, uncompressed * 2)

        with self.assertRaises(FileExistsError):
            gzip.open(self.filename, "xb")
        support.unlink(self.filename)
        with gzip.open(self.filename, "xb") as f:
            f.write(uncompressed)
        with open(self.filename, "rb") as f:
            file_data = gzip.decompress(f.read())
            self.assertEqual(file_data, uncompressed)
Ejemplo n.º 18
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')
Ejemplo n.º 19
0
        def test_with_extension(ext):
            # The extension is normally ".py", perhaps ".pyw".
            source = TESTFN + ext
            if is_jython:
                pyc = TESTFN + "$py.class"
            else:
                pyc = TESTFN + ".pyc"

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

            if TESTFN in sys.modules:
                del sys.modules[TESTFN]
            importlib.invalidate_caches()
            try:
                try:
                    mod = __import__(TESTFN)
                except ImportError as err:
                    self.fail("import from %s failed: %s" % (ext, err))

                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:
                forget(TESTFN)
                unlink(source)
                unlink(pyc)
Ejemplo n.º 20
0
 def restore_files(self, saved_value):
     fn = support.TESTFN
     if fn not in saved_value and (fn + '/') not in saved_value:
         if os.path.isfile(fn):
             support.unlink(fn)
         elif os.path.isdir(fn):
             support.rmtree(fn)
Ejemplo n.º 21
0
def remove_files(name):
    for f in (name + ".py",
              name + ".pyc",
              name + ".pyw",
              name + "$py.class"):
        unlink(f)
    rmtree('__pycache__')
Ejemplo n.º 22
0
    def test_input(self):
        self.write_testfile()
        fp = open(TESTFN, 'r')
        savestdin = sys.stdin
        savestdout = sys.stdout # Eats the echo
        try:
            sys.stdin = fp
            sys.stdout = BitBucket()
            self.assertEqual(input(), "1+1")
            self.assertEqual(input(), 'The quick brown fox jumps over the lazy dog.')
            self.assertEqual(input('testing\n'), 'Dear John')

            # SF 1535165: don't segfault on closed stdin
            # sys.stdout must be a regular file for triggering
            sys.stdout = savestdout
            sys.stdin.close()
            self.assertRaises(ValueError, input)

            sys.stdout = BitBucket()
            sys.stdin = io.StringIO("NULL\0")
            self.assertRaises(TypeError, input, 42, 42)
            sys.stdin = io.StringIO("    'whitespace'")
            self.assertEqual(input(), "    'whitespace'")
            sys.stdin = io.StringIO()
            self.assertRaises(EOFError, input)

            del sys.stdout
            self.assertRaises(RuntimeError, input, 'prompt')
            del sys.stdin
            self.assertRaises(RuntimeError, input, 'prompt')
        finally:
            sys.stdin = savestdin
            sys.stdout = savestdout
            fp.close()
            unlink(TESTFN)
        def do_test(firstlines, message, charset, lineno):
            # Raise the message in a subprocess, and catch the output
            try:
                output = open(TESTFN, "w", encoding=charset)
                output.write("""{0}if 1:
                    import traceback;
                    raise RuntimeError('{1}')
                    """.format(firstlines, message))
                output.close()
                process = subprocess.Popen([sys.executable, TESTFN],
                    stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
                stdout, stderr = process.communicate()
                stdout = stdout.decode(output_encoding).splitlines()
            finally:
                unlink(TESTFN)

            # The source lines are encoded with the 'backslashreplace' handler
            encoded_message = message.encode(output_encoding,
                                             'backslashreplace')
            # and we just decoded them with the output_encoding.
            message_ascii = encoded_message.decode(output_encoding)

            err_line = "raise RuntimeError('{0}')".format(message_ascii)
            err_msg = "RuntimeError: {0}".format(message_ascii)

            self.assertIn(("line %s" % lineno), stdout[1],
                "Invalid line number: {0!r} instead of {1}".format(
                    stdout[1], lineno))
            self.assertTrue(stdout[2].endswith(err_line),
                "Invalid traceback line: {0!r} instead of {1!r}".format(
                    stdout[2], err_line))
            self.assertTrue(stdout[3] == err_msg,
                "Invalid error message: {0!r} instead of {1!r}".format(
                    stdout[3], err_msg))
 def test_codingspec(self):
     try:
         for enc in ALL_CJKENCODINGS:
             code = '# coding: {}\n'.format(enc)
             exec(code)
     finally:
         support.unlink(TESTFN)
 def test_codingspec(self):
     try:
         for enc in ALL_CJKENCODINGS:
             print('# coding:', enc, file=io.open(TESTFN, 'w'))
             exec(open(TESTFN).read())
     finally:
         support.unlink(TESTFN)
Ejemplo n.º 26
0
 def testThreads(self):
     # BufferedWriter should not raise exceptions or crash
     # when called from multiple threads.
     try:
         # We use a real file object because it allows us to
         # exercise situations where the GIL is released before
         # writing the buffer to the raw streams. This is in addition
         # to concurrency issues due to switching threads in the middle
         # of Python code.
         with io.open(support.TESTFN, "wb", buffering=0) as raw:
             bufio = io.BufferedWriter(raw, 8)
             errors = []
             def f():
                 try:
                     # Write enough bytes to flush the buffer
                     s = b"a" * 19
                     for i in range(50):
                         bufio.write(s)
                 except Exception as e:
                     errors.append(e)
                     raise
             threads = [threading.Thread(target=f) for x in range(20)]
             for t in threads:
                 t.start()
             time.sleep(0.02) # yield
             for t in threads:
                 t.join()
             self.assertFalse(errors,
                 "the following exceptions were caught: %r" % errors)
     finally:
         support.unlink(support.TESTFN)
Ejemplo n.º 27
0
    def test_builtin_map(self):
        self.assertEqual([x+1 for x in SequenceClass(5)], list(range(1, 6)))

        d = {"one": 1, "two": 2, "three": 3}
        self.assertEqual(list(map(lambda k, d=d: (k, d[k]), d)), list(d.items()))
        dkeys = list(d.keys())
        expected = [(i < len(d) and dkeys[i] or None,
                     i,
                     i < len(d) and dkeys[i] or None)
                    for i in range(5)]

        # Deprecated map(None, ...)
        with check_py3k_warnings():
            self.assertEqual(list(SequenceClass(5)), list(range(5)))
            self.assertEqual(list(d), list(d.keys()))
            self.assertEqual(map(None, d,
                                       SequenceClass(5),
                                       iter(d.keys())),
                             expected)

        f = open(TESTFN, "w")
        try:
            for i in range(10):
                f.write("xy" * i + "\n") # line i has len 2*i+1
        finally:
            f.close()
        f = open(TESTFN, "r")
        try:
            self.assertEqual(list(map(len, f)), list(range(1, 21, 2)))
        finally:
            f.close()
            try:
                unlink(TESTFN)
            except OSError:
                pass
Ejemplo n.º 28
0
def setUpModule():
    try:
        import signal
        # The default handler for SIGXFSZ is to abort the process.
        # By ignoring it, system calls exceeding the file size resource
        # limit will raise OSError instead of crashing the interpreter.
        signal.signal(signal.SIGXFSZ, signal.SIG_IGN)
    except (ImportError, AttributeError):
        pass

    # On Windows and Mac OSX this test consumes large resources; It
    # takes a long time to build the >2 GiB file and takes >2 GiB of disk
    # space therefore the resource must be enabled to run this test.
    # If not, nothing after this line stanza will be executed.
    if sys.platform[:3] == 'win' or sys.platform == 'darwin':
        requires('largefile',
                 'test requires %s bytes and a long time to run' % str(size))
    else:
        # Only run if the current filesystem supports large files.
        # (Skip this test on Windows, since we now always support
        # large files.)
        f = open(TESTFN, 'wb', buffering=0)
        try:
            # 2**31 == 2147483648
            f.seek(2147483649)
            # Seeking is not enough of a test: you must write and flush, too!
            f.write(b'x')
            f.flush()
        except (OSError, OverflowError):
            raise unittest.SkipTest("filesystem does not have "
                                    "largefile support")
        finally:
            f.close()
            unlink(TESTFN)
Ejemplo n.º 29
0
    def test_symlink(self):
        # On Windows, the EXE needs to know where pythonXY.dll is at so we have
        # to add the directory to the path.
        env = None
        if sys.platform == "win32":
            env = {k.upper(): os.environ[k] for k in os.environ}
            env["PATH"] = "{};{}".format(
                os.path.dirname(sys.executable), env.get("PATH", ""))
            # Requires PYTHONHOME as well since we locate stdlib from the
            # EXE path and not the DLL path (which should be fixed)
            env["PYTHONHOME"] = os.path.dirname(sys.executable)
            if sysconfig.is_python_build(True):
                env["PYTHONPATH"] = os.path.dirname(os.__file__)

        # Issue 7880
        def get(python, env=None):
            cmd = [python, '-c',
                   'import sysconfig; print(sysconfig.get_platform())']
            p = subprocess.Popen(cmd, stdout=subprocess.PIPE,
                                 stderr=subprocess.PIPE, env=env)
            out, err = p.communicate()
            if p.returncode:
                print((out, err))
                self.fail('Non-zero return code {0} (0x{0:08X})'
                            .format(p.returncode))
            return out, err
        real = os.path.realpath(sys.executable)
        link = os.path.abspath(TESTFN)
        os.symlink(real, link)
        try:
            self.assertEqual(get(real), get(link, env))
        finally:
            unlink(link)
Ejemplo n.º 30
0
 def test_write_long_to_file(self):
     for v in range(marshal.version + 1):
         _testcapi.pymarshal_write_long_to_file(0x12345678, support.TESTFN, v)
         with open(support.TESTFN, 'rb') as f:
             data = f.read()
         support.unlink(support.TESTFN)
         self.assertEqual(data, b'\x78\x56\x34\x12')
Ejemplo n.º 31
0
 def _clean(self):
     forget(TESTFN)
     rmtree('__pycache__')
     unlink(self.source)
Ejemplo n.º 32
0
 def tearDown(self):
     unlink(TESTFN)
Ejemplo n.º 33
0
 def setUp(self):
     unlink(TESTFN)
Ejemplo n.º 34
0
 def tearDown(self):
     for suffix in ["", "1", "2"]:
         support.unlink(support.TESTFN + suffix)
         safe_rmdir(support.TESTFN + suffix)
Ejemplo n.º 35
0
    def test_realpath_symlink_loops(self):
        # Bug #930024, return the path unchanged if we get into an infinite
        # symlink loop.
        try:
            old_path = abspath('.')
            os.symlink(ABSTFN, ABSTFN)
            self.assertEqual(realpath(ABSTFN), ABSTFN)

            os.symlink(ABSTFN + "1", ABSTFN + "2")
            os.symlink(ABSTFN + "2", ABSTFN + "1")
            self.assertEqual(realpath(ABSTFN + "1"), ABSTFN + "1")
            self.assertEqual(realpath(ABSTFN + "2"), ABSTFN + "2")

            self.assertEqual(realpath(ABSTFN + "1/x"), ABSTFN + "1/x")
            self.assertEqual(realpath(ABSTFN + "1/.."), dirname(ABSTFN))
            self.assertEqual(realpath(ABSTFN + "1/../x"),
                             dirname(ABSTFN) + "/x")
            os.symlink(ABSTFN + "x", ABSTFN + "y")
            self.assertEqual(
                realpath(ABSTFN + "1/../" + basename(ABSTFN) + "y"),
                ABSTFN + "y")
            self.assertEqual(
                realpath(ABSTFN + "1/../" + basename(ABSTFN) + "1"),
                ABSTFN + "1")

            os.symlink(basename(ABSTFN) + "a/b", ABSTFN + "a")
            self.assertEqual(realpath(ABSTFN + "a"), ABSTFN + "a/b")

            os.symlink(
                "../" + basename(dirname(ABSTFN)) + "/" + basename(ABSTFN) +
                "c", ABSTFN + "c")
            self.assertEqual(realpath(ABSTFN + "c"), ABSTFN + "c")

            # Test using relative path as well.
            os.chdir(dirname(ABSTFN))
            self.assertEqual(realpath(basename(ABSTFN)), ABSTFN)
        finally:
            os.chdir(old_path)
            support.unlink(ABSTFN)
            support.unlink(ABSTFN + "1")
            support.unlink(ABSTFN + "2")
            support.unlink(ABSTFN + "y")
            support.unlink(ABSTFN + "c")
            support.unlink(ABSTFN + "a")
Ejemplo n.º 36
0
 def test_realpath_relative(self):
     try:
         os.symlink(posixpath.relpath(ABSTFN + "1"), ABSTFN)
         self.assertEqual(realpath(ABSTFN), ABSTFN + "1")
     finally:
         support.unlink(ABSTFN)
Ejemplo n.º 37
0
    def test_issue5604(self):
        # Test cannot cover imp.load_compiled function.
        # Martin von Loewis note what shared library cannot have non-ascii
        # character because init_xxx function cannot be compiled
        # and issue never happens for dynamic modules.
        # But sources modified to follow generic way for processing pathes.

        # the return encoding could be uppercase or None
        fs_encoding = sys.getfilesystemencoding()

        # covers utf-8 and Windows ANSI code pages
        # one non-space symbol from every page
        # (http://en.wikipedia.org/wiki/Code_page)
        known_locales = {
            'utf-8': b'\xc3\xa4',
            'cp1250': b'\x8C',
            'cp1251': b'\xc0',
            'cp1252': b'\xc0',
            'cp1253': b'\xc1',
            'cp1254': b'\xc0',
            'cp1255': b'\xe0',
            'cp1256': b'\xe0',
            'cp1257': b'\xc0',
            'cp1258': b'\xc0',
        }

        if sys.platform == 'darwin':
            self.assertEqual(fs_encoding, 'utf-8')
            # Mac OS X uses the Normal Form D decomposition
            # http://developer.apple.com/mac/library/qa/qa2001/qa1173.html
            special_char = b'a\xcc\x88'
        else:
            special_char = known_locales.get(fs_encoding)

        if not special_char:
            self.skipTest(
                "can't run this test with %s as filesystem encoding" %
                fs_encoding)
        decoded_char = special_char.decode(fs_encoding)
        temp_mod_name = 'test_imp_helper_' + decoded_char
        test_package_name = 'test_imp_helper_package_' + decoded_char
        init_file_name = os.path.join(test_package_name, '__init__.py')
        try:
            # if the curdir is not in sys.path the test fails when run with
            # ./python ./Lib/test/regrtest.py test_imp
            sys.path.insert(0, os.curdir)
            with open(temp_mod_name + '.py', 'w') as file:
                file.write('a = 1\n')
            file, filename, info = imp.find_module(temp_mod_name)
            with file:
                self.assertIsNotNone(file)
                self.assertTrue(filename[:-3].endswith(temp_mod_name))
                self.assertEqual(info[0], '.py')
                self.assertEqual(info[1], 'U')
                self.assertEqual(info[2], imp.PY_SOURCE)

                mod = imp.load_module(temp_mod_name, file, filename, info)
                self.assertEqual(mod.a, 1)

            mod = imp.load_source(temp_mod_name, temp_mod_name + '.py')
            self.assertEqual(mod.a, 1)

            mod = imp.load_compiled(
                temp_mod_name, imp.cache_from_source(temp_mod_name + '.py'))
            self.assertEqual(mod.a, 1)

            if not os.path.exists(test_package_name):
                os.mkdir(test_package_name)
            with open(init_file_name, 'w') as file:
                file.write('b = 2\n')
            if support.check_impl_detail(cpython=True):
                package = imp.load_package(test_package_name,
                                           test_package_name)
                self.assertEqual(package.b, 2)
        finally:
            del sys.path[0]
            for ext in ('.py', '.pyc', '.pyo'):
                support.unlink(temp_mod_name + ext)
                support.unlink(init_file_name + ext)
            support.rmtree(test_package_name)
Ejemplo n.º 38
0
    def testRaising(self):
        self.raise_catch(AttributeError, "AttributeError")
        self.assertRaises(AttributeError, getattr, sys, "undefined_attribute")

        self.raise_catch(EOFError, "EOFError")
        fp = open(TESTFN, 'w')
        fp.close()
        fp = open(TESTFN, 'r')
        savestdin = sys.stdin
        try:
            try:
                import marshal
                marshal.loads(b'')
            except EOFError:
                pass
        finally:
            sys.stdin = savestdin
            fp.close()
            unlink(TESTFN)

        self.raise_catch(OSError, "OSError")
        self.assertRaises(OSError, open, 'this file does not exist', 'r')

        self.raise_catch(ImportError, "ImportError")
        self.assertRaises(ImportError, __import__, "undefined_module")

        self.raise_catch(IndexError, "IndexError")
        x = []
        self.assertRaises(IndexError, x.__getitem__, 10)

        self.raise_catch(KeyError, "KeyError")
        x = {}
        self.assertRaises(KeyError, x.__getitem__, 'key')

        self.raise_catch(KeyboardInterrupt, "KeyboardInterrupt")

        self.raise_catch(MemoryError, "MemoryError")

        self.raise_catch(NameError, "NameError")
        try:
            x = undefined_variable
        except NameError:
            pass

        self.raise_catch(OverflowError, "OverflowError")
        x = 1
        for dummy in range(128):
            x += x  # this simply shouldn't blow up

        self.raise_catch(RuntimeError, "RuntimeError")
        self.raise_catch(RecursionError, "RecursionError")

        self.raise_catch(SyntaxError, "SyntaxError")
        try:
            exec('/\n')
        except SyntaxError:
            pass

        self.raise_catch(IndentationError, "IndentationError")

        self.raise_catch(TabError, "TabError")
        try:
            compile("try:\n\t1/0\n    \t1/0\nfinally:\n pass\n", '<string>',
                    'exec')
        except TabError:
            pass
        else:
            self.fail("TabError not raised")

        self.raise_catch(SystemError, "SystemError")

        self.raise_catch(SystemExit, "SystemExit")
        self.assertRaises(SystemExit, sys.exit, 0)

        self.raise_catch(TypeError, "TypeError")
        try:
            [] + ()
        except TypeError:
            pass

        self.raise_catch(ValueError, "ValueError")
        self.assertRaises(ValueError, chr, 17 << 16)

        self.raise_catch(ZeroDivisionError, "ZeroDivisionError")
        try:
            x = 1 / 0
        except ZeroDivisionError:
            pass

        self.raise_catch(Exception, "Exception")
        try:
            x = 1 / 0
        except Exception as e:
            pass

        self.raise_catch(StopAsyncIteration, "StopAsyncIteration")
Ejemplo n.º 39
0
def unlink(file_name):
    from test import support
    try:
        support.unlink(file_name)
    except OSError:
        pass
Ejemplo n.º 40
0
def remove_files(name):
    for f in (name + ".py", name + ".pyc", name + ".pyw", name + "$py.class"):
        unlink(f)
    rmtree('__pycache__')
Ejemplo n.º 41
0
 def tearDown(self):
     support.unlink(TESTFN)
Ejemplo n.º 42
0
 def tearDown(self):
     if self.g is not None:
         self.g.close()
     unlink(filename)
Ejemplo n.º 43
0
def temporary_filename():
    filename = tempfile.mktemp()
    try:
        yield filename
    finally:
        support.unlink(filename)
Ejemplo n.º 44
0
 def tearDown(self):
     if self.f:
         self.f.close()
     support.unlink(TESTFN)
Ejemplo n.º 45
0
 def testEmptyFile(self):
     support.unlink(TESTMOD)
     open(TESTMOD, 'w+').close()
     self.assertZipFailure(TESTMOD)
Ejemplo n.º 46
0
 def tearDown(self):
     support.unlink(self.filename)
Ejemplo n.º 47
0
 def tearDown(self):
     support.unlink(self.addr)
     BaseTestAPI.tearDown(self)
Ejemplo n.º 48
0
 def testNotZipFile(self):
     support.unlink(TESTMOD)
     fp = open(TESTMOD, 'w+')
     fp.write('a' * 22)
     fp.close()
     self.assertZipFailure(TESTMOD)
Ejemplo n.º 49
0
 def test_unlink(self):
     with open(TESTFN, "w") as f:
         pass
     support.unlink(TESTFN)
     self.assertFalse(os.path.exists(TESTFN))
     support.unlink(TESTFN)
Ejemplo n.º 50
0
def bind_af_aware(sock, addr):
    """Helper function to bind a socket according to its family."""
    if HAS_UNIX_SOCKETS and sock.family == socket.AF_UNIX:
        # Make sure the path doesn't exist.
        support.unlink(addr)
    sock.bind(addr)
Ejemplo n.º 51
0
 def test_mkfifo(self):
     support.unlink(support.TESTFN)
     posix.mkfifo(support.TESTFN, stat.S_IRUSR | stat.S_IWUSR)
     self.assertTrue(stat.S_ISFIFO(posix.stat(support.TESTFN).st_mode))
Ejemplo n.º 52
0
 def tearDown(self):
     if self.f and not self.f.closed:
         self.f.close()
     unlink(TESTFN)
Ejemplo n.º 53
0
    def test_builtin_zip(self):
        self.assertEqual(list(zip()), [])
        self.assertEqual(list(zip(*[])), [])
        self.assertEqual(list(zip(*[(1, 2), 'ab'])), [(1, 'a'), (2, 'b')])

        self.assertRaises(TypeError, zip, None)
        self.assertRaises(TypeError, zip, range(10), 42)
        self.assertRaises(TypeError, zip, range(10), zip)

        self.assertEqual(list(zip(IteratingSequenceClass(3))), [(0, ), (1, ),
                                                                (2, )])
        self.assertEqual(list(zip(SequenceClass(3))), [(0, ), (1, ), (2, )])

        d = {"one": 1, "two": 2, "three": 3}
        self.assertEqual(list(d.items()), list(zip(d, d.values())))

        # Generate all ints starting at constructor arg.
        class IntsFrom:
            def __init__(self, start):
                self.i = start

            def __iter__(self):
                return self

            def __next__(self):
                i = self.i
                self.i = i + 1
                return i

        f = open(TESTFN, "w")
        try:
            f.write("a\n" "bbb\n" "cc\n")
        finally:
            f.close()
        f = open(TESTFN, "r")
        try:
            self.assertEqual(list(zip(IntsFrom(0), f, IntsFrom(-100))),
                             [(0, "a\n", -100), (1, "bbb\n", -99),
                              (2, "cc\n", -98)])
        finally:
            f.close()
            try:
                unlink(TESTFN)
            except OSError:
                pass

        self.assertEqual(list(zip(range(5))), [(i, ) for i in range(5)])

        # Classes that lie about their lengths.
        class NoGuessLen5:
            def __getitem__(self, i):
                if i >= 5:
                    raise IndexError
                return i

        class Guess3Len5(NoGuessLen5):
            def __len__(self):
                return 3

        class Guess30Len5(NoGuessLen5):
            def __len__(self):
                return 30

        def lzip(*args):
            return list(zip(*args))

        self.assertEqual(len(Guess3Len5()), 3)
        self.assertEqual(len(Guess30Len5()), 30)
        self.assertEqual(lzip(NoGuessLen5()), lzip(range(5)))
        self.assertEqual(lzip(Guess3Len5()), lzip(range(5)))
        self.assertEqual(lzip(Guess30Len5()), lzip(range(5)))

        expected = [(i, i) for i in range(5)]
        for x in NoGuessLen5(), Guess3Len5(), Guess30Len5():
            for y in NoGuessLen5(), Guess3Len5(), Guess30Len5():
                self.assertEqual(lzip(x, y), expected)
Ejemplo n.º 54
0
 def tearDown(self):
     for teardown_file in self.teardown_files:
         support.unlink(teardown_file)
     self._warnings_manager.__exit__(None, None, None)
Ejemplo n.º 55
0
 def tearDown(self):
     rmtree(TESTFN)
     unlink(TESTFN)
Ejemplo n.º 56
0
 def setUp(self):
     support.unlink(TESTFN)
     support.rmtree(TESTDIRN)
Ejemplo n.º 57
0
 def testEmptyFile(self):
     support.unlink(TESTMOD)
     support.create_empty_file(TESTMOD)
     self.assertZipFailure(TESTMOD)
Ejemplo n.º 58
0
def tearDownModule():
    unlink(TESTFN)
Ejemplo n.º 59
0
 def setUp(self):
     support.unlink(self.filename)
Ejemplo n.º 60
0
 def cleanup():
     writer.close()
     support.unlink(self.fname)