Python os.chmod() Examples

The following are 30 code examples for showing how to use os.chmod(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module os , or try the search function .

Example 1
Project: aegea   Author: kislyuk   File: ssm.py    License: Apache License 2.0 7 votes vote down vote up
def ensure_session_manager_plugin():
    session_manager_dir = os.path.join(config.user_config_dir, "bin")
    PATH = os.environ.get("PATH", "") + ":" + session_manager_dir
    if shutil.which("session-manager-plugin", path=PATH):
        subprocess.check_call(["session-manager-plugin"], env=dict(os.environ, PATH=PATH))
    else:
        os.makedirs(session_manager_dir, exist_ok=True)
        target_path = os.path.join(session_manager_dir, "session-manager-plugin")
        if platform.system() == "Darwin":
            download_session_manager_plugin_macos(target_path=target_path)
        elif platform.linux_distribution()[0] == "Ubuntu":
            download_session_manager_plugin_linux(target_path=target_path)
        else:
            download_session_manager_plugin_linux(target_path=target_path, pkg_format="rpm")
        os.chmod(target_path, stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR)
        subprocess.check_call(["session-manager-plugin"], env=dict(os.environ, PATH=PATH))
    return shutil.which("session-manager-plugin", path=PATH) 
Example 2
Project: delocate   Author: matthew-brett   File: test_tools.py    License: BSD 2-Clause "Simplified" License 7 votes vote down vote up
def test_ensure_writable():
    # Test ensure writable decorator
    with InTemporaryDirectory():
        with open('test.bin', 'wt') as fobj:
            fobj.write('A line\n')
        # Set to user rw, else r
        os.chmod('test.bin', 0o644)
        st = os.stat('test.bin')
        @ensure_writable
        def foo(fname):
            pass
        foo('test.bin')
        assert_equal(os.stat('test.bin'), st)
        # No-one can write
        os.chmod('test.bin', 0o444)
        st = os.stat('test.bin')
        foo('test.bin')
        assert_equal(os.stat('test.bin'), st) 
Example 3
Project: delocate   Author: matthew-brett   File: tools.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def ensure_permissions(mode_flags=stat.S_IWUSR):
    """decorator to ensure a filename has given permissions.

    If changed, original permissions are restored after the decorated
    modification.
    """

    def decorator(f):
        def modify(filename, *args, **kwargs):
            m = chmod_perms(filename) if exists(filename) else mode_flags
            if not m & mode_flags:
                os.chmod(filename, m | mode_flags)
            try:
                return f(filename, *args, **kwargs)
            finally:
                # restore original permissions
                if not m & mode_flags:
                    os.chmod(filename, m)
        return modify

    return decorator


# Open filename, checking for read permission 
Example 4
Project: smbprotocol   Author: jborean93   File: test_smbclient_shutil.py    License: MIT License 6 votes vote down vote up
def test_copymode_local_to_local_symlink_dont_follow(tmpdir):
    test_dir = tmpdir.mkdir('test')
    src_filename = "%s\\source.txt" % test_dir
    dst_filename = "%s\\target.txt" % test_dir

    with open(src_filename, mode='w') as fd:
        fd.write(u"content")
    os.chmod(src_filename, stat.S_IREAD)

    with open(dst_filename, mode='w') as fd:
        fd.write(u"content")

    src_link = "%s\\source-link.txt" % test_dir
    dst_link = "%s\\target-link.txt" % test_dir

    os.symlink(src_filename, src_link)
    os.symlink(dst_filename, dst_link)

    expected = "chmod: follow_symlinks unavailable on this platform"
    with pytest.raises(NotImplementedError, match=re.escape(expected)):
        copymode(src_link, dst_link, follow_symlinks=False) 
Example 5
Project: smbprotocol   Author: jborean93   File: test_smbclient_shutil.py    License: MIT License 6 votes vote down vote up
def test_copystat_local_to_local(tmpdir):
    test_dir = tmpdir.mkdir("test")
    src_filename = "%s\\source.txt" % test_dir
    dst_filename = "%s\\target.txt" % test_dir

    with open(src_filename, mode='w') as fd:
        fd.write(u"content")
    os.chmod(src_filename, stat.S_IREAD)
    os.utime(src_filename, (1024, 1024))

    with open(dst_filename, mode='w') as fd:
        fd.write(u"content")

    copystat(src_filename, dst_filename)

    actual = os.stat(dst_filename)
    assert actual.st_atime == 1024
    assert actual.st_mtime == 1024
    assert stat.S_IMODE(actual.st_mode) & stat.S_IWRITE == 0 
Example 6
Project: smbprotocol   Author: jborean93   File: test_smbclient_shutil.py    License: MIT License 6 votes vote down vote up
def test_copystat_local_to_local_symlink_dont_follow_fail(tmpdir):
    test_dir = tmpdir.mkdir('test')
    src_filename = "%s\\source.txt" % test_dir
    dst_filename = "%s\\target.txt" % test_dir

    with open(src_filename, mode='w') as fd:
        fd.write(u"content")
    os.chmod(src_filename, stat.S_IREAD)

    with open(dst_filename, mode='w') as fd:
        fd.write(u"content")

    src_link = "%s\\source-link.txt" % test_dir
    dst_link = "%s\\target-link.txt" % test_dir

    os.symlink(src_filename, src_link)
    os.symlink(dst_filename, dst_link)

    expected = "follow_symlinks unavailable on this platform"
    with pytest.raises(NotImplementedError, match=re.escape(expected)):
        copystat(src_link, dst_link, follow_symlinks=False) 
Example 7
Project: fine-lm   Author: akzaidi   File: generator_utils.py    License: MIT License 6 votes vote down vote up
def gunzip_file(gz_path, new_path):
  """Unzips from gz_path into new_path.

  Args:
    gz_path: path to the zipped file.
    new_path: path to where the file will be unzipped.
  """
  if tf.gfile.Exists(new_path):
    tf.logging.info("File %s already exists, skipping unpacking" % new_path)
    return
  tf.logging.info("Unpacking %s to %s" % (gz_path, new_path))
  # We may be unpacking into a newly created directory, add write mode.
  mode = stat.S_IRWXU or stat.S_IXGRP or stat.S_IRGRP or stat.S_IROTH
  os.chmod(os.path.dirname(new_path), mode)
  with gzip.open(gz_path, "rb") as gz_file:
    with tf.gfile.GFile(new_path, mode="wb") as new_file:
      for line in gz_file:
        new_file.write(line) 
Example 8
Project: calmjs   Author: calmjs   File: test_utils.py    License: GNU General Public License v2.0 6 votes vote down vote up
def test_found_win32(self):
        sys.platform = 'win32'
        tempdir = os.environ['PATH'] = mkdtemp(self)
        os.environ['PATHEXT'] = pathsep.join(('.com', '.exe', '.bat'))
        f = join(tempdir, 'binary.exe')
        with open(f, 'w'):
            pass
        os.chmod(f, 0o777)
        self.assertEqual(which('binary'), f)
        self.assertEqual(which('binary.exe'), f)
        self.assertEqual(which(f), f)
        self.assertIsNone(which('binary.com'))

        os.environ['PATH'] = ''
        self.assertEqual(which('binary', path=tempdir), f)
        self.assertEqual(which('binary.exe', path=tempdir), f)
        self.assertEqual(which(f, path=tempdir), f)
        self.assertIsNone(which('binary.com', path=tempdir)) 
Example 9
Project: mx   Author: graalvm   File: mx_native.py    License: GNU General Public License v2.0 6 votes vote down vote up
def _run(self, *args, **kwargs):
        cmd = [self.binary, '-j', self.parallelism]
        if mx.get_opts().very_verbose:
            cmd += ['-v']
        cmd += args

        out = kwargs.get('out', mx.OutputCapture())
        err = kwargs.get('err', subprocess.STDOUT)
        if mx.get_opts().verbose:
            if callable(out) and '-n' not in args:
                out = mx.TeeOutputCapture(out)
            if callable(err):
                err = mx.TeeOutputCapture(err)

        try:
            rc = mx.run(cmd, nonZeroIsFatal=False, out=out, err=err, cwd=self.build_dir)
        except OSError as e:
            if e.errno != errno.EACCES:
                mx.abort('Error executing \'{}\': {}'.format(' '.join(cmd), str(e)))
            mx.logv('{} is not executable. Trying to change permissions...'.format(self.binary))
            os.chmod(self.binary, 0o755)
            self._run(*args, **kwargs)  # retry
        else:
            not rc or mx.abort(rc if mx.get_opts().verbose else out.data)  # pylint: disable=expression-not-assigned 
Example 10
Project: cutout   Author: jojoin   File: filecache.py    License: MIT License 6 votes vote down vote up
def set(self, key, value, timeout=None):
        if timeout is None:
            timeout = self.default_timeout
        filename = self._get_filename(key)
        self._prune()
        try:
            fd, tmp = tempfile.mkstemp(suffix=self._fs_transaction_suffix,
                                       dir=self._path)
            f = os.fdopen(fd, 'wb')
            try:
                pickle.dump(int(time() + timeout), f, 1)
                pickle.dump(value, f, pickle.HIGHEST_PROTOCOL)
            finally:
                f.close()
            rename(tmp, filename)
            os.chmod(filename, self._mode)
        except (IOError, OSError):
            pass 
Example 11
Project: jawfish   Author: war-and-code   File: shutil.py    License: MIT License 6 votes vote down vote up
def copymode(src, dst, *, follow_symlinks=True):
    """Copy mode bits from src to dst.

    If follow_symlinks is not set, symlinks aren't followed if and only
    if both `src` and `dst` are symlinks.  If `lchmod` isn't available
    (e.g. Linux) this method does nothing.

    """
    if not follow_symlinks and os.path.islink(src) and os.path.islink(dst):
        if hasattr(os, 'lchmod'):
            stat_func, chmod_func = os.lstat, os.lchmod
        else:
            return
    elif hasattr(os, 'chmod'):
        stat_func, chmod_func = os.stat, os.chmod
    else:
        return

    st = stat_func(src)
    chmod_func(dst, stat.S_IMODE(st.st_mode)) 
Example 12
Project: simnibs   Author: simnibs   File: examples.py    License: GNU General Public License v3.0 6 votes vote down vote up
def replace_gmsh():
    fn_gmsh = path2bin('gmsh')
    fn_gmsh_tmp = path2bin('gmsh_tmp')
    # move
    shutil.move(fn_gmsh, fn_gmsh_tmp)
    # replace
    if sys.platform == 'win32':
        fn_script = fn_gmsh[:4] + '.cmd'
        with open(fn_script, 'w') as f:
            f.write('echo "GMSH"')
    else:
        with open(fn_gmsh, 'w') as f:
            f.write('#! /bin/bash -e\n')
            f.write(f'"echo" "$@"')
        os.chmod(
            fn_gmsh,
            os.stat(fn_gmsh).st_mode |
            stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH
        )
    yield
    shutil.move(fn_gmsh_tmp, fn_gmsh) 
Example 13
Project: gphotos-sync   Author: gilesknap   File: test_regression.py    License: MIT License 6 votes vote down vote up
def ___test_folder_not_writeable(self):
        # make sure we get permissions error and not 'database is locked'
        s = ts.SetupDbAndCredentials()
        s.test_setup("test_folder_not_writeable", trash_files=True, trash_db=True)
        try:
            if os.name == "nt":
                os.chmod(str(s.root), stat.S_IREAD)
            else:
                s.root.chmod(0o444)
            with self.assertRaises(PermissionError):
                s.gp.main([str(s.root), "--skip-shared-albums"])
        finally:
            if os.name == "nt":
                os.chmod(str(s.root), stat.S_IWRITE | stat.S_IREAD)
            else:
                os.chmod(str(s.root), 0o777)
            shutil.rmtree(str(s.root)) 
Example 14
Project: unicorn-hat-hd   Author: pimoroni   File: paint.py    License: MIT License 5 votes vote down vote up
def save(filename):
    try:
        os.mkdir('saves/')
    except OSError:
        pass
    try:
        data = unicornhathd.get_pixels()
        data = repr(data)
        data = data.replace('array', 'list')
        print(filename, data)
        file = open('saves/' + filename + '.py', 'w')
        file.write("""#!/usr/bin/env python
import unicornhathd
import signal

unicornhathd.rotation(0)

pixels = {}

for x in range(unicornhathd.WIDTH):
    for y in range(unicornhathd.HEIGHT):
        r, g, b = pixels[x][y]
        unicornhathd.set_pixel(x, y, r, g, b)

unicornhathd.show()

print("\\nShowing: {}\\nPress Ctrl+C to exit!")

signal.pause()
""".format(data, filename))
        file.close()
        os.chmod('saves/' + filename + '.py', 0o777 | stat.S_IEXEC)

        return("ok" + str(unicornhathd.get_pixels()))
    except AttributeError:
        print("Unable to save, please update")
        print("unicornhathdhathd library!")
        return("fail") 
Example 15
Project: jumpserver-python-sdk   Author: jumpserver   File: models.py    License: GNU General Public License v2.0 5 votes vote down vote up
def private_key_file(self):
        if not self.key_dir:
            self.key_dir = '.'

        if not self.private_key:
            return None
        key_name = '.' + md5(self.private_key.encode('utf-8')).hexdigest()
        key_path = os.path.join(self.key_dir, key_name)
        if not os.path.exists(key_path):
            with open(key_path, 'w') as f:
                f.write(self.private_key)
            os.chmod(key_path, 0o400)
        return key_path 
Example 16
Project: godot-mono-builds   Author: godotengine   File: os_utils.py    License: MIT License 5 votes vote down vote up
def chmod_plus_x(file):
    import os
    import stat
    umask = os.umask(0)
    os.umask(umask)
    st = os.stat(file)
    os.chmod(file, st.st_mode | ((stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH) & ~umask)) 
Example 17
Project: ALF   Author: blackberry   File: __init__.py    License: Apache License 2.0 5 votes vote down vote up
def rm_full_dir(path, ignore_errors=False):
    """
    This function is used to remove a directory and all files and
    directories within it (like `rm -rf`).
    """
    if os.path.isdir(path):
        try:
            os.chmod(path, os.stat(path).st_mode | stat.S_IRWXU
                                                 & ~stat.S_ISVTX)
        except OSError:
            pass
        f_last = 0
        while True:
            f_count = 0
            for root, d_names, f_names in os.walk(path):
                try:
                    os.chmod(root, os.stat(root).st_mode | stat.S_IRWXU
                                                         & ~stat.S_ISVTX)
                except OSError:
                    pass
                for fs_name in f_names + d_names:
                    target = os.path.join(root, fs_name)
                    try:
                        os.chmod(target, os.stat(target).st_mode
                                              | stat.S_IRWXU
                                              & ~stat.S_ISVTX)
                    except OSError:
                        pass
                    f_count += 1
                f_count += 1
            # do this until we get the same count twice, ie. all files we can
            # chmod our way into have been found
            if f_last == f_count:
                break
            f_last = f_count
        shutil.rmtree(path, ignore_errors) 
Example 18
Project: ALF   Author: blackberry   File: Radamsa.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self):
        if sys.platform.startswith("linux"):
            self.bin = os.path.join(TOOL_DIR, "radamsa-linux")
            if os.path.isfile(self.bin):
                os.chmod(self.bin, os.stat(self.bin).st_mode | stat.S_IXUSR)
            else:
                raise RuntimeError("Missing file %s" % self.bin)
        elif sys.platform.startswith("win32"):
            self.bin = os.path.join(TOOL_DIR, "radamsa-windows.exe")
            if not os.path.isfile(self.bin):
                raise RuntimeError("Missing file %s" % self.bin)
        else:
            raise RuntimeError("RadamsaFuzzer not supported on this platform")
        self.sys_rnd = random.SystemRandom() 
Example 19
Project: hubic-wrapper-to-swift   Author: puzzle1536   File: hubic.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __del__(self):
        if self.config_file:
            if options.verbose:
                print "-- Write config file back : %s " % self.config_file
            self.hubic_config = ConfigParser.RawConfigParser()

            self.hubic_config.add_section('hubic')
            if self.client_id:
                self.hubic_config.set('hubic', 'client_id', self.client_id)
            if self.client_secret:
                self.hubic_config.set('hubic', 'client_secret', self.client_secret)
            if self.redirect_uri:
                self.hubic_config.set('hubic', 'redirect_uri', self.redirect_uri)
            if self.username:
                self.hubic_config.set('hubic', 'username', self.username)
            if self.password:
                self.hubic_config.set('hubic', 'password', self.password)
            if self.refresh_token:
                self.hubic_config.set('hubic', 'refresh_token', self.refresh_token)
            if self.access_token:
                self.hubic_config.set('hubic', 'access_token', self.access_token)
            if self.token_expire:
                self.hubic_config.set('hubic', 'token_expire', self.token_expire)

            self.hubic_config.add_section('openstack')
            if self.os_auth_token:
                self.hubic_config.set('openstack', 'os_auth_token', self.os_auth_token)
            if self.os_storage_url:
                self.hubic_config.set('openstack', 'os_storage_url', self.os_storage_url)
            if self.os_token_expire:
                self.hubic_config.set('openstack', 'os_token_expire', self.os_token_expire)

            with open(self.config_file, 'wb') as configfile:
                self.hubic_config.write(configfile)
            os.chmod(self.config_file, 0600) 
Example 20
Project: python_labview_automation   Author: ni   File: labview.py    License: MIT License 5 votes vote down vote up
def make_writable(directory):
        os.chmod(directory, stat.S_IWUSR & stat.S_IWOTH) 
Example 21
Project: sqliv   Author: the-robot   File: setup.py    License: GNU General Public License v3.0 5 votes vote down vote up
def install(file_path, exec_path):
    """full installation of SQLiv to the system"""

    os.mkdir(file_path)
    copy2("sqliv.py", file_path)
    copy2("requirements.txt", file_path)
    copy2("LICENSE", file_path)
    copy2("README.md", file_path)

    os.mkdir(file_path + "/src")
    copy_tree("src", file_path + "/src")

    os.mkdir(file_path + "/lib")
    copy_tree("lib", file_path + "/lib")

    # python dependencies with pip
    dependencies("install")

    # add executable
    with open(exec_path, 'w') as installer:
        installer.write('#!/bin/bash\n')
        installer.write('\n')
        installer.write('python2 {}/sqliv.py "$@"\n'.format(file_path))

    # S_IRWXU = rwx for owner
    # S_IRGRP | S_IXGRP = rx for group
    # S_IROTH | S_IXOTH = rx for other
    os.chmod(exec_path, stat.S_IRWXU | stat.S_IRGRP | stat.S_IXGRP | stat.S_IROTH | stat.S_IXOTH) 
Example 22
Project: arxiv-collector   Author: djsutherland   File: arxiv_collector.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_latexmk(version="ctan", dest="latexmk", verbose=True):
    try:
        from urllib.request import urlopen
    except ImportError:
        from urllib2 import urlopen as _urlopen
        from contextlib import closing

        def urlopen(*args, **kwargs):
            return closing(_urlopen(*args, **kwargs))

    import shutil
    import zipfile

    if version.lower() == "ctan":
        url = "http://mirrors.ctan.org/support/latexmk.zip"
    else:
        v = version.replace(".", "")
        url = "http://personal.psu.edu/jcc8/software/latexmk-jcc/latexmk-{}.zip".format(v)

    with io.BytesIO() as bio:
        if verbose:
            print("Downloading latexmk {}...".format(version), file=sys.stderr, end="")
        with urlopen(url) as web:
            shutil.copyfileobj(web, bio, length=131072)

        with zipfile.ZipFile(bio) as z:
            for zinfo in z.infolist():
                if os.path.basename(zinfo.filename) == "latexmk.pl":
                    with z.open(zinfo) as script, io.open(dest, "wb") as out:
                        shutil.copyfileobj(script, out)

                    # executable: https://stackoverflow.com/a/30463972/344821
                    mode = os.stat(dest).st_mode
                    mode |= (mode & 0o444) >> 2  # copy R bits to X
                    os.chmod(dest, mode)
                    break
            else:
                raise ValueError("Couldn't find latexmk.pl in {}".format(url))

        if verbose:
            print("saved to `{}`.".format(dest), file=sys.stderr) 
Example 23
Project: macops   Author: google   File: can_haz_image.py    License: Apache License 2.0 5 votes vote down vote up
def WriteImageInfo(self, mounted_sparsebundle, package_report):
    """Writes information about the image to a plist file in the image."""
    imageinfo = ('%s/etc/imageinfo.plist' % mounted_sparsebundle)

    cmd = ['defaults', 'write', imageinfo, 'ImageVersion',
           '-string', self.image_creation_time]
    (unused_stdout, stderr, rc) = RunProcess(cmd)
    if rc:
      print 'Failed to write ImageVersion: %s' % stderr

    cmd = ['defaults', 'write', imageinfo, 'ImageMethod',
           '-string', 'can_haz_image']
    (unused_stdout, stderr, rc) = RunProcess(cmd)
    if rc:
      print 'Failed to write ImageMethod: %s' % stderr

    for package in package_report:
      cmd = ['defaults', 'write', imageinfo, 'ImagePackages',
             '-array-add', package]
      (unused_stdout, stderr, rc) = RunProcess(cmd)
      if rc:
        print 'Failed to write ImagePackages: %s' % stderr

    # chmod to 0644, chown to root:wheel
    os.chmod(imageinfo, 0644)
    os.chown(imageinfo, 0, 0) 
Example 24
Project: pgrepup   Author: rtshome   File: database.py    License: GNU General Public License v3.0 5 votes vote down vote up
def create_pgpass_file():
    fname = "%s/pgpass_repup" % get_tmp_folder()
    pgpass = open(fname, 'w')
    pgpass.writelines((
        # File format for pgpass: https://www.postgresql.org/docs/9.5/static/libpq-pgpass.html
        # hostname:port:database:username:password
        "%(host)s:%(port)s:*:%(user)s:%(password)s\n" % get_connection_params('Source'),
        "%(host)s:%(port)s:*:%(user)s:%(password)s\n" % get_connection_params('Destination')
    ))
    pgpass.close()
    os.chmod(fname, 0o600)
    return fname 
Example 25
Project: pgrepup   Author: rtshome   File: config.py    License: GNU General Public License v3.0 5 votes vote down vote up
def save(filename=None, print_save_result=True):
    if filename is None and this.filename is None:
        raise ConfigFileNotFound("Missing config file to write to")

    if filename is None:
        filename = this.filename

    cfg_file = open(filename, 'w')
    this.config.write(cfg_file)
    cfg_file.close()
    os.chmod(filename, 0o600)

    if print_save_result:
        print("Configuration saved to %s." % filename)
        print("You can now use the check command to verify setup of source and destination databases") 
Example 26
Project: delocate   Author: matthew-brett   File: fuse.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _copyfile(in_fname, out_fname):
    # Copies files without read / write permission
    perms = chmod_perms(in_fname)
    with open_rw(in_fname, 'rb') as fobj:
        contents = fobj.read()
    with open_rw(out_fname, 'wb') as fobj:
        fobj.write(contents)
    os.chmod(out_fname, perms) 
Example 27
Project: delocate   Author: matthew-brett   File: tools.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def chmod_perms(fname):
    # Permissions relevant to chmod
    return stat.S_IMODE(os.stat(fname).st_mode) 
Example 28
Project: delocate   Author: matthew-brett   File: test_delocating.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _make_libtree(out_path):
    liba, libb, libc, test_lib = _copy_libs(
        [LIBA, LIBB, LIBC, TEST_LIB], out_path)
    sub_path = pjoin(out_path, 'subsub')
    slibc, stest_lib = _copy_libs([libc, test_lib], sub_path)
    # Set execute permissions
    for exe in (test_lib, stest_lib):
        os.chmod(exe, 0o744)
    # Check test-lib doesn't work because of relative library paths
    assert_raises(RuntimeError, back_tick, [test_lib])
    assert_raises(RuntimeError, back_tick, [stest_lib])
    # Fixup the relative path library names by setting absolute paths
    for fname, using, path in (
        (libb, 'liba.dylib', out_path),
        (libc, 'liba.dylib', out_path),
        (libc, 'libb.dylib', out_path),
        (test_lib, 'libc.dylib', out_path),
        (slibc, 'liba.dylib', out_path),
        (slibc, 'libb.dylib', out_path),
        (stest_lib, 'libc.dylib', sub_path),
                        ):
        set_install_name(fname, using, pjoin(path, using))
    # Check scripts now execute correctly
    back_tick([test_lib])
    back_tick([stest_lib])
    return liba, libb, libc, test_lib, slibc, stest_lib 
Example 29
Project: delocate   Author: matthew-brett   File: test_install_names.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_get_install_names():
    # Test install name listing
    assert_equal(set(get_install_names(LIBA)),
                 set(EXT_LIBS))
    assert_equal(set(get_install_names(LIBB)),
                 set(('liba.dylib',) + EXT_LIBS))
    assert_equal(set(get_install_names(LIBC)),
                 set(('liba.dylib', 'libb.dylib') + EXT_LIBS))
    assert_equal(set(get_install_names(TEST_LIB)),
                 set(('libc.dylib',) + EXT_LIBS))
    # Non-object file returns empty tuple
    assert_equal(get_install_names(__file__), ())
    # Static archive and object files returns empty tuple
    assert_equal(get_install_names(A_OBJECT), ())
    assert_equal(get_install_names(LIBA_STATIC), ())
    # ico file triggers another error message and should also return an empty tuple  # noqa: E501
    assert_equal(get_install_names(ICO_FILE), ())
    # Python file (__file__ above may be a pyc file)
    assert_equal(get_install_names(PY_FILE), ())
    # Binary file (in fact a truncated SAS file)
    assert_equal(get_install_names(BIN_FILE), ())
    # Test when no read permission
    with InTemporaryDirectory():
        shutil.copyfile(LIBA, 'test.dylib')
        assert_equal(set(get_install_names('test.dylib')),
                     set(EXT_LIBS))
        # No permissions, no found libs
        os.chmod('test.dylib', 0)
        assert_equal(get_install_names('test.dylib'), ()) 
Example 30
Project: delocate   Author: matthew-brett   File: test_tools.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_zip2():
    # Test utilities to unzip and zip up
    with InTemporaryDirectory():
        os.mkdir('a_dir')
        os.mkdir('zips')
        _write_file(pjoin('a_dir', 'file1.txt'), 'File one')
        s_dir = pjoin('a_dir', 's_dir')
        os.mkdir(s_dir)
        _write_file(pjoin(s_dir, 'file2.txt'), 'File two')
        zip_fname = pjoin('zips', 'my.zip')
        dir2zip('a_dir', zip_fname)
        zip2dir(zip_fname, 'another_dir')
        assert_equal(os.listdir('another_dir'), ['file1.txt', 's_dir'])
        assert_equal(os.listdir(pjoin('another_dir', 's_dir')), ['file2.txt'])
        # Try zipping from a subdirectory, with a different extension
        dir2zip(s_dir, 'another.ext')
        # Remove original tree just to be sure
        shutil.rmtree('a_dir')
        zip2dir('another.ext', 'third_dir')
        assert_equal(os.listdir('third_dir'), ['file2.txt'])
        # Check permissions kept in zip unzip cycle
        os.mkdir('a_dir')
        permissions = stat.S_IRUSR | stat.S_IWGRP | stat.S_IXGRP
        fname = pjoin('a_dir', 'permitted_file')
        _write_file(fname, 'Some script or something')
        os.chmod(fname, permissions)
        dir2zip('a_dir', 'test.zip')
        zip2dir('test.zip', 'another_dir')
        out_fname = pjoin('another_dir', 'permitted_file')
        assert_equal(os.stat(out_fname).st_mode & 0o777, permissions)