How to use the py.code function in py

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 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 / testing / test_deprecated_api.py View on Github external
class MyDirectory(py.test.collect.Directory):
                Module = MyModule
                def run(self):
                    return ['somefile.py']
                def join(self, name):
                    if name == "somefile.py":
                        return self.Module(self.fspath.join(name), parent=self)

            def pytest_collect_directory(path, parent):
                if path.basename == "subconf":
                    return MyDirectory(path, parent)
        """)
        subconf = testdir.mkpydir("subconf")
        somefile = subconf.join("somefile.py")
        somefile.write(py.code.Source("""
            def check(): pass
            class Cls:
                def check2(self): pass
        """))
        config = testdir.parseconfig(somefile)
        dirnode = config.getnode(somefile.dirpath())
        colitems = dirnode.collect()
        w = recwarn.pop(DeprecationWarning)
        assert w.filename.find("conftest.py") != -1
        #recwarn.resetregistry()
        #assert 0, (w.message, w.filename, w.lineno)
        assert len(colitems) == 1
        modcol = colitems[0]
        assert modcol.name == "somefile.py"
        colitems = modcol.collect()
        recwarn.pop(DeprecationWarning)
github pytest-dev / pytest / py / _code / code.py View on Github external
def __init__(self, rawcode):
        rawcode = py.code.getrawcode(rawcode)
        self.raw = rawcode
        try:
            self.filename = rawcode.co_filename
            self.firstlineno = rawcode.co_firstlineno - 1
            self.name = rawcode.co_name
        except AttributeError:
            raise TypeError("not a code object: %r" %(rawcode,))
github pytest-dev / pytest / py / _code / code.py View on Github external
def repr_traceback_entry(self, entry, excinfo=None):
        # excinfo is not None if this is the last tb entry
        source = self._getentrysource(entry)
        if source is None:
            source = py.code.Source("???")
            line_index = 0
        else:
            # entry.getfirstlinesource() can be -1, should be 0 on jython
            line_index = entry.lineno - max(entry.getfirstlinesource(), 0)

        lines = []
        if self.style in ("short", "long"):
            short = self.style == "short"
            reprargs = None
            if not short:
                reprargs = self.repr_args(entry)
            s = self.get_source(source, line_index, excinfo, short=short)
            lines.extend(s)
            if short:
                message = "in %s" %(entry.name)
            else:
github pytest-dev / pytest / py / apigen / tracer / description.py View on Github external
def cut_stack(stack, frame, upward_frame=None):
    if hasattr(frame, 'raw'):
        frame = frame.raw
    if upward_frame:
        if hasattr(upward_frame, 'raw'):
            upward_frame = upward_frame.raw
        lst = [py.code.Frame(i) for i in stack[stack.index(frame):\
                stack.index(upward_frame)+1]]
        if len(lst) > 1:
            return CallStack(lst[:-1])
        return CallStack(lst)
    return CallStack([py.code.Frame(i) for i in stack[stack.index(frame):]])
github pytest-dev / pytest / py / misc / testing / test_update_website.py View on Github external
def setup_pkg(testname):
    temp = py.test.ensuretemp(testname)
    pkgpath = temp.ensure('pkg', dir=True)
    pyfile = pkgpath.ensure('mod.py').write(py.code.Source("""
        def foo(x):
            return x + 1
    """))
    testfile = pkgpath.ensure('test/test_mod.py').write(py.code.Source("""
        from pkg.sub import foo
        def test_foo():
            assert foo(1) == 2
    """))
    initfile = pkgpath.ensure('__init__.py').write(py.code.Source("""
        import py
        from py.__.initpkg import initpkg
        initpkg(__name__, exportdefs={
            'sub.foo': ('./mod.py', 'foo'),
        })
    """))
    initfile = pkgpath.ensure('apigen/apigen.py').write(py.code.Source("""
        from py.__.apigen.apigen import build, \
             get_documentable_items_pkgdir as get_documentable_items
    """))
    return pkgpath
github pytest-dev / pytest / py / _code / code.py View on Github external
def patch_builtins(assertion=True, compile=True):
    """ put compile and AssertionError builtins to Python's builtins. """
    if assertion:
        from py._code import assertion
        l = oldbuiltins.setdefault('AssertionError', [])
        l.append(py.builtin.builtins.AssertionError)
        py.builtin.builtins.AssertionError = assertion.AssertionError
    if compile:
        l = oldbuiltins.setdefault('compile', [])
        l.append(py.builtin.builtins.compile)
        py.builtin.builtins.compile = py.code.compile
github servo / mozjs / mozjs / third_party / python / py / py / _code / source.py View on Github external
def getsource(obj, **kwargs):
    obj = py.code.getrawcode(obj)
    try:
        strsrc = inspect.getsource(obj)
    except IndentationError:
        strsrc = "\"Buggy python version consider upgrading, cannot get source\""
    assert isinstance(strsrc, str)
    return Source(strsrc, **kwargs)
github spack / spack / lib / spack / external / py / _code / code.py View on Github external
def __init__(self, frame):
        self.lineno = frame.f_lineno - 1
        self.f_globals = frame.f_globals
        self.f_locals = frame.f_locals
        self.raw = frame
        self.code = py.code.Code(frame.f_code)