How to use the py.code.Source 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 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 / code / test_source.py View on Github external
def test_source_strips():
    source = Source("")
    assert source == Source()
    assert str(source) == ''
    assert source.strip() == source
github tox-dev / tox / tox / _pytestplugin.py View on Github external
def fnmatch_lines(self, lines2):
        if isinstance(lines2, str):
            lines2 = py.code.Source(lines2)
        if isinstance(lines2, py.code.Source):
            lines2 = lines2.strip().lines

        from fnmatch import fnmatch
        lines1 = self.lines[:]
        nextline = None
        extralines = []
        __tracebackhide__ = True
        for line in lines2:
            nomatchprinted = False
            while lines1:
                nextline = lines1.pop(0)
                if line == nextline:
                    print_("exact match:", repr(line))
                    break
                elif fnmatch(nextline, line):
github tav / plexnet / third_party / generic / pypy / py / code / testing / test_source.py View on Github external
def test_isparseable():
    assert Source("hello").isparseable()
    assert Source("if 1:\n  pass").isparseable()
    assert Source(" \nif 1:\n  pass").isparseable()
    assert not Source("if 1:\n").isparseable() 
    assert not Source(" \nif 1:\npass").isparseable()
github tav / plexnet / third_party / generic / pypy / pypy / rlib / rstruct / runpack.py View on Github external
miniglobals.update(globals())
        for i in rg:
            fmtdesc, rep, mask = self.formats[i]
            miniglobals['unpacker%d' % i] = fmtdesc.unpack
            if mask is not None:
                perform_lst.append('master_reader.align(%d)' % mask)
            if not fmtdesc.needcount:
                perform_lst.append('unpacker%d(reader%d)' % (i, i))
            else:
                perform_lst.append('unpacker%d(reader%d, %d)' % (i, i, rep))
            miniglobals['reader_cls%d' % i] = reader_for_pos(i)
        readers = ";".join(["reader%d = reader_cls%d(master_reader)" % (i, i)
                             for i in rg])
        perform = ";".join(perform_lst)
        unpackers = ','.join(['reader%d.value' % i for i in rg])
        source = py.code.Source("""
        def unpack(s):
            master_reader = MasterReader(s)
            %(readers)s
            %(perform)s
            return (%(unpackers)s)
        """ % locals())
        exec source.compile() in miniglobals
        self.unpack = miniglobals['unpack'] # override not-rpython version
github cornell-brg / pymtl3 / pymtl / old_passes / MetaBlkPass.py View on Github external
gen_tick_src += "\n\ndef meta_blk{}():\n  ".format(i)

        gen_tick_src += "\n  ".join( [ "update_blk{}__{}() # {}" \
                                      .format( i, j, schedule_names[(i, j)] )
                                      for j in xrange( len(meta_blk) )] )

        if i < len(metas)-1:
          gen_tick_src += "\ntry:\n"
          gen_tick_src += "  dont_trace_here(0, False, meta_blk{}.__code__)\n".format( i )
          gen_tick_src += "except NameError:\n"
          gen_tick_src += "  pass\n"

      gen_tick_src += "\ndef tick_top():\n  "
      gen_tick_src += "; ".join( [ "meta_blk{}()".format(i) for i in xrange(len(metas)) ] )

      exec py.code.Source( gen_tick_src ).compile() in locals()

    elif mode == 'meta_loop':

      gen_tick_src = ""

      # The "comment" that will be used for update calls.
      schedule_names = {}

      for i in xrange( len(metas) ):
        meta = metas[i]
        for j in xrange( len(meta) ):
          blk = meta[j]
          schedule_names[ (i, j) ] = "[br: {}] {}" \
            .format( m._all_meta['br'][id(blk)], blk.__name__ )

          # Copy the scheduled functions to update_blkX__Y
github cornell-brg / pymtl3 / pymtl / passes / SimLevel1.py View on Github external
def generate_tick_func( self, schedule, mode='unroll' ):

    if mode == 'normal':
      def tick_normal():
        for blk in schedule:
          blk()

      return tick_normal

    if mode == 'unroll': # Berkin's recipe
      strs = map( "  update_blk{}()".format, xrange( len( schedule ) ) )
      gen_schedule_src = py.code.Source("""
        {}
        def tick_unroll():
          # The code below does the actual calling of update blocks.
          {}

        """.format( "; ".join( map(
                    "update_blk{0} = schedule[{0}]".format,
                        xrange( len( schedule ) ) ) ),
                    "\n          ".join( strs ) ) )

      exec gen_schedule_src.compile() in locals()
      return tick_unroll

    if mode == 'hacky':

      class RewriteSelf(ast.NodeVisitor):
github cornell-brg / pymtl3 / pymtl / old_update / UpdatesExpl.py View on Github external
def _generate_tick_func( s ):
    _schedule_list = s._schedule_list

    # + Berkin's recipe
    strs = map( "  update_blk{}()".format, xrange( len( _schedule_list ) ) )
    gen_schedule_src = py.code.Source("""
      {}
      def cycle():
        # The code below does the actual calling of update blocks.
        {}

      """.format( "; ".join( map(
                  "update_blk{0} = _schedule_list[{0}]".format,
                      xrange( len( _schedule_list ) ) ) ),
                  "\n        ".join( strs ) ) )

    if verbose: print "Generate schedule source: ", gen_schedule_src
    exec gen_schedule_src.compile() in locals()

    s.cycle = cycle