Python py.path() Examples

The following are 30 code examples of py.path(). 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 py , or try the search function .
Example #1
Source File: test_local.py    From py with MIT License 7 votes vote down vote up
def test_setmtime(self):
        import tempfile
        import time
        try:
            fd, name = tempfile.mkstemp()
            os.close(fd)
        except AttributeError:
            name = tempfile.mktemp()
            open(name, 'w').close()
        try:
            mtime = int(time.time())-100
            path = local(name)
            assert path.mtime() != mtime
            path.setmtime(mtime)
            assert path.mtime() == mtime
            path.setmtime()
            assert path.mtime() != mtime
        finally:
            os.remove(name) 
Example #2
Source File: test_svnwc.py    From py with MIT License 6 votes vote down vote up
def test_make_repo(path1, tmpdir):
    repo = tmpdir.join("repo")
    py.process.cmdexec('svnadmin create %s' % repo)
    if sys.platform == 'win32':
        repo = '/' + str(repo).replace('\\', '/')
    repo = py.path.svnurl("file://%s" % repo)
    wc = py.path.svnwc(tmpdir.join("wc"))
    wc.checkout(repo)
    assert wc.rev == 0
    assert len(wc.listdir()) == 0
    p = wc.join("a_file")
    p.write("test file")
    p.add()
    rev = wc.commit("some test")
    assert p.info().rev == 1
    assert rev == 1
    rev = wc.commit()
    assert rev is None 
Example #3
Source File: test_svnauth.py    From py with MIT License 6 votes vote down vote up
def test_lock_unlock_status(self, setup):
        port = setup.port
        wc = py.path.svnwc(setup.temppath, auth=setup.auth)
        wc.checkout(
            'svn://localhost:%s/%s' % (port, setup.repopath.basename,))
        wc.ensure('foo', file=True)
        wc.commit('added foo file')
        foo = wc.join('foo')
        foo.lock()
        status = foo.status()
        assert status.locked
        foo.unlock()
        status = foo.status()
        assert not status.locked

        auth = SvnAuth('unknown', 'unknown', interactive=False)
        foo.auth = auth
        py.test.raises(Exception, 'foo.lock()')
        py.test.raises(Exception, 'foo.unlock()') 
Example #4
Source File: code.py    From python-netsurv with MIT License 6 votes vote down vote up
def filter_traceback(entry):
    """Return True if a TracebackEntry instance should be removed from tracebacks:
    * dynamically generated code (no code to show up for it);
    * internal traceback from pytest or its internal libraries, py and pluggy.
    """
    # entry.path might sometimes return a str object when the entry
    # points to dynamically generated code
    # see https://bitbucket.org/pytest-dev/py/issues/71
    raw_filename = entry.frame.code.raw.co_filename
    is_generated = "<" in raw_filename and ">" in raw_filename
    if is_generated:
        return False
    # entry.path might point to a non-existing file, in which case it will
    # also return a str object. see #1133
    p = py.path.local(entry.path)
    return (
        not p.relto(_PLUGGY_DIR) and not p.relto(_PYTEST_DIR) and not p.relto(_PY_DIR)
    ) 
Example #5
Source File: test_svnauth.py    From py with MIT License 6 votes vote down vote up
def __init__(self, request):
        if not svnbin:
            py.test.skip("svn binary required")
        if not request.config.option.runslowtests:
            py.test.skip('use --runslowtests to run these tests')

        tmpdir = request.getfuncargvalue("tmpdir")
        repodir = tmpdir.join("repo")
        py.process.cmdexec('svnadmin create %s' % repodir)
        if sys.platform == 'win32':
            repodir = '/' + str(repodir).replace('\\', '/')
        self.repo = py.path.svnurl("file://%s" % repodir)
        if sys.platform == 'win32':
            # remove trailing slash...
            repodir = repodir[1:]
        self.repopath = py.path.local(repodir)
        self.temppath = tmpdir.mkdir("temppath")
        self.auth = SvnAuth('johnny', 'foo', cache_auth=False,
                                    interactive=False)
        make_repo_auth(self.repopath, {'johnny': ('foo', 'rw')})
        self.port, self.pid = serve_bg(self.repopath.dirpath())
        # XXX caching is too global
        py.path.svnurl._lsnorevcache._dict.clear()
        request.addfinalizer(lambda: py.process.kill(self.pid)) 
Example #6
Source File: instances_test.py    From glyphsLib with Apache License 2.0 6 votes vote down vote up
def test_reencode_glyphs(tmpdir):
    data_dir = py.path.local(DATA)

    designspace_path = data_dir / "TestReencode.designspace"
    designspace_path.copy(tmpdir)

    ufo_path = data_dir / "TestReencode-Regular.ufo"
    ufo_path.copy(tmpdir.ensure_dir("TestReencode-Regular.ufo"))

    instance_dir = tmpdir.ensure_dir("instance_ufo")
    ufo_path.copy(instance_dir.ensure_dir("TestReencode-Regular.ufo"))
    ufo_path.copy(instance_dir.ensure_dir("TestReencodeUI-Regular.ufo"))

    ufos = apply_instance_data(str(tmpdir / "TestReencode.designspace"))

    assert len(ufos) == 2
    assert ufos[0]["A"].unicode == 0x0041
    assert ufos[0]["A.alt"].unicode is None
    assert ufos[0]["C"].unicode == 0x0043
    # Reencode Glyphs: A.alt=0041, C=
    assert ufos[1]["A"].unicode is None
    assert ufos[1]["A.alt"].unicode == 0x0041
    assert ufos[1]["C"].unicode is None 
Example #7
Source File: test_svnauth.py    From py with MIT License 6 votes vote down vote up
def make_repo_auth(repo, userdata):
    """ write config to repo

        user information in userdata is used for auth
        userdata has user names as keys, and a tuple (password, readwrite) as
        values, where 'readwrite' is either 'r' or 'rw'
    """
    confdir = py.path.local(repo).join('conf')
    confdir.join('svnserve.conf').write('''\
[general]
anon-access = none
password-db = passwd
authz-db = authz
realm = TestRepo
''')
    authzdata = '[/]\n'
    passwddata = '[users]\n'
    for user in userdata:
        authzdata += '%s = %s\n' % (user, userdata[user][1])
        passwddata += '%s = %s\n' % (user, userdata[user][0])
    confdir.join('authz').write(authzdata)
    confdir.join('passwd').write(passwddata) 
Example #8
Source File: test_download.py    From sentinelsat with GNU General Public License v3.0 6 votes vote down vote up
def test_download_all_lta(api, tmpdir):
    # Corresponding IDs, same products as in test_download_all.
    ids = [
        "5618ce1b-923b-4df2-81d9-50b53e5aded9",  # offline
        "f46cbca6-6e5e-45b0-80cd-382683a8aea5",  # online
        "e00af686-2e20-43a6-8b8f-f9e411255cee",  # online
    ]
    product_infos, triggered, failed_downloads = api.download_all(
        ids, str(tmpdir), n_concurrent_dl=1
    )
    assert len(failed_downloads) == 0
    assert len(triggered) == 1
    assert len(product_infos) == len(ids) - len(failed_downloads) - len(triggered)
    assert all(x["Online"] is False for x in triggered.values())

    # test downloaded products
    for product_id, product_info in product_infos.items():
        pypath = py.path.local(product_info["path"])
        assert pypath.check(exists=1, file=1)
        assert pypath.purebasename in product_info["title"]
        assert pypath.size() == product_info["size"]

    tmpdir.remove() 
Example #9
Source File: test_svnauth.py    From py with MIT License 6 votes vote down vote up
def test_update(self, setup):
        wc1 = py.path.svnwc(setup.temppath.ensure('wc1', dir=True),
                            auth=setup.auth)
        wc2 = py.path.svnwc(setup.temppath.ensure('wc2', dir=True),
                            auth=setup.auth)
        wc1.checkout(
            'svn://localhost:%s/%s' % (setup.port, setup.repopath.basename))
        wc2.checkout(
            'svn://localhost:%s/%s' % (setup.port, setup.repopath.basename))
        wc1.ensure('foo', dir=True)
        wc1.commit('added foo dir')
        wc2.update()
        assert wc2.join('foo').check()

        auth = SvnAuth('unknown', 'unknown', interactive=False)
        wc2.auth = auth
        py.test.raises(Exception, 'wc2.update()') 
Example #10
Source File: test_svnauth.py    From py with MIT License 6 votes vote down vote up
def test_diff(self, setup):
        port = setup.port
        wc = py.path.svnwc(setup.temppath, auth=setup.auth)
        wc.checkout(
            'svn://localhost:%s/%s' % (port, setup.repopath.basename,))
        wc.ensure('foo', file=True)
        wc.commit('added foo file')
        wc.update()
        rev = int(wc.status().rev)
        foo = wc.join('foo')
        foo.write('bar')
        diff = foo.diff()
        assert '\n+bar\n' in diff
        foo.commit('added some content')
        diff = foo.diff()
        assert not diff
        diff = foo.diff(rev=rev)
        assert '\n+bar\n' in diff

        auth = SvnAuth('unknown', 'unknown', interactive=False)
        foo.auth = auth
        py.test.raises(Exception, 'foo.diff(rev=rev)') 
Example #11
Source File: code.py    From python-netsurv with MIT License 6 votes vote down vote up
def cut(self, path=None, lineno=None, firstlineno=None, excludepath=None):
        """ return a Traceback instance wrapping part of this Traceback

            by provding any combination of path, lineno and firstlineno, the
            first frame to start the to-be-returned traceback is determined

            this allows cutting the first part of a Traceback instance e.g.
            for formatting reasons (removing some uninteresting bits that deal
            with handling of the exception/traceback)
        """
        for x in self:
            code = x.frame.code
            codepath = code.path
            if (
                (path is None or codepath == path)
                and (
                    excludepath is None
                    or not hasattr(codepath, "relto")
                    or not codepath.relto(excludepath)
                )
                and (lineno is None or x.lineno == lineno)
                and (firstlineno is None or x.frame.code.firstlineno == firstlineno)
            ):
                return Traceback(x._rawentry, self._excinfo)
        return self 
Example #12
Source File: code.py    From python-netsurv with MIT License 6 votes vote down vote up
def getsource(self, astcache=None):
        """ return failing source code. """
        # we use the passed in astcache to not reparse asttrees
        # within exception info printing
        from _pytest._code.source import getstatementrange_ast

        source = self.frame.code.fullsource
        if source is None:
            return None
        key = astnode = None
        if astcache is not None:
            key = self.frame.code.path
            if key is not None:
                astnode = astcache.get(key, None)
        start = self.getfirstlinesource()
        try:
            astnode, _, end = getstatementrange_ast(
                self.lineno, source, astnode=astnode
            )
        except SyntaxError:
            end = self.lineno + 1
        else:
            if key is not None:
                astcache[key] = astnode
        return source[start:end] 
Example #13
Source File: code.py    From python-netsurv with MIT License 6 votes vote down vote up
def filter_traceback(entry):
    """Return True if a TracebackEntry instance should be removed from tracebacks:
    * dynamically generated code (no code to show up for it);
    * internal traceback from pytest or its internal libraries, py and pluggy.
    """
    # entry.path might sometimes return a str object when the entry
    # points to dynamically generated code
    # see https://bitbucket.org/pytest-dev/py/issues/71
    raw_filename = entry.frame.code.raw.co_filename
    is_generated = "<" in raw_filename and ">" in raw_filename
    if is_generated:
        return False
    # entry.path might point to a non-existing file, in which case it will
    # also return a str object. see #1133
    p = py.path.local(entry.path)
    return (
        not p.relto(_PLUGGY_DIR) and not p.relto(_PYTEST_DIR) and not p.relto(_PY_DIR)
    ) 
Example #14
Source File: code.py    From python-netsurv with MIT License 6 votes vote down vote up
def getsource(self, astcache=None):
        """ return failing source code. """
        # we use the passed in astcache to not reparse asttrees
        # within exception info printing
        from _pytest._code.source import getstatementrange_ast

        source = self.frame.code.fullsource
        if source is None:
            return None
        key = astnode = None
        if astcache is not None:
            key = self.frame.code.path
            if key is not None:
                astnode = astcache.get(key, None)
        start = self.getfirstlinesource()
        try:
            astnode, _, end = getstatementrange_ast(
                self.lineno, source, astnode=astnode
            )
        except SyntaxError:
            end = self.lineno + 1
        else:
            if key is not None:
                astcache[key] = astnode
        return source[start:end] 
Example #15
Source File: test_pytest_plugins.py    From tox with MIT License 6 votes vote down vote up
def test_broken_py_path_local_join_workaround_on_Windows(self, tmpdir, initproj, monkeypatch):
        # construct an absolute folder path for our src_root folder without the
        # Windows drive indicator
        src_root = tmpdir.join("spam")
        src_root = _path_parts(src_root)
        src_root[0] = ""
        src_root = "/".join(src_root)

        # make sure tmpdir drive is the current one so the constructed src_root
        # folder path gets interpreted correctly on Windows
        monkeypatch.chdir(tmpdir)

        # will throw an assertion error if the bug is not worked around
        initproj("spam-666", src_root=src_root)

        init_file = tmpdir.join("spam", "spam", "__init__.py")
        expected = b'""" module spam """' + linesep_bytes() + b"__version__ = '666'"
        assert init_file.read_binary() == expected 
Example #16
Source File: test_svnwc.py    From py with MIT License 6 votes vote down vote up
def test_exists_svn_root(self, path1):
        assert path1.check()

    #def test_not_exists_rev(self, path1):
    #    url = path1.__class__(path1url, rev=500)
    #    assert url.check(exists=0)

    #def test_nonexisting_listdir_rev(self, path1):
    #    url = path1.__class__(path1url, rev=500)
    #    raises(py.error.ENOENT, url.listdir)

    #def test_newrev(self, path1):
    #    url = path1.new(rev=None)
    #    assert url.rev == None
    #    assert url.strpath == path1.strpath
    #    url = path1.new(rev=10)
    #    assert url.rev == 10

    #def test_info_rev(self, path1):
    #    url = path1.__class__(path1url, rev=1155)
    #    url = url.join("samplefile")
    #    res = url.info()
    #    assert res.size > len("samplefile") and res.created_rev == 1155

    # the following tests are easier if we have a path class 
Example #17
Source File: test_svnauth.py    From py with MIT License 6 votes vote down vote up
def test_copy(self, setup):
        port = setup.port
        u = py.path.svnurl(
            'svn://localhost:%s/%s' % (port, setup.repopath.basename),
            auth=setup.auth)
        foo = u.mkdir('foo')
        assert foo.check()
        bar = u.join('bar')
        foo.copy(bar)
        assert bar.check()
        assert bar.auth is setup.auth

        auth = SvnAuth('foo', 'bar', interactive=False)
        u = py.path.svnurl(
            'svn://localhost:%s/%s' % (port, setup.repopath.basename),
            auth=auth)
        foo = u.join('foo')
        bar = u.join('bar')
        py.test.raises(Exception, 'foo.copy(bar)') 
Example #18
Source File: test_local.py    From py with MIT License 6 votes vote down vote up
def test_eq_with_none_and_custom_fspath(self, monkeypatch, path1):
        import os
        import shutil
        import tempfile

        d = tempfile.mkdtemp()
        monkeypatch.chdir(d)
        shutil.rmtree(d)

        monkeypatch.delitem(sys.modules, 'pathlib', raising=False)
        monkeypatch.setattr(sys, 'path', [''] + sys.path)

        with pytest.raises(FileNotFoundError):
            import pathlib  # noqa: F401

        assert path1 != None  # noqa: E711 
Example #19
Source File: test_svnwc.py    From py with MIT License 5 votes vote down vote up
def test_svn_1_2(self, path1):
        output = """
        Path: test_svnwc.py
        Name: test_svnwc.py
        URL: http://codespeak.net/svn/py/dist/py/path/svn/wccommand.py
        Repository UUID: fd0d7bf2-dfb6-0310-8d31-b7ecfe96aada
        Revision: 28137
        Node Kind: file
        Schedule: normal
        Last Changed Author: jan
        Last Changed Rev: 27939
        Last Changed Date: 2006-05-30 20:45:26 +0200 (Tue, 30 May 2006)
        Text Last Updated: 2006-06-01 00:42:53 +0200 (Thu, 01 Jun 2006)
        Properties Last Updated: 2006-05-23 11:54:59 +0200 (Tue, 23 May 2006)
        Checksum: 357e44880e5d80157cc5fbc3ce9822e3
        """
        path = py.path.local(__file__).dirpath().chdir()
        try:
            info = InfoSvnWCCommand(output)
        finally:
            path.chdir()
        assert info.last_author == 'jan'
        assert info.kind == 'file'
        assert info.mtime == 1149021926.0
        assert info.url == 'http://codespeak.net/svn/py/dist/py/path/svn/wccommand.py'
        assert info.time == 1149021926000000.0
        assert info.rev == 28137 
Example #20
Source File: test_svnwc.py    From py with MIT License 5 votes vote down vote up
def test_characters_tilde():
    py.path.svnwc('/tmp/test~') 
Example #21
Source File: test_svnwc.py    From py with MIT License 5 votes vote down vote up
def test_status_wrong_xml(self, path1):
        # testing for XML without author - this used to raise an exception
        xml = '<entry path="/home/jean/zope/venv/projectdb/parts/development-products/DataGridField">\n<wc-status item="incomplete" props="none" revision="784">\n</wc-status>\n</entry>'
        st = XMLWCStatus.fromstring(xml, path1)
        assert len(st.incomplete) == 1 
Example #22
Source File: test_svnwc.py    From py with MIT License 5 votes vote down vote up
def test_status_noauthor(self, path1):
        # testing for XML without author - this used to raise an exception
        xml = '''\
        <entry path="/tmp/pytest-23/wc">
        <wc-status item="normal" props="none" revision="0">
        <commit revision="0">
        <date>2008-08-19T16:50:53.400198Z</date>
        </commit>
        </wc-status>
        </entry>
        '''
        XMLWCStatus.fromstring(xml, path1) 
Example #23
Source File: test_svnwc.py    From py with MIT License 5 votes vote down vote up
def test_nonversioned_remove(self, path1):
        assert path1.check(versioned=1)
        somefile = path1.join('nonversioned/somefile')
        nonwc = py.path.local(somefile)
        nonwc.ensure()
        assert somefile.check()
        assert not somefile.check(versioned=True)
        somefile.remove() # this used to fail because it tried to 'svn rm' 
Example #24
Source File: code.py    From python-netsurv with MIT License 5 votes vote down vote up
def _getreprcrash(self):
        exconly = self.exconly(tryshort=True)
        entry = self.traceback.getcrashentry()
        path, lineno = entry.frame.code.raw.co_filename, entry.lineno
        return ReprFileLocation(path, lineno + 1, exconly) 
Example #25
Source File: test_download.py    From sentinelsat with GNU General Public License v3.0 5 votes vote down vote up
def test_download_all(api, tmpdir, smallest_online_products):
    ids = [product["id"] for product in smallest_online_products]

    # Download normally
    product_infos, triggered, failed_downloads = api.download_all(
        ids, str(tmpdir), n_concurrent_dl=1, max_attempts=1
    )
    assert len(failed_downloads) == 0
    assert len(triggered) == 0
    assert len(product_infos) == len(ids)
    for product_id, product_info in product_infos.items():
        pypath = py.path.local(product_info["path"])
        assert pypath.check(exists=1, file=1)
        assert pypath.purebasename in product_info["title"]
        assert pypath.size() == product_info["size"] 
Example #26
Source File: test_pytest_plugins.py    From tox with MIT License 5 votes vote down vote up
def test_on_py_path(self):
        cwd_parts = _path_parts(py.path.local())
        folder_parts = _path_parts(py.path.local("a/b/c"))
        assert folder_parts[len(cwd_parts) :] == ["a", "b", "c"] 
Example #27
Source File: code.py    From python-netsurv with MIT License 5 votes vote down vote up
def path(self):
        """ return a path object pointing to source code (note that it
        might not point to an actually existing file). """
        try:
            p = py.path.local(self.raw.co_filename)
            # maybe don't try this checking
            if not p.check():
                raise OSError("py.path check failed.")
        except OSError:
            # XXX maybe try harder like the weird logic
            # in the standard lib [linecache.updatecache] does?
            p = self.raw.co_filename

        return p 
Example #28
Source File: code.py    From python-netsurv with MIT License 5 votes vote down vote up
def __repr__(self):
        return "<TracebackEntry %s:%d>" % (self.frame.code.path, self.lineno + 1) 
Example #29
Source File: code.py    From python-netsurv with MIT License 5 votes vote down vote up
def repr_traceback_entry(self, entry, excinfo=None):
        import _pytest._code

        source = self._getentrysource(entry)
        if source is None:
            source = _pytest._code.Source("???")
            line_index = 0
        else:
            line_index = entry.lineno - entry.getfirstlinesource()

        lines = []
        style = entry._repr_style
        if style is None:
            style = self.style
        if style in ("short", "long"):
            short = style == "short"
            reprargs = self.repr_args(entry) if not short else None
            s = self.get_source(source, line_index, excinfo, short=short)
            lines.extend(s)
            if short:
                message = "in %s" % (entry.name)
            else:
                message = excinfo and excinfo.typename or ""
            path = self._makepath(entry.path)
            filelocrepr = ReprFileLocation(path, entry.lineno + 1, message)
            localsrepr = None
            if not short:
                localsrepr = self.repr_locals(entry.locals)
            return ReprEntry(lines, reprargs, localsrepr, filelocrepr, style)
        if excinfo:
            lines.extend(self.get_exconly(excinfo, indent=4))
        return ReprEntry(lines, None, None, None, style) 
Example #30
Source File: code.py    From python-netsurv with MIT License 5 votes vote down vote up
def path(self):
        """ path to the source code """
        return self.frame.code.path