Python errno.ENAMETOOLONG Examples

The following are 28 code examples of errno.ENAMETOOLONG(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module errno , or try the search function .
Example #1
Source File: socket.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def bind(self, address):
        if isinstance(address, unicode):
            address = address.encode('utf8')
        rc = C.zmq_bind(self._zmq_socket, address)
        if rc < 0:
            if IPC_PATH_MAX_LEN and C.zmq_errno() == errno_mod.ENAMETOOLONG:
                # py3compat: address is bytes, but msg wants str
                if str is unicode:
                    address = address.decode('utf-8', 'replace')
                path = address.split('://', 1)[-1]
                msg = ('ipc path "{0}" is longer than {1} '
                                'characters (sizeof(sockaddr_un.sun_path)).'
                                .format(path, IPC_PATH_MAX_LEN))
                raise ZMQError(C.zmq_errno(), msg=msg)
            else:
                _check_rc(rc) 
Example #2
Source File: socket.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def bind(self, address):
        if isinstance(address, unicode):
            address = address.encode('utf8')
        rc = C.zmq_bind(self._zmq_socket, address)
        if rc < 0:
            if IPC_PATH_MAX_LEN and C.zmq_errno() == errno_mod.ENAMETOOLONG:
                # py3compat: address is bytes, but msg wants str
                if str is unicode:
                    address = address.decode('utf-8', 'replace')
                path = address.split('://', 1)[-1]
                msg = ('ipc path "{0}" is longer than {1} '
                                'characters (sizeof(sockaddr_un.sun_path)).'
                                .format(path, IPC_PATH_MAX_LEN))
                raise ZMQError(C.zmq_errno(), msg=msg)
            else:
                _check_rc(rc) 
Example #3
Source File: wad.py    From CDTB with GNU Lesser General Public License v3.0 6 votes vote down vote up
def extract(self, fwad, output_path):
        """Read data, convert it if needed, and write it to a file

        On error, partially retrieved files are removed.
        File redirections are skipped.
        """

        data = self.read_data(fwad)
        if data is None:
            return

        try:
            with write_file_or_remove(output_path) as fout:
                fout.write(data)
        except OSError as e:
            # Windows does not support path components longer than 255
            # ignore such files
            # TODO: Find a better way of handling these files
            if e.errno in (errno.EINVAL, errno.ENAMETOOLONG):
                logger.warning(f"ignore file with invalid path: {self.path}")
            else:
                raise 
Example #4
Source File: pytest_profiling.py    From pytest-plugins with MIT License 6 votes vote down vote up
def pytest_runtest_protocol(self, item, nextitem):
        prof_filename = os.path.abspath(os.path.join(self.dir, clean_filename(item.name) + ".prof"))
        try:
            os.makedirs(os.path.dirname(prof_filename))
        except OSError:
            pass
        prof = cProfile.Profile()
        prof.enable()
        yield
        prof.disable()
        try:
            prof.dump_stats(prof_filename)
        except EnvironmentError as err:
            if err.errno != errno.ENAMETOOLONG:
                raise

            if len(item.name) < LARGE_FILENAME_HASH_LEN:
                raise

            hash_str = md5(item.name.encode('utf-8')).hexdigest()[:LARGE_FILENAME_HASH_LEN]
            prof_filename = os.path.join(self.dir, hash_str + ".prof")
            prof.dump_stats(prof_filename)
        self.profs.append(prof_filename) 
Example #5
Source File: java_executor.py    From judge-server with GNU Affero General Public License v3.0 6 votes vote down vote up
def create_files(self, problem_id, source_code, *args, **kwargs):
        super().create_files(problem_id, source_code, *args, **kwargs)
        # This step is necessary because of Unicode classnames
        try:
            source_code = utf8text(source_code)
        except UnicodeDecodeError:
            raise CompileError('Your UTF-8 is bad, and you should feel bad')
        class_name = find_class(source_code)
        self._code = self._file('%s.java' % class_name.group(1))
        try:
            with open(self._code, 'wb') as fo:
                fo.write(utf8bytes(source_code))
        except IOError as e:
            if e.errno in (errno.ENAMETOOLONG, errno.ENOENT, errno.EINVAL):
                raise CompileError('Why do you need a class name so long? As a judge, I sentence your code to death.\n')
            raise
        self._class_name = class_name.group(1) 
Example #6
Source File: storage.py    From Kenshin with Apache License 2.0 6 votes vote down vote up
def rebuildLink(instance_data_dir, instance_link_dir):
    for schema_name in os.listdir(instance_data_dir):
        hs_file_pat = os.path.join(instance_data_dir, schema_name, '*.hs')
        for fp in glob.glob(hs_file_pat):
            with open(fp) as f:
                header = kenshin.header(f)
                metric_list = header['tag_list']
                for metric in metric_list:
                    if metric != '':
                        link_path = getMetricPathByInstanceDir(instance_link_dir, metric)
                        try:
                            _createLinkHelper(link_path, fp)
                        except OSError as exc:
                            if exc.errno == errno.ENAMETOOLONG:
                                pass
                            else:
                                raise 
Example #7
Source File: kenshin-rebuild-link.py    From Kenshin with Apache License 2.0 6 votes vote down vote up
def main():
    if len(sys.argv) < 3:
        print('Need data_dir and link_dir.\n'
              'e.g.: kenshin-rebuild-link.py /kenshin/data/a /kenshin/link/a')
        sys.exit(1)

    data_dir, link_dir = sys.argv[1:]
    data_dir = os.path.abspath(data_dir)
    link_dir = os.path.abspath(link_dir)

    for schema_name in os.listdir(data_dir):
        hs_file_pat = os.path.join(data_dir, schema_name, '*.hs')
        for fp in glob.glob(hs_file_pat):
            with open(fp) as f:
                header = kenshin.header(f)
                metric_list = header['tag_list']
                for metric in metric_list:
                    if metric != '':
                        try:
                            create_link(metric, link_dir, fp)
                        except OSError as exc:
                            if exc.errno == errno.ENAMETOOLONG:
                                pass
                            else:
                                raise 
Example #8
Source File: socket.py    From pySINDy with MIT License 6 votes vote down vote up
def bind(self, address):
        if isinstance(address, unicode):
            address = address.encode('utf8')
        rc = C.zmq_bind(self._zmq_socket, address)
        if rc < 0:
            if IPC_PATH_MAX_LEN and C.zmq_errno() == errno_mod.ENAMETOOLONG:
                # py3compat: address is bytes, but msg wants str
                if str is unicode:
                    address = address.decode('utf-8', 'replace')
                path = address.split('://', 1)[-1]
                msg = ('ipc path "{0}" is longer than {1} '
                                'characters (sizeof(sockaddr_un.sun_path)).'
                                .format(path, IPC_PATH_MAX_LEN))
                raise ZMQError(C.zmq_errno(), msg=msg)
            else:
                _check_rc(rc) 
Example #9
Source File: crawler.py    From wg-gesucht-crawler-cli with MIT License 5 votes vote down vote up
def update_files(self, url, ad_info):
        MAX_FILENAME_LENGTH = 245

        ad_page_soup, ad_title, ad_submitter, ad_url = (
            ad_info["ad_page_soup"],
            ad_info["ad_title"],
            ad_info["ad_submitter"],
            ad_info["ad_url"],
        )
        # save url to file, so as not to send a message to them again
        with open(
            os.path.join(self.ad_links_folder, "WG Ad Links.csv"),
            "a",
            newline="",
            encoding="utf-8",
        ) as file_write:
            csv_file_write = csv.writer(file_write)
            csv_file_write.writerow([url, ad_submitter, ad_title])

        # save a copy of the ad for offline viewing, in case the ad is deleted before the user can view it online
        max_ad_title_length = MAX_FILENAME_LENGTH - len(ad_submitter) - len(ad_url)
        if len(ad_title) > max_ad_title_length:
            ad_title = ad_title[: max_ad_title_length - 1] + "..."

        file_name = "{}-{}-{}".format(ad_submitter, ad_title, ad_url)
        try:
            with open(
                os.path.join(self.offline_ad_folder, file_name), "w", encoding="utf-8"
            ) as outfile:
                outfile.write(str(ad_page_soup))
        except OSError as err:
            if err.errno == errno.ENAMETOOLONG:
                self.logger.exception(
                    "File name of {} is too long, could not save this ad offline".format(
                        file_name
                    )
                ) 
Example #10
Source File: zipfile.py    From aptsources-cleanup with MIT License 5 votes vote down vote up
def _resolve_path_component(self, inspected, uninspected, pwd, seen_set):
		c = uninspected.pop()
		#_eprintf('_resolve_path_component(): {!r}, {!r}, {!r}', inspected, c, uninspected)

		if not c or c == os.curdir:
			return None

		if c == os.pardir:
			if not inspected:
				uninspected.append(c)
				uninspected.reverse()
				raise self._OSError(
					errno.ENOENT, 'Path points outside of this archive',
					"/".join(uninspected))
			inspected.pop()
			return None

		inspected.append(c)
		c_full = "/".join(inspected)
		c_info = self.NameToInfo.get(c_full)
		if c_info is None or not stat.S_ISLNK(c_info.external_attr >> 16):
			if self.debug >= 2:
				_eprintf('{:s}: {!r}',
					('Not a symlink', 'Does not exist')[c_info is None],
					':'.join((self.filename, c_full)))
			return c_info
		if c_info.is_dir():
			raise BadZipFile(
				"{:s}:{!r} claims to be both a directory and a symbolic link."
					.format(self.filename, c_info))
		if len(c_info.filename) - len(c) + c_info.file_size > self._max_path:
			raise self._OSError(errno.ENAMETOOLONG, None, c_info.filename)

		if not seen_set.add(c_info.filename):
			raise self._OSError(errno.ELOOP, None, c_info.filename)
		uninspected.extend(reversed(
			self._read_symlink(c_info, pwd).rstrip("/").split("/")))
		inspected.pop()
		return c_info 
Example #11
Source File: questions.py    From python-inquirer with MIT License 5 votes vote down vote up
def is_pathname_valid(pathname):
    """
    `True` if the passed pathname is a valid pathname for the current OS;
    `False` otherwise.
    """
    try:
        if not isinstance(pathname, str) or not pathname:
            return False

        _, pathname = os.path.splitdrive(pathname)

        root_dirname = os.environ.get('HOMEDRIVE', 'C:') \
            if sys.platform == 'win32' else os.path.sep

        assert os.path.isdir(root_dirname)
        root_dirname = root_dirname.rstrip(os.path.sep) + os.path.sep

        for pathname_part in pathname.split(os.path.sep):
            try:
                os.lstat(root_dirname + pathname_part)
            except OSError as exc:
                if hasattr(exc, 'winerror'):
                    if exc.winerror == ERROR_INVALID_NAME:
                        return False
                elif exc.errno in {errno.ENAMETOOLONG, errno.ERANGE}:
                    return False
    except (ValueError, TypeError):
        return False
    else:
        return True 
Example #12
Source File: file_utils.py    From conary with Apache License 2.0 5 votes vote down vote up
def removeIfExists(path):
    try:
        os.unlink(path)
    except OSError, err:
        if err.errno in (errno.ENOENT, errno.ENAMETOOLONG):
            return False
        raise 
Example #13
Source File: file_utils.py    From conary with Apache License 2.0 5 votes vote down vote up
def lexists(path):
    try:
        os.lstat(path)
    except OSError, err:
        if err.errno in (errno.ENOENT, errno.ENOTDIR, errno.ENAMETOOLONG,
                errno.EACCES):
            return False
        raise 
Example #14
Source File: path.py    From eddy with GNU General Public License v3.0 5 votes vote down vote up
def isPathValid(path):
    """
    Returns True if the given path is valid, False otherwise.
    :type path: str
    :rtype: bool
    """
    try:
        if not path or not isinstance(path, str):
            return False
        path = expandPath(path)
        path = os.path.splitdrive(path)[1]
        root = os.path.sep
        if __WIN32:
            root = os.environ.get('HOMEDRIVE', 'C:')
        root = '{0}{1}'.format(root.rstrip(os.path.sep), os.path.sep)
        assert os.path.isdir(root)
        for part in path.split(os.path.sep):
            try:
                os.lstat(os.path.join(root, part))
            except OSError as exc:
                if hasattr(exc, 'winerror'):
                    if exc.winerror == 123:
                        return False
                if exc.errno in {errno.ENAMETOOLONG, errno.ERANGE}:
                    return False
    except TypeError:
        return False
    else:
        return True 
Example #15
Source File: storage.py    From Kenshin with Apache License 2.0 5 votes vote down vote up
def createLink(metric, file_path):
    metric_path = getMetricPath(metric)
    try:
        _createLinkHelper(metric_path, file_path)
    except OSError as exc:
        if exc.errno == errno.ENAMETOOLONG:
            pass
        else:
            raise 
Example #16
Source File: common_test.py    From bucket-antivirus-function with Apache License 2.0 5 votes vote down vote up
def test_create_dir_doesnt_exist_but_raises(self, mock_os, mock_path):
        mock_path.exists.return_value = False
        mock_os.makedirs.side_effect = OSError(errno.ENAMETOOLONG, "nametoolong")
        with self.assertRaises(OSError):
            create_dir("testpath")
        self.assertTrue(
            mock_os.makedirs.called, "Failed to make directories if path not present."
        ) 
Example #17
Source File: _error_translation.py    From pyzfs with Apache License 2.0 5 votes vote down vote up
def lzc_receive_translate_error(ret, snapname, fd, force, origin, props):
    if ret == 0:
        return
    if ret == errno.EINVAL:
        if not _is_valid_snap_name(snapname) and not _is_valid_fs_name(snapname):
            raise lzc_exc.NameInvalid(snapname)
        elif len(snapname) > MAXNAMELEN:
            raise lzc_exc.NameTooLong(snapname)
        elif origin is not None and not _is_valid_snap_name(origin):
            raise lzc_exc.NameInvalid(origin)
        else:
            raise lzc_exc.BadStream()
    if ret == errno.ENOENT:
        if not _is_valid_snap_name(snapname):
            raise lzc_exc.NameInvalid(snapname)
        else:
            raise lzc_exc.DatasetNotFound(snapname)
    if ret == errno.EEXIST:
        raise lzc_exc.DatasetExists(snapname)
    if ret == errno.ENOTSUP:
        raise lzc_exc.StreamFeatureNotSupported()
    if ret == errno.ENODEV:
        raise lzc_exc.StreamMismatch(_fs_name(snapname))
    if ret == errno.ETXTBSY:
        raise lzc_exc.DestinationModified(_fs_name(snapname))
    if ret == errno.EBUSY:
        raise lzc_exc.DatasetBusy(_fs_name(snapname))
    if ret == errno.ENOSPC:
        raise lzc_exc.NoSpace(_fs_name(snapname))
    if ret == errno.EDQUOT:
        raise lzc_exc.QuotaExceeded(_fs_name(snapname))
    if ret == errno.ENAMETOOLONG:
        raise lzc_exc.NameTooLong(snapname)
    if ret == errno.EROFS:
        raise lzc_exc.ReadOnlyPool(_pool_name(snapname))
    if ret == errno.EAGAIN:
        raise lzc_exc.SuspendedPool(_pool_name(snapname))

    raise lzc_exc.StreamIOError(ret) 
Example #18
Source File: _error_translation.py    From pyzfs with Apache License 2.0 5 votes vote down vote up
def lzc_send_translate_error(ret, snapname, fromsnap, fd, flags):
    if ret == 0:
        return
    if ret == errno.EXDEV and fromsnap is not None:
        if _pool_name(fromsnap) != _pool_name(snapname):
            raise lzc_exc.PoolsDiffer(snapname)
        else:
            raise lzc_exc.SnapshotMismatch(snapname)
    elif ret == errno.EINVAL:
        if (fromsnap is not None and not _is_valid_snap_name(fromsnap) and
                not _is_valid_bmark_name(fromsnap)):
            raise lzc_exc.NameInvalid(fromsnap)
        elif not _is_valid_snap_name(snapname) and not _is_valid_fs_name(snapname):
            raise lzc_exc.NameInvalid(snapname)
        elif fromsnap is not None and len(fromsnap) > MAXNAMELEN:
            raise lzc_exc.NameTooLong(fromsnap)
        elif len(snapname) > MAXNAMELEN:
            raise lzc_exc.NameTooLong(snapname)
        elif fromsnap is not None and _pool_name(fromsnap) != _pool_name(snapname):
            raise lzc_exc.PoolsDiffer(snapname)
    elif ret == errno.ENOENT:
        if (fromsnap is not None and not _is_valid_snap_name(fromsnap) and
                not _is_valid_bmark_name(fromsnap)):
            raise lzc_exc.NameInvalid(fromsnap)
        raise lzc_exc.SnapshotNotFound(snapname)
    elif ret == errno.ENAMETOOLONG:
        if fromsnap is not None and len(fromsnap) > MAXNAMELEN:
            raise lzc_exc.NameTooLong(fromsnap)
        else:
            raise lzc_exc.NameTooLong(snapname)
    raise lzc_exc.StreamIOError(ret) 
Example #19
Source File: _validator.py    From pytablereader with MIT License 5 votes vote down vote up
def is_fifo(file_path):
    try:
        return stat.S_ISFIFO(os.stat(file_path).st_mode)
    except OSError as e:
        if e.errno not in (EBADF, ENAMETOOLONG, ENOENT, ENOTDIR):
            raise

        return False
    except ValueError:
        return False 
Example #20
Source File: socket.py    From Computable with MIT License 5 votes vote down vote up
def bind(self, address):
        rc = C.zmq_bind(self._zmq_socket, address)
        if rc < 0:
            if IPC_PATH_MAX_LEN and C.zmq_errno() == errno_mod.ENAMETOOLONG:
                # py3compat: address is bytes, but msg wants str
                if str is unicode:
                    address = address.decode('utf-8', 'replace')
                path = address.split('://', 1)[-1]
                msg = ('ipc path "{0}" is longer than {1} '
                                'characters (sizeof(sockaddr_un.sun_path)).'
                                .format(path, IPC_PATH_MAX_LEN))
                raise ZMQError(C.zmq_errno(), msg=msg)
            else:
                _check_rc(rc) 
Example #21
Source File: export.py    From CDTB with GNU Lesser General Public License v3.0 5 votes vote down vote up
def _export_wad(self, wad, overwrite=True):
        logger.info(f"export {wad.path} ({len(wad.files)})")
        # similar to Wad.extract()
        # unknown files are skipped
        with open(wad.path, 'rb') as fwad:
            for wadfile in wad.files:
                if wadfile.path is None:
                    continue

                converter = self._get_converter(wadfile.path)
                if not overwrite and converter.converted_paths_exist(self.output, wadfile.path):
                    continue

                data = wadfile.read_data(fwad)
                if data is None:
                    continue  # should not happen, file redirections have been filtered already

                try:
                    converter.convert(BytesIO(data), self.output, wadfile.path)
                except FileConversionError as e:
                    logger.warning(f"cannot convert file '{wadfile.path}': {e}")
                except OSError as e:
                    # Windows does not support path components longer than 255
                    # ignore such files
                    if e.errno in (errno.EINVAL, errno.ENAMETOOLONG):
                        logger.warning(f"ignore file with invalid path: {wad.path}")
                    else:
                        raise 
Example #22
Source File: _file.py    From sqlitebiter with MIT License 5 votes vote down vote up
def __is_fifo(self, file_path: Path) -> bool:
        try:
            return stat.S_ISFIFO(os.stat(file_path).st_mode)
        except OSError as e:
            if e.errno not in (EBADF, ENAMETOOLONG, ENOENT, ENOTDIR):
                raise

            return False
        except ValueError:
            return False 
Example #23
Source File: test_posix.py    From gcblue with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def test_getcwd_long_pathnames(self):
        dirname = 'getcwd-test-directory-0123456789abcdef-01234567890abcdef'
        curdir = os.getcwd()
        base_path = os.path.abspath(test_support.TESTFN) + '.getcwd'

        try:
            os.mkdir(base_path)
            os.chdir(base_path)
        except:
            self.skipTest("cannot create directory for testing")

        try:
            def _create_and_do_getcwd(dirname, current_path_length = 0):
                try:
                    os.mkdir(dirname)
                except:
                    self.skipTest("mkdir cannot create directory sufficiently "
                                  "deep for getcwd test")

                os.chdir(dirname)
                try:
                    os.getcwd()
                    if current_path_length < 4099:
                        _create_and_do_getcwd(dirname, current_path_length + len(dirname) + 1)
                except OSError as e:
                    expected_errno = errno.ENAMETOOLONG
                    # The following platforms have quirky getcwd()
                    # behaviour -- see issue 9185 and 15765 for
                    # more information.
                    quirky_platform = (
                        'sunos' in sys.platform or
                        'netbsd' in sys.platform or
                        'openbsd' in sys.platform
                    )
                    if quirky_platform:
                        expected_errno = errno.ERANGE
                    self.assertEqual(e.errno, expected_errno)
                finally:
                    os.chdir('..')
                    os.rmdir(dirname)

            _create_and_do_getcwd(dirname)

        finally:
            os.chdir(curdir)
            shutil.rmtree(base_path) 
Example #24
Source File: test_posix.py    From oss-ftp with MIT License 4 votes vote down vote up
def test_getcwd_long_pathnames(self):
        dirname = 'getcwd-test-directory-0123456789abcdef-01234567890abcdef'
        curdir = os.getcwd()
        base_path = os.path.abspath(test_support.TESTFN) + '.getcwd'

        try:
            os.mkdir(base_path)
            os.chdir(base_path)
        except:
            self.skipTest("cannot create directory for testing")

        try:
            def _create_and_do_getcwd(dirname, current_path_length = 0):
                try:
                    os.mkdir(dirname)
                except:
                    self.skipTest("mkdir cannot create directory sufficiently "
                                  "deep for getcwd test")

                os.chdir(dirname)
                try:
                    os.getcwd()
                    if current_path_length < 4099:
                        _create_and_do_getcwd(dirname, current_path_length + len(dirname) + 1)
                except OSError as e:
                    expected_errno = errno.ENAMETOOLONG
                    # The following platforms have quirky getcwd()
                    # behaviour -- see issue 9185 and 15765 for
                    # more information.
                    quirky_platform = (
                        'sunos' in sys.platform or
                        'netbsd' in sys.platform or
                        'openbsd' in sys.platform
                    )
                    if quirky_platform:
                        expected_errno = errno.ERANGE
                    self.assertEqual(e.errno, expected_errno)
                finally:
                    os.chdir('..')
                    os.rmdir(dirname)

            _create_and_do_getcwd(dirname)

        finally:
            os.chdir(curdir)
            shutil.rmtree(base_path) 
Example #25
Source File: test_posix.py    From BinderFilter with MIT License 4 votes vote down vote up
def test_getcwd_long_pathnames(self):
        if hasattr(posix, 'getcwd'):
            dirname = 'getcwd-test-directory-0123456789abcdef-01234567890abcdef'
            curdir = os.getcwd()
            base_path = os.path.abspath(test_support.TESTFN) + '.getcwd'

            try:
                os.mkdir(base_path)
                os.chdir(base_path)
            except:
#               Just returning nothing instead of the SkipTest exception,
#               because the test results in Error in that case.
#               Is that ok?
#                raise unittest.SkipTest, "cannot create directory for testing"
                return

            try:
                def _create_and_do_getcwd(dirname, current_path_length = 0):
                    try:
                        os.mkdir(dirname)
                    except:
                        raise unittest.SkipTest, "mkdir cannot create directory sufficiently deep for getcwd test"

                    os.chdir(dirname)
                    try:
                        os.getcwd()
                        if current_path_length < 4099:
                            _create_and_do_getcwd(dirname, current_path_length + len(dirname) + 1)
                    except OSError as e:
                        expected_errno = errno.ENAMETOOLONG
                        # The following platforms have quirky getcwd()
                        # behaviour -- see issue 9185 and 15765 for
                        # more information.
                        quirky_platform = (
                            'sunos' in sys.platform or
                            'netbsd' in sys.platform or
                            'openbsd' in sys.platform
                        )
                        if quirky_platform:
                            expected_errno = errno.ERANGE
                        self.assertEqual(e.errno, expected_errno)
                    finally:
                        os.chdir('..')
                        os.rmdir(dirname)

                _create_and_do_getcwd(dirname)

            finally:
                os.chdir(curdir)
                shutil.rmtree(base_path) 
Example #26
Source File: test_posix.py    From CTFCrackTools-V2 with GNU General Public License v3.0 4 votes vote down vote up
def test_getcwd_long_pathnames(self):
        if hasattr(posix, 'getcwd'):
            dirname = 'getcwd-test-directory-0123456789abcdef-01234567890abcdef'
            curdir = os.getcwd()
            base_path = os.path.abspath(test_support.TESTFN) + '.getcwd'

            try:
                os.mkdir(base_path)
                os.chdir(base_path)
            except:
#               Just returning nothing instead of the SkipTest exception,
#               because the test results in Error in that case.
#               Is that ok?
#                raise unittest.SkipTest, "cannot create directory for testing"
                return

            try:
                def _create_and_do_getcwd(dirname, current_path_length = 0):
                    try:
                        os.mkdir(dirname)
                    except:
                        raise unittest.SkipTest, "mkdir cannot create directory sufficiently deep for getcwd test"

                    os.chdir(dirname)
                    try:
                        os.getcwd()
                        if current_path_length < 4099:
                            _create_and_do_getcwd(dirname, current_path_length + len(dirname) + 1)
                    except OSError as e:
                        expected_errno = errno.ENAMETOOLONG
                        if 'sunos' in sys.platform or 'openbsd' in sys.platform:
                            expected_errno = errno.ERANGE # Issue 9185
                        self.assertEqual(e.errno, expected_errno)
                    finally:
                        os.chdir('..')
                        os.rmdir(dirname)

                _create_and_do_getcwd(dirname)

            finally:
                os.chdir(curdir)
                shutil.rmtree(base_path) 
Example #27
Source File: test_posix.py    From ironpython2 with Apache License 2.0 4 votes vote down vote up
def test_getcwd_long_pathnames(self):
        dirname = 'getcwd-test-directory-0123456789abcdef-01234567890abcdef'
        curdir = os.getcwd()
        base_path = os.path.abspath(test_support.TESTFN) + '.getcwd'

        try:
            os.mkdir(base_path)
            os.chdir(base_path)
        except:
            self.skipTest("cannot create directory for testing")

        try:
            def _create_and_do_getcwd(dirname, current_path_length = 0):
                try:
                    os.mkdir(dirname)
                except:
                    self.skipTest("mkdir cannot create directory sufficiently "
                                  "deep for getcwd test")

                os.chdir(dirname)
                try:
                    os.getcwd()
                    if current_path_length < 4099:
                        _create_and_do_getcwd(dirname, current_path_length + len(dirname) + 1)
                except OSError as e:
                    expected_errno = errno.ENAMETOOLONG
                    # The following platforms have quirky getcwd()
                    # behaviour -- see issue 9185 and 15765 for
                    # more information.
                    quirky_platform = (
                        'sunos' in sys.platform or
                        'netbsd' in sys.platform or
                        'openbsd' in sys.platform
                    )
                    if quirky_platform:
                        expected_errno = errno.ERANGE
                    if 'darwin' in sys.platform:
                        # macOS 10.15 may return errno.ENOENT instead
                        self.assertIn(e.errno, (errno.ENOENT, errno.ENAMETOOLONG))
                    else:
                        self.assertEqual(e.errno, expected_errno)
                finally:
                    os.chdir('..')
                    os.rmdir(dirname)

            _create_and_do_getcwd(dirname)

        finally:
            os.chdir(curdir)
            shutil.rmtree(base_path) 
Example #28
Source File: test_posix.py    From CTFCrackTools with GNU General Public License v3.0 4 votes vote down vote up
def test_getcwd_long_pathnames(self):
        if hasattr(posix, 'getcwd'):
            dirname = 'getcwd-test-directory-0123456789abcdef-01234567890abcdef'
            curdir = os.getcwd()
            base_path = os.path.abspath(test_support.TESTFN) + '.getcwd'

            try:
                os.mkdir(base_path)
                os.chdir(base_path)
            except:
#               Just returning nothing instead of the SkipTest exception,
#               because the test results in Error in that case.
#               Is that ok?
#                raise unittest.SkipTest, "cannot create directory for testing"
                return

            try:
                def _create_and_do_getcwd(dirname, current_path_length = 0):
                    try:
                        os.mkdir(dirname)
                    except:
                        raise unittest.SkipTest, "mkdir cannot create directory sufficiently deep for getcwd test"

                    os.chdir(dirname)
                    try:
                        os.getcwd()
                        if current_path_length < 4099:
                            _create_and_do_getcwd(dirname, current_path_length + len(dirname) + 1)
                    except OSError as e:
                        expected_errno = errno.ENAMETOOLONG
                        if 'sunos' in sys.platform or 'openbsd' in sys.platform:
                            expected_errno = errno.ERANGE # Issue 9185
                        self.assertEqual(e.errno, expected_errno)
                    finally:
                        os.chdir('..')
                        os.rmdir(dirname)

                _create_and_do_getcwd(dirname)

            finally:
                os.chdir(curdir)
                shutil.rmtree(base_path)