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
    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)
    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.assertFalse(line) # Must be at EOF
            f.close()
        finally:
            support.unlink(support.TESTFN)
    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
def remove_files(name):
    for f in (name + ".py",
              name + ".pyc",
              name + ".pyw",
              name + "$py.class"):
        unlink(f)
    rmtree('__pycache__')
 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')
    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
    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)
    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 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')
Beispiel #11
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)
 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)
 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)
 def test_realpath_basic(self):
     # Basic operation.
     try:
         os.symlink(ABSTFN + "1", ABSTFN)
         self.assertEqual(realpath(ABSTFN), ABSTFN + "1")
     finally:
         support.unlink(ABSTFN)
        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)
    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)
    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
    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
Beispiel #19
0
    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(OSError, z.get_data, 'abc')
            self.assertRaises(error, z.get_source, 'abc')
            self.assertRaises(error, z.is_package, 'abc')
        finally:
            zipimport._zip_directory_cache.clear()
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 comsumes large resources; It
    # takes a long time to build the >2GB file and takes >2GB 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)
Beispiel #21
0
 def urlretrieve(self, *args, **kwargs):
     resource = args[0]
     with support.transient_internet(resource):
         file_location, info = urllib.request.urlretrieve(*args, **kwargs)
         try:
             yield file_location, info
         finally:
             support.unlink(file_location)
Beispiel #22
0
 def test_x_mode(self):
     for mode in ("x", "xb", "xt"):
         unlink(self.filename)
         with self.open(self.filename, mode) as f:
             pass
         with self.assertRaises(FileExistsError):
             with self.open(self.filename, mode) as f:
                 pass
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)
        support.bind_unix_socket(sock, addr)
    else:
        sock.bind(addr)
Beispiel #24
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')
Beispiel #25
0
 def test_write_object_to_file(self):
     obj = ('\u20ac', b'abc', 123, 45.6, 7 + 8j, 'long line ' * 1000)
     for v in range(marshal.version + 1):
         _testcapi.pymarshal_write_object_to_file(obj, support.TESTFN, v)
         with open(support.TESTFN, 'rb') as f:
             data = f.read()
         support.unlink(support.TESTFN)
         self.assertEqual(marshal.loads(data), obj)
Beispiel #26
0
def test_main():
    try:
        support.run_unittest(
            UncompressedZipImportTestCase,
            CompressedZipImportTestCase,
            BadFileZipImportTestCase,
        )
    finally:
        support.unlink(TESTMOD)
 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)
 def test_fromfile_ioerror(self):
     # Issue #5395: Check if fromfile raises a proper OSError
     # instead of EOFError.
     a = array.array(self.typecode)
     f = open(support.TESTFN, 'wb')
     try:
         self.assertRaises(OSError, a.fromfile, f, len(self.example))
     finally:
         f.close()
         support.unlink(support.TESTFN)
 def test_realpath_repeated_indirect_symlinks(self):
     # Issue #6975.
     try:
         os.mkdir(ABSTFN)
         os.symlink('../' + basename(ABSTFN), ABSTFN + '/self')
         os.symlink('self/self/self', ABSTFN + '/link')
         self.assertEqual(realpath(ABSTFN + '/link'), ABSTFN)
     finally:
         support.unlink(ABSTFN + '/self')
         support.unlink(ABSTFN + '/link')
         safe_rmdir(ABSTFN)
Beispiel #30
0
 def helper(self, sample, *extra):
     new = marshal.loads(marshal.dumps(sample, *extra))
     self.assertEqual(sample, new)
     try:
         with open(support.TESTFN, "wb") as f:
             marshal.dump(sample, f, *extra)
         with open(support.TESTFN, "rb") as f:
             new = marshal.load(f)
         self.assertEqual(sample, new)
     finally:
         support.unlink(support.TESTFN)