Python os.chdir() Examples

The following are code examples for showing how to use os.chdir(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: leapp-repository   Author: oamg   File: conftest.py    Apache License 2.0 6 votes vote down vote up
def pytest_sessionstart(session):

    actor_path = os.environ.get('LEAPP_TESTED_ACTOR', None)
    library_path = os.environ.get('LEAPP_TESTED_LIBRARY', None)

    if actor_path:
        repo = load_repo(actor_path)

        actor = None
        # find which actor is being tested
        for a in repo.actors:
            if a.full_path == actor_path.rstrip('/'):
                actor = a
                break

        if not actor:
            return

        # load actor context so libraries can be imported on module level
        session.leapp_repository = repo
        session.actor_context = actor.injected_context()
        session.actor_context.__enter__()
    elif library_path:
        load_repo(library_path)
        os.chdir(library_path) 
Example 2
Project: pyblish-win   Author: pyblish   File: test_archive_util.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_tarfile_root_owner(self):
        tmpdir, tmpdir2, base_name =  self._create_files()
        old_dir = os.getcwd()
        os.chdir(tmpdir)
        group = grp.getgrgid(0)[0]
        owner = pwd.getpwuid(0)[0]
        try:
            archive_name = make_tarball(base_name, 'dist', compress=None,
                                        owner=owner, group=group)
        finally:
            os.chdir(old_dir)

        # check if the compressed tarball was created
        self.assertTrue(os.path.exists(archive_name))

        # now checks the rights
        archive = tarfile.open(archive_name)
        try:
            for member in archive.getmembers():
                self.assertEqual(member.uid, 0)
                self.assertEqual(member.gid, 0)
        finally:
            archive.close() 
Example 3
Project: pyblish-win   Author: pyblish   File: test_install.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_record(self):
        install_dir = self.mkdtemp()
        project_dir, dist = self.create_dist(py_modules=['hello'],
                                             scripts=['sayhi'])
        os.chdir(project_dir)
        self.write_file('hello.py', "def main(): print 'o hai'")
        self.write_file('sayhi', 'from hello import main; main()')

        cmd = install(dist)
        dist.command_obj['install'] = cmd
        cmd.root = install_dir
        cmd.record = os.path.join(project_dir, 'filelist')
        cmd.ensure_finalized()
        cmd.run()

        f = open(cmd.record)
        try:
            content = f.read()
        finally:
            f.close()

        found = [os.path.basename(line) for line in content.splitlines()]
        expected = ['hello.py', 'hello.pyc', 'sayhi',
                    'UNKNOWN-0.0.0-py%s.%s.egg-info' % sys.version_info[:2]]
        self.assertEqual(found, expected) 
Example 4
Project: pyblish-win   Author: pyblish   File: test_posixpath.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_realpath_deep_recursion(self):
            depth = 10
            old_path = abspath('.')
            try:
                os.mkdir(ABSTFN)
                for i in range(depth):
                    os.symlink('/'.join(['%d' % i] * 10), ABSTFN + '/%d' % (i + 1))
                os.symlink('.', ABSTFN + '/0')
                self.assertEqual(realpath(ABSTFN + '/%d' % depth), ABSTFN)

                # Test using relative path as well.
                os.chdir(ABSTFN)
                self.assertEqual(realpath('%d' % depth), ABSTFN)
            finally:
                os.chdir(old_path)
                for i in range(depth + 1):
                    test_support.unlink(ABSTFN + '/%d' % i)
                safe_rmdir(ABSTFN) 
Example 5
Project: pyblish-win   Author: pyblish   File: test_posixpath.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_realpath_resolve_parents(self):
            # We also need to resolve any symlinks in the parents of a relative
            # path passed to realpath. E.g.: current working directory is
            # /usr/doc with 'doc' being a symlink to /usr/share/doc. We call
            # realpath("a"). This should return /usr/share/doc/a/.
            try:
                old_path = abspath('.')
                os.mkdir(ABSTFN)
                os.mkdir(ABSTFN + "/y")
                os.symlink(ABSTFN + "/y", ABSTFN + "/k")

                os.chdir(ABSTFN + "/k")
                self.assertEqual(realpath("a"), ABSTFN + "/y/a")
            finally:
                os.chdir(old_path)
                test_support.unlink(ABSTFN + "/k")
                safe_rmdir(ABSTFN + "/y")
                safe_rmdir(ABSTFN) 
Example 6
Project: pyblish-win   Author: pyblish   File: test_posixpath.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_realpath_resolve_first(self):
            # Bug #1213894: The first component of the path, if not absolute,
            # must be resolved too.

            try:
                old_path = abspath('.')
                os.mkdir(ABSTFN)
                os.mkdir(ABSTFN + "/k")
                os.symlink(ABSTFN, ABSTFN + "link")
                os.chdir(dirname(ABSTFN))

                base = basename(ABSTFN)
                self.assertEqual(realpath(base + "link"), ABSTFN)
                self.assertEqual(realpath(base + "link/k"), ABSTFN + "/k")
            finally:
                os.chdir(old_path)
                test_support.unlink(ABSTFN + "link")
                safe_rmdir(ABSTFN + "/k")
                safe_rmdir(ABSTFN) 
Example 7
Project: pyblish-win   Author: pyblish   File: test_subprocess.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_cwd(self):
        tmpdir = tempfile.gettempdir()
        # We cannot use os.path.realpath to canonicalize the path,
        # since it doesn't expand Tru64 {memb} strings. See bug 1063571.
        cwd = os.getcwd()
        os.chdir(tmpdir)
        tmpdir = os.getcwd()
        os.chdir(cwd)
        p = subprocess.Popen([sys.executable, "-c",
                          'import sys,os;'
                          'sys.stdout.write(os.getcwd())'],
                         stdout=subprocess.PIPE,
                         cwd=tmpdir)
        self.addCleanup(p.stdout.close)
        normcase = os.path.normcase
        self.assertEqual(normcase(p.stdout.read()), normcase(tmpdir)) 
Example 8
Project: pyblish-win   Author: pyblish   File: test_shutil.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_tarfile_root_owner(self):
        tmpdir, tmpdir2, base_name =  self._create_files()
        old_dir = os.getcwd()
        os.chdir(tmpdir)
        group = grp.getgrgid(0)[0]
        owner = pwd.getpwuid(0)[0]
        try:
            archive_name = _make_tarball(base_name, 'dist', compress=None,
                                         owner=owner, group=group)
        finally:
            os.chdir(old_dir)

        # check if the compressed tarball was created
        self.assertTrue(os.path.exists(archive_name))

        # now checks the rights
        archive = tarfile.open(archive_name)
        try:
            for member in archive.getmembers():
                self.assertEqual(member.uid, 0)
                self.assertEqual(member.gid, 0)
        finally:
            archive.close() 
Example 9
Project: pyblish-win   Author: pyblish   File: test_pep277.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_normalize(self):
        files = set(f for f in self.files if isinstance(f, unicode))
        others = set()
        for nf in set(['NFC', 'NFD', 'NFKC', 'NFKD']):
            others |= set(normalize(nf, file) for file in files)
        others -= files
        for name in others:
            self._apply_failure(open, name, IOError)
            self._apply_failure(os.stat, name, OSError)
            self._apply_failure(os.chdir, name, OSError)
            self._apply_failure(os.rmdir, name, OSError)
            self._apply_failure(os.remove, name, OSError)
            # listdir may append a wildcard to the filename, so dont check
            self._apply_failure(os.listdir, name, OSError, False)

    # Skip the test on darwin, because darwin uses a normalization different
    # than Python NFD normalization: filenames are different even if we use
    # Python NFD normalization. 
Example 10
Project: ieml   Author: IEMLdev   File: word_to_latex.py    GNU General Public License v3.0 6 votes vote down vote up
def compile_latex(latex_str):
    old_cwd = os.getcwd()

    with tempfile.TemporaryDirectory() as tempdir:
        path = os.path.join(tempdir, 'output')

        logger.error(path)
        doc = Document(path, data=[dumps_list([latex_str], escape=False)], geometry_options='landscape')

        doc.packages.append(Package('xcolor', ['dvipsnames','table']))
        try:
            doc.generate_pdf(clean_tex=False, silent=False)
            doc.generate_tex()
        except subprocess.CalledProcessError as e:
            os.chdir(old_cwd)  # because pylatex change it but doesnt restore it
            raise e

        with open(path + '.pdf', 'rb') as fp:
            return fp.read() 
Example 11
Project: pydockenv   Author: se7entyse7en   File: test_port_mapper.py    Apache License 2.0 6 votes vote down vote up
def test_port_mapping_single_port(self):
        env_name = self._env_name()
        proj_name, py_version = 'test-proj', '3.7'

        proj_dir = self._create_project_dir(proj_name)
        self._commander.run(
            f'create --name={env_name} --version={py_version} {str(proj_dir)}')
        with self._commander.active_env(env_name) as env:
            os.chdir(proj_dir)

            port = 8000
            out = self._commander.run(
                f'run -d -p {port} -- python -m http.server {port}', env=env)
            self.assertCommandOk(out)
            self.assertPortMapperExists(env_name, port)

            s = requests.Session()
            s.mount('http://', HTTPAdapter(
                max_retries=Retry(connect=3, backoff_factor=1)))
            r = s.get(f'http://localhost:{port}')

            self.assertEqual(r.status_code, 200, msg=r.content) 
Example 12
Project: pydockenv   Author: se7entyse7en   File: test_port_mapper.py    Apache License 2.0 6 votes vote down vote up
def test_port_mapping_multi_ports(self):
        env_name = self._env_name()
        proj_name, py_version = 'test-proj', '3.7'

        proj_dir = self._create_project_dir(proj_name)
        self._commander.run(
            f'create --name={env_name} --version={py_version} {str(proj_dir)}')
        with self._commander.active_env(env_name) as env:
            os.chdir(proj_dir)

            for port in range(8000, 8003):
                out = self._commander.run(
                    f'run -d -p {port} -- python -m http.server {port}',
                    env=env
                )
                self.assertCommandOk(out)
                self.assertPortMapperExists(env_name, port)

                s = requests.Session()
                s.mount('http://', HTTPAdapter(
                    max_retries=Retry(connect=3, backoff_factor=1)))
                r = s.get(f'http://localhost:{port}')

                self.assertEqual(r.status_code, 200, msg=r.content) 
Example 13
Project: pydockenv   Author: se7entyse7en   File: base.py    Apache License 2.0 6 votes vote down vote up
def tearDown(self):
        os.chdir(self._cwd)
        try:
            for i in range(1, self._env_index):
                env_name = self._create_env_name(i)
                try:
                    Client.get_instance().containers.get(
                        definitions.CONTAINERS_PREFIX + env_name).remove(
                            force=True)
                    delete_network(env_name)
                except docker.errors.NotFound:
                    pass

                self._remove_port_mappers(env_name)
        finally:
            shutil.rmtree(self._test_dir.name) 
Example 14
Project: 2015-SpaceInvaders-Bot-Python   Author: EntelectChallenge   File: ez_setup.py    MIT License 6 votes vote down vote up
def archive_context(filename):
    """
    Unzip filename to a temporary directory, set to the cwd.

    The unzipped target is cleaned up after.
    """
    tmpdir = tempfile.mkdtemp()
    log.warn('Extracting in %s', tmpdir)
    old_wd = os.getcwd()
    try:
        os.chdir(tmpdir)
        with ContextualZipFile(filename) as archive:
            archive.extractall()

        # going in the directory
        subdir = os.path.join(tmpdir, os.listdir(tmpdir)[0])
        os.chdir(subdir)
        log.warn('Now working in %s', subdir)
        yield

    finally:
        os.chdir(old_wd)
        shutil.rmtree(tmpdir) 
Example 15
Project: ubittool   Author: carlosperate   File: make.py    MIT License 5 votes vote down vote up
def _set_cwd():
    """Set cwd to the path necessary for these commands to work correctly.

    All commands depend on this file folder being the current working
    directory.
    """
    os.chdir(_this_file_dir()) 
Example 16
Project: pyblish-win   Author: pyblish   File: setuptools_build_ext.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def write_stub(self, output_dir, ext, compile=False):
        log.info("writing stub loader for %s to %s",ext._full_name, output_dir)
        stub_file = os.path.join(output_dir, *ext._full_name.split('.'))+'.py'
        if compile and os.path.exists(stub_file):
            raise DistutilsError(stub_file+" already exists! Please delete.")
        if not self.dry_run:
            f = open(stub_file,'w')
            f.write('\n'.join([
                "def __bootstrap__():",
                "   global __bootstrap__, __file__, __loader__",
                "   import sys, os, pkg_resources, imp"+if_dl(", dl"),
                "   __file__ = pkg_resources.resource_filename(__name__,%r)"
                   % os.path.basename(ext._file_name),
                "   del __bootstrap__",
                "   if '__loader__' in globals():",
                "       del __loader__",
                if_dl("   old_flags = sys.getdlopenflags()"),
                "   old_dir = os.getcwd()",
                "   try:",
                "     os.chdir(os.path.dirname(__file__))",
                if_dl("     sys.setdlopenflags(dl.RTLD_NOW)"),
                "     imp.load_dynamic(__name__,__file__)",
                "   finally:",
                if_dl("     sys.setdlopenflags(old_flags)"),
                "     os.chdir(old_dir)",
                "__bootstrap__()",
                "" # terminal \n
            ]))
            f.close()
        if compile:
            from distutils.util import byte_compile
            byte_compile([stub_file], optimize=0,
                         force=True, dry_run=self.dry_run)
            optimize = self.get_finalized_command('install_lib').optimize
            if optimize > 0:
                byte_compile([stub_file], optimize=optimize,
                             force=True, dry_run=self.dry_run)
            if os.path.exists(stub_file) and not self.dry_run:
                os.unlink(stub_file) 
Example 17
Project: pyblish-win   Author: pyblish   File: test_sdist.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def setUp(self):
        # PyPIRCCommandTestCase creates a temp dir already
        # and put it in self.tmp_dir
        super(SDistTestCase, self).setUp()
        # setting up an environment
        self.old_path = os.getcwd()
        os.mkdir(join(self.tmp_dir, 'somecode'))
        os.mkdir(join(self.tmp_dir, 'dist'))
        # a package, and a README
        self.write_file((self.tmp_dir, 'README'), 'xxx')
        self.write_file((self.tmp_dir, 'somecode', '__init__.py'), '#')
        self.write_file((self.tmp_dir, 'setup.py'), SETUP_PY)
        os.chdir(self.tmp_dir) 
Example 18
Project: pyblish-win   Author: pyblish   File: test_sdist.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def tearDown(self):
        # back to normal
        os.chdir(self.old_path)
        super(SDistTestCase, self).tearDown() 
Example 19
Project: pyblish-win   Author: pyblish   File: test_archive_util.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def _make_tarball(self, target_name):
        # creating something to tar
        tmpdir = self.mkdtemp()
        self.write_file([tmpdir, 'file1'], 'xxx')
        self.write_file([tmpdir, 'file2'], 'xxx')
        os.mkdir(os.path.join(tmpdir, 'sub'))
        self.write_file([tmpdir, 'sub', 'file3'], 'xxx')

        tmpdir2 = self.mkdtemp()
        unittest.skipUnless(splitdrive(tmpdir)[0] == splitdrive(tmpdir2)[0],
                            "source and target should be on same drive")

        base_name = os.path.join(tmpdir2, target_name)

        # working with relative paths to avoid tar warnings
        old_dir = os.getcwd()
        os.chdir(tmpdir)
        try:
            make_tarball(splitdrive(base_name)[1], '.')
        finally:
            os.chdir(old_dir)

        # check if the compressed tarball was created
        tarball = base_name + '.tar.gz'
        self.assertTrue(os.path.exists(tarball))

        # trying an uncompressed one
        base_name = os.path.join(tmpdir2, target_name)
        old_dir = os.getcwd()
        os.chdir(tmpdir)
        try:
            make_tarball(splitdrive(base_name)[1], '.', compress=None)
        finally:
            os.chdir(old_dir)
        tarball = base_name + '.tar'
        self.assertTrue(os.path.exists(tarball)) 
Example 20
Project: pyblish-win   Author: pyblish   File: test_archive_util.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_compress_deprecated(self):
        tmpdir, tmpdir2, base_name =  self._create_files()

        # using compress and testing the PendingDeprecationWarning
        old_dir = os.getcwd()
        os.chdir(tmpdir)
        try:
            with check_warnings() as w:
                warnings.simplefilter("always")
                make_tarball(base_name, 'dist', compress='compress')
        finally:
            os.chdir(old_dir)
        tarball = base_name + '.tar.Z'
        self.assertTrue(os.path.exists(tarball))
        self.assertEqual(len(w.warnings), 1)

        # same test with dry_run
        os.remove(tarball)
        old_dir = os.getcwd()
        os.chdir(tmpdir)
        try:
            with check_warnings() as w:
                warnings.simplefilter("always")
                make_tarball(base_name, 'dist', compress='compress',
                             dry_run=True)
        finally:
            os.chdir(old_dir)
        self.assertFalse(os.path.exists(tarball))
        self.assertEqual(len(w.warnings), 1) 
Example 21
Project: pyblish-win   Author: pyblish   File: support.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def tearDown(self):
        # Restore working dir, for Solaris and derivatives, where rmdir()
        # on the current directory fails.
        os.chdir(self.old_cwd)
        super(TempdirManager, self).tearDown()
        while self.tempdirs:
            d = self.tempdirs.pop()
            shutil.rmtree(d, os.name in ('nt', 'cygwin')) 
Example 22
Project: pyblish-win   Author: pyblish   File: test_build_py.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_empty_package_dir(self):
        # See SF 1668596/1720897.
        cwd = os.getcwd()

        # create the distribution files.
        sources = self.mkdtemp()
        open(os.path.join(sources, "__init__.py"), "w").close()

        testdir = os.path.join(sources, "doc")
        os.mkdir(testdir)
        open(os.path.join(testdir, "testfile"), "w").close()

        os.chdir(sources)
        old_stdout = sys.stdout
        sys.stdout = StringIO.StringIO()

        try:
            dist = Distribution({"packages": ["pkg"],
                                 "package_dir": {"pkg": ""},
                                 "package_data": {"pkg": ["doc/*"]}})
            # script_name need not exist, it just need to be initialized
            dist.script_name = os.path.join(sources, "setup.py")
            dist.script_args = ["build"]
            dist.parse_command_line()

            try:
                dist.run_commands()
            except DistutilsFileError:
                self.fail("failed package_data test when package_dir is ''")
        finally:
            # Restore state.
            os.chdir(cwd)
            sys.stdout = old_stdout 
Example 23
Project: pyblish-win   Author: pyblish   File: test_build_py.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_dir_in_package_data(self):
        """
        A directory in package_data should not be added to the filelist.
        """
        # See bug 19286
        sources = self.mkdtemp()
        pkg_dir = os.path.join(sources, "pkg")

        os.mkdir(pkg_dir)
        open(os.path.join(pkg_dir, "__init__.py"), "w").close()

        docdir = os.path.join(pkg_dir, "doc")
        os.mkdir(docdir)
        open(os.path.join(docdir, "testfile"), "w").close()

        # create the directory that could be incorrectly detected as a file
        os.mkdir(os.path.join(docdir, 'otherdir'))

        os.chdir(sources)
        dist = Distribution({"packages": ["pkg"],
                             "package_data": {"pkg": ["doc/*"]}})
        # script_name need not exist, it just need to be initialized
        dist.script_name = os.path.join(sources, "setup.py")
        dist.script_args = ["build"]
        dist.parse_command_line()

        try:
            dist.run_commands()
        except DistutilsFileError:
            self.fail("failed package_data when data dir includes a dir") 
Example 24
Project: pyblish-win   Author: pyblish   File: test_bdist_rpm.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def tearDown(self):
        os.chdir(self.old_location)
        sys.argv = self.old_sys_argv[0]
        sys.argv[:] = self.old_sys_argv[1]
        super(BuildRpmTestCase, self).tearDown()

    # XXX I am unable yet to make this test work without
    # spurious sdtout/stderr output under Mac OS X 
Example 25
Project: pyblish-win   Author: pyblish   File: test_bdist_rpm.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_quiet(self):
        # let's create a package
        tmp_dir = self.mkdtemp()
        os.environ['HOME'] = tmp_dir   # to confine dir '.rpmdb' creation
        pkg_dir = os.path.join(tmp_dir, 'foo')
        os.mkdir(pkg_dir)
        self.write_file((pkg_dir, 'setup.py'), SETUP_PY)
        self.write_file((pkg_dir, 'foo.py'), '#')
        self.write_file((pkg_dir, 'MANIFEST.in'), 'include foo.py')
        self.write_file((pkg_dir, 'README'), '')

        dist = Distribution({'name': 'foo', 'version': '0.1',
                             'py_modules': ['foo'],
                             'url': 'xxx', 'author': 'xxx',
                             'author_email': 'xxx'})
        dist.script_name = 'setup.py'
        os.chdir(pkg_dir)

        sys.argv = ['setup.py']
        cmd = bdist_rpm(dist)
        cmd.fix_python = True

        # running in quiet mode
        cmd.quiet = 1
        cmd.ensure_finalized()
        cmd.run()

        dist_created = os.listdir(os.path.join(pkg_dir, 'dist'))
        self.assertIn('foo-0.1-1.noarch.rpm', dist_created)

        # bug #2945: upload ignores bdist_rpm files
        self.assertIn(('bdist_rpm', 'any', 'dist/foo-0.1-1.src.rpm'), dist.dist_files)
        self.assertIn(('bdist_rpm', 'any', 'dist/foo-0.1-1.noarch.rpm'), dist.dist_files)

    # XXX I am unable yet to make this test work without
    # spurious sdtout/stderr output under Mac OS X 
Example 26
Project: pyblish-win   Author: pyblish   File: test_bdist_rpm.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_no_optimize_flag(self):
        # let's create a package that brakes bdist_rpm
        tmp_dir = self.mkdtemp()
        os.environ['HOME'] = tmp_dir   # to confine dir '.rpmdb' creation
        pkg_dir = os.path.join(tmp_dir, 'foo')
        os.mkdir(pkg_dir)
        self.write_file((pkg_dir, 'setup.py'), SETUP_PY)
        self.write_file((pkg_dir, 'foo.py'), '#')
        self.write_file((pkg_dir, 'MANIFEST.in'), 'include foo.py')
        self.write_file((pkg_dir, 'README'), '')

        dist = Distribution({'name': 'foo', 'version': '0.1',
                             'py_modules': ['foo'],
                             'url': 'xxx', 'author': 'xxx',
                             'author_email': 'xxx'})
        dist.script_name = 'setup.py'
        os.chdir(pkg_dir)

        sys.argv = ['setup.py']
        cmd = bdist_rpm(dist)
        cmd.fix_python = True

        cmd.quiet = 1
        cmd.ensure_finalized()
        cmd.run()

        dist_created = os.listdir(os.path.join(pkg_dir, 'dist'))
        self.assertIn('foo-0.1-1.noarch.rpm', dist_created)

        # bug #2945: upload ignores bdist_rpm files
        self.assertIn(('bdist_rpm', 'any', 'dist/foo-0.1-1.src.rpm'), dist.dist_files)
        self.assertIn(('bdist_rpm', 'any', 'dist/foo-0.1-1.noarch.rpm'), dist.dist_files)

        os.remove(os.path.join(pkg_dir, 'dist', 'foo-0.1-1.noarch.rpm')) 
Example 27
Project: pyblish-win   Author: pyblish   File: test_bdist_dumb.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_finalize_options(self):
        pkg_dir, dist = self.create_dist()
        os.chdir(pkg_dir)
        cmd = bdist_dumb(dist)
        self.assertEqual(cmd.bdist_dir, None)
        cmd.finalize_options()

        # bdist_dir is initialized to bdist_base/dumb if not set
        base = cmd.get_finalized_command('bdist').bdist_base
        self.assertEqual(cmd.bdist_dir, os.path.join(base, 'dumb'))

        # the format is set to a default value depending on the os.name
        default = cmd.default_format[os.name]
        self.assertEqual(cmd.format, default) 
Example 28
Project: pyblish-win   Author: pyblish   File: test_install.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_record_extensions(self):
        install_dir = self.mkdtemp()
        project_dir, dist = self.create_dist(ext_modules=[
            Extension('xx', ['xxmodule.c'])])
        os.chdir(project_dir)
        support.copy_xxmodule_c(project_dir)

        buildextcmd = build_ext(dist)
        support.fixup_build_ext(buildextcmd)
        buildextcmd.ensure_finalized()

        cmd = install(dist)
        dist.command_obj['install'] = cmd
        dist.command_obj['build_ext'] = buildextcmd
        cmd.root = install_dir
        cmd.record = os.path.join(project_dir, 'filelist')
        cmd.ensure_finalized()
        cmd.run()

        f = open(cmd.record)
        try:
            content = f.read()
        finally:
            f.close()

        found = [os.path.basename(line) for line in content.splitlines()]
        expected = [_make_ext_name('xx'),
                    'UNKNOWN-0.0.0-py%s.%s.egg-info' % sys.version_info[:2]]
        self.assertEqual(found, expected) 
Example 29
Project: pyblish-win   Author: pyblish   File: regrtest.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def restore_cwd(self, saved_cwd):
        os.chdir(saved_cwd) 
Example 30
Project: pyblish-win   Author: pyblish   File: test_posixpath.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
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)
                test_support.unlink(ABSTFN)
                test_support.unlink(ABSTFN+"1")
                test_support.unlink(ABSTFN+"2")
                test_support.unlink(ABSTFN+"y")
                test_support.unlink(ABSTFN+"c")
                test_support.unlink(ABSTFN+"a") 
Example 31
Project: pyblish-win   Author: pyblish   File: test_posixpath.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
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:
                old_path = abspath('.')
                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.
                os.chdir(dirname(ABSTFN))
                self.assertEqual(realpath(basename(ABSTFN) + "/link-y/.."),
                                 ABSTFN + "/k")
            finally:
                os.chdir(old_path)
                test_support.unlink(ABSTFN + "/link-y")
                safe_rmdir(ABSTFN + "/k/y")
                safe_rmdir(ABSTFN + "/k")
                safe_rmdir(ABSTFN) 
Example 32
Project: pyblish-win   Author: pyblish   File: test_httpservers.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def tearDown(self):
        try:
            os.chdir(self.cwd)
            try:
                shutil.rmtree(self.tempdir)
            except OSError:
                pass
        finally:
            BaseTestCase.tearDown(self) 
Example 33
Project: pyblish-win   Author: pyblish   File: test_httpservers.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def setUp(self):
        BaseTestCase.setUp(self)
        self.parent_dir = tempfile.mkdtemp()
        self.cgi_dir = os.path.join(self.parent_dir, 'cgi-bin')
        self.cgi_child_dir = os.path.join(self.cgi_dir, 'child-dir')
        os.mkdir(self.cgi_dir)
        os.mkdir(self.cgi_child_dir)

        # The shebang line should be pure ASCII: use symlink if possible.
        # See issue #7668.
        if hasattr(os, 'symlink'):
            self.pythonexe = os.path.join(self.parent_dir, 'python')
            os.symlink(sys.executable, self.pythonexe)
        else:
            self.pythonexe = sys.executable

        self.nocgi_path = os.path.join(self.parent_dir, 'nocgi.py')
        with open(self.nocgi_path, 'w') as fp:
            fp.write(cgi_file1 % self.pythonexe)
        os.chmod(self.nocgi_path, 0777)

        self.file1_path = os.path.join(self.cgi_dir, 'file1.py')
        with open(self.file1_path, 'w') as file1:
            file1.write(cgi_file1 % self.pythonexe)
        os.chmod(self.file1_path, 0777)

        self.file2_path = os.path.join(self.cgi_dir, 'file2.py')
        with open(self.file2_path, 'w') as file2:
            file2.write(cgi_file2 % self.pythonexe)
        os.chmod(self.file2_path, 0777)

        self.file3_path = os.path.join(self.cgi_child_dir, 'file3.py')
        with open(self.file3_path, 'w') as file3:
            file3.write(cgi_file1 % self.pythonexe)
        os.chmod(self.file3_path, 0777)

        self.cwd = os.getcwd()
        os.chdir(self.parent_dir) 
Example 34
Project: pyblish-win   Author: pyblish   File: test_httpservers.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def tearDown(self):
        try:
            os.chdir(self.cwd)
            if self.pythonexe != sys.executable:
                os.remove(self.pythonexe)
            os.remove(self.nocgi_path)
            os.remove(self.file1_path)
            os.remove(self.file2_path)
            os.remove(self.file3_path)
            os.rmdir(self.cgi_child_dir)
            os.rmdir(self.cgi_dir)
            os.rmdir(self.parent_dir)
        finally:
            BaseTestCase.tearDown(self) 
Example 35
Project: pyblish-win   Author: pyblish   File: test_httpservers.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_main(verbose=None):
    try:
        cwd = os.getcwd()
        test_support.run_unittest(BaseHTTPRequestHandlerTestCase,
                                  SimpleHTTPRequestHandlerTestCase,
                                  BaseHTTPServerTestCase,
                                  SimpleHTTPServerTestCase,
                                  CGIHTTPServerTestCase
                                 )
    finally:
        os.chdir(cwd) 
Example 36
Project: pyblish-win   Author: pyblish   File: test_tarfile.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_add_self(self):
        # Test for #1257255.
        dstname = os.path.abspath(tmpname)

        tar = tarfile.open(tmpname, self.mode)
        self.assertTrue(tar.name == dstname, "archive name must be absolute")

        tar.add(dstname)
        self.assertTrue(tar.getnames() == [], "added the archive to itself")

        cwd = os.getcwd()
        os.chdir(TEMPDIR)
        tar.add(dstname)
        os.chdir(cwd)
        self.assertTrue(tar.getnames() == [], "added the archive to itself") 
Example 37
Project: pyblish-win   Author: pyblish   File: test_subprocess.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_exceptions(self):
        # caught & re-raised exceptions
        with self.assertRaises(OSError) as c:
            p = subprocess.Popen([sys.executable, "-c", ""],
                                 cwd="/this/path/does/not/exist")
        # The attribute child_traceback should contain "os.chdir" somewhere.
        self.assertIn("os.chdir", c.exception.child_traceback) 
Example 38
Project: pyblish-win   Author: pyblish   File: test_shutil.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_make_tarball(self):
        # creating something to tar
        tmpdir = self.mkdtemp()
        self.write_file([tmpdir, 'file1'], 'xxx')
        self.write_file([tmpdir, 'file2'], 'xxx')
        os.mkdir(os.path.join(tmpdir, 'sub'))
        self.write_file([tmpdir, 'sub', 'file3'], 'xxx')

        tmpdir2 = self.mkdtemp()
        # force shutil to create the directory
        os.rmdir(tmpdir2)
        unittest.skipUnless(splitdrive(tmpdir)[0] == splitdrive(tmpdir2)[0],
                            "source and target should be on same drive")

        base_name = os.path.join(tmpdir2, 'archive')

        # working with relative paths to avoid tar warnings
        old_dir = os.getcwd()
        os.chdir(tmpdir)
        try:
            _make_tarball(splitdrive(base_name)[1], '.')
        finally:
            os.chdir(old_dir)

        # check if the compressed tarball was created
        tarball = base_name + '.tar.gz'
        self.assertTrue(os.path.exists(tarball))

        # trying an uncompressed one
        base_name = os.path.join(tmpdir2, 'archive')
        old_dir = os.getcwd()
        os.chdir(tmpdir)
        try:
            _make_tarball(splitdrive(base_name)[1], '.', compress=None)
        finally:
            os.chdir(old_dir)
        tarball = base_name + '.tar'
        self.assertTrue(os.path.exists(tarball)) 
Example 39
Project: pyblish-win   Author: pyblish   File: test_shutil.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_make_zipfile_in_curdir(self):
        # Issue #21280
        root_dir = self.mkdtemp()
        saved_dir = os.getcwd()
        try:
            os.chdir(root_dir)
            self.assertEqual(make_archive('test', 'zip'), 'test.zip')
            self.assertTrue(os.path.isfile('test.zip'))
        finally:
            os.chdir(saved_dir) 
Example 40
Project: pyblish-win   Author: pyblish   File: test_os.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_chdir(self):
        self.assertRaises(WindowsError, os.chdir, test_support.TESTFN) 
Example 41
Project: pyblish-win   Author: pyblish   File: test_posix.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_chdir(self):
        posix.chdir(os.curdir)
        self.assertRaises(OSError, posix.chdir, test_support.TESTFN) 
Example 42
Project: pyblish-win   Author: pyblish   File: test_py_compile.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def setUp(self):
        self.directory = tempfile.mkdtemp()
        self.source_path = os.path.join(self.directory, '_test.py')
        self.pyc_path = self.source_path + 'c'
        self.cwd_drive = os.path.splitdrive(os.getcwd())[0]
        # In these tests we compute relative paths.  When using Windows, the
        # current working directory path and the 'self.source_path' might be
        # on different drives.  Therefore we need to switch to the drive where
        # the temporary source file lives.
        drive = os.path.splitdrive(self.source_path)[0]
        if drive:
            os.chdir(drive)

        with open(self.source_path, 'w') as file:
            file.write('x = 123\n') 
Example 43
Project: pyblish-win   Author: pyblish   File: test_py_compile.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_cwd(self):
        cwd = os.getcwd()
        os.chdir(self.directory)
        py_compile.compile(os.path.basename(self.source_path),
                           os.path.basename(self.pyc_path))
        os.chdir(cwd)
        self.assertTrue(os.path.exists(self.pyc_path)) 
Example 44
Project: pyblish-win   Author: pyblish   File: test_pep277.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_failures(self):
        # Pass non-existing Unicode filenames all over the place.
        for name in self.files:
            name = "not_" + name
            self._apply_failure(open, name, IOError)
            self._apply_failure(os.stat, name, OSError)
            self._apply_failure(os.chdir, name, OSError)
            self._apply_failure(os.rmdir, name, OSError)
            self._apply_failure(os.remove, name, OSError)
            # listdir may append a wildcard to the filename, so dont check
            self._apply_failure(os.listdir, name, OSError, False) 
Example 45
Project: pyblish-win   Author: pyblish   File: test_pep277.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_directory(self):
        dirname = os.path.join(test_support.TESTFN,
                               u'Gr\xfc\xdf-\u66e8\u66e9\u66eb')
        filename = u'\xdf-\u66e8\u66e9\u66eb'
        oldwd = os.getcwd()
        os.mkdir(dirname)
        os.chdir(dirname)
        try:
            with open(filename, 'w') as f:
                f.write((filename + '\n').encode("utf-8"))
            os.access(filename,os.R_OK)
            os.remove(filename)
        finally:
            os.chdir(oldwd)
            os.rmdir(dirname) 
Example 46
Project: pyblish-win   Author: pyblish   File: test_argparse.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def setUp(self):
        self.temp_dir = tempfile.mkdtemp()
        self.old_dir = os.getcwd()
        os.chdir(self.temp_dir) 
Example 47
Project: pyblish-win   Author: pyblish   File: test_unicode_file.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def _do_directory(self, make_name, chdir_name, encoded):
        cwd = os.getcwd()
        if os.path.isdir(make_name):
            os.rmdir(make_name)
        os.mkdir(make_name)
        try:
            os.chdir(chdir_name)
            try:
                if not encoded:
                    cwd_result = os.getcwdu()
                    name_result = make_name
                else:
                    cwd_result = os.getcwd().decode(TESTFN_ENCODING)
                    name_result = make_name.decode(TESTFN_ENCODING)

                cwd_result = unicodedata.normalize("NFD", cwd_result)
                name_result = unicodedata.normalize("NFD", name_result)

                self.assertEqual(os.path.basename(cwd_result),name_result)
            finally:
                os.chdir(cwd)
        finally:
            os.rmdir(make_name)

    # The '_test' functions 'entry points with params' - ie, what the
    # top-level 'test' functions would be if they could take params 
Example 48
Project: pyblish-win   Author: pyblish   File: test_unicode_file.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_directories(self):
        # For all 'equivalent' combinations:
        #  Make dir with encoded, chdir with unicode, checkdir with encoded
        #  (or unicode/encoded/unicode, etc
        ext = ".dir"
        self._do_directory(TESTFN_ENCODED+ext, TESTFN_ENCODED+ext, True)
        self._do_directory(TESTFN_ENCODED+ext, TESTFN_UNICODE+ext, True)
        self._do_directory(TESTFN_UNICODE+ext, TESTFN_ENCODED+ext, False)
        self._do_directory(TESTFN_UNICODE+ext, TESTFN_UNICODE+ext, False)
        # Our directory name that can't use a non-unicode name.
        if TESTFN_UNENCODABLE is not None:
            self._do_directory(TESTFN_UNENCODABLE+ext,
                               TESTFN_UNENCODABLE+ext,
                               False) 
Example 49
Project: pyblish-win   Author: pyblish   File: ScriptBinding.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def run_module_event(self, event):
        """Run the module after setting up the environment.

        First check the syntax.  If OK, make sure the shell is active and
        then transfer the arguments, set the run environment's working
        directory to the directory of the module being executed and also
        add that directory to its sys.path if not already included.

        """
        filename = self.getfilename()
        if not filename:
            return 'break'
        code = self.checksyntax(filename)
        if not code:
            return 'break'
        if not self.tabnanny(filename):
            return 'break'
        interp = self.shell.interp
        if PyShell.use_subprocess:
            interp.restart_subprocess(with_cwd=False)
        dirname = os.path.dirname(filename)
        # XXX Too often this discards arguments the user just set...
        interp.runcommand("""if 1:
            __file__ = {filename!r}
            import sys as _sys
            from os.path import basename as _basename
            if (not _sys.argv or
                _basename(_sys.argv[0]) != _basename(__file__)):
                _sys.argv = [__file__]
            import os as _os
            _os.chdir({dirname!r})
            del _sys, _basename, _os
            \n""".format(filename=filename, dirname=dirname))
        interp.prepend_syspath(filename)
        # XXX KBK 03Jul04 When run w/o subprocess, runtime warnings still
        #         go to __stderr__.  With subprocess, they go to the shell.
        #         Need to change streams in PyShell.ModifiedInterpreter.
        interp.runcode(code)
        return 'break' 
Example 50
Project: arm_now   Author: nongiach   File: arm_now.py    MIT License 5 votes vote down vote up
def do_offline():
    URL = "https://github.com/nongiach/arm_now_templates/archive/master.zip"
    templates = str(Path.home()) + "/.config/arm_now/templates/"
    master_zip = str(Path.home()) + "/.config/arm_now/templates/master.zip"
    os.makedirs(templates)
    # download_from_github(arch)
    download(URL, master_zip, Config.DOWNLOAD_CACHE_DIR)
    os.chdir(templates)
    check_call("unzip master.zip", shell=True)
    check_call("mv arm_now_templates-master/* .", shell=True)
    check_call("rm -rf arm_now_templates-master/ README.md master.zip", shell=True)