How to use py - 10 common examples

To help you get started, we’ve selected a few py examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github spack / spack / lib / spack / external / _pytest / pytester.py View on Github external
def _run(self, *cmdargs):
        cmdargs = [str(x) for x in cmdargs]
        p1 = self.tmpdir.join("stdout")
        p2 = self.tmpdir.join("stderr")
        print_("running:", ' '.join(cmdargs))
        print_("     in:", str(py.path.local()))
        f1 = codecs.open(str(p1), "w", encoding="utf8")
        f2 = codecs.open(str(p2), "w", encoding="utf8")
        try:
            now = time.time()
            popen = self.popen(cmdargs, stdout=f1, stderr=f2,
                close_fds=(sys.platform != "win32"))
            ret = popen.wait()
        finally:
            f1.close()
            f2.close()
        f1 = codecs.open(str(p1), "r", encoding="utf8")
        f2 = codecs.open(str(p2), "r", encoding="utf8")
        try:
            out = f1.read().splitlines()
            err = f2.read().splitlines()
        finally:
github tox-dev / tox / tests / unit / test_z_cmdline.py View on Github external
def test_log_pcall(self, mocksession):
        mocksession.logging_levels(quiet=Verbosity.DEFAULT, verbose=Verbosity.INFO)
        mocksession.config.logdir.ensure(dir=1)
        assert not mocksession.config.logdir.listdir()
        with mocksession.newaction("what", "something") as action:
            action.popen(["echo"])
            match = mocksession.report.getnext("logpopen")
            log_name = py.path.local(match[1].split(">")[-1].strip()).relto(
                mocksession.config.logdir
            )
            assert log_name == "what-0.log"
github pytest-dev / pytest / testing / test_conftesthandle.py View on Github external
@py.test.mark.multi(name='test tests whatever .dotdir'.split())
def test_setinitial_conftest_subdirs(testdir, name):
    sub = testdir.mkdir(name)
    subconftest = sub.ensure("conftest.py")
    conftest = Conftest()
    conftest.setinitial([sub.dirpath(), '--confcutdir=%s' % testdir.tmpdir])
    if name not in ('whatever', '.dotdir'):
        assert  subconftest in conftest._conftestpath2mod
        assert len(conftest._conftestpath2mod) == 1
    else:
        assert  subconftest not in conftest._conftestpath2mod
        assert len(conftest._conftestpath2mod) == 0
github ropez / pytest-describe / test / test_custom_prefix.py View on Github external
def test_collect_custom_prefix(testdir):
    testdir.makeini(ini)

    a_dir = testdir.mkpydir('a_dir')
    a_dir.join('test_a.py').write(py.code.Source("""
        def foo_scope():
            def bar_context():
                def passes():
                    pass
    """))

    result = testdir.runpytest('--collectonly')
    expected_lines = map(re.compile, [
        r"collected 1 item(s)?",
        r"\s*",
        r"\s*",
        r"\s*",
        r"\s*",
    ])
    for line in expected_lines:
        assert any([line.match(r) is not None for r in result.outlines])
github ropez / pytest-describe / test / test_output.py View on Github external
def test_verbose_output(testdir):
    a_dir = testdir.mkpydir('a_dir')
    a_dir.join('test_a.py').write(py.code.Source("""
        def describe_something():
            def describe_nested_ok():
                def passes():
                    assert True
            def describe_nested_bad():
                def fails():
                    assert False
    """))

    result = testdir.runpytest('-v')
    expected = [
        'a_dir/test_a.py::describe_something::describe_nested_bad::fails FAILED',
        'a_dir/test_a.py::describe_something::describe_nested_ok::passes PASSED',
    ]
    for line in expected:
        assert any(out for out in result.outlines if out.startswith(line))
github pytest-dev / pytest / testing / test_lastfailed.py View on Github external
def test_lastfailed_usecase(self, testdir, monkeypatch):
        monkeypatch.setenv("PYTHONDONTWRITEBYTECODE", 1)
        p = testdir.makepyfile("""
            def test_1():
                assert 0
            def test_2():
                assert 0
            def test_3():
                assert 1
        """)
        result = testdir.runpytest()
        result.stdout.fnmatch_lines([
            "*2 failed*",
        ])
        p.write(py.code.Source("""
            def test_1():
                assert 1

            def test_2():
                assert 1

            def test_3():
                assert 0
        """))
        result = testdir.runpytest("--lf")
        result.stdout.fnmatch_lines([
            "*2 passed*1 desel*",
        ])
        result = testdir.runpytest("--lf")
        result.stdout.fnmatch_lines([
            "*1 failed*2 passed*",
github moinwiki / moin-1.9 / MoinMoin / _tests / compat.py View on Github external
('x,y', 'x==y',  'failIfEqual,assertNotEqual, assertNotEquals'),
        ]
    items = []
    for sig, expr, names in aliasmap:
        names = map(str.strip, names.split(','))
        sigsubst = expr.replace('y', '%s').replace('x', '%s')
        for name in names:
            items.append("""
                def %(name)s(self, %(sig)s, msg=""):
                    __tracebackhide__ = True
                    if %(expr)s:
                        raise Failed(msg=msg + (%(sigsubst)r %% (%(sig)s)))
            """ % locals() )

    source = "".join(items)
    exec py.code.Source(source).compile()

__all__ = ['TestCase']
github pytest-dev / pytest / py / apigen / linker.py View on Github external
def get_lazyhref(self, linkid):
        return '%s://%s' % (TEMPLINK_PROTO, linkid)

    def set_link(self, linkid, target):
        assert linkid not in self._linkid2target
        self._linkid2target[linkid] = target

    def get_target(self, tempurl, fromlocation=None):
        assert tempurl.startswith('%s://' % (TEMPLINK_PROTO,))
        linkid = '://'.join(tempurl.split('://')[1:])
        linktarget = self._linkid2target[linkid]
        if fromlocation is not None:
            linktarget = relpath(fromlocation, linktarget)
        return linktarget

    _reg_tempurl = py.std.re.compile('["\'](%s:\/\/[^"\s]*)["\']' % (
                                      TEMPLINK_PROTO,))
    def replace_dirpath(self, dirpath, stoponerrors=True):
        """ replace temporary links in all html files in dirpath and below """
        for fpath in dirpath.visit('*.html'):
            html = fpath.read()
            while 1:
                match = self._reg_tempurl.search(html)
                if not match:
                    break
                tempurl = match.group(1)
                try:
                    html = html.replace('"' + tempurl + '"',
                                        '"' + self.get_target(tempurl,
                                                fpath.relto(dirpath)) + '"')
                except KeyError:
                    if stoponerrors:
github pytest-dev / execnet / testing / test_gateway.py View on Github external
def test_deprecation(recwarn, monkeypatch):
    execnet.PopenGateway().exit()
    assert recwarn.pop(DeprecationWarning)
    monkeypatch.setattr(py.std.socket, 'socket', lambda *args: 0/0)
    py.test.raises(Exception, 'execnet.SocketGateway("localhost", 8811)')
    assert recwarn.pop(DeprecationWarning)
    monkeypatch.setattr(py.std.subprocess, 'Popen', lambda *args,**kwargs: 0/0)
    py.test.raises(Exception, 'execnet.SshGateway("not-existing")')
    assert recwarn.pop(DeprecationWarning)
github pytest-dev / pytest / _py / rest / convert.py View on Github external
def convert_dot(fn, new_extension):
    if not py.path.local.sysfind("dot"):
        raise SystemExit("ERROR: dot not found")
    result = fn.new(ext=new_extension)
    print(result)
    arg = "-T%s" % (format_to_dotargument[new_extension], )
    py.std.os.system('dot "%s" "%s" > "%s"' % (arg, fn, result))
    if new_extension == "eps":
        ps = result.new(ext="ps")
        result.move(ps)
        ps2eps(ps)
        ps.remove()
    elif new_extension == "pdf":
        # convert to eps file first, to get the bounding box right
        eps = result.new(ext="eps")
        ps = result.new(ext="ps")
        result.move(ps)
        ps2eps(ps)
        eps2pdf(eps)
        ps.remove()
        eps.remove()
    return result