code
stringlengths
1
1.72M
language
stringclasses
1 value
class cls(object): def __init__(self, x): self.x = x def one(x): return x+3 def nottwo(): pass
Python
import py from py.__.initpkg import initpkg initpkg(__name__, description="test package", exportdefs = { 'pak.mod.one': ('./pak/mod.py', 'one'), 'pak.mod.two': ('./pak/mod.py', 'nottwo'), 'notpak.notmod.notclass': ('./pak/mod.py', 'cls'), 'somenamespace': ('./pak/somenamespace.py', '*'), })
Python
""" magic - some operations which helps to extend PDB with some magic data. Actually there is only explicit tracking of data, might be extended to automatic at some point. """ # some magic stuff to have singleton of DocStorage, but initialised explicitely import weakref import py from py.__.apigen.tracer.docstorage import DocStorage from py.__.apigen.tracer.tracer import Tracer import sys class DocStorageKeeper(object): doc_storage = DocStorage() doc_storage.tracer = Tracer(doc_storage) doc_storage.from_dict({}) def set_storage(cl, ds): cl.doc_storage = ds cl.doc_storage.tracer = Tracer(ds) set_storage = classmethod(set_storage) def get_storage(): return DocStorageKeeper.doc_storage def stack_copier(frame): # copy all stack, not only frame num = 0 gather = False stack = [] try: while 1: if gather: stack.append(py.code.Frame(sys._getframe(num))) else: if sys._getframe(num) is frame.raw: gather = True num += 1 except ValueError: pass return stack def trace(keep_frames=False, frame_copier=lambda x:x): def decorator(fun): ds = get_storage() # in case we do not have this function inside doc storage, we # want to have it desc = ds.find_desc(py.code.Code(fun.func_code)) if desc is None: desc = ds.add_desc(fun.func_name, fun, keep_frames=keep_frames, frame_copier=frame_copier) def wrapper(*args, **kwargs): ds.tracer.start_tracing() retval = fun(*args, **kwargs) ds.tracer.end_tracing() return retval return wrapper return decorator
Python
import py html = py.xml.html # HTML related stuff class H(html): class Content(html.div): def __init__(self, *args): super(H.Content, self).__init__(id='apigen-content', *args) class Description(html.div): pass class NamespaceDescription(Description): pass class NamespaceItem(html.div): pass class NamespaceDef(html.h1): pass class ClassDescription(Description): pass class ClassDef(html.div): def __init__(self, classname, bases, docstring, sourcelink, attrs, methods): header = H.h1('class %s(' % (classname,)) for i, (name, href) in py.builtin.enumerate(bases): if i > 0: header.append(', ') link = name if href is not None: link = H.a(name, href=href) header.append(H.BaseDescription(link)) header.append('):') super(H.ClassDef, self).__init__(header) self.append(H.div(H.Docstring(docstring or '*no docstring available*'), sourcelink, class_='classdoc')) if attrs: self.append(H.h2('class attributes and properties:')) for name, val in attrs: self.append(H.PropertyDescription(name, val)) if methods: self.append(H.h2('methods:')) for methodhtml in methods: self.append(methodhtml) class MethodDescription(Description): pass class MethodDef(html.h2): pass class FunctionDescription(Description): def __init__(self, localname, argdesc, docstring, valuedesc, csource, callstack): infoid = 'info_%s' % (localname.replace('.', '_dot_'),) docstringid = 'docstring_%s' % (localname.replace('.', '_dot_'),) fd = H.FunctionDef(localname, argdesc, onclick=('showhideel(' 'document.getElementById("%s")); ' % (infoid,))) infodiv = H.div( H.Docstring(docstring or '*no docstring available*', id=docstringid), H.FunctionInfo(valuedesc, csource, callstack, id=infoid, style="display: none"), class_='funcdocinfo') super(H.FunctionDescription, self).__init__(fd, infodiv) class FunctionDef(html.h2): style = html.Style(cursor='pointer') def __init__(self, name, argdesc, **kwargs): class_ = kwargs.pop('class_', 'funcdef') super(H.FunctionDef, self).__init__('def %s%s:' % (name, argdesc), class_=class_, **kwargs) class FunctionInfo(html.div): def __init__(self, valuedesc, csource, callstack, **kwargs): super(H.FunctionInfo, self).__init__(valuedesc, H.br(), csource, callstack, class_='funcinfo', **kwargs) class PropertyDescription(html.div): def __init__(self, name, value): if type(value) not in [str, unicode]: value = str(value) if len(value) > 100: value = value[:100] + '...' super(H.PropertyDescription, self).__init__(name, ': ', H.em(value), class_='property') class ParameterDescription(html.div): pass class Docstring(html.div): style = html.Style(white_space='pre', color='#666', margin_left='1em', margin_bottom='1em') class Navigation(html.div): #style = html.Style(min_height='99%', float='left', margin_top='1.2em', # overflow='auto', width='15em', white_space='nowrap') pass class NavigationItem(html.div): def __init__(self, linker, linkid, name, indent, selected): href = linker.get_lazyhref(linkid) super(H.NavigationItem, self).__init__((indent * 2 * u'\xa0'), H.a(name, href=href)) if selected: self.attr.class_ = 'selected' class BaseDescription(html.span): pass class SourceSnippet(html.div): def __init__(self, text, href, sourceels=None): if sourceels is None: sourceels = [] link = text if href: link = H.a(text, href=href) super(H.SourceSnippet, self).__init__( link, H.div(*sourceels)) class PythonSource(Content): style = html.Style(font_size='0.8em') def __init__(self, *sourceels): super(H.PythonSource, self).__init__( H.div(*sourceels)) class SourceBlock(html.table): def __init__(self): tbody = H.tbody() row = H.tr() tbody.append(row) linenocell = H.td(style='width: 1%') row.append(linenocell) linecell = H.td() row.append(linecell) self.linenotable = lntable = H.table() self.linenotbody = lntbody = H.tbody() lntable.append(lntbody) linenocell.append(lntable) self.linetable = ltable = H.table() self.linetbody = ltbody = H.tbody() ltable.append(ltbody) linecell.append(ltable) super(H.SourceBlock, self).__init__(tbody, class_='codeblock') def add_line(self, lineno, els): self.linenotbody.append(H.tr(H.td(lineno, class_='lineno'))) self.linetbody.append(H.tr(H.td(H.pre(class_='code', *els), class_='codecell'))) class NonPythonSource(Content): def __init__(self, *args): super(H.NonPythonSource, self).__init__(H.pre(*args)) class DirList(Content): def __init__(self, dirs, files): dirs = [H.DirListItem(text, href) for (text, href) in dirs] files = [H.DirListItem(text, href) for (text, href) in files] super(H.DirList, self).__init__( H.h2('directories'), dirs, H.h2('files'), files, ) class DirListItem(html.div): def __init__(self, text, href): super(H.DirListItem, self).__init__(H.a(text, href=href)) class ValueDescList(html.ul): def __init__(self, *args, **kwargs): super(H.ValueDescList, self).__init__(*args, **kwargs) class ValueDescItem(html.li): pass class CallStackDescription(Description): pass class CallStackLink(html.div): def __init__(self, filename, lineno, href): super(H.CallStackLink, self).__init__( H.a("stack trace %s - line %s" % (filename, lineno), href=href)) class Hideable(html.div): def __init__(self, name, class_, *content): super(H.Hideable, self).__init__( H.div(H.a('show/hide %s' % (name,), href='#', onclick=('showhideel(getnextsibling(this));' 'return false;')), H.div(style='display: none', class_=class_, *content)))
Python
""" this contains the code that actually builds the pages using layout.py building the docs happens in two passes: the first one takes care of collecting contents and navigation items, the second builds the actual HTML """ import py from layout import LayoutPage class Project(py.__.doc.confrest.Project): """ a full project this takes care of storing information on the first pass, and building pages + indexes on the second """ def __init__(self): self.content_items = {} def add_item(self, path, content): """ add a single item (page) path is a (relative) path to the object, used for building links and navigation content is an instance of some py.xml.html item """ assert path not in self.content_items, 'duplicate path %s' % (path,) self.content_items[path] = content def build(self, outputpath): """ convert the tree to actual HTML uses the LayoutPage class below for each page and takes care of building index documents for the root and each sub directory """ opath = py.path.local(outputpath) opath.ensure(dir=True) paths = self.content_items.keys() paths.sort() for path in paths: # build the page using the LayoutPage class page = self.Page(self, path, stylesheeturl=self.stylesheet) page.contentspace.append(self.content_items[path]) ipath = opath.join(path) if not ipath.dirpath().check(): # XXX create index.html(?) ipath.ensure(file=True) ipath.write(page.unicode().encode(self.encoding)) def process(self, txtpath): """ this allows using the project from confrest """ # XXX not interesting yet, but who knows later (because of the # cool nav) if __name__ == '__main__': # XXX just to have an idea of how to use this... proj = Project() here = py.path.local('.') for fpath in here.visit(): if fpath.check(file=True): proj.add_item(fpath, convert_to_html_somehow(fpath)) proj.build()
Python
import re import sys import parser d={} # d is the dictionary of unittest changes, keyed to the old name # used by unittest. # d[old][0] is the new replacement function. # d[old][1] is the operator you will substitute, or '' if there is none. # d[old][2] is the possible number of arguments to the unittest # function. # Old Unittest Name new name operator # of args d['assertRaises'] = ('raises', '', ['Any']) d['fail'] = ('raise AssertionError', '', [0,1]) d['assert_'] = ('assert', '', [1,2]) d['failIf'] = ('assert not', '', [1,2]) d['assertEqual'] = ('assert', ' ==', [2,3]) d['failIfEqual'] = ('assert not', ' ==', [2,3]) d['assertIn'] = ('assert', ' in', [2,3]) d['assertNotIn'] = ('assert', ' not in', [2,3]) d['assertNotEqual'] = ('assert', ' !=', [2,3]) d['failUnlessEqual'] = ('assert', ' ==', [2,3]) d['assertAlmostEqual'] = ('assert round', ' ==', [2,3,4]) d['failIfAlmostEqual'] = ('assert not round', ' ==', [2,3,4]) d['assertNotAlmostEqual'] = ('assert round', ' !=', [2,3,4]) d['failUnlessAlmostEquals'] = ('assert round', ' ==', [2,3,4]) # the list of synonyms d['failUnlessRaises'] = d['assertRaises'] d['failUnless'] = d['assert_'] d['assertEquals'] = d['assertEqual'] d['assertNotEquals'] = d['assertNotEqual'] d['assertAlmostEquals'] = d['assertAlmostEqual'] d['assertNotAlmostEquals'] = d['assertNotAlmostEqual'] # set up the regular expressions we will need leading_spaces = re.compile(r'^(\s*)') # this never fails pat = '' for k in d.keys(): # this complicated pattern to match all unittests pat += '|' + r'^(\s*)' + 'self.' + k + r'\(' # \tself.whatever( old_names = re.compile(pat[1:]) linesep='\n' # nobody will really try to convert files not read # in text mode, will they? def blocksplitter(fp): '''split a file into blocks that are headed by functions to rename''' blocklist = [] blockstring = '' for line in fp: interesting = old_names.match(line) if interesting : if blockstring: blocklist.append(blockstring) blockstring = line # reset the block else: blockstring += line blocklist.append(blockstring) return blocklist def rewrite_utest(block): '''rewrite every block to use the new utest functions''' '''returns the rewritten unittest, unless it ran into problems, in which case it just returns the block unchanged. ''' utest = old_names.match(block) if not utest: return block old = utest.group(0).lstrip()[5:-1] # the name we want to replace new = d[old][0] # the name of the replacement function op = d[old][1] # the operator you will use , or '' if there is none. possible_args = d[old][2] # a list of the number of arguments the # unittest function could possibly take. if possible_args == ['Any']: # just rename assertRaises & friends return re.sub('self.'+old, new, block) message_pos = possible_args[-1] # the remaining unittests can have an optional message to print # when they fail. It is always the last argument to the function. try: indent, argl, trailer = decompose_unittest(old, block) except SyntaxError: # but we couldn't parse it! return block argnum = len(argl) if argnum not in possible_args: # sanity check - this one isn't real either return block elif argnum == message_pos: message = argl[-1] argl = argl[:-1] else: message = None if argnum is 0 or (argnum is 1 and argnum is message_pos): #unittest fail() string = '' if message: message = ' ' + message elif message_pos is 4: # assertAlmostEqual & friends try: pos = argl[2].lstrip() except IndexError: pos = '7' # default if none is specified string = '(%s -%s, %s)%s 0' % (argl[0], argl[1], pos, op ) else: # assert_, assertEquals and all the rest string = ' ' + op.join(argl) if message: string = string + ',' + message return indent + new + string + trailer def decompose_unittest(old, block): '''decompose the block into its component parts''' ''' returns indent, arglist, trailer indent -- the indentation arglist -- the arguments to the unittest function trailer -- any extra junk after the closing paren, such as #commment ''' indent = re.match(r'(\s*)', block).group() pat = re.search('self.' + old + r'\(', block) args, trailer = get_expr(block[pat.end():], ')') arglist = break_args(args, []) if arglist == ['']: # there weren't any return indent, [], trailer for i in range(len(arglist)): try: parser.expr(arglist[i].lstrip('\t ')) except SyntaxError: if i == 0: arglist[i] = '(' + arglist[i] + ')' else: arglist[i] = ' (' + arglist[i] + ')' return indent, arglist, trailer def break_args(args, arglist): '''recursively break a string into a list of arguments''' try: first, rest = get_expr(args, ',') if not rest: return arglist + [first] else: return [first] + break_args(rest, arglist) except SyntaxError: return arglist + [args] def get_expr(s, char): '''split a string into an expression, and the rest of the string''' pos=[] for i in range(len(s)): if s[i] == char: pos.append(i) if pos == []: raise SyntaxError # we didn't find the expected char. Ick. for p in pos: # make the python parser do the hard work of deciding which comma # splits the string into two expressions try: parser.expr('(' + s[:p] + ')') return s[:p], s[p+1:] except SyntaxError: # It's not an expression yet pass raise SyntaxError # We never found anything that worked. if __name__ == '__main__': import sys import py usage = "usage: %prog [-s [filename ...] | [-i | -c filename ...]]" optparser = py.compat.optparse.OptionParser(usage) def select_output (option, opt, value, optparser, **kw): if hasattr(optparser, 'output'): optparser.error( 'Cannot combine -s -i and -c options. Use one only.') else: optparser.output = kw['output'] optparser.add_option("-s", "--stdout", action="callback", callback=select_output, callback_kwargs={'output':'stdout'}, help="send your output to stdout") optparser.add_option("-i", "--inplace", action="callback", callback=select_output, callback_kwargs={'output':'inplace'}, help="overwrite files in place") optparser.add_option("-c", "--copy", action="callback", callback=select_output, callback_kwargs={'output':'copy'}, help="copy files ... fn.py --> fn_cp.py") options, args = optparser.parse_args() output = getattr(optparser, 'output', 'stdout') if output in ['inplace', 'copy'] and not args: optparser.error( '-i and -c option require at least one filename') if not args: s = '' for block in blocksplitter(sys.stdin.read()): s += rewrite_utest(block) sys.stdout.write(s) else: for infilename in args: # no error checking to see if we can open, etc. infile = file(infilename) s = '' for block in blocksplitter(infile): s += rewrite_utest(block) if output == 'inplace': outfile = file(infilename, 'w+') elif output == 'copy': # yes, just go clobber any existing .cp outfile = file (infilename[:-3]+ '_cp.py', 'w+') else: outfile = sys.stdout outfile.write(s)
Python
#
Python
#
Python
import py from py.__.process.cmdexec import ExecutionFailed font_to_package = {"times": "times", "helvetica": "times", "new century schoolbock": "newcent", "avant garde": "newcent", "palatino": "palatino", } sans_serif_fonts = {"helvetica": True, "avant garde": True, } def merge_files(pathlist, pagebreak=False): if len(pathlist) == 1: return pathlist[0].read() sectnum = False toc = False result = [] includes = {} for path in pathlist: lines = path.readlines() for line in lines: # prevent several table of contents # and especially sectnum several times if ".. contents::" in line: if not toc: toc = True result.append(line) elif ".. sectnum::" in line: if not sectnum: sectnum = True result.append(line) elif line.strip().startswith(".. include:: "): #XXX slightly unsafe inc = line.strip()[13:] if inc not in includes: includes[inc] = True result.append(line) else: result.append(line) if pagebreak: result.append(".. raw:: latex \n\n \\newpage\n\n") if pagebreak: result.pop() #remove the last pagebreak again return "".join(result) def create_stylesheet(options, path): fill_in = {} if "logo" in options: fill_in["have_logo"] = "" fill_in["logo"] = options["logo"] else: fill_in["have_logo"] = "%" fill_in["logo"] = "" if "font" in options: font = options["font"].lower() fill_in["font_package"] = font_to_package[font] fill_in["specified_font"] = "" fill_in["sans_serif"] = font not in sans_serif_fonts and "%" or "" else: fill_in["specified_font"] = "%" fill_in["sans_serif"] = "%" fill_in["font_package"] = "" if 'toc_depth' in options: fill_in["have_tocdepth"] = "" fill_in["toc_depth"] = options["toc_depth"] else: fill_in["have_tocdepth"] = "%" fill_in["toc_depth"] = "" fill_in["heading"] = options.get("heading", "") template_file = path.join("rest.sty.template") if not template_file.check(): template_file = py.magic.autopath().dirpath().join("rest.sty.template") return template_file.read() % fill_in def process_configfile(configfile, debug=False): old = py.path.local() py.path.local(configfile).dirpath().chdir() configfile = py.path.local(configfile) path = configfile.dirpath() configfile_dic = {} py.std.sys.path.insert(0, str(path)) execfile(str(configfile), configfile_dic) pagebreak = configfile_dic.get("pagebreak", False) rest_sources = [py.path.local(p) for p in configfile_dic['rest_sources']] rest = configfile.new(ext='txt') if len(rest_sources) > 1: assert rest not in rest_sources content = merge_files(rest_sources, pagebreak) if len(rest_sources) > 1: rest.write(content) sty = configfile.new(ext='sty') content = create_stylesheet(configfile_dic, path) sty.write(content) rest_options = None if 'rest_options' in configfile_dic: rest_options = configfile_dic['rest_options'] process_rest_file(rest, sty.basename, debug, rest_options) #cleanup: if not debug: sty.remove() if rest not in rest_sources: rest.remove() old.chdir() def process_rest_file(restfile, stylesheet=None, debug=False, rest_options=None): from docutils.core import publish_cmdline if not py.path.local.sysfind("pdflatex"): raise SystemExit("ERROR: pdflatex not found") old = py.path.local() f = py.path.local(restfile) path = f.dirpath() path.chdir() pdf = f.new(ext="pdf") if pdf.check(): pdf.remove() tex = f.new(ext="tex").basename options = [f, "--input-encoding=latin-1", "--graphicx-option=auto", "--traceback"] if stylesheet is not None: sty = path.join(stylesheet) if sty.check(): options.append('--stylesheet=%s' % (sty.relto(f.dirpath()), )) options.append(f.new(basename=tex)) options = map(str, options) if rest_options is not None: options.extend(rest_options) publish_cmdline(writer_name='latex', argv=options) i = 0 while i < 10: # there should never be as many as five reruns, but to be sure try: latexoutput = py.process.cmdexec('pdflatex "%s"' % (tex, )) except ExecutionFailed, e: print "ERROR: pdflatex execution failed" print "pdflatex stdout:" print e.out print "pdflatex stderr:" print e.err raise SystemExit if debug: print latexoutput if py.std.re.search("LaTeX Warning:.*Rerun", latexoutput) is None: break i += 1 old.chdir() #cleanup: if not debug: for ext in "log aux tex out".split(): p = pdf.new(ext=ext) p.remove()
Python
import py from py.__.rest import rst from py.xml import html class RestTransformer(object): def __init__(self, tree): self.tree = tree self._titledepths = {} self._listmarkers = [] def parse(self, handler): handler.startDocument() self.parse_nodes(self.tree.children, handler) handler.endDocument() def parse_nodes(self, nodes, handler): for node in nodes: name = node.__class__.__name__ if name == 'Rest': continue getattr(self, 'handle_%s' % (name,))(node, handler) def handle_Title(self, node, handler): depthkey = (node.abovechar, node.belowchar) if depthkey not in self._titledepths: if not self._titledepths: depth = 1 else: depth = max(self._titledepths.values()) + 1 self._titledepths[depthkey] = depth else: depth = self._titledepths[depthkey] handler.startTitle(depth) self.parse_nodes(node.children, handler) handler.endTitle(depth) def handle_ListItem(self, node, handler): # XXX oomph... startlist = False c = node.parent.children nodeindex = c.index(node) if nodeindex == 0: startlist = True else: prev = c[nodeindex - 1] if not isinstance(prev, rst.ListItem): startlist = True elif prev.indent < node.indent: startlist = True endlist = False if nodeindex == len(c) - 1: endlist = True else: next = c[nodeindex + 1] if not isinstance(next, rst.ListItem): endlist = True elif next.indent < node.indent: endlist = True type = isinstance(node, rst.OrderedListItem) and 'o' or 'u' handler.startListItem('u', startlist) self.parse_nodes(node.children, handler) handler.endListItem('u', endlist) def handle_Transition(self, node, handler): handler.handleTransition() def handle_Paragraph(self, node, handler): handler.startParagraph() self.parse_nodes(node.children, handler) handler.endParagraph() def handle_SubParagraph(self, node, handler): handler.startSubParagraph() self.parse_nodes(node.children, handler) handler.endSubParagraph() def handle_LiteralBlock(self, node, handler): handler.handleLiteralBlock(node._text) def handle_Text(self, node, handler): handler.handleText(node._text) def handle_Em(self, node, handler): handler.handleEm(node._text) def handle_Strong(self, node, handler): handler.handleStrong(node._text) def handle_Quote(self, node, handler): handler.handleQuote(node._text) def handle_Link(self, node, handler): handler.handleLink(node._text, node.target) def entitize(txt): for char, repl in (('&', 'amp'), ('>', 'gt'), ('<', 'lt'), ('"', 'quot'), ("'", 'apos')): txt = txt.replace(char, '&%s;' % (repl,)) return txt class HTMLHandler(object): def __init__(self, title='untitled rest document'): self.title = title self.root = None self.tagstack = [] self._currlist = None def startDocument(self): h = html.html() self.head = head = html.head() self.title = title = html.title(self.title) self._push(h) h.append(head) h.append(title) self.body = body = html.body() self._push(body) def endDocument(self): self._pop() # body self._pop() # html def startTitle(self, depth): h = getattr(html, 'h%s' % (depth,))() self._push(h) def endTitle(self, depth): self._pop() def startParagraph(self): self._push(html.p()) def endParagraph(self): self._pop() def startSubParagraph(self): self._push(html.p(**{'class': 'sub'})) def endSubParagraph(self): self._pop() def handleLiteralBlock(self, text): pre = html.pre(text) if self.tagstack: self.tagstack[-1].append(pre) else: self.root = pre def handleText(self, text): self.tagstack[-1].append(text) def handleEm(self, text): self.tagstack[-1].append(html.em(text)) def handleStrong(self, text): self.tagstack[-1].append(html.strong(text)) def startListItem(self, type, startlist): if startlist: nodename = type == 'o' and 'ol' or 'ul' self._push(getattr(html, nodename)()) self._push(html.li()) def endListItem(self, type, closelist): self._pop() if closelist: self._pop() def handleLink(self, text, target): self.tagstack[-1].append(html.a(text, href=target)) def _push(self, el): if self.tagstack: self.tagstack[-1].append(el) else: self.root = el self.tagstack.append(el) def _pop(self): self.tagstack.pop() def _html(self): return self.root.unicode() html = property(_html)
Python
# XXX this file is messy since it tries to deal with several docutils versions import py from py.__.rest.convert import convert_dot, latexformula2png import sys import docutils from docutils import nodes from docutils.parsers.rst import directives, states, roles from docutils.parsers.rst.directives import images if hasattr(images, "image"): directives_are_functions = True else: directives_are_functions = False try: from docutils.utils import unescape # docutils version > 0.3.5 except ImportError: from docutils.parsers.rst.states import unescape # docutils 0.3.5 if not directives_are_functions: ImageClass = images.Image else: class ImageClass(object): option_spec = images.image.options def run(self): return images.image(u'image', self.arguments, self.options, self.content, self.lineno, self.content_offset, self.block_text, self.state, self.state_machine) backend_to_image_format = {"html": "png", "latex": "pdf"} class GraphvizDirective(ImageClass): def convert(self, fn, path): path = py.path.local(path).dirpath() dot = path.join(fn) result = convert_dot(dot, backend_to_image_format[_backend]) return result.relto(path) def run(self): newname = self.convert(self.arguments[0], self.state.document.settings._source) text = self.block_text.replace("graphviz", "image", 1) self.block_text = text.replace(self.arguments[0], newname, 1) self.name = u'image' self.arguments = [newname] return ImageClass.run(self) def old_interface(self): def f(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine): for arg in "name arguments options content lineno " \ "content_offset block_text state state_machine".split(): setattr(self, arg, locals()[arg]) return self.run() f.arguments = (1, 0, 1) f.options = self.option_spec return f _backend = None def set_backend_and_register_directives(backend): #XXX this is only used to work around the inflexibility of docutils: # a directive does not know the target format global _backend _backend = backend if not directives_are_functions: directives.register_directive("graphviz", GraphvizDirective) else: directives.register_directive("graphviz", GraphvizDirective().old_interface()) roles.register_canonical_role("latexformula", latexformula_role) def latexformula_role(name, rawtext, text, lineno, inliner, options={}, content=[]): if _backend == 'latex': options['format'] = 'latex' return roles.raw_role(name, rawtext, text, lineno, inliner, options, content) else: # XXX: make the place of the image directory configurable sourcedir = py.path.local(inliner.document.settings._source).dirpath() imagedir = sourcedir.join("img") if not imagedir.check(): imagedir.mkdir() # create halfway senseful imagename: # use hash of formula + alphanumeric characters of it # could imagename = "%s_%s.png" % ( hash(text), "".join([c for c in text if c.isalnum()])) image = imagedir.join(imagename) latexformula2png(unescape(text, True), image) imagenode = nodes.image(image.relto(sourcedir), uri=image.relto(sourcedir)) return [imagenode], [] latexformula_role.content = True latexformula_role.options = {} def register_linkrole(role_name, callback): def source_role(name, rawtext, text, lineno, inliner, options={}, content=[]): text, target = callback(name, text) reference_node = nodes.reference(rawtext, text, name=text, refuri=target) return [reference_node], [] source_role.content = True source_role.options = {} roles.register_canonical_role(role_name, source_role)
Python
import py from py.__.process.cmdexec import ExecutionFailed # utility functions to convert between various formats format_to_dotargument = {"png": "png", "eps": "ps", "ps": "ps", "pdf": "ps", } def ps2eps(ps): # XXX write a pure python version if not py.path.local.sysfind("ps2epsi") and \ not py.path.local.sysfind("ps2eps"): raise SystemExit("neither ps2eps nor ps2epsi found") try: eps = ps.new(ext=".eps") py.process.cmdexec('ps2epsi "%s" "%s"' % (ps, eps)) except ExecutionFailed: py.process.cmdexec('ps2eps -l -f "%s"' % ps) def ps2pdf(ps, compat_level="1.2"): if not py.path.local.sysfind("gs"): raise SystemExit("ERROR: gs not found") pdf = ps.new(ext=".pdf") options = dict(OPTIONS="-dSAFER -dCompatibilityLevel=%s" % compat_level, infile=ps, outfile=pdf) cmd = ('gs %(OPTIONS)s -q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite ' '"-sOutputFile=%(outfile)s" %(OPTIONS)s -c .setpdfwrite ' '-f "%(infile)s"') % options py.process.cmdexec(cmd) return pdf def eps2pdf(eps): # XXX write a pure python version if not py.path.local.sysfind("epstopdf"): raise SystemExit("ERROR: epstopdf not found") py.process.cmdexec('epstopdf "%s"' % eps) def dvi2eps(dvi, dest=None): if dest is None: dest = eps.new(ext=".eps") command = 'dvips -q -E -n 1 -D 600 -p 1 -o "%s" "%s"' % (dest, dvi) if not py.path.local.sysfind("dvips"): raise SystemExit("ERROR: dvips not found") py.process.cmdexec(command) 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 class latexformula2png(object): def __init__(self, formula, dest, temp=None): self.formula = formula try: import Image self.Image = Image self.scale = 2 # create a larger image self.upscale = 5 # create the image upscale times larger, then scale it down except ImportError: self.scale = 2 self.upscale = 1 self.Image = None self.output_format = ('pngmono', 'pnggray', 'pngalpha')[2] if temp is None: temp = py.test.ensuretemp("latexformula") self.temp = temp self.latex = self.temp.join('formula.tex') self.dvi = self.temp.join('formula.dvi') self.eps = self.temp.join('formula.eps') self.png = self.temp.join('formula.png') self.saveas(dest) def saveas(self, dest): self.gen_latex() self.gen_dvi() dvi2eps(self.dvi, self.eps) self.gen_png() self.scale_image() self.png.copy(dest) def gen_latex(self): self.latex.write (""" \\documentclass{article} \\pagestyle{empty} \\begin{document} %s \\pagebreak \\end{document} """ % (self.formula)) def gen_dvi(self): origdir = py.path.local() self.temp.chdir() py.process.cmdexec('latex "%s"' % (self.latex)) origdir.chdir() def gen_png(self): tempdir = py.path.local.mkdtemp() re_bbox = py.std.re.compile('%%BoundingBox:\s*(\d+) (\d+) (\d+) (\d+)') eps = self.eps.read() x1, y1, x2, y2 = [int(i) for i in re_bbox.search(eps).groups()] X = x2 - x1 + 2 Y = y2 - y1 + 2 mx = -x1 my = -y1 ps = self.temp.join('temp.ps') source = self.eps ps.write(""" 1 1 1 setrgbcolor newpath -1 -1 moveto %(X)d -1 lineto %(X)d %(Y)d lineto -1 %(Y)d lineto closepath fill %(mx)d %(my)d translate 0 0 0 setrgbcolor (%(source)s) run """ % locals()) sx = int((x2 - x1) * self.scale * self.upscale) sy = int((y2 - y1) * self.scale * self.upscale) res = 72 * self.scale * self.upscale command = ('gs -q -g%dx%d -r%dx%d -sDEVICE=%s -sOutputFile="%s" ' '-dNOPAUSE -dBATCH "%s"') % ( sx, sy, res, res, self.output_format, self.png, ps) py.process.cmdexec(command) def scale_image(self): if self.Image is None: return image = self.Image.open(str(self.png)) image.resize((image.size[0] / self.upscale, image.size[1] / self.upscale), self.Image.ANTIALIAS).save(str(self.png))
Python
""" reStructuredText generation tools provides an api to build a tree from nodes, which can be converted to ReStructuredText on demand note that not all of ReST is supported, a usable subset is offered, but certain features aren't supported, and also certain details (like how links are generated, or how escaping is done) can not be controlled """ from __future__ import generators import py def escape(txt): """escape ReST markup""" if not isinstance(txt, str) and not isinstance(txt, unicode): txt = str(txt) # XXX this takes a very naive approach to escaping, but it seems to be # sufficient... for c in '\\*`|:_': txt = txt.replace(c, '\\%s' % (c,)) return txt class RestError(Exception): """ raised on containment errors (wrong parent) """ class AbstractMetaclass(type): def __new__(cls, *args): obj = super(AbstractMetaclass, cls).__new__(cls, *args) parent_cls = obj.parentclass if parent_cls is None: return obj if not isinstance(parent_cls, list): class_list = [parent_cls] else: class_list = parent_cls if obj.allow_nesting: class_list.append(obj) for _class in class_list: if not _class.allowed_child: _class.allowed_child = {obj:True} else: _class.allowed_child[obj] = True return obj class AbstractNode(object): """ Base class implementing rest generation """ sep = '' __metaclass__ = AbstractMetaclass parentclass = None # this exists to allow parent to know what # children can exist allow_nesting = False allowed_child = {} defaults = {} _reg_whitespace = py.std.re.compile('\s+') def __init__(self, *args, **kwargs): self.parent = None self.children = [] for child in args: self._add(child) for arg in kwargs: setattr(self, arg, kwargs[arg]) def join(self, *children): """ add child nodes returns a reference to self """ for child in children: self._add(child) return self def add(self, child): """ adds a child node returns a reference to the child """ self._add(child) return child def _add(self, child): if child.__class__ not in self.allowed_child: raise RestError("%r cannot be child of %r" % \ (child.__class__, self.__class__)) self.children.append(child) child.parent = self def __getitem__(self, item): return self.children[item] def __setitem__(self, item, value): self.children[item] = value def text(self): """ return a ReST string representation of the node """ return self.sep.join([child.text() for child in self.children]) def wordlist(self): """ return a list of ReST strings for this node and its children """ return [self.text()] class Rest(AbstractNode): """ Root node of a document """ sep = "\n\n" def __init__(self, *args, **kwargs): AbstractNode.__init__(self, *args, **kwargs) self.links = {} def render_links(self, check=False): """render the link attachments of the document""" assert not check, "Link checking not implemented" if not self.links: return "" link_texts = [] # XXX this could check for duplicates and remove them... for link, target in self.links.iteritems(): link_texts.append(".. _`%s`: %s" % (escape(link), target)) return "\n" + "\n".join(link_texts) + "\n\n" def text(self): outcome = [] if (isinstance(self.children[0], Transition) or isinstance(self.children[-1], Transition)): raise ValueError, ('document must not begin or end with a ' 'transition') for child in self.children: outcome.append(child.text()) # always a trailing newline text = self.sep.join([i for i in outcome if i]) + "\n" return text + self.render_links() class Transition(AbstractNode): """ a horizontal line """ parentclass = Rest def __init__(self, char='-', width=80, *args, **kwargs): self.char = char self.width = width super(Transition, self).__init__(*args, **kwargs) def text(self): return (self.width - 1) * self.char class Paragraph(AbstractNode): """ simple paragraph """ parentclass = Rest sep = " " indent = "" width = 80 def __init__(self, *args, **kwargs): # make shortcut args = list(args) for num, arg in py.builtin.enumerate(args): if isinstance(arg, str): args[num] = Text(arg) super(Paragraph, self).__init__(*args, **kwargs) def text(self): texts = [] for child in self.children: texts += child.wordlist() buf = [] outcome = [] lgt = len(self.indent) def grab(buf): outcome.append(self.indent + self.sep.join(buf)) texts.reverse() while texts: next = texts[-1] if not next: texts.pop() continue if lgt + len(self.sep) + len(next) <= self.width or not buf: buf.append(next) lgt += len(next) + len(self.sep) texts.pop() else: grab(buf) lgt = len(self.indent) buf = [] grab(buf) return "\n".join(outcome) class SubParagraph(Paragraph): """ indented sub paragraph """ indent = " " class Title(Paragraph): """ title element """ parentclass = Rest belowchar = "=" abovechar = "" def text(self): txt = self._get_text() lines = [] if self.abovechar: lines.append(self.abovechar * len(txt)) lines.append(txt) if self.belowchar: lines.append(self.belowchar * len(txt)) return "\n".join(lines) def _get_text(self): txt = [] for node in self.children: txt += node.wordlist() return ' '.join(txt) class AbstractText(AbstractNode): parentclass = [Paragraph, Title] start = "" end = "" def __init__(self, _text): self._text = _text def text(self): text = self.escape(self._text) return self.start + text + self.end def escape(self, text): if not isinstance(text, str) and not isinstance(text, unicode): text = str(text) if self.start: text = text.replace(self.start, '\\%s' % (self.start,)) if self.end and self.end != self.start: text = text.replace(self.end, '\\%s' % (self.end,)) return text class Text(AbstractText): def wordlist(self): text = escape(self._text) return self._reg_whitespace.split(text) class LiteralBlock(AbstractText): parentclass = Rest start = '::\n\n' def text(self): if not self._text.strip(): return '' text = self.escape(self._text).split('\n') for i, line in py.builtin.enumerate(text): if line.strip(): text[i] = ' %s' % (line,) return self.start + '\n'.join(text) class Em(AbstractText): start = "*" end = "*" class Strong(AbstractText): start = "**" end = "**" class Quote(AbstractText): start = '``' end = '``' class Anchor(AbstractText): start = '_`' end = '`' class Footnote(AbstractText): def __init__(self, note, symbol=False): raise NotImplemented('XXX') class Citation(AbstractText): def __init__(self, text, cite): raise NotImplemented('XXX') class ListItem(Paragraph): allow_nesting = True item_chars = '*+-' def text(self): idepth = self.get_indent_depth() indent = self.indent + (idepth + 1) * ' ' txt = '\n\n'.join(self.render_children(indent)) ret = [] item_char = self.item_chars[idepth] ret += [indent[len(item_char)+1:], item_char, ' ', txt[len(indent):]] return ''.join(ret) def render_children(self, indent): txt = [] buffer = [] def render_buffer(fro, to): if not fro: return p = Paragraph(indent=indent, *fro) p.parent = self.parent to.append(p.text()) for child in self.children: if isinstance(child, AbstractText): buffer.append(child) else: if buffer: render_buffer(buffer, txt) buffer = [] txt.append(child.text()) render_buffer(buffer, txt) return txt def get_indent_depth(self): depth = 0 current = self while (current.parent is not None and isinstance(current.parent, ListItem)): depth += 1 current = current.parent return depth class OrderedListItem(ListItem): item_chars = ["#."] * 5 class DListItem(ListItem): item_chars = None def __init__(self, term, definition, *args, **kwargs): self.term = term super(DListItem, self).__init__(definition, *args, **kwargs) def text(self): idepth = self.get_indent_depth() indent = self.indent + (idepth + 1) * ' ' txt = '\n\n'.join(self.render_children(indent)) ret = [] ret += [indent[2:], self.term, '\n', txt] return ''.join(ret) class Link(AbstractText): start = '`' end = '`_' def __init__(self, _text, target): self._text = _text self.target = target self.rest = None def text(self): if self.rest is None: self.rest = self.find_rest() if self.rest.links.get(self._text, self.target) != self.target: raise ValueError('link name %r already in use for a different ' 'target' % (self.target,)) self.rest.links[self._text] = self.target return AbstractText.text(self) def find_rest(self): # XXX little overkill, but who cares... next = self while next.parent is not None: next = next.parent return next class InternalLink(AbstractText): start = '`' end = '`_' class LinkTarget(Paragraph): def __init__(self, name, target): self.name = name self.target = target def text(self): return ".. _`%s`:%s\n" % (self.name, self.target) class Substitution(AbstractText): def __init__(self, text, **kwargs): raise NotImplemented('XXX') class Directive(Paragraph): indent = ' ' def __init__(self, name, *args, **options): self.name = name self.content = options.pop('content', []) children = list(args) super(Directive, self).__init__(*children) self.options = options def text(self): # XXX not very pretty... namechunksize = len(self.name) + 2 self.children.insert(0, Text('X' * namechunksize)) txt = super(Directive, self).text() txt = '.. %s::%s' % (self.name, txt[namechunksize + 3:],) options = '\n'.join([' :%s: %s' % (k, v) for (k, v) in self.options.iteritems()]) if options: txt += '\n%s' % (options,) if self.content: txt += '\n' for item in self.content: assert item.parentclass == Rest, 'only top-level items allowed' assert not item.indent item.indent = ' ' txt += '\n' + item.text() return txt
Python
import py import sys class File(object): """ log consumer wrapping a file(-like) object """ def __init__(self, f): assert hasattr(f, 'write') assert isinstance(f, file) or not hasattr(f, 'open') self._file = f def __call__(self, msg): """ write a message to the log """ print >>self._file, str(msg) class Path(object): """ log consumer able to write log messages into """ def __init__(self, filename, append=False, delayed_create=False, buffering=1): self._append = append self._filename = filename self._buffering = buffering if not delayed_create: self._openfile() def _openfile(self): mode = self._append and 'a' or 'w' f = open(str(self._filename), mode, buffering=self._buffering) self._file = f def __call__(self, msg): """ write a message to the log """ if not hasattr(self, "_file"): self._openfile() print >> self._file, msg def STDOUT(msg): """ consumer that writes to sys.stdout """ print >>sys.stdout, str(msg) def STDERR(msg): """ consumer that writes to sys.stderr """ print >>sys.stderr, str(msg) class Syslog: """ consumer that writes to the syslog daemon """ for priority in "LOG_EMERG LOG_ALERT LOG_CRIT LOG_ERR LOG_WARNING LOG_NOTICE LOG_INFO LOG_DEBUG".split(): try: exec("%s = py.std.syslog.%s" % (priority, priority)) except AttributeError: pass def __init__(self, priority = None): self.priority = self.LOG_INFO if priority is not None: self.priority = priority def __call__(self, msg): """ write a message to the log """ py.std.syslog.syslog(self.priority, str(msg)) def setconsumer(keywords, consumer): """ create a consumer for a set of keywords """ # normalize to tuples if isinstance(keywords, str): keywords = tuple(map(None, keywords.split())) elif hasattr(keywords, 'keywords'): keywords = keywords.keywords elif not isinstance(keywords, tuple): raise TypeError("key %r is not a string or tuple" % (keywords,)) if consumer is not None and not callable(consumer): if not hasattr(consumer, 'write'): raise TypeError("%r should be None, callable or file-like" % (consumer,)) consumer = File(consumer) py.log.Producer(keywords).set_consumer(consumer)
Python
#
Python
""" py lib's basic logging/tracing functionality EXPERIMENTAL EXPERIMENTAL EXPERIMENTAL (especially the dispatching) WARNING: this module is not allowed to contain any 'py' imports, Instead, it is very self-contained and should not depend on CPython/stdlib versions, either. One reason for these restrictions is that this module should be sendable via py.execnet across the network in an very early phase. """ class Message(object): def __init__(self, keywords, args): self.keywords = keywords self.args = args def content(self): return " ".join(map(str, self.args)) def prefix(self): return "[%s] " % (":".join(self.keywords)) def __str__(self): return self.prefix() + self.content() class Producer(object): """ Log producer API which sends messages to be logged to a 'consumer' object, which then prints them to stdout, stderr, files, etc. """ Message = Message # to allow later customization keywords2consumer = {} def __init__(self, keywords): if isinstance(keywords, str): keywords = tuple(keywords.split()) self.keywords = keywords def __repr__(self): return "<py.log.Producer %s>" % ":".join(self.keywords) def __getattr__(self, name): if '_' in name: raise AttributeError, name producer = self.__class__(self.keywords + (name,)) setattr(self, name, producer) return producer def __call__(self, *args): """ write a message to the appropriate consumer(s) """ func = self.get_consumer(self.keywords) if func is not None: func(self.Message(self.keywords, args)) def get_consumer(self, keywords): """ return a consumer matching keywords tries to find the most suitable consumer by walking, starting from the back, the list of keywords, the first consumer matching a keyword is returned (falling back to py.log.default) """ for i in range(len(self.keywords), 0, -1): try: return self.keywords2consumer[self.keywords[:i]] except KeyError: continue return self.keywords2consumer.get('default', default_consumer) def set_consumer(self, consumer): """ register a consumer matching our own keywords """ self.keywords2consumer[self.keywords] = consumer default = Producer('default') def _getstate(): return Producer.keywords2consumer.copy() def _setstate(state): Producer.keywords2consumer.clear() Producer.keywords2consumer.update(state) def default_consumer(msg): """ the default consumer, prints the message to stdout (using 'print') """ print str(msg) Producer.keywords2consumer['default'] = default_consumer
Python
class Message(object): def __init__(self, processor, *args): self.content = args self.processor = processor self.keywords = (processor.logger._ident, processor.name) def strcontent(self): return " ".join(map(str, self.content)) def strprefix(self): return '[%s] ' % ":".join(map(str, self.keywords)) def __str__(self): return self.strprefix() + self.strcontent() class Processor(object): def __init__(self, logger, name, consume): self.logger = logger self.name = name self.consume = consume def __call__(self, *args): try: consume = self.logger._override except AttributeError: consume = self.consume if consume is not None: msg = Message(self, *args) consume(msg) class Logger(object): _key2logger = {} def __init__(self, ident): self._ident = ident self._key2logger[ident] = self self._keywords = () def set_sub(self, **kwargs): for name, value in kwargs.items(): self._setsub(name, value) def ensure_sub(self, **kwargs): for name, value in kwargs.items(): if not hasattr(self, name): self._setsub(name, value) def set_override(self, consumer): self._override = lambda msg: consumer(msg) def del_override(self): try: del self._override except AttributeError: pass def _setsub(self, name, dest): assert "_" not in name setattr(self, name, Processor(self, name, dest)) def get(ident="global", **kwargs): """ return the Logger with id 'ident', instantiating if appropriate """ try: log = Logger._key2logger[ident] except KeyError: log = Logger(ident) log.ensure_sub(**kwargs) return log
Python
""" logging API ('producers' and 'consumers' connected via keywords) """
Python
import py class Directory(py.test.collect.Directory): # XXX see in which situations/platforms we want # run tests here #def recfilter(self, path): # if py.std.sys.platform == 'linux2': # if path.basename == 'greenlet': # return False # return super(Directory, self).recfilter(path) #def run(self): # py.test.skip("c-extension testing needs platform selection") pass
Python
from distutils.core import setup from distutils.extension import Extension setup ( name = "greenlet", version = "0.1", ext_modules=[Extension(name = 'greenlet', sources = ['greenlet.c'])] )
Python
import thread, sys __all__ = ['greenlet', 'main', 'getcurrent'] class greenlet(object): __slots__ = ('run', '_controller') def __init__(self, run=None, parent=None): if run is not None: self.run = run if parent is not None: self.parent = parent def switch(self, *args): global _passaround_ _passaround_ = None, args, None self._controller.switch(self) exc, val, tb = _passaround_ del _passaround_ if exc is None: if isinstance(val, tuple) and len(val) == 1: return val[0] else: return val else: raise exc, val, tb def __nonzero__(self): return self._controller.isactive() def __new__(cls, *args, **kwds): self = object.__new__(cls) self._controller = _Controller() return self def __del__(self): #print 'DEL:', self if self._controller.parent is None: return # don't kill the main greenlet while self._controller.isactive(): self._controller.kill(self) def getparent(self): return self._controller.parent def setparent(self, nparent): if not isinstance(nparent, greenlet): raise TypeError, "parent must be a greenlet" p = nparent while p is not None: if p is self: raise ValueError, "cyclic parent chain" p = p._controller.parent self._controller.parent = nparent parent = property(getparent, setparent) del getparent del setparent class _Controller: # Controllers are separated from greenlets to allow greenlets to be # deallocated while running, when their last reference goes away. # Care is taken to keep only references to controllers in thread's # frames' local variables. # _Controller.parent: the parent greenlet. # _Controller.lock: the lock used for synchronization # it is not set before the greenlet starts # it is None after the greenlet stops def __init__(self): self.parent = _current_ def isactive(self): return getattr(self, 'lock', None) is not None def switch(self, target): previous = _current_._controller self.switch_no_wait(target) # wait until someone releases this thread's lock previous.lock.acquire() def switch_no_wait(self, target): # lock tricks: each greenlet has its own lock which is almost always # in 'acquired' state: # * the current greenlet runs with its lock acquired # * all other greenlets wait on their own lock's acquire() call global _current_ try: while 1: _current_ = target lock = self.lock if lock is not None: break target = self.parent self = target._controller except AttributeError: # start the new greenlet lock = self.lock = thread.allocate_lock() lock.acquire() thread.start_new_thread(self.run_thread, (target.run,)) else: # release (re-enable) the target greenlet's thread lock.release() def run_thread(self, run): #print 'ENTERING', self global _passaround_ exc, val, tb = _passaround_ if exc is None: try: result = run(*val) except SystemExit, e: _passaround_ = None, (e,), None except: _passaround_ = sys.exc_info() else: _passaround_ = None, (result,), None self.lock = None #print 'LEAVING', self self.switch_no_wait(self.parent) def kill(self, target): # see comments in greenlet.c:green_dealloc() global _passaround_ self._parent_ = _current_ _passaround_ = SystemExit, None, None self.switch(target) exc, val, tb = _passaround_ del _passaround_ if exc is not None: if val is None: print >> sys.stderr, "Exception", "%s" % (exc,), else: print >> sys.stderr, "Exception", "%s: %s" % (exc, val), print >> sys.stderr, "in", self, "ignored" _current_ = None main = greenlet() main._controller.lock = thread.allocate_lock() main._controller.lock.acquire() _current_ = main def getcurrent(): return _current_
Python
# -*- coding: utf-8 -*- """ the py lib is a development support library featuring py.test, ad-hoc distributed execution, micro-threads and svn abstractions. """ from initpkg import initpkg version = "0.9.1-alpha" initpkg(__name__, description = "py lib: agile development and test support library", revision = int('$LastChangedRevision: 40834 $'.split(':')[1][:-1]), lastchangedate = '$LastChangedDate: 2007-03-20 09:20:33 -0300 (Tue, 20 Mar 2007) $', version = version, url = "http://codespeak.net/py", download_url = "XXX", # "http://codespeak.net/download/py/py-%s.tar.gz" %(version,), license = "MIT license", platforms = ['unix', 'linux', 'cygwin', 'win32'], author = "holger krekel, Carl Friedrich Bolz, Guido Wesdorp, Maciej Fijalkowski, Armin Rigo & others", author_email = "py-dev@codespeak.net", long_description = globals()['__doc__'], # EXPORTED API exportdefs = { # helpers for use from test functions or collectors 'test.__doc__' : ('./test/__init__.py', '__doc__'), 'test.raises' : ('./test/raises.py', 'raises'), 'test.deprecated_call' : ('./test/deprecate.py', 'deprecated_call'), 'test.skip' : ('./test/item.py', 'skip'), 'test.fail' : ('./test/item.py', 'fail'), 'test.exit' : ('./test/session.py', 'exit'), # configuration/initialization related test api 'test.config' : ('./test/config.py', 'config_per_process'), 'test.ensuretemp' : ('./test/config.py', 'ensuretemp'), 'test.cmdline.main' : ('./test/cmdline.py', 'main'), # for customization of collecting/running tests 'test.collect.Collector' : ('./test/collect.py', 'Collector'), 'test.collect.Directory' : ('./test/collect.py', 'Directory'), 'test.collect.Module' : ('./test/collect.py', 'Module'), 'test.collect.DoctestFile' : ('./test/collect.py', 'DoctestFile'), 'test.collect.Class' : ('./test/collect.py', 'Class'), 'test.collect.Instance' : ('./test/collect.py', 'Instance'), 'test.collect.Generator' : ('./test/collect.py', 'Generator'), 'test.collect.Item' : ('./test/item.py', 'Item'), 'test.collect.Function' : ('./test/item.py', 'Function'), # thread related API (still in early design phase) '_thread.WorkerPool' : ('./thread/pool.py', 'WorkerPool'), '_thread.NamedThreadPool' : ('./thread/pool.py', 'NamedThreadPool'), '_thread.ThreadOut' : ('./thread/io.py', 'ThreadOut'), # hook into the top-level standard library 'std' : ('./misc/std.py', 'std'), 'process.__doc__' : ('./process/__init__.py', '__doc__'), 'process.cmdexec' : ('./process/cmdexec.py', 'cmdexec'), # path implementation 'path.__doc__' : ('./path/__init__.py', '__doc__'), 'path.svnwc' : ('./path/svn/wccommand.py', 'SvnWCCommandPath'), 'path.svnurl' : ('./path/svn/urlcommand.py', 'SvnCommandPath'), 'path.local' : ('./path/local/local.py', 'LocalPath'), # some nice slightly magic APIs 'magic.__doc__' : ('./magic/__init__.py', '__doc__'), 'magic.greenlet' : ('./magic/greenlet.py', 'greenlet'), 'magic.invoke' : ('./magic/invoke.py', 'invoke'), 'magic.revoke' : ('./magic/invoke.py', 'revoke'), 'magic.patch' : ('./magic/patch.py', 'patch'), 'magic.revert' : ('./magic/patch.py', 'revert'), 'magic.autopath' : ('./magic/autopath.py', 'autopath'), 'magic.AssertionError' : ('./magic/assertion.py', 'AssertionError'), # python inspection/code-generation API 'code.__doc__' : ('./code/__init__.py', '__doc__'), 'code.compile' : ('./code/source.py', 'compile_'), 'code.Source' : ('./code/source.py', 'Source'), 'code.Code' : ('./code/code.py', 'Code'), 'code.Frame' : ('./code/frame.py', 'Frame'), 'code.ExceptionInfo' : ('./code/excinfo.py', 'ExceptionInfo'), 'code.Traceback' : ('./code/traceback2.py', 'Traceback'), # backports and additions of builtins 'builtin.__doc__' : ('./builtin/__init__.py', '__doc__'), 'builtin.enumerate' : ('./builtin/enumerate.py', 'enumerate'), 'builtin.reversed' : ('./builtin/reversed.py', 'reversed'), 'builtin.sorted' : ('./builtin/sorted.py', 'sorted'), 'builtin.BaseException' : ('./builtin/exception.py', 'BaseException'), 'builtin.set' : ('./builtin/set.py', 'set'), 'builtin.frozenset' : ('./builtin/set.py', 'frozenset'), # gateways into remote contexts 'execnet.__doc__' : ('./execnet/__init__.py', '__doc__'), 'execnet.SocketGateway' : ('./execnet/register.py', 'SocketGateway'), 'execnet.PopenGateway' : ('./execnet/register.py', 'PopenGateway'), 'execnet.SshGateway' : ('./execnet/register.py', 'SshGateway'), # execnet scripts 'execnet.RSync' : ('./execnet/rsync.py', 'RSync'), # input-output helping 'io.__doc__' : ('./io/__init__.py', '__doc__'), 'io.dupfile' : ('./io/dupfile.py', 'dupfile'), 'io.FDCapture' : ('./io/fdcapture.py', 'FDCapture'), 'io.StdCapture' : ('./io/stdcapture.py', 'StdCapture'), 'io.StdCaptureFD' : ('./io/stdcapture.py', 'StdCaptureFD'), # error module, defining all errno's as Classes 'error' : ('./misc/error.py', 'error'), # small and mean xml/html generation 'xml.__doc__' : ('./xmlobj/__init__.py', '__doc__'), 'xml.html' : ('./xmlobj/html.py', 'html'), 'xml.Tag' : ('./xmlobj/xml.py', 'Tag'), 'xml.raw' : ('./xmlobj/xml.py', 'raw'), 'xml.Namespace' : ('./xmlobj/xml.py', 'Namespace'), 'xml.escape' : ('./xmlobj/misc.py', 'escape'), # logging API ('producers' and 'consumers' connected via keywords) 'log.__doc__' : ('./log/__init__.py', '__doc__'), 'log.Producer' : ('./log/producer.py', 'Producer'), 'log.default' : ('./log/producer.py', 'default'), 'log._getstate' : ('./log/producer.py', '_getstate'), 'log._setstate' : ('./log/producer.py', '_setstate'), 'log.setconsumer' : ('./log/consumer.py', 'setconsumer'), 'log.Path' : ('./log/consumer.py', 'Path'), 'log.STDOUT' : ('./log/consumer.py', 'STDOUT'), 'log.STDERR' : ('./log/consumer.py', 'STDERR'), 'log.Syslog' : ('./log/consumer.py', 'Syslog'), 'log.get' : ('./log/logger.py', 'get'), # compatibility modules (taken from 2.4.4) 'compat.__doc__' : ('./compat/__init__.py', '__doc__'), 'compat.doctest' : ('./compat/doctest.py', '*'), 'compat.optparse' : ('./compat/optparse.py', '*'), 'compat.textwrap' : ('./compat/textwrap.py', '*'), 'compat.subprocess' : ('./compat/subprocess.py', '*'), })
Python
from struct import pack, unpack, calcsize def message(tp, *values): strtype = type('') typecodes = [''] for v in values: if type(v) is strtype: typecodes.append('%ds' % len(v)) elif 0 <= v < 256: typecodes.append('B') else: typecodes.append('l') typecodes = ''.join(typecodes) assert len(typecodes) < 256 return pack(("!B%dsc" % len(typecodes)) + typecodes, len(typecodes), typecodes, tp, *values) def decodemessage(data): if data: limit = ord(data[0]) + 1 if len(data) >= limit: typecodes = "!c" + data[1:limit] end = limit + calcsize(typecodes) if len(data) >= end: return unpack(typecodes, data[limit:end]), data[end:] #elif end > 1000000: # raise OverflowError return None, data
Python
#import os import struct from collections import deque class InvalidPacket(Exception): pass FLAG_NAK1 = 0xE0 FLAG_NAK = 0xE1 FLAG_REG = 0xE2 FLAG_CFRM = 0xE3 FLAG_RANGE_START = 0xE0 FLAG_RANGE_STOP = 0xE4 max_old_packets = 256 # must be <= 256 class PipeLayer(object): timeout = 1 headersize = 4 def __init__(self): #self.localid = os.urandom(4) #self.remoteid = None self.cur_time = 0 self.out_queue = deque() self.out_nextseqid = 0 self.out_nextrepeattime = None self.in_nextseqid = 0 self.in_outoforder = {} self.out_oldpackets = deque() self.out_flags = FLAG_REG self.out_resend = 0 self.out_resend_skip = False def queue(self, data): if data: self.out_queue.appendleft(data) def queue_size(self): total = 0 for data in self.out_queue: total += len(data) return total def in_sync(self): return not self.out_queue and self.out_nextrepeattime is None def settime(self, curtime): self.cur_time = curtime if self.out_queue: if len(self.out_oldpackets) < max_old_packets: return 0 # more data to send now if self.out_nextrepeattime is not None: return max(0, self.out_nextrepeattime - curtime) else: return None def encode(self, maxlength): #print ' '*self._dump_indent, '--- OUTQ', self.out_resend, self.out_queue if len(self.out_oldpackets) >= max_old_packets: # congestion, stalling payload = 0 else: payload = maxlength - 4 if payload <= 0: raise ValueError("encode(): buffer too small") if (self.out_nextrepeattime is not None and self.out_nextrepeattime <= self.cur_time): # no ACK received so far, send a packet (possibly empty) if not self.out_queue: payload = 0 else: if not self.out_queue: # no more data to send return None if payload == 0: # congestion return None # prepare a packet seqid = self.out_nextseqid flags = self.out_flags self.out_flags = FLAG_REG # clear out the flags for the next time if payload > 0: self.out_nextseqid = (seqid + 1) & 0xFFFF data = self.out_queue.pop() packetlength = len(data) if self.out_resend > 0: if packetlength > payload: raise ValueError("XXX need constant buffer size for now") self.out_resend -= 1 if self.out_resend_skip: if self.out_resend > 0: self.out_queue.pop() self.out_resend -= 1 self.out_nextseqid = (seqid + 2) & 0xFFFF self.out_resend_skip = False packetpayload = data else: packet = [] while packetlength <= payload: packet.append(data) if not self.out_queue: break data = self.out_queue.pop() packetlength += len(data) else: rest = len(data) + payload - packetlength packet.append(data[:rest]) self.out_queue.append(data[rest:]) packetpayload = ''.join(packet) self.out_oldpackets.appendleft(packetpayload) #print ' '*self._dump_indent, '--- OLDPK', self.out_oldpackets else: # a pure ACK packet, no payload if self.out_oldpackets and flags == FLAG_REG: flags = FLAG_CFRM packetpayload = '' packet = struct.pack("!BBH", flags, self.in_nextseqid & 0xFF, seqid) + packetpayload if self.out_oldpackets: self.out_nextrepeattime = self.cur_time + self.timeout else: self.out_nextrepeattime = None #self.dump('OUT', packet) return packet def decode(self, rawdata): if len(rawdata) < 4: raise InvalidPacket #print ' '*self._dump_indent, '------ out %d (+%d) in %d' % (self.out_nextseqid, self.out_resend, self.in_nextseqid) #self.dump('IN ', rawdata) in_flags, ack_seqid, in_seqid = struct.unpack("!BBH", rawdata[:4]) if not (FLAG_RANGE_START <= in_flags < FLAG_RANGE_STOP): raise InvalidPacket in_diff = (in_seqid - self.in_nextseqid ) & 0xFFFF ack_diff = (self.out_nextseqid + self.out_resend - ack_seqid) & 0xFF if in_diff >= max_old_packets: return '' # invalid, but can occur as a late repetition if ack_diff != len(self.out_oldpackets): # forget all acknowledged packets if ack_diff > len(self.out_oldpackets): return '' # invalid, but can occur with packet reordering while len(self.out_oldpackets) > ack_diff: #print ' '*self._dump_indent, '--- POP', repr(self.out_oldpackets[-1]) self.out_oldpackets.pop() if self.out_oldpackets: self.out_nextrepeattime = self.cur_time + self.timeout else: self.out_nextrepeattime = None # all packets ACKed if in_flags == FLAG_NAK or in_flags == FLAG_NAK1: # this is a NAK: resend the old packets as far as they've not # also been ACK'ed in the meantime (can occur with reordering) while self.out_resend < len(self.out_oldpackets): self.out_queue.append(self.out_oldpackets[self.out_resend]) self.out_resend += 1 self.out_nextseqid = (self.out_nextseqid - 1) & 0xFFFF #print ' '*self._dump_indent, '--- REP', self.out_nextseqid, repr(self.out_queue[-1]) self.out_resend_skip = in_flags == FLAG_NAK1 elif in_flags == FLAG_CFRM: # this is a CFRM: request for confirmation self.out_nextrepeattime = self.cur_time # receive this packet's payload if it is the next in the sequence if in_diff == 0: if len(rawdata) > 4: #print ' '*self._dump_indent, 'RECV ', self.in_nextseqid, repr(rawdata[4:]) self.in_nextseqid = (self.in_nextseqid + 1) & 0xFFFF result = [rawdata[4:]] while self.in_nextseqid in self.in_outoforder: result.append(self.in_outoforder.pop(self.in_nextseqid)) self.in_nextseqid = (self.in_nextseqid + 1) & 0xFFFF return ''.join(result) else: # we missed at least one intermediate packet: send a NAK if len(rawdata) > 4: self.in_outoforder[in_seqid] = rawdata[4:] if ((self.in_nextseqid + 1) & 0xFFFF) in self.in_outoforder: self.out_flags = FLAG_NAK1 else: self.out_flags = FLAG_NAK self.out_nextrepeattime = self.cur_time return '' _dump_indent = 0 def dump(self, dir, rawdata): in_flags, ack_seqid, in_seqid = struct.unpack("!BBH", rawdata[:4]) print ' ' * self._dump_indent, dir, if in_flags == FLAG_NAK: print 'NAK', elif in_flags == FLAG_NAK1: print 'NAK1', elif in_flags == FLAG_CFRM: print 'CFRM', #print ack_seqid, in_seqid, '(%d bytes)' % (len(rawdata)-4,) print ack_seqid, in_seqid, repr(rawdata[4:]) def pipe_over_udp(udpsock, send_fd=-1, recv_fd=-1, timeout=1.0, inactivity_timeout=None): """Example: send all data showing up in send_fd over the given UDP socket, and write incoming data into recv_fd. The send_fd and recv_fd are plain file descriptors. When an EOF is read from send_fd, this function returns (after making sure that all data was received by the remote side). """ import os from select import select from time import time p = PipeLayer() p.timeout = timeout iwtdlist = [udpsock] if send_fd >= 0: iwtdlist.append(send_fd) running = True while running or not p.in_sync(): delay = delay1 = p.settime(time()) if delay is None: delay = inactivity_timeout iwtd, owtd, ewtd = select(iwtdlist, [], [], delay) if iwtd: if send_fd in iwtd: data = os.read(send_fd, 1500 - p.headersize) if not data: # EOF iwtdlist.remove(send_fd) running = False else: #print 'queue', len(data) p.queue(data) if udpsock in iwtd: packet = udpsock.recv(65535) #print 'decode', len(packet) p.settime(time()) data = p.decode(packet) i = 0 while i < len(data): i += os.write(recv_fd, data[i:]) elif delay1 is None: break # long inactivity p.settime(time()) packet = p.encode(1500) if packet: #print 'send', len(packet) #if os.urandom(1) >= '\x08': # emulate packet losses udpsock.send(packet) class PipeOverUdp(object): def __init__(self, udpsock, timeout=1.0): import thread, os self.os = os self.sendpipe = os.pipe() self.recvpipe = os.pipe() thread.start_new_thread(pipe_over_udp, (udpsock, self.sendpipe[0], self.recvpipe[1], timeout)) def __del__(self): os = self.os if self.sendpipe: os.close(self.sendpipe[0]) os.close(self.sendpipe[1]) self.sendpipe = None if self.recvpipe: os.close(self.recvpipe[0]) os.close(self.recvpipe[1]) self.recvpipe = None close = __del__ def send(self, data): if not self.sendpipe: raise IOError("I/O operation on a closed PipeOverUdp") return self.os.write(self.sendpipe[1], data) def sendall(self, data): i = 0 while i < len(data): i += self.send(data[i:]) def recv(self, bufsize): if not self.recvpipe: raise IOError("I/O operation on a closed PipeOverUdp") return self.os.read(self.recvpipe[0], bufsize) def recvall(self, bufsize): buf = [] while bufsize > 0: data = self.recv(bufsize) buf.append(data) bufsize -= len(data) return ''.join(buf) def fileno(self): if not self.recvpipe: raise IOError("I/O operation on a closed PipeOverUdp") return self.recvpipe[0] def ofileno(self): if not self.sendpipe: raise IOError("I/O operation on a closed PipeOverUdp") return self.sendpipe[1]
Python
""" This is a base implementation of thread-like network programming on top of greenlets. From API available here it's quite unlikely that you would like to use anything except wait(). Higher level interface is available in pipe directory """ import os, sys try: from stackless import greenlet except ImportError: import py greenlet = py.magic.greenlet from collections import deque from select import select as _select from time import time as _time from heapq import heappush, heappop, heapify TRACE = False def meetingpoint(): senders = deque() # list of senders, or [None] if Giver closed receivers = deque() # list of receivers, or [None] if Receiver closed return (MeetingPointGiver(senders, receivers), MeetingPointAccepter(senders, receivers)) def producer(func, *args, **kwds): iterable = func(*args, **kwds) giver, accepter = meetingpoint() def autoproducer(): try: giver.wait() for obj in iterable: giver.give(obj) giver.wait() finally: giver.close() autogreenlet(autoproducer) return accepter class MeetingPointBase(object): def __init__(self, senders, receivers): self.senders = senders self.receivers = receivers self.g_active = g_active def close(self): while self.senders: if self.senders[0] is None: break packet = self.senders.popleft() if packet.g_from is not None: self.g_active.append(packet.g_from) else: self.senders.append(None) while self.receivers: if self.receivers[0] is None: break other = self.receivers.popleft() self.g_active.append(other) else: self.receivers.append(None) __del__ = close def closed(self): return self.receivers and self.receivers[0] is None class MeetingPointGiver(MeetingPointBase): def give(self, obj): if self.receivers: if self.receivers[0] is None: raise MeetingPointClosed other = self.receivers.popleft() g_active.append(g_getcurrent()) packet = _Packet() packet.payload = obj other.switch(packet) if not packet.accepted: raise Interrupted("packet not accepted") else: packet = _Packet() packet.g_from = g_getcurrent() packet.payload = obj try: self.senders.append(packet) g_dispatcher.switch() if not packet.accepted: raise Interrupted("packet not accepted") except: remove_by_id(self.senders, packet) raise def give_queued(self, obj): if self.receivers: self.give(obj) else: packet = _Packet() packet.g_from = None packet.payload = obj self.senders.append(packet) def ready(self): return self.receivers and self.receivers[0] is not None def wait(self): if self.receivers: if self.receivers[0] is None: raise MeetingPointClosed else: packet = _Packet() packet.g_from = g_getcurrent() packet.empty = True self.senders.append(packet) try: g_dispatcher.switch() if not packet.accepted: raise Interrupted("no accepter found") except: remove_by_id(self.senders, packet) raise def trigger(self): if self.ready(): self.give(None) class MeetingPointAccepter(MeetingPointBase): def accept(self): while self.senders: if self.senders[0] is None: raise MeetingPointClosed packet = self.senders.popleft() packet.accepted = True if packet.g_from is not None: g_active.append(packet.g_from) if not packet.empty: return packet.payload g = g_getcurrent() self.receivers.append(g) try: packet = g_dispatcher.switch() except: remove_by_id(self.receivers, g) raise if type(packet) is not _Packet: remove_by_id(self.receivers, g) raise Interrupted("no packet") packet.accepted = True return packet.payload def ready(self): for packet in self.senders: if packet is None: return False if not packet.empty: return True return False def wait_trigger(self, timeout=None, default=None): if timeout is None: return self.accept() else: timer = Timer(timeout) try: try: return self.accept() finally: timer.stop() except Interrupted: if timer.finished: return default raise class MeetingPointClosed(greenlet.GreenletExit): pass class Interrupted(greenlet.GreenletExit): pass class ConnexionClosed(greenlet.GreenletExit): pass class _Packet(object): empty = False accepted = False def remove_by_id(d, obj): lst = [x for x in d if x is not obj] d.clear() d.extend(lst) def wait_input(sock): _register(g_iwtd, sock) def recv(sock, bufsize): wait_input(sock) buf = sock.recv(bufsize) if not buf: raise ConnexionClosed("inbound connexion closed") return buf def recvall(sock, bufsize): in_front = False data = [] while bufsize > 0: _register(g_iwtd, sock, in_front=in_front) buf = sock.recv(bufsize) if not buf: raise ConnexionClosed("inbound connexion closed") data.append(buf) bufsize -= len(buf) in_front = True return ''.join(data) def read(fd, bufsize): assert fd >= 0 wait_input(fd) buf = os.read(fd, bufsize) if not buf: raise ConnexionClosed("inbound connexion closed") return buf def readall(fd, bufsize): assert fd >= 0 in_front = False data = [] while bufsize > 0: _register(g_iwtd, fd, in_front=in_front) buf = os.read(fd, bufsize) if not buf: raise ConnexionClosed("inbound connexion closed") data.append(buf) bufsize -= len(buf) in_front = True return ''.join(data) def wait_output(sock): _register(g_owtd, sock) def sendall(sock, buffer): in_front = False while buffer: _register(g_owtd, sock, in_front=in_front) count = sock.send(buffer) buffer = buffer[count:] in_front = True def writeall(fd, buffer): assert fd >= 0 in_front = False while buffer: _register(g_owtd, fd, in_front=in_front) count = os.write(fd, buffer) if not count: raise ConnexionClosed("outbound connexion closed") buffer = buffer[count:] in_front = True def sleep(duration): timer = Timer(duration) try: _suspend_forever() finally: ok = timer.finished timer.stop() if not ok: raise Interrupted def _suspend_forever(): g_dispatcher.switch() def oneof(*callables): assert callables for c in callables: assert callable(c) greenlets = [tracinggreenlet(c) for c in callables] g_active.extend(greenlets) res = g_dispatcher.switch() for g in greenlets: g.interrupt() return res def allof(*callables): for c in callables: assert callable(c) greenlets = [tracinggreenlet(lambda i=i, c=c: (i, c())) for i, c in enumerate(callables)] g_active.extend(greenlets) result = [None] * len(callables) for _ in callables: num, res = g_dispatcher.switch() result[num] = res return tuple(result) class Timer(object): started = False finished = False def __init__(self, timeout): self.g = g_getcurrent() entry = (_time() + timeout, self) if g_timers_mixed: g_timers.append(entry) else: heappush(g_timers, entry) def stop(self): global g_timers_mixed if not self.finished: for i, (activationtime, timer) in enumerate(g_timers): if timer is self: g_timers[i] = g_timers[-1] g_timers.pop() g_timers_mixed = True break self.finished = True # ____________________________________________________________ class tracinggreenlet(greenlet): def __init__(self, function, *args, **kwds): self.function = function self.args = args self.kwds = kwds def __repr__(self): ## args = ', '.join([repr(s) for s in self.args] + ## ['%s=%r' % keyvalue for keyvalue in self.kwds.items()]) ## return '<autogreenlet %s(%s)>' % (self.function.__name__, args) return '<%s %s at %s>' % (self.__class__.__name__, self.function.__name__, hex(id(self))) def run(self): self.trace("start") try: res = self.function(*self.args, **self.kwds) except Exception, e: self.trace("stop (%s%s)", e.__class__.__name__, str(e) and (': '+str(e))) raise else: self.trace("done") return res def trace(self, msg, *args): if TRACE: print self, msg % args def interrupt(self): self.throw(Interrupted) class autogreenlet(tracinggreenlet): def __init__(self, *args, **kwargs): super(autogreenlet, self).__init__(*args, **kwargs) self.parent = g_dispatcher g_active.append(self) g_active = deque() g_iwtd = {} g_owtd = {} g_timers = [] g_timers_mixed = False g_getcurrent = greenlet.getcurrent def _register(g_wtd, sock, in_front=False): d = g_wtd.setdefault(sock, deque()) g = g_getcurrent() if in_front: d.appendleft(g) else: d.append(g) try: if g_dispatcher.switch() is not g_wtd: raise Interrupted except: remove_by_id(d, g) raise ##def _unregister_timer(): ## ... def check_dead_greenlets(mapping): to_remove = [i for i, v in mapping.items() if not v] for k in to_remove: del mapping[k] #def check_waiters(active): # if active in g_waiters: # for g in g_waiters[active]: # g.switch() # del g_waiters[active] def dispatcher_mainloop(): global g_timers_mixed GreenletExit = greenlet.GreenletExit while 1: try: while g_active: #print 'active:', g_active[0] g_active.popleft().switch() # active.switch() # if active.dead: # check_waiters(active) # del active if g_timers: if g_timers_mixed: heapify(g_timers) g_timers_mixed = False activationtime, timer = g_timers[0] delay = activationtime - _time() if delay <= 0.0: if timer.started: heappop(g_timers) #print 'timeout:', g timer.finished = True timer.g.switch() # if timer.g.dead: # check_waiters(timer.g) continue delay = 0.0 timer.started = True else: check_dead_greenlets(g_iwtd) check_dead_greenlets(g_owtd) if not (g_iwtd or g_owtd): # nothing to do, switch to the main greenlet g_dispatcher.parent.switch() continue delay = None #print 'selecting...', g_iwtd.keys(), g_owtd.keys(), delay iwtd, owtd, _ = _select(g_iwtd.keys(), g_owtd.keys(), [], delay) #print 'done' for s in owtd: if s in g_owtd: d = g_owtd[s] #print 'owtd:', d[0] g = d.popleft() if not d: try: del g_owtd[s] except KeyError: pass g.switch(g_owtd) # if g.dead: # check_waiters(g) for s in iwtd: if s in g_iwtd: d = g_iwtd[s] #print 'iwtd:', d[0] g = d.popleft() if not d: try: del g_iwtd[s] except KeyError: pass g.switch(g_iwtd) # if g.dead: # check_waiters(g) except GreenletExit: raise except: import sys g_dispatcher.parent.throw(*sys.exc_info()) g_dispatcher = greenlet(dispatcher_mainloop) #g_waiters = {}
Python
from py.__.green import greensock2 import socket, errno, os error = socket.error class _delegate(object): def __init__(self, methname): self.methname = methname def __get__(self, obj, typ=None): result = getattr(obj._s, self.methname) setattr(obj, self.methname, result) return result class GreenSocket(object): def __init__(self, family = socket.AF_INET, type = socket.SOCK_STREAM, proto = 0): self._s = socket.socket(family, type, proto) self._s.setblocking(False) def fromsocket(cls, s): if isinstance(s, GreenSocket): s = s._s result = GreenSocket.__new__(cls) result._s = s s.setblocking(False) return result fromsocket = classmethod(fromsocket) def accept(self): while 1: try: s, addr = self._s.accept() break except error, e: if e.args[0] not in (errno.EAGAIN, errno.EWOULDBLOCK): raise self.wait_input() return self.fromsocket(s), addr bind = _delegate("bind") close = _delegate("close") def connect(self, addr): err = self.connect_ex(addr) if err: raise error(err, os.strerror(err)) def connect_ex(self, addr): err = self._s.connect_ex(addr) if err == errno.EINPROGRESS: greensock2.wait_output(self._s) err = self._s.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) return err #XXX dup fileno = _delegate("fileno") getpeername = _delegate("getpeername") getsockname = _delegate("getsockname") getsockopt = _delegate("getsockopt") listen = _delegate("listen") def makefile(self, mode='r', bufsize=-1): # hack, but reusing the internal socket._fileobject should just work return socket._fileobject(self, mode, bufsize) def recv(self, bufsize): return greensock2.recv(self._s, bufsize) def recvall(self, bufsize): return greensock2.recvall(self._s, bufsize) def recvfrom(self, bufsize): self.wait_input() buf, addr = self._s.recvfrom(bufsize) if not buf: raise ConnexionClosed("inbound connexion closed") return buf, addr def send(self, data): self.wait_output() return self._s.send(data) def sendto(self, data, addr): self.wait_output() return self._s.sendto(data, addr) def sendall(self, data): greensock2.sendall(self._s, data) setsockopt = _delegate("setsockopt") shutdown = _delegate("shutdown") def shutdown_rd(self): try: self._s.shutdown(socket.SHUT_RD) except error: pass def shutdown_wr(self): try: self._s.shutdown(socket.SHUT_WR) except error: pass def wait_input(self): greensock2.wait_input(self._s) def wait_output(self): greensock2.wait_output(self._s)
Python
from py.__.green.pipe.common import BufferedInput class MeetingPointInput(BufferedInput): def __init__(self, accepter): self.accepter = accepter def wait_input(self): while not self.in_buf: self.in_buf = self.accepter.accept() def shutdown_rd(self): self.accepter.close() class MeetingPointOutput(BufferedInput): def __init__(self, giver): self.giver = giver def wait_output(self): self.giver.wait() def sendall(self, buffer): self.giver.give(buffer) def shutdown_wr(self): self.giver.close()
Python
from py.__.green import greensock2 VERBOSE = True if VERBOSE: def log(msg, *args): print '*', msg % args else: def log(msg, *args): pass class BufferedInput(object): in_buf = '' def recv(self, bufsize): self.wait_input() buf = self.in_buf[:bufsize] self.in_buf = self.in_buf[bufsize:] return buf def recvall(self, bufsize): result = [] while bufsize > 0: buf = self.recv(bufsize) result.append(buf) bufsize -= len(buf) return ''.join(result) # ____________________________________________________________ def forwardpipe(s1, s2): try: while 1: s2.wait_output() buffer = s1.recv(32768) log('[%r -> %r] %r', s1, s2, buffer) s2.sendall(buffer) del buffer finally: s2.shutdown_wr() s1.shutdown_rd() def linkpipes(s1, s2): greensock2.autogreenlet(forwardpipe, s1, s2) greensock2.autogreenlet(forwardpipe, s2, s1)
Python
import os from py.__.green import greensock2 class FDInput(object): def __init__(self, read_fd, close=True): self.read_fd = read_fd self._close = close # a flag or a callback def shutdown_rd(self): fd = self.read_fd if fd is not None: self.read_fd = None close = self._close if close: self._close = False if close == True: os.close(fd) else: close() __del__ = shutdown_rd def wait_input(self): greensock2.wait_input(self.read_fd) def recv(self, bufsize): ## f = open('LOG', 'a') ## import os; print >> f, '[%d] RECV' % (os.getpid(),) ## f.close() res = greensock2.read(self.read_fd, bufsize) ## f = open('LOG', 'a') ## import os; print >> f, '[%d] RECV %r' % (os.getpid(), res) ## f.close() return res def recvall(self, bufsize): return greensock2.readall(self.read_fd, bufsize) class FDOutput(object): def __init__(self, write_fd, close=True): self.write_fd = write_fd self._close = close # a flag or a callback def shutdown_wr(self): fd = self.write_fd if fd is not None: self.write_fd = None close = self._close if close: self._close = False if close == True: os.close(fd) else: close() __del__ = shutdown_wr def wait_output(self): greensock2.wait_output(self.write_fd) def sendall(self, buffer): ## f = open('LOG', 'a') ## import os; print >> f, '[%d] %r' % (os.getpid(), buffer) ## f.close() greensock2.writeall(self.write_fd, buffer)
Python
""" This is a higher level network interface based on top of greensock2. Objects here are ready to use, specific examples are listed in tests (test_pipelayer and test_greensock2). The limitation is that you're not supposed to use threads + blocking I/O at all. """
Python
import BaseHTTPServer from py.__.green import greensock2 from py.__.green.pipe.gsocket import GreenSocket class GreenMixIn: """Mix-in class to handle each request in a new greenlet.""" def process_request_greenlet(self, request, client_address): """Same as in BaseServer but as a greenlet. In addition, exception handling is done here. """ try: self.finish_request(request, client_address) self.close_request(request) except: self.handle_error(request, client_address) self.close_request(request) def process_request(self, request, client_address): """Start a new greenlet to process the request.""" greensock2.autogreenlet(self.process_request_greenlet, request, client_address) class GreenHTTPServer(GreenMixIn, BaseHTTPServer.HTTPServer): protocol_version = "HTTP/1.1" def server_bind(self): self.socket = GreenSocket.fromsocket(self.socket) BaseHTTPServer.HTTPServer.server_bind(self) def test_simple(handler_class=None): if handler_class is None: from SimpleHTTPServer import SimpleHTTPRequestHandler handler_class = SimpleHTTPRequestHandler server_address = ('', 8000) httpd = GreenHTTPServer(server_address, handler_class) sa = httpd.socket.getsockname() print "Serving HTTP on", sa[0], "port", sa[1], "..." httpd.serve_forever()
Python
""" This is an implementation of an execnet protocol on top of a transport layer provided by the greensock2 interface. It has the same semantics, but does not use threads at all (which makes it suitable for specific enviroments, like pypy-c). There are some features lacking, most notable: - callback support for channels - socket gateway - bootstrapping (there is assumption of pylib being available on remote side, which is not always true) """ import sys, os, py, inspect from py.__.green import greensock2 from py.__.green.msgstruct import message, decodemessage MSG_REMOTE_EXEC = 'r' MSG_OBJECT = 'o' MSG_ERROR = 'e' MSG_CHAN_CLOSE = 'c' MSG_FATAL = 'f' MSG_CHANNEL = 'n' class Gateway(object): def __init__(self, input, output, is_remote=False): self.input = input self.output = output self.nextchannum = int(is_remote) self.receivers = {} self.greenlet = greensock2.autogreenlet(self.serve_forever, is_remote) def remote_exec(self, remote_source): remote_source = py.code.Source(remote_source) chan = self.newchannel() msg = message(MSG_REMOTE_EXEC, chan.n, str(remote_source)) self.output.sendall(msg) return chan def newchannel(self): n = self.nextchannum self.nextchannum += 2 return self.make_channel(n) def make_channel(self, n): giver, accepter = greensock2.meetingpoint() assert n not in self.receivers self.receivers[n] = giver return Channel(self, n, accepter) def serve_forever(self, is_remote=False): try: buffer = "" while 1: msg, buffer = decodemessage(buffer) if msg is None: buffer += self.input.recv(16384) else: handler = HANDLERS[msg[0]] handler(self, *msg[1:]) except greensock2.greenlet.GreenletExit: raise except: if is_remote: msg = message(MSG_FATAL, format_error(*sys.exc_info())) self.output.sendall(msg) else: raise def msg_remote_exec(self, n, source): def do_execute(channel): try: d = {'channel': channel} exec source in d except: channel.report_error(*sys.exc_info()) else: channel.close() greensock2.autogreenlet(do_execute, self.make_channel(n)) def msg_object(self, n, objrepr): obj = eval(objrepr) if n in self.receivers: self.receivers[n].give_queued(obj) def msg_error(self, n, s): if n in self.receivers: self.receivers[n].give_queued(RemoteError(s)) self.receivers[n].close() del self.receivers[n] def msg_chan_close(self, n): if n in self.receivers: self.receivers[n].close() del self.receivers[n] def msg_channel(self, n, m): if n in self.receivers: self.receivers[n].give_queued(self.make_channel(m)) def msg_fatal(self, s): raise RemoteError(s) HANDLERS = { MSG_REMOTE_EXEC: Gateway.msg_remote_exec, MSG_OBJECT: Gateway.msg_object, MSG_ERROR: Gateway.msg_error, MSG_CHAN_CLOSE: Gateway.msg_chan_close, MSG_CHANNEL: Gateway.msg_channel, MSG_FATAL: Gateway.msg_fatal, } class Channel(object): def __init__(self, gw, n, accepter): self.gw = gw self.n = n self.accepter = accepter def send(self, obj): if isinstance(obj, Channel): assert obj.gw is self.gw msg = message(MSG_CHANNEL, self.n, obj.n) else: msg = message(MSG_OBJECT, self.n, repr(obj)) self.gw.output.sendall(msg) def receive(self): obj = self.accepter.accept() if isinstance(obj, RemoteError): raise obj else: return obj def close(self): try: self.gw.output.sendall(message(MSG_CHAN_CLOSE, self.n)) except OSError: pass def report_error(self, exc_type, exc_value, exc_traceback=None): s = format_error(exc_type, exc_value, exc_traceback) try: self.gw.output.sendall(message(MSG_ERROR, self.n, s)) except OSError: pass class RemoteError(Exception): pass def format_error(exc_type, exc_value, exc_traceback=None): import traceback, StringIO s = StringIO.StringIO() traceback.print_exception(exc_type, exc_value, exc_traceback, file=s) return s.getvalue() class PopenCmdGateway(Gateway): action = "exec input()" def __init__(self, cmdline): from py.__.green.pipe.fd import FDInput, FDOutput child_in, child_out = os.popen2(cmdline, 't', 0) fdin = FDInput(child_out.fileno(), child_out.close) fdout = FDOutput(child_in.fileno(), child_in.close) fdout.sendall(self.get_bootstrap_code()) super(PopenCmdGateway, self).__init__(input = fdin, output = fdout) def get_bootstrap_code(): # XXX assumes that the py lib is installed on the remote side src = [] src.append('from py.__.green import greenexecnet') src.append('greenexecnet.PopenCmdGateway.run_server()') src.append('') return '%r\n' % ('\n'.join(src),) get_bootstrap_code = staticmethod(get_bootstrap_code) def run_server(): from py.__.green.pipe.fd import FDInput, FDOutput gw = Gateway(input = FDInput(os.dup(0)), output = FDOutput(os.dup(1)), is_remote = True) # for now, ignore normal I/O fd = os.open('/dev/null', os.O_RDWR) os.dup2(fd, 0) os.dup2(fd, 1) os.close(fd) greensock2._suspend_forever() run_server = staticmethod(run_server) class PopenGateway(PopenCmdGateway): def __init__(self, python=sys.executable): cmdline = '"%s" -u -c "%s"' % (python, self.action) super(PopenGateway, self).__init__(cmdline) class SshGateway(PopenCmdGateway): def __init__(self, sshaddress, remotepython='python', identity=None): self.sshaddress = sshaddress remotecmd = '%s -u -c "%s"' % (remotepython, self.action) cmdline = [sshaddress, remotecmd] # XXX Unix style quoting for i in range(len(cmdline)): cmdline[i] = "'" + cmdline[i].replace("'", "'\\''") + "'" cmd = 'ssh -C' if identity is not None: cmd += ' -i %s' % (identity,) cmdline.insert(0, cmd) super(SshGateway, self).__init__(' '.join(cmdline)) ##f = open('LOG', 'a') ##import os; print >> f, '[%d] READY' % (os.getpid(),) ##f.close()
Python
#
Python
import os import sys import py class FDCapture: """ Capture IO to/from a given os-level filedescriptor. """ def __init__(self, targetfd, tmpfile=None): self.targetfd = targetfd if tmpfile is None: tmpfile = self.maketmpfile() self.tmpfile = tmpfile self._savefd = os.dup(targetfd) os.dup2(self.tmpfile.fileno(), targetfd) self._patched = [] def setasfile(self, name, module=sys): """ patch <module>.<name> to self.tmpfile """ key = (module, name) self._patched.append((key, getattr(module, name))) setattr(module, name, self.tmpfile) def unsetfiles(self): """ unpatch all patched items """ while self._patched: (module, name), value = self._patched.pop() setattr(module, name, value) def done(self): """ unpatch and clean up, returns the self.tmpfile (file object) """ os.dup2(self._savefd, self.targetfd) self.unsetfiles() os.close(self._savefd) self.tmpfile.seek(0) return self.tmpfile def maketmpfile(self): """ create a temporary file """ f = os.tmpfile() newf = py.io.dupfile(f) f.close() return newf def writeorg(self, str): """ write a string to the original file descriptor """ tempfp = os.tmpfile() try: os.dup2(self._savefd, tempfp.fileno()) tempfp.write(str) finally: tempfp.close()
Python
import os import sys import py try: from cStringIO import StringIO except ImportError: from StringIO import StringIO class Capture(object): def call(cls, func, *args, **kwargs): """ return a (res, out, err) tuple where out and err represent the output/error output during function execution. call the given function with args/kwargs and capture output/error during its execution. """ so = cls() try: res = func(*args, **kwargs) finally: out, err = so.reset() return res, out, err call = classmethod(call) def reset(self): """ reset sys.stdout and sys.stderr returns a tuple of file objects (out, err) for the captured data """ outfile, errfile = self.done() return outfile.read(), errfile.read() class StdCaptureFD(Capture): """ This class allows to capture writes to FD1 and FD2 and may connect a NULL file to FD0 (and prevent reads from sys.stdin) """ def __init__(self, out=True, err=True, mixed=False, in_=True, patchsys=True): if in_: self._oldin = (sys.stdin, os.dup(0)) sys.stdin = DontReadFromInput() fd = os.open(devnullpath, os.O_RDONLY) os.dup2(fd, 0) os.close(fd) if out: self.out = py.io.FDCapture(1) if patchsys: self.out.setasfile('stdout') if err: if mixed and out: tmpfile = self.out.tmpfile else: tmpfile = None self.err = py.io.FDCapture(2, tmpfile=tmpfile) if patchsys: self.err.setasfile('stderr') def done(self): """ return (outfile, errfile) and stop capturing. """ outfile = errfile = emptyfile if hasattr(self, 'out'): outfile = self.out.done() if hasattr(self, 'err'): errfile = self.err.done() if hasattr(self, '_oldin'): oldsys, oldfd = self._oldin os.dup2(oldfd, 0) os.close(oldfd) sys.stdin = oldsys return outfile, errfile class StdCapture(Capture): """ This class allows to capture writes to sys.stdout|stderr "in-memory" and will raise errors on tries to read from sys.stdin. It only modifies sys.stdout|stderr|stdin attributes and does not touch underlying File Descriptors (use StdCaptureFD for that). """ def __init__(self, out=True, err=True, in_=True, mixed=False): self._out = out self._err = err self._in = in_ if out: self.oldout = sys.stdout sys.stdout = self.newout = StringIO() if err: self.olderr = sys.stderr if out and mixed: newerr = self.newout else: newerr = StringIO() sys.stderr = self.newerr = newerr if in_: self.oldin = sys.stdin sys.stdin = self.newin = DontReadFromInput() def reset(self): """ return captured output as strings and restore sys.stdout/err.""" x, y = self.done() return x.read(), y.read() def done(self): """ return (outfile, errfile) and stop capturing. """ o,e = sys.stdout, sys.stderr outfile = errfile = emptyfile if self._out: try: sys.stdout = self.oldout except AttributeError: raise IOError("stdout capturing already reset") del self.oldout outfile = self.newout outfile.seek(0) if self._err: try: sys.stderr = self.olderr except AttributeError: raise IOError("stderr capturing already reset") del self.olderr errfile = self.newerr errfile.seek(0) if self._in: sys.stdin = self.oldin return outfile, errfile class DontReadFromInput: """Temporary stub class. Ideally when stdin is accessed, the capturing should be turned off, with possibly all data captured so far sent to the screen. This should be configurable, though, because in automated test runs it is better to crash than hang indefinitely. """ def read(self, *args): raise IOError("reading from stdin while output is captured") readline = read readlines = read __iter__ = read try: devnullpath = os.devnull except AttributeError: if os.name == 'nt': devnullpath = 'NUL' else: devnullpath = '/dev/null' emptyfile = StringIO()
Python
""" input/output helping """
Python
#
Python
import os def dupfile(f, mode=None, buffering=0, raising=False): """ return a new open file object that's a duplicate of f mode is duplicated if not given, 'buffering' controls buffer size (defaulting to no buffering) and 'raising' defines whether an exception is raised when an incompatible file object is passed in (if raising is False, the file object itself will be returned) """ try: fd = f.fileno() except AttributeError: if raising: raise return f newfd = os.dup(fd) mode = mode and mode or f.mode return os.fdopen(newfd, mode, buffering)
Python
import httplib, mimetypes """Copied from the cookbook see ActiveState's ASPN http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/146306 """ def post_multipart(host, selector, fields, files): """ Post fields and files to an http host as multipart/form-data. fields is a sequence of (name, value) elements for regular form fields. files is a sequence of (name, filename, value) elements for data to be uploaded as files Return the server's response page. """ content_type, body = encode_multipart_formdata(fields, files) h = httplib.HTTP(host) h.putrequest('POST', selector) h.putheader('content-type', content_type) h.putheader('content-length', str(len(body))) h.endheaders() h.send(body) errcode, errmsg, headers = h.getreply() return h.file.read() def encode_multipart_formdata(fields, files): """ fields is a sequence of (name, value) elements for regular form fields. files is a sequence of (name, filename, value) elements for data to be uploaded as files Return (content_type, body) ready for httplib.HTTP instance """ BOUNDARY = '----------ThIs_Is_tHe_bouNdaRY_$' CRLF = '\r\n' L = [] for (key, value) in fields: L.append('--' + BOUNDARY) L.append('Content-Disposition: form-data; name="%s"' % key) L.append('') L.append(value) for (key, filename, value) in files: L.append('--' + BOUNDARY) L.append('Content-Disposition: form-data; name="%s"; filename="%s"' % (key, filename)) L.append('Content-Type: %s' % get_content_type(filename)) L.append('') L.append(value) L.append('--' + BOUNDARY + '--') L.append('') body = CRLF.join(L) content_type = 'multipart/form-data; boundary=%s' % BOUNDARY return content_type, body def get_content_type(filename): return mimetypes.guess_type(filename)[0] or 'application/octet-stream'
Python
import py import re from exception import * from post_multipart import post_multipart #import css_checker def check_html(string): """check an HTML string for wellformedness and validity""" tempdir = py.test.ensuretemp('check_html') filename = 'temp%s.html' % (hash(string), ) tempfile = tempdir.join(filename) tempfile.write(string) ret = post_multipart('validator.w3.org', '/check', [], [('uploaded_file', 'somehtml.html', string)]) is_valid = get_validation_result_from_w3_html(ret) return is_valid reg_validation_result = re.compile('<td[^>]*class="(in)?valid"[^>]*>([^<]*)<', re.M | re.S) def get_validation_result_from_w3_html(html): match = reg_validation_result.search(html) valid = match.group(1) is None text = match.group(2).strip() if not valid: temp = py.test.ensuretemp('/w3_results_%s.html' % hash(html), dir=0) temp.write(html) raise HTMLError( "The html is not valid. See the report file at '%s'" % temp) return valid #def check_css(string, basepath, htmlpath='/'): # """check the CSS of an HTML string # # check whether an HTML string contains CSS rels, and if so check whether # any classes defined in the HTML actually have a matching CSS selector # """ # c = css_checker.css_checker(string, basepath, htmlpath) # # raises a CSSError when failing, this is done from the tester class to # # allow being more verbose than just 'something went wrong' # return c.check()
Python
class CSSError(Exception): """raised when there's a problem with the CSS""" class HTMLError(Exception): """raised when there's a problem with the HTML"""
Python
import py # # main entry point # def main(args=None): warn_about_missing_assertion() if args is None: args = py.std.sys.argv[1:] config = py.test.config config.parse(args) session = config.initsession() try: failures = session.main() if failures: raise SystemExit, 1 except KeyboardInterrupt: if not config.option.verbose: print print "KeyboardInterrupt (-v to see traceback)" raise SystemExit, 2 else: raise def warn_about_missing_assertion(): try: assert False except AssertionError: pass else: py.std.warnings.warn("Assertions are turned off!" " (are you using python -O?)")
Python
""" Collect test items at filesystem and python module levels. Collectors and test items form a tree. The difference between a collector and a test item as seen from the session is smalll. Collectors usually return a list of child collectors/items whereas items usually return None indicating a successful test run. The is a schematic example of a tree of collectors and test items:: Directory Module Class Instance Function Generator ... Function Generator Function Directory ... """ from __future__ import generators import py from py.__.test.outcome import Skipped def configproperty(name): def fget(self): #print "retrieving %r property from %s" %(name, self.fspath) return self._config.getvalue(name, self.fspath) return property(fget) class Collector(object): """ Collector instances are iteratively generated (through their run() and join() methods) and form a tree. attributes:: parent: attribute pointing to the parent collector (or None if it is the root collector) name: basename of this collector object """ def __init__(self, name, parent=None): self.name = name self.parent = parent self._config = getattr(parent, '_config', py.test.config) if parent is not None: if hasattr(parent, 'config'): py.test.pdb() self.fspath = getattr(parent, 'fspath', None) Module = configproperty('Module') DoctestFile = configproperty('DoctestFile') Directory = configproperty('Directory') Class = configproperty('Class') Instance = configproperty('Instance') Function = configproperty('Function') Generator = configproperty('Generator') _stickyfailure = None def __repr__(self): return "<%s %r>" %(self.__class__.__name__, self.name) def __eq__(self, other): # XXX a rather strict check for now to not confuse # the SetupState.prepare() logic return self is other def __hash__(self): return hash((self.name, self.parent)) def __ne__(self, other): return not self == other def __cmp__(self, other): s1 = self._getsortvalue() s2 = other._getsortvalue() #print "cmp", s1, s2 return cmp(s1, s2) def run(self): """ returns a list of names available from this collector. You can return an empty list. Callers of this method must take care to catch exceptions properly. The session object guards its calls to ``colitem.run()`` in its ``session.runtraced(colitem)`` method, including catching of stdout. """ raise NotImplementedError("abstract") def join(self, name): """ return a child item for the given name. Usually the session feeds the join method with each name obtained from ``colitem.run()``. If the return value is None it means the ``colitem`` was not able to resolve with the given name. """ def obj(): def fget(self): try: return self._obj except AttributeError: self._obj = obj = self._getobj() return obj def fset(self, value): self._obj = value return property(fget, fset, None, "underlying object") obj = obj() def _getobj(self): return getattr(self.parent.obj, self.name) def multijoin(self, namelist): """ return a list of colitems for the given namelist. """ return [self.join(name) for name in namelist] def _getpathlineno(self): return self.fspath, py.std.sys.maxint def setup(self): pass def teardown(self): pass def listchain(self): """ return list of all parent collectors up to ourself. """ l = [self] while 1: x = l[-1] if x.parent is not None: l.append(x.parent) else: l.reverse() return l def listnames(self): return [x.name for x in self.listchain()] def _getitembynames(self, namelist): if isinstance(namelist, str): namelist = namelist.split("/") cur = self for name in namelist: if name: next = cur.join(name) assert next is not None, (cur, name, namelist) cur = next return cur def _haskeyword(self, keyword): return keyword in self.name def _getmodpath(self): """ return dotted module path (relative to the containing). """ inmodule = False newl = [] for x in self.listchain(): if not inmodule and not isinstance(x, Module): continue if not inmodule: inmodule = True continue if newl and x.name[:1] in '([': newl[-1] += x.name else: newl.append(x.name) return ".".join(newl) def _skipbykeyword(self, keyword): """ raise Skipped() exception if the given keyword matches for this collector. """ if not keyword: return chain = self.listchain() for key in filter(None, keyword.split()): eor = key[:1] == '-' if eor: key = key[1:] if not (eor ^ self._matchonekeyword(key, chain)): py.test.skip("test not selected by keyword %r" %(keyword,)) def _matchonekeyword(self, key, chain): for subitem in chain: if subitem._haskeyword(key): return True return False def _tryiter(self, yieldtype=None, reporterror=None, keyword=None): """ yield stop item instances from flattening the collector. XXX deprecated: this way of iteration is not safe in all cases. """ if yieldtype is None: yieldtype = py.test.collect.Item if isinstance(self, yieldtype): try: self._skipbykeyword(keyword) yield self except Skipped: if reporterror is not None: excinfo = py.code.ExceptionInfo() reporterror((excinfo, self)) else: if not isinstance(self, py.test.collect.Item): try: if reporterror is not None: reporterror((None, self)) for x in self.run(): for y in self.join(x)._tryiter(yieldtype, reporterror, keyword): yield y except KeyboardInterrupt: raise except: if reporterror is not None: excinfo = py.code.ExceptionInfo() reporterror((excinfo, self)) def _getsortvalue(self): return self.name _captured_out = _captured_err = None def startcapture(self): return None # by default collectors don't capture output def finishcapture(self): return None # by default collectors don't capture output def _getouterr(self): return self._captured_out, self._captured_err def _get_collector_trail(self): """ Shortcut """ return self._config.get_collector_trail(self) class FSCollector(Collector): def __init__(self, fspath, parent=None): fspath = py.path.local(fspath) super(FSCollector, self).__init__(fspath.basename, parent) self.fspath = fspath class Directory(FSCollector): def filefilter(self, path): if path.check(file=1): b = path.purebasename ext = path.ext return (b.startswith('test_') or b.endswith('_test')) and ext in ('.txt', '.py') def recfilter(self, path): if path.check(dir=1, dotfile=0): return path.basename not in ('CVS', '_darcs', '{arch}') def run(self): files = [] dirs = [] for p in self.fspath.listdir(): if self.filefilter(p): files.append(p.basename) elif self.recfilter(p): dirs.append(p.basename) files.sort() dirs.sort() return files + dirs def join(self, name): name2items = self.__dict__.setdefault('_name2items', {}) try: res = name2items[name] except KeyError: p = self.fspath.join(name) res = None if p.check(file=1): if p.ext == '.py': res = self.Module(p, parent=self) elif p.ext == '.txt': res = self.DoctestFile(p, parent=self) elif p.check(dir=1): Directory = py.test.config.getvalue('Directory', p) res = Directory(p, parent=self) name2items[name] = res return res class PyCollectorMixin(object): def funcnamefilter(self, name): return name.startswith('test') def classnamefilter(self, name): return name.startswith('Test') def _buildname2items(self): # NB. we avoid random getattrs and peek in the __dict__ instead d = {} dicts = [getattr(self.obj, '__dict__', {})] for basecls in py.std.inspect.getmro(self.obj.__class__): dicts.append(basecls.__dict__) seen = {} for dic in dicts: for name, obj in dic.items(): if name in seen: continue seen[name] = True res = self.makeitem(name, obj) if res is not None: d[name] = res return d def makeitem(self, name, obj, usefilters=True): if (not usefilters or self.classnamefilter(name)) and \ py.std.inspect.isclass(obj): return self.Class(name, parent=self) elif (not usefilters or self.funcnamefilter(name)) and callable(obj): if obj.func_code.co_flags & 32: # generator function return self.Generator(name, parent=self) else: return self.Function(name, parent=self) def _prepare(self): if not hasattr(self, '_name2items'): ex = getattr(self, '_name2items_exception', None) if ex is not None: raise ex[0], ex[1], ex[2] try: self._name2items = self._buildname2items() except (SystemExit, KeyboardInterrupt): raise except: self._name2items_exception = py.std.sys.exc_info() raise def run(self): self._prepare() itemlist = self._name2items.values() itemlist.sort() return [x.name for x in itemlist] def join(self, name): self._prepare() return self._name2items.get(name, None) class Module(FSCollector, PyCollectorMixin): def run(self): if getattr(self.obj, 'disabled', 0): return [] return PyCollectorMixin.run(self) def join(self, name): res = super(Module, self).join(name) if res is None: attr = getattr(self.obj, name, None) if attr is not None: res = self.makeitem(name, attr, usefilters=False) return res def startcapture(self): self._config._startcapture(self, path=self.fspath) def finishcapture(self): self._config._finishcapture(self) def __repr__(self): return "<%s %r>" % (self.__class__.__name__, self.name) def obj(self): try: return self._obj except AttributeError: failure = getattr(self, '_stickyfailure', None) if failure is not None: raise failure[0], failure[1], failure[2] try: self._obj = obj = self.fspath.pyimport() except KeyboardInterrupt: raise except: self._stickyfailure = py.std.sys.exc_info() raise return obj obj = property(obj, None, None, "module object") def setup(self): if hasattr(self.obj, 'setup_module'): self.obj.setup_module(self.obj) def teardown(self): if hasattr(self.obj, 'teardown_module'): self.obj.teardown_module(self.obj) class Class(PyCollectorMixin, Collector): def run(self): if getattr(self.obj, 'disabled', 0): return [] return ["()"] def join(self, name): assert name == '()' return self.Instance(name, self) def setup(self): setup_class = getattr(self.obj, 'setup_class', None) if setup_class is not None: setup_class = getattr(setup_class, 'im_func', setup_class) setup_class(self.obj) def teardown(self): teardown_class = getattr(self.obj, 'teardown_class', None) if teardown_class is not None: teardown_class = getattr(teardown_class, 'im_func', teardown_class) teardown_class(self.obj) def _getsortvalue(self): # try to locate the class in the source - not nice, but probably # the most useful "solution" that we have try: file = (py.std.inspect.getsourcefile(self.obj) or py.std.inspect.getfile(self.obj)) if not file: raise IOError lines, lineno = py.std.inspect.findsource(self.obj) return py.path.local(file), lineno except IOError: pass # fall back... for x in self._tryiter((py.test.collect.Generator, py.test.collect.Item)): return x._getsortvalue() class Instance(PyCollectorMixin, Collector): def _getobj(self): return self.parent.obj() def Function(self): return getattr(self.obj, 'Function', Collector.Function.__get__(self)) # XXX for python 2.2 Function = property(Function) from py.__.test.item import FunctionMixin # XXX import order issues :-( class Generator(FunctionMixin, PyCollectorMixin, Collector): def run(self): self._prepare() itemlist = self._name2items return [itemlist["[%d]" % num].name for num in xrange(len(itemlist))] def _buildname2items(self): d = {} # slightly hackish to invoke setup-states on # collection ... self.Function._state.prepare(self) for i, x in py.builtin.enumerate(self.obj()): call, args = self.getcallargs(x) if not callable(call): raise TypeError("yielded test %r not callable" %(call,)) name = "[%d]" % i d[name] = self.Function(name, self, args, obj=call, sort_value = i) return d def getcallargs(self, obj): if isinstance(obj, (tuple, list)): call, args = obj[0], obj[1:] else: call, args = obj, () return call, args class DoctestFile(PyCollectorMixin, FSCollector): def run(self): return [self.fspath.basename] def join(self, name): from py.__.test.doctest import DoctestText if name == self.fspath.basename: item = DoctestText(self.fspath.basename, parent=self) item._content = self.fspath.read() return item
Python
import py from inspect import isclass, ismodule from py.__.test.outcome import Skipped, Failed, Passed _dummy = object() class SetupState(object): """ shared state for setting up/tearing down tests. """ def __init__(self): self.stack = [] def teardown_all(self): while self.stack: col = self.stack.pop() col.teardown() def prepare(self, colitem): """ setup objects along the collector chain to the test-method Teardown any unneccessary previously setup objects. """ needed_collectors = colitem.listchain() while self.stack: if self.stack == needed_collectors[:len(self.stack)]: break col = self.stack.pop() col.teardown() for col in needed_collectors[len(self.stack):]: #print "setting up", col col.setup() self.stack.append(col) class Item(py.test.collect.Collector): def startcapture(self): self._config._startcapture(self, path=self.fspath) def finishcapture(self): self._config._finishcapture(self) class FunctionMixin(object): """ mixin for the code common to Function and Generator. """ def _getpathlineno(self): code = py.code.Code(self.obj) return code.path, code.firstlineno def _getsortvalue(self): return self._getpathlineno() def setup(self): """ perform setup for this test function. """ if getattr(self.obj, 'im_self', None): name = 'setup_method' else: name = 'setup_function' obj = self.parent.obj meth = getattr(obj, name, None) if meth is not None: return meth(self.obj) def teardown(self): """ perform teardown for this test function. """ if getattr(self.obj, 'im_self', None): name = 'teardown_method' else: name = 'teardown_function' obj = self.parent.obj meth = getattr(obj, name, None) if meth is not None: return meth(self.obj) class Function(FunctionMixin, Item): """ a Function Item is responsible for setting up and executing a Python callable test object. """ _state = SetupState() def __init__(self, name, parent, args=(), obj=_dummy, sort_value = None): super(Function, self).__init__(name, parent) self._args = args if obj is not _dummy: self._obj = obj self._sort_value = sort_value def __repr__(self): return "<%s %r>" %(self.__class__.__name__, self.name) def _getsortvalue(self): if self._sort_value is None: return self._getpathlineno() return self._sort_value def run(self): """ setup and execute the underlying test function. """ self._state.prepare(self) self.execute(self.obj, *self._args) def execute(self, target, *args): """ execute the given test function. """ target(*args) # # triggering specific outcomes while executing Items # def skip(msg="unknown reason"): """ skip with the given Message. """ __tracebackhide__ = True raise Skipped(msg=msg) def fail(msg="unknown failure"): """ fail with the given Message. """ __tracebackhide__ = True raise Failed(msg=msg)
Python
import py from py.__.test.outcome import Outcome, Failed, Passed, Skipped class Session(object): """ A Session gets test Items from Collectors, # executes the Items and sends the Outcome to the Reporter. """ def __init__(self, config): self._memo = [] self.config = config def shouldclose(self): return False def header(self, colitems): """ setup any neccessary resources ahead of the test run. """ if not self.config.option.nomagic: py.magic.invoke(assertion=1) def footer(self, colitems): """ teardown any resources after a test run. """ py.test.collect.Function._state.teardown_all() if not self.config.option.nomagic: py.magic.revoke(assertion=1) def fixoptions(self): """ check, fix and determine conflicting options. """ option = self.config.option # implied options if option.usepdb: if not option.nocapture: option.nocapture = True # conflicting options if option.looponfailing and option.usepdb: raise ValueError, "--looponfailing together with --pdb not supported." if option.looponfailing and option.dist: raise ValueError, "--looponfailing together with --dist not supported." if option.executable and option.usepdb: raise ValueError, "--exec together with --pdb not supported." def start(self, colitem): """ hook invoked before each colitem.run() invocation. """ def finish(self, colitem, outcome): """ hook invoked after each colitem.run() invocation. """ self._memo.append((colitem, outcome)) def startiteration(self, colitem, subitems): pass def getitemoutcomepairs(self, cls): return [x for x in self._memo if isinstance(x[1], cls)] def main(self): """ main loop for running tests. """ colitems = self.config.getcolitems() try: self.header(colitems) try: try: for colitem in colitems: self.runtraced(colitem) except KeyboardInterrupt: raise finally: self.footer(colitems) except Exit, ex: pass def runtraced(self, colitem): if self.shouldclose(): raise Exit, "received external close signal" outcome = None colitem.startcapture() try: self.start(colitem) try: try: if colitem._stickyfailure: raise colitem._stickyfailure outcome = self.run(colitem) except (KeyboardInterrupt, Exit): raise except Outcome, outcome: if outcome.excinfo is None: outcome.excinfo = py.code.ExceptionInfo() except: excinfo = py.code.ExceptionInfo() outcome = Failed(excinfo=excinfo) assert (outcome is None or isinstance(outcome, (list, Outcome))) finally: self.finish(colitem, outcome) if isinstance(outcome, Failed) and self.config.option.exitfirst: py.test.exit("exit on first problem configured.", item=colitem) finally: colitem.finishcapture() def run(self, colitem): if self.config.option.collectonly and isinstance(colitem, py.test.collect.Item): return if isinstance(colitem, py.test.collect.Item): colitem._skipbykeyword(self.config.option.keyword) res = colitem.run() if res is None: return Passed() elif not isinstance(res, (list, tuple)): raise TypeError("%r.run() returned neither " "list, tuple nor None: %r" % (colitem, res)) else: finish = self.startiteration(colitem, res) try: for name in res: obj = colitem.join(name) assert obj is not None self.runtraced(obj) finally: if finish: finish() return res class Exit(Exception): """ for immediate program exits without tracebacks and reporter/summary. """ def __init__(self, msg="unknown reason", item=None): self.msg = msg Exception.__init__(self, msg) def exit(msg, item=None): raise Exit(msg=msg, item=item)
Python
import py class DoctestText(py.test.collect.Item): def _setcontent(self, content): self._content = content #def buildname2items(self): # parser = py.compat.doctest.DoctestParser() # l = parser.get_examples(self._content) # d = {} # globs = {} # locs # for i, example in py.builtin.enumerate(l): # ex = ExampleItem(example) # d[str(i)] = ex def run(self): mod = py.std.types.ModuleType(self.name) #for line in s.split('\n'): # if line.startswith(prefix): # exec py.code.Source(line[len(prefix):]).compile() in mod.__dict__ # line = "" # else: # l.append(line) self.execute(mod, self._content) def execute(self, mod, docstring): mod.__doc__ = docstring failed, tot = py.compat.doctest.testmod(mod, verbose=1) if failed: py.test.fail("doctest %s: %s failed out of %s" %( self.fspath, failed, tot))
Python
import py def deprecated_call(func, *args, **kwargs): """ assert that calling func(*args, **kwargs) triggers a DeprecationWarning. """ l = [] oldwarn = py.std.warnings.warn_explicit def warn_explicit(*args, **kwargs): l.append(args) oldwarn(*args, **kwargs) py.magic.patch(py.std.warnings, 'warn_explicit', warn_explicit) try: _ = func(*args, **kwargs) finally: py.magic.revert(py.std.warnings, 'warn_explicit') assert l
Python
""" reporter - different reporter for different purposes ;-) Still lacks: 1. Hanging nodes are not done well """ import py from py.__.test.terminal.out import getout from py.__.test.rsession import repevent from py.__.test.rsession import outcome from py.__.misc.terminal_helper import ansi_print, get_terminal_width from py.__.test.representation import Presenter import sys class AbstractReporter(object): def __init__(self, config, hosts): self.config = config self.hosts = hosts self.failed_tests_outcome = [] self.skipped_tests_outcome = [] self.out = getout(py.std.sys.stdout) self.presenter = Presenter(self.out, config) self.failed = dict([(host, 0) for host in hosts]) self.skipped = dict([(host, 0) for host in hosts]) self.passed = dict([(host, 0) for host in hosts]) self.to_rsync = {} def get_item_name(self, event, colitem): return "/".join(colitem.listnames()) def report(self, what): repfun = getattr(self, "report_" + what.__class__.__name__, self.report_unknown) try: return repfun(what) except (KeyboardInterrupt, SystemExit): raise except: print "Internal reporting problem" excinfo = py.code.ExceptionInfo() for i in excinfo.traceback: print str(i)[2:-1] print excinfo def report_unknown(self, what): if self.config.option.verbose: print "Unknown report: %s" % what def report_SendItem(self, item): address = item.host.hostname assert isinstance(item.host.hostname, str) if self.config.option.verbose: print "Sending %s to %s" % (item.item, address) def report_HostRSyncing(self, item): hostrepr = self._hostrepr(item.host) if item.synced: if (item.host.hostname == "localhost" and item.root == item.remotepath): print "%15s: skipping inplace rsync of %r" %( hostrepr, item.remotepath) else: print "%15s: skip duplicate rsync to %r" % ( hostrepr, item.remotepath) else: print "%15s: rsync %r to remote %r" % (hostrepr, item.root.basename, item.remotepath) def report_HostGatewayReady(self, item): self.to_rsync[item.host] = len(item.roots) hostrepr = self._hostrepr(item.host) self.out.write("%15s: gateway initialised (remote topdir: %s)\n"\ % (hostrepr, item.host.gw_remotepath)) def report_HostRSyncRootReady(self, item): self.to_rsync[item.host] -= 1 if not self.to_rsync[item.host]: self._host_ready(item) def _host_ready(self, item): self.hosts_to_rsync -= 1 hostrepr = self._hostrepr(item.host) if self.hosts_to_rsync: print "%15s: READY (still %d to go)" % (hostrepr, self.hosts_to_rsync) else: print "%15s: READY" % hostrepr def report_TestStarted(self, item): hostreprs = [self._hostrepr(host) for host in item.hosts] txt = " Test started, hosts: %s " % ", ".join(hostreprs) self.hosts_to_rsync = len(item.hosts) self.out.sep("=", txt) self.timestart = item.timestart self.out.write("local top directory: %s\n" % item.topdir) for i, root in py.builtin.enumerate(item.roots): outof = "%d/%d" %(i+1, len(item.roots)) self.out.write("local RSync root [%s]: %s\n" % (outof, root)) def report_RsyncFinished(self, item): self.timersync = item.time def report_ImmediateFailure(self, event): self.repr_failure(event.item, event.outcome) def report_TestFinished(self, item): self.out.line() assert hasattr(self, 'timestart') self.timeend = item.timeend self.skips() self.failures() if hasattr(self, 'nodes'): # XXX: Testing self.hangs() self.summary() return len(self.failed_tests_outcome) > 0 report_InterruptedExecution = report_TestFinished report_CrashedExecution = report_TestFinished def hangs(self): h = [] if self.config.option.exitfirst: # reporting hanging nodes in that case makes no sense at all # but we should share some code in all reporters than return for node in self.nodes: h += [(i, node.channel.gateway.sshaddress) for i in node.pending] if h: self.out.sep("=", " HANGING NODES ") for i, node in h: self.out.line("%s on %s" % (" ".join(i.listnames()), node)) def failures(self): if self.failed_tests_outcome: self.out.sep("=", " FAILURES ") for event in self.failed_tests_outcome: if isinstance(event, repevent.ReceivedItemOutcome): host = self.gethost(event) self.out.sep('_', "%s on %s" % (" ".join(event.item.listnames()), host)) if event.outcome.signal: self.presenter.repr_item_info(event.item) self.repr_signal(event.item, event.outcome) else: self.repr_failure(event.item, event.outcome) else: self.out.sep('_', " ".join(event.item.listnames())) out = outcome.Outcome(excinfo=event.excinfo) self.repr_failure(event.item, outcome.ReprOutcome(out.make_repr())) def gethost(self, event): return event.host.hostname def repr_failure(self, item, outcome): excinfo = outcome.excinfo traceback = excinfo.traceback if not traceback: self.out.line("empty traceback from item %r" % (item,)) return handler = getattr(self.presenter, 'repr_failure_tb%s' % self.config.option.tbstyle) handler(item, excinfo, traceback, lambda: self.repr_out_err(outcome)) def repr_out_err(self, outcome): if outcome.stdout: self.out.sep('-', " Captured process stdout: ") self.out.write(outcome.stdout) if outcome.stderr: self.out.sep('-', " Captured process stderr: ") self.out.write(outcome.stderr) def repr_signal(self, item, outcome): signal = outcome.signal self.out.line("Received signal: %d" % outcome.signal) self.repr_out_err(outcome) def _hostrepr(self, host): return host.hostid def skips(self): texts = {} for event in self.skipped_tests_outcome: colitem = event.item if isinstance(event, repevent.ReceivedItemOutcome): outcome = event.outcome text = outcome.skipped itemname = self.get_item_name(event, colitem) elif isinstance(event, repevent.SkippedTryiter): text = str(event.excinfo.value) itemname = "/".join(colitem.listnames()) if text not in texts: texts[text] = [itemname] else: texts[text].append(itemname) if texts: self.out.line() self.out.sep('_', 'reasons for skipped tests') for text, items in texts.items(): for item in items: self.out.line('Skipped in %s' % item) self.out.line("reason: %s" % text) def summary(self): def gather(dic): total = 0 for key, val in dic.iteritems(): total += val return total def create_str(name, count): if count: return ", %d %s" % (count, name) return "" total_passed = gather(self.passed) total_failed = gather(self.failed) total_skipped = gather(self.skipped) total = total_passed + total_failed + total_skipped skipped_str = create_str("skipped", total_skipped) failed_str = create_str("failed", total_failed) self.print_summary(total, skipped_str, failed_str) def print_summary(self, total, skipped_str, failed_str): self.out.sep("=", " %d test run%s%s in %.2fs (rsync: %.2f)" % (total, skipped_str, failed_str, self.timeend - self.timestart, self.timersync - self.timestart)) def report_SkippedTryiter(self, event): #event.outcome.excinfo.source = self.skipped_tests_outcome.append(event) def report_FailedTryiter(self, event): pass # XXX: right now we do not do anything with it def report_ReceivedItemOutcome(self, event): host = event.host hostrepr = self._hostrepr(host) if event.outcome.passed: self.passed[host] += 1 sys.stdout.write("%15s: PASSED " % hostrepr) elif event.outcome.skipped: self.skipped_tests_outcome.append(event) self.skipped[host] += 1 sys.stdout.write("%15s: SKIPPED " % hostrepr) else: self.failed[host] += 1 self.failed_tests_outcome.append(event) sys.stdout.write("%15s: " % hostrepr) ansi_print("FAILED", esc=(31,1), newline=False, file=sys.stdout) sys.stdout.write(" ") # we should have printed 20 characters to this point itempath = ".".join(event.item.listnames()[1:-1]) funname = event.item.listnames()[-1] lgt = get_terminal_width() - 20 # mark the function name, to be sure to_display = len(itempath) + len(funname) + 1 if to_display > lgt: sys.stdout.write("..." + itempath[to_display-lgt+4:]) else: sys.stdout.write(itempath) sys.stdout.write(" ") ansi_print(funname, esc=32, file=sys.stdout) def report_Nodes(self, event): self.nodes = event.nodes class RemoteReporter(AbstractReporter): def get_item_name(self, event, colitem): return event.host.hostname + ":" + \ "/".join(colitem.listnames()) def report_FailedTryiter(self, event): self.out.line("FAILED TO LOAD MODULE: %s\n" % "/".join(event.item.listnames())) self.failed_tests_outcome.append(event) # argh! bad hack, need to fix it self.failed[self.hosts[0]] += 1 def report_SkippedTryiter(self, event): self.out.line("Skipped (%s) %s\n" % (str(event.excinfo.value), "/". join(event.item.listnames()))) class LocalReporter(AbstractReporter): def get_item_name(self, event, colitem): return "/".join(colitem.listnames()) def report_SkippedTryiter(self, event): #self.show_item(event.item, False) if isinstance(event.item, py.test.collect.Module): self.out.write("- skipped (%s)" % event.excinfo.value) else: self.out.write("s") self.skipped_tests_outcome.append(event) def report_FailedTryiter(self, event): #self.show_item(event.item, False) self.out.write("- FAILED TO LOAD MODULE") self.failed_tests_outcome.append(event) self.failed[self.hosts[0]] += 1 def report_ReceivedItemOutcome(self, event): host = self.hosts[0] if event.outcome.passed: self.passed[host] += 1 self.out.write(".") elif event.outcome.skipped: self.skipped_tests_outcome.append(event) self.skipped[host] += 1 self.out.write("s") else: self.failed[host] += 1 self.failed_tests_outcome.append(event) self.out.write("F") def report_ItemStart(self, event): self.show_item(event.item) def show_item(self, item, count_elems = True): if isinstance(item, py.test.collect.Module): # XXX This is a terrible hack, I don't like it # and will rewrite it at some point #self.count = 0 lgt = len(list(item._tryiter())) #self.lgt = lgt # print names relative to current workdir name = "/".join(item.listnames()) local = str(py.path.local()) d = str(self.config.topdir) if local.startswith(d): local = local[len(d) + 1:] if local and name.startswith(local): name = name[len(local) + 1:] self.out.write("\n%s[%d] " % (name, lgt)) def gethost(self, event): return 'localhost' def hangs(self): pass
Python
""" web server for py.test """ from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler import thread, threading import re import time import random import Queue import os import sys import socket import py from py.__.test.rsession.rsession import RSession from py.__.test.rsession import repevent from py.__.test import collect from py.__.test.rsession.webdata import json DATADIR = py.path.local(__file__).dirpath("webdata") FUNCTION_LIST = ["main", "show_skip", "show_traceback", "show_info", "hide_info", "show_host", "hide_host", "hide_messagebox", "opt_scroll"] try: from pypy.rpython.ootypesystem.bltregistry import MethodDesc, BasicExternal,\ described from pypy.translator.js.main import rpython2javascript from pypy.translator.js import commproxy from pypy.rpython.extfunc import _callable commproxy.USE_MOCHIKIT = False IMPORTED_PYPY = True except (ImportError, NameError): class BasicExternal(object): pass def described(*args, **kwargs): def decorator(func): return func return decorator def _callable(*args, **kwargs): pass IMPORTED_PYPY = False def add_item(event): """ A little helper """ item = event.item itemtype = item.__class__.__name__ itemname = item.name fullitemname = "/".join(item.listnames()) d = {'fullitemname': fullitemname, 'itemtype': itemtype, 'itemname': itemname} #if itemtype == 'Module': try: d['length'] = str(len(list(event.item._tryiter()))) except: d['length'] = "?" return d class MultiQueue(object): """ a tailor-made queue (internally using Queue) for py.test.rsession.web API-wise the main difference is that the get() method gets a sessid argument, which is used to determine what data to feed to the client when a data queue for a sessid doesn't yet exist, it is created, and filled with data that has already been fed to the other clients """ def __init__(self): self._cache = [] self._session_queues = {} self._lock = py.std.thread.allocate_lock() def put(self, item): self._lock.acquire() try: self._cache.append(item) for key, q in self._session_queues.items(): q.put(item) finally: self._lock.release() def _del(self, sessid): self._lock.acquire() try: del self._session_queues[sessid] finally: self._lock.release() def get(self, sessid): self._lock.acquire() try: if not sessid in self._session_queues: self._create_session_queue(sessid) finally: self._lock.release() return self._session_queues[sessid].get(sessid) def empty(self): self._lock.acquire() try: if not self._session_queues: return not len(self._cache) for q in self._session_queues.values(): if not q.empty(): return False finally: self._lock.release() return True def empty_queue(self, sessid): return self._session_queues[sessid].empty() def _create_session_queue(self, sessid): self._session_queues[sessid] = q = Queue.Queue() for item in self._cache: q.put(item) class ExportedMethods(BasicExternal): _render_xmlhttp = True def __init__(self): self.pending_events = MultiQueue() self.start_event = threading.Event() self.end_event = threading.Event() self.skip_reasons = {} self.fail_reasons = {} self.stdout = {} self.stderr = {} self.all = 0 self.to_rsync = {} def findmodule(self, item): # find the most outwards parent which is module current = item while current: if isinstance(current, collect.Module): break current = current.parent if current is not None: return str(current.name), str("/".join(current.listnames())) else: return str(item.parent.name), str("/".join(item.parent.listnames())) def show_hosts(self): self.start_event.wait() to_send = {} for host in self.hosts: to_send[host.hostid] = host.hostname return to_send show_hosts = described(retval={str:str}, args=[('callback', _callable([{str:str}]))])(show_hosts) def show_skip(self, item_name="aa"): return {'item_name': item_name, 'reason': self.skip_reasons[item_name]} show_skip = described(retval={str:str}, args=[('item_name',str),('callback', _callable([{str:str}]))])(show_skip) def show_fail(self, item_name="aa"): return {'item_name':item_name, 'traceback':str(self.fail_reasons[item_name]), 'stdout':self.stdout[item_name], 'stderr':self.stderr[item_name]} show_fail = described(retval={str:str}, args=[('item_name',str),('callback', _callable([{str:str}]))])(show_fail) _sessids = None _sesslock = py.std.thread.allocate_lock() def show_sessid(self): if not self._sessids: self._sessids = [] self._sesslock.acquire() try: while 1: sessid = ''.join(py.std.random.sample( py.std.string.lowercase, 8)) if sessid not in self._sessids: self._sessids.append(sessid) break finally: self._sesslock.release() return sessid show_sessid = described(retval=str, args=[('callback', _callable([str]))])(show_sessid) def failed(self, **kwargs): if not 'sessid' in kwargs: return sessid = kwargs['sessid'] to_del = -1 for num, i in enumerate(self._sessids): if i == sessid: to_del = num if to_del != -1: del self._sessids[to_del] self.pending_events._del(kwargs['sessid']) def show_all_statuses(self, sessid=-1): retlist = [self.show_status_change(sessid)] while not self.pending_events.empty_queue(sessid): retlist.append(self.show_status_change(sessid)) retval = retlist return retval show_all_statuses = described(retval=[{str:str}],args= [('sessid',str), ('callback',_callable([[{str:str}]]))])(show_all_statuses) def show_status_change(self, sessid): event = self.pending_events.get(sessid) if event is None: self.end_event.set() return {} # some dispatcher here if isinstance(event, repevent.ReceivedItemOutcome): args = {} outcome = event.outcome for key, val in outcome.__dict__.iteritems(): args[key] = str(val) args.update(add_item(event)) mod_name, mod_fullname = self.findmodule(event.item) args['modulename'] = str(mod_name) args['fullmodulename'] = str(mod_fullname) fullitemname = args['fullitemname'] if outcome.skipped: self.skip_reasons[fullitemname] = outcome.skipped elif outcome.excinfo: self.fail_reasons[fullitemname] = self.repr_failure_tblong( event.item, outcome.excinfo, outcome.excinfo.traceback) self.stdout[fullitemname] = outcome.stdout self.stderr[fullitemname] = outcome.stderr elif outcome.signal: self.fail_reasons[fullitemname] = "Received signal %d" % outcome.signal self.stdout[fullitemname] = outcome.stdout self.stderr[fullitemname] = outcome.stderr if event.channel: args['hostkey'] = event.channel.gateway.host.hostid else: args['hostkey'] = '' elif isinstance(event, repevent.ItemStart): args = add_item(event) elif isinstance(event, repevent.TestFinished): args = {} args['run'] = str(self.all) args['fails'] = str(len(self.fail_reasons)) args['skips'] = str(len(self.skip_reasons)) elif isinstance(event, repevent.SendItem): args = add_item(event) args['hostkey'] = event.channel.gateway.host.hostid elif isinstance(event, repevent.HostRSyncRootReady): self.ready_hosts[event.host] = True args = {'hostname' : event.host.hostname, 'hostkey' : event.host.hostid} elif isinstance(event, repevent.FailedTryiter): args = add_item(event) elif isinstance(event, repevent.SkippedTryiter): args = add_item(event) args['reason'] = str(event.excinfo.value) else: args = {} args['event'] = str(event) args['type'] = event.__class__.__name__ return args def repr_failure_tblong(self, item, excinfo, traceback): lines = [] for index, entry in py.builtin.enumerate(traceback): lines.append('----------') lines.append("%s: %s" % (entry.path, entry.lineno)) lines += self.repr_source(entry.relline, entry.source) lines.append("%s: %s" % (excinfo.typename, excinfo.value)) return "\n".join(lines) def repr_source(self, relline, source): lines = [] for num, line in enumerate(str(source).split("\n")): if num == relline: lines.append(">>>>" + line) else: lines.append(" " + line) return lines def report_ReceivedItemOutcome(self, event): self.all += 1 self.pending_events.put(event) def report_FailedTryiter(self, event): fullitemname = "/".join(event.item.listnames()) self.fail_reasons[fullitemname] = self.repr_failure_tblong( event.item, event.excinfo, event.excinfo.traceback) self.stdout[fullitemname] = '' self.stderr[fullitemname] = '' self.pending_events.put(event) def report_ItemStart(self, event): if isinstance(event.item, py.test.collect.Module): self.pending_events.put(event) def report_unknown(self, event): # XXX: right now, we just pass it for showing self.pending_events.put(event) def _host_ready(self, event): self.pending_events.put(event) def report_HostGatewayReady(self, item): self.to_rsync[item.host] = len(item.roots) def report_HostRSyncRootReady(self, item): self.to_rsync[item.host] -= 1 if not self.to_rsync[item.host]: self._host_ready(item) def report_TestStarted(self, event): # XXX: It overrides out self.hosts self.hosts = {} self.ready_hosts = {} for host in event.hosts: self.hosts[host] = host self.ready_hosts[host] = False self.start_event.set() self.pending_events.put(event) def report(self, what): repfun = getattr(self, "report_" + what.__class__.__name__, self.report_unknown) try: repfun(what) except (KeyboardInterrupt, SystemExit): raise except: print "Internal reporting problem" excinfo = py.code.ExceptionInfo() for i in excinfo.traceback: print str(i)[2:-1] print excinfo ## try: ## self.wait_flag.acquire() ## self.pending_events.insert(0, event) ## self.wait_flag.notify() ## finally: ## self.wait_flag.release() exported_methods = ExportedMethods() class TestHandler(BaseHTTPRequestHandler): exported_methods = exported_methods def do_GET(self): path = self.path if path.endswith("/"): path = path[:-1] if path.startswith("/"): path = path[1:] m = re.match('^(.*)\?(.*)$', path) if m: path = m.group(1) getargs = m.group(2) else: getargs = "" name_path = path.replace(".", "_") method_to_call = getattr(self, "run_" + name_path, None) if method_to_call is None: exec_meth = getattr(self.exported_methods, name_path, None) if exec_meth is None: self.send_error(404, "File %s not found" % path) else: try: self.serve_data('text/json', json.write(exec_meth(**self.parse_args(getargs)))) except socket.error: # client happily disconnected exported_methods.failed(**self.parse_args(getargs)) else: method_to_call() def parse_args(self, getargs): # parse get argument list if getargs == "": return {} unquote = py.std.urllib.unquote args = {} arg_pairs = getargs.split("&") for arg in arg_pairs: key, value = arg.split("=") args[unquote(key)] = unquote(value) return args def log_message(self, format, *args): # XXX just discard it pass do_POST = do_GET def run_(self): self.run_index() def run_index(self): data = py.path.local(DATADIR).join("index.html").open().read() self.serve_data("text/html", data) def run_jssource(self): js_name = py.path.local(__file__).dirpath("webdata").join("source.js") web_name = py.path.local(__file__).dirpath().join("webjs.py") if IMPORTED_PYPY and web_name.mtime() > js_name.mtime(): from py.__.test.rsession import webjs javascript_source = rpython2javascript(webjs, FUNCTION_LIST, use_pdb=False) open(str(js_name), "w").write(javascript_source) self.serve_data("text/javascript", javascript_source) else: js_source = open(str(js_name), "r").read() self.serve_data("text/javascript", js_source) def serve_data(self, content_type, data): self.send_response(200) self.send_header("Content-type", content_type) self.send_header("Content-length", len(data)) self.end_headers() self.wfile.write(data) def start_server(server_address = ('', 8000), handler=TestHandler, start_new=True): httpd = HTTPServer(server_address, handler) if start_new: thread.start_new_thread(httpd.serve_forever, ()) print "Server started, listening on port %d" % (httpd.server_port,) return httpd else: print "Server started, listening on port %d" % (httpd.server_port,) httpd.serve_forever() def kill_server(): exported_methods.pending_events.put(None) while not exported_methods.pending_events.empty(): time.sleep(.1) exported_methods.end_event.wait()
Python
import sys, os import py import time import thread, threading from py.__.test.rsession.master import MasterNode from py.__.test.rsession.slave import setup_slave from py.__.test.rsession import repevent class HostInfo(object): """ Class trying to store all necessary attributes for host """ _hostname2list = {} def __init__(self, spec, addrel=""): parts = spec.split(':', 1) self.hostname = parts.pop(0) self.relpath = parts and parts.pop(0) or "" if self.hostname == "localhost" and not self.relpath: self.inplacelocal = True addrel = "" # inplace localhosts cannot have additions else: self.inplacelocal = False if not self.relpath: self.relpath = "pytestcache-%s" % self.hostname if addrel: self.relpath += "/" + addrel # XXX too os-dependent assert not parts assert self.inplacelocal or self.relpath self.hostid = self._getuniqueid(self.hostname) def _getuniqueid(self, hostname): l = self._hostname2list.setdefault(hostname, []) hostid = hostname + "[%d]" % len(l) l.append(hostid) return hostid def initgateway(self, python="python"): if self.hostname == "localhost": self.gw = py.execnet.PopenGateway(python=python) else: self.gw = py.execnet.SshGateway(self.hostname, remotepython=python) if self.inplacelocal: self.gw.remote_exec(py.code.Source( sethomedir, "sethomedir()" )).waitclose() self.gw_remotepath = None else: assert self.relpath channel = self.gw.remote_exec(py.code.Source( gethomedir, sethomedir, "sethomedir()", getpath_relto_home, """ channel.send(getpath_relto_home(%r)) """ % self.relpath, )) self.gw_remotepath = channel.receive() def __str__(self): return "<HostInfo %s:%s>" % (self.hostname, self.relpath) __repr__ = __str__ def __hash__(self): return hash(self.hostid) def __eq__(self, other): return self.hostid == other.hostid def __ne__(self, other): return not self.hostid == other.hostid class HostRSync(py.execnet.RSync): """ RSyncer that filters out common files """ def __init__(self, sourcedir, *args, **kwargs): self._synced = {} ignores= None if 'ignores' in kwargs: ignores = kwargs.pop('ignores') self._ignores = ignores or [] super(HostRSync, self).__init__(sourcedir=sourcedir, **kwargs) def filter(self, path): path = py.path.local(path) if not path.ext in ('.pyc', '.pyo'): if not path.basename.endswith('~'): if path.check(dotfile=0): for x in self._ignores: if path == x: break else: return True def add_target_host(self, host, destrelpath="", reporter=lambda x: None): remotepath = host.gw_remotepath key = host.hostname, host.relpath if host.inplacelocal: remotepath = self._sourcedir self._synced[key] = True elif destrelpath: remotepath = os.path.join(remotepath, destrelpath) synced = key in self._synced reporter(repevent.HostRSyncing(host, py.path.local(self._sourcedir), remotepath, synced)) def hostrsynced(host=host): reporter(repevent.HostRSyncRootReady(host, self._sourcedir)) if key in self._synced: hostrsynced() return self._synced[key] = True super(HostRSync, self).add_target(host.gw, remotepath, finishedcallback=hostrsynced, delete=True, ) return remotepath class HostManager(object): def __init__(self, config, hosts=None): self.config = config roots = self.config.getvalue_pathlist("dist_rsync_roots") addrel = "" if roots is None: roots = [self.config.topdir] addrel = self.config.topdir.basename self._addrel = addrel self.roots = roots if hosts is None: hosts = self.config.getvalue("dist_hosts") hosts = [HostInfo(x, addrel) for x in hosts] self.hosts = hosts def prepare_gateways(self, reporter): python = self.config.getvalue("dist_remotepython") for host in self.hosts: host.initgateway(python=python) reporter(repevent.HostGatewayReady(host, self.roots)) host.gw.host = host def init_rsync(self, reporter): ignores = self.config.getvalue_pathlist("dist_rsync_ignore") self.prepare_gateways(reporter) # send each rsync root for root in self.roots: rsync = HostRSync(root, ignores=ignores, verbose=self.config.option.verbose) if self._addrel: destrelpath = "" else: destrelpath = root.basename for host in self.hosts: rsync.add_target_host(host, destrelpath, reporter) rsync.send(raises=False) def setup_hosts(self, reporter): self.init_rsync(reporter) nodes = [] for host in self.hosts: if hasattr(host.gw, 'remote_exec'): # otherwise dummy for tests :/ ch = setup_slave(host, self.config) nodes.append(MasterNode(ch, reporter)) return nodes def teardown_hosts(self, reporter, channels, nodes, waiter=lambda : time.sleep(.1), exitfirst=False): for channel in channels: channel.send(None) clean = exitfirst while not clean: clean = True for node in nodes: if node.pending: clean = False waiter() self.teardown_gateways(reporter, channels) def kill_channels(self, channels): for channel in channels: channel.send(42) def teardown_gateways(self, reporter, channels): for channel in channels: #try: try: repevent.wrapcall(reporter, channel.waitclose, 1) except IOError: # timeout # force closing channel.close() channel.gateway.exit() def gethomedir(): import os homedir = os.environ.get('HOME', '') if not homedir: homedir = os.environ.get('HOMEPATH', '.') return os.path.abspath(homedir) def getpath_relto_home(targetpath): import os if not os.path.isabs(targetpath): homedir = gethomedir() targetpath = os.path.join(homedir, targetpath) return os.path.normpath(targetpath) def sethomedir(): import os homedir = os.environ.get('HOME', '') if not homedir: homedir = os.environ.get('HOMEPATH', '.') os.chdir(homedir)
Python
""" javascript source for py.test distributed """ import py from py.__.test.rsession.web import exported_methods try: from pypy.translator.js.modules import dom from pypy.translator.js.helper import __show_traceback except ImportError: py.test.skip("PyPy not found") def create_elem(s): return dom.document.createElement(s) def get_elem(el): return dom.document.getElementById(el) def create_text_elem(txt): return dom.document.createTextNode(txt) tracebacks = {} skips = {} counters = {} max_items = {} short_item_names = {} MAX_COUNTER = 30 # Maximal size of one-line table class Globals(object): def __init__(self): self.pending = [] self.host = "" self.data_empty = True glob = Globals() class Options(object): """ Store global options """ def __init__(self): self.scroll = True opts = Options() def comeback(msglist): if len(msglist) == 0: return for item in glob.pending[:]: if not process(item): return glob.pending = [] for msg in msglist: if not process(msg): return exported_methods.show_all_statuses(glob.sessid, comeback) def show_info(data="aa"): info = dom.document.getElementById("info") info.style.visibility = "visible" while len(info.childNodes): info.removeChild(info.childNodes[0]) txt = create_text_elem(data) info.appendChild(txt) info.style.backgroundColor = "beige" # XXX: Need guido def hide_info(): info = dom.document.getElementById("info") info.style.visibility = "hidden" def show_interrupt(): glob.finished = True dom.document.title = "Py.test [interrupted]" dom.document.getElementById("Tests").childNodes[0].nodeValue = "Tests [interrupted]" def show_crash(): glob.finished = True dom.document.title = "Py.test [crashed]" dom.document.getElementById("Tests").childNodes[0].nodeValue = "Tests [crashed]" SCROLL_LINES = 50 def opt_scroll(): if opts.scroll: opts.scroll = False else: opts.scroll = True def scroll_down_if_needed(mbox): if not opts.scroll: return #if dom.window.scrollMaxY - dom.window.scrollY < SCROLL_LINES: mbox.parentNode.scrollIntoView() def hide_messagebox(): mbox = dom.document.getElementById("messagebox") while mbox.childNodes: mbox.removeChild(mbox.childNodes[0]) def make_module_box(msg): tr = create_elem("tr") td = create_elem("td") tr.appendChild(td) td.appendChild(create_text_elem("%s[0/%s]" % (msg['itemname'], msg['length']))) max_items[msg['fullitemname']] = int(msg['length']) short_item_names[msg['fullitemname']] = msg['itemname'] td.id = '_txt_' + msg['fullitemname'] #tr.setAttribute("id", msg['fullitemname']) td.setAttribute("onmouseover", "show_info('%s')" % (msg['fullitemname'],)) td.setAttribute("onmouseout", "hide_info()") td2 = create_elem('td') tr.appendChild(td2) table = create_elem("table") td2.appendChild(table) tbody = create_elem('tbody') tbody.id = msg['fullitemname'] table.appendChild(tbody) counters[msg['fullitemname']] = 0 return tr def add_received_item_outcome(msg, module_part): if msg['hostkey']: host_elem = dom.document.getElementById(msg['hostkey']) glob.host_pending[msg['hostkey']].pop() count = len(glob.host_pending[msg['hostkey']]) host_elem.childNodes[0].nodeValue = '%s[%s]' % ( glob.host_dict[msg['hostkey']], count) td = create_elem("td") td.setAttribute("onmouseover", "show_info('%s')" % ( msg['fullitemname'],)) td.setAttribute("onmouseout", "hide_info()") item_name = msg['fullitemname'] # TODO: dispatch output if msg["passed"] == 'True': txt = create_text_elem(".") td.appendChild(txt) elif msg["skipped"] != 'None' and msg["skipped"] != "False": exported_methods.show_skip(item_name, skip_come_back) link = create_elem("a") link.setAttribute("href", "javascript:show_skip('%s')" % ( msg['fullitemname'],)) txt = create_text_elem('s') link.appendChild(txt) td.appendChild(link) else: link = create_elem("a") link.setAttribute("href", "javascript:show_traceback('%s')" % ( msg['fullitemname'],)) txt = create_text_elem('F') link.setAttribute('class', 'error') link.appendChild(txt) td.appendChild(link) exported_methods.show_fail(item_name, fail_come_back) if counters[msg['fullmodulename']] % MAX_COUNTER == 0: tr = create_elem("tr") module_part.appendChild(tr) name = msg['fullmodulename'] counters[name] += 1 counter_part = get_elem('_txt_' + name) newcontent = "%s[%d/%d]" % (short_item_names[name], counters[name], max_items[name]) counter_part.childNodes[0].nodeValue = newcontent module_part.childNodes[-1].appendChild(td) def process(msg): if len(msg) == 0: return False elem = dom.document.getElementById("testmain") #elem.innerHTML += '%s<br/>' % msg['event'] main_t = dom.document.getElementById("main_table") if msg['type'] == 'ItemStart': # we start a new directory or what #if msg['itemtype'] == 'Module': tr = make_module_box(msg) main_t.appendChild(tr) elif msg['type'] == 'SendItem': host_elem = dom.document.getElementById(msg['hostkey']) glob.host_pending[msg['hostkey']].insert(0, msg['fullitemname']) count = len(glob.host_pending[msg['hostkey']]) host_elem.childNodes[0].nodeValue = '%s[%s]' % ( glob.host_dict[msg['hostkey']], count) elif msg['type'] == 'HostRSyncRootReady': host_elem = dom.document.getElementById(msg['hostkey']) host_elem.style.background = \ "#00ff00" host_elem.childNodes[0].nodeValue = '%s[0]' % ( glob.host_dict[msg['hostkey']],) elif msg['type'] == 'ReceivedItemOutcome': module_part = get_elem(msg['fullmodulename']) if not module_part: glob.pending.append(msg) return True add_received_item_outcome(msg, module_part) elif msg['type'] == 'TestFinished': text = "FINISHED %s run, %s failures, %s skipped" % (msg['run'], msg['fails'], msg['skips']) glob.finished = True dom.document.title = "Py.test %s" % text dom.document.getElementById("Tests").childNodes[0].nodeValue = \ "Tests [%s]" % text elif msg['type'] == 'FailedTryiter': module_part = get_elem(msg['fullitemname']) if not module_part: glob.pending.append(msg) return True tr = create_elem("tr") td = create_elem("td") a = create_elem("a") a.setAttribute("href", "javascript:show_traceback('%s')" % ( msg['fullitemname'],)) txt = create_text_elem("- FAILED TO LOAD MODULE") a.appendChild(txt) td.appendChild(a) tr.appendChild(td) module_part.appendChild(tr) item_name = msg['fullitemname'] exported_methods.show_fail(item_name, fail_come_back) elif msg['type'] == 'SkippedTryiter': module_part = get_elem(msg['fullitemname']) if not module_part: glob.pending.append(msg) return True tr = create_elem("tr") td = create_elem("td") txt = create_text_elem("- skipped (%s)" % (msg['reason'],)) td.appendChild(txt) tr.appendChild(td) module_part.appendChild(tr) elif msg['type'] == 'RsyncFinished': glob.rsync_done = True elif msg['type'] == 'InterruptedExecution': show_interrupt() elif msg['type'] == 'CrashedExecution': show_crash() if glob.data_empty: mbox = dom.document.getElementById('messagebox') scroll_down_if_needed(mbox) return True def show_skip(item_name="aa"): set_msgbox(item_name, skips[item_name]) def set_msgbox(item_name, data): msgbox = get_elem("messagebox") while len(msgbox.childNodes): msgbox.removeChild(msgbox.childNodes[0]) pre = create_elem("pre") txt = create_text_elem(item_name + "\n" + data) pre.appendChild(txt) msgbox.appendChild(pre) dom.window.location.assign("#message") glob.data_empty = False def show_traceback(item_name="aa"): data = ("====== Traceback: =========\n%s\n======== Stdout: ========\n%s\n" "========== Stderr: ==========\n%s\n" % tracebacks[item_name]) set_msgbox(item_name, data) def fail_come_back(msg): tracebacks[msg['item_name']] = (msg['traceback'], msg['stdout'], msg['stderr']) def skip_come_back(msg): skips[msg['item_name']] = msg['reason'] def reshow_host(): if glob.host == "": return show_host(glob.host) def show_host(host_name="aa"): elem = dom.document.getElementById("jobs") if elem.childNodes: elem.removeChild(elem.childNodes[0]) tbody = create_elem("tbody") for item in glob.host_pending[host_name]: tr = create_elem("tr") td = create_elem("td") td.appendChild(create_text_elem(item)) tr.appendChild(td) tbody.appendChild(tr) elem.appendChild(tbody) elem.style.visibility = "visible" glob.host = host_name dom.setTimeout(reshow_host, 100) def hide_host(): elem = dom.document.getElementById("jobs") while len(elem.childNodes): elem.removeChild(elem.childNodes[0]) elem.style.visibility = "hidden" glob.host = "" def update_rsync(): if glob.finished: return elem = dom.document.getElementById("Tests") if glob.rsync_done is True: elem.childNodes[0].nodeValue = "Tests" return text = "Rsyncing" + '.' * glob.rsync_dots glob.rsync_dots += 1 if glob.rsync_dots > 5: glob.rsync_dots = 0 elem.childNodes[0].nodeValue = "Tests [%s]" % text dom.setTimeout(update_rsync, 1000) def host_init(host_dict): tbody = dom.document.getElementById("hostsbody") for host in host_dict.keys(): tr = create_elem('tr') tbody.appendChild(tr) td = create_elem("td") td.style.background = "#ff0000" txt = create_text_elem(host_dict[host]) td.appendChild(txt) td.id = host tr.appendChild(td) td.setAttribute("onmouseover", "show_host('%s')" % host) td.setAttribute("onmouseout", "hide_host()") glob.rsync_dots = 0 glob.rsync_done = False dom.setTimeout(update_rsync, 1000) glob.host_dict = host_dict glob.host_pending = {} for key in host_dict.keys(): glob.host_pending[key] = [] def key_pressed(key): if key.charCode == ord('s'): scroll_box = dom.document.getElementById("opt_scroll") if opts.scroll: scroll_box.removeAttribute("checked") opts.scroll = False else: scroll_box.setAttribute("checked", "true") opts.scroll = True def sessid_comeback(id): glob.sessid = id exported_methods.show_all_statuses(id, comeback) def main(): glob.finished = False exported_methods.show_hosts(host_init) exported_methods.show_sessid(sessid_comeback) dom.document.onkeypress = key_pressed dom.document.getElementById("opt_scroll").setAttribute("checked", "True")
Python
import string import types ## json.py implements a JSON (http://json.org) reader and writer. ## Copyright (C) 2005 Patrick D. Logan ## Contact mailto:patrickdlogan@stardecisions.com ## ## This library is free software; you can redistribute it and/or ## modify it under the terms of the GNU Lesser General Public ## License as published by the Free Software Foundation; either ## version 2.1 of the License, or (at your option) any later version. ## ## This library is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ## Lesser General Public License for more details. ## ## You should have received a copy of the GNU Lesser General Public ## License along with this library; if not, write to the Free Software ## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA class _StringGenerator(object): def __init__(self, string): self.string = string self.index = -1 def peek(self): i = self.index + 1 if i < len(self.string): return self.string[i] else: return None def next(self): self.index += 1 if self.index < len(self.string): return self.string[self.index] else: raise StopIteration def all(self): return self.string class WriteException(Exception): pass class ReadException(Exception): pass class JsonReader(object): hex_digits = {'A': 10,'B': 11,'C': 12,'D': 13,'E': 14,'F':15} escapes = {'t':'\t','n':'\n','f':'\f','r':'\r','b':'\b'} def read(self, s): self._generator = _StringGenerator(s) result = self._read() return result def _read(self): self._eatWhitespace() peek = self._peek() if peek is None: raise ReadException, "Nothing to read: '%s'" % self._generator.all() if peek == '{': return self._readObject() elif peek == '[': return self._readArray() elif peek == '"': return self._readString() elif peek == '-' or peek.isdigit(): return self._readNumber() elif peek == 't': return self._readTrue() elif peek == 'f': return self._readFalse() elif peek == 'n': return self._readNull() elif peek == '/': self._readComment() return self._read() else: raise ReadException, "Input is not valid JSON: '%s'" % self._generator.all() def _readTrue(self): self._assertNext('t', "true") self._assertNext('r', "true") self._assertNext('u', "true") self._assertNext('e', "true") return True def _readFalse(self): self._assertNext('f', "false") self._assertNext('a', "false") self._assertNext('l', "false") self._assertNext('s', "false") self._assertNext('e', "false") return False def _readNull(self): self._assertNext('n', "null") self._assertNext('u', "null") self._assertNext('l', "null") self._assertNext('l', "null") return None def _assertNext(self, ch, target): if self._next() != ch: raise ReadException, "Trying to read %s: '%s'" % (target, self._generator.all()) def _readNumber(self): isfloat = False result = self._next() peek = self._peek() while peek is not None and (peek.isdigit() or peek == "."): isfloat = isfloat or peek == "." result = result + self._next() peek = self._peek() try: if isfloat: return float(result) else: return int(result) except ValueError: raise ReadException, "Not a valid JSON number: '%s'" % result def _readString(self): result = "" assert self._next() == '"' try: while self._peek() != '"': ch = self._next() if ch == "\\": ch = self._next() if ch in 'brnft': ch = self.escapes[ch] elif ch == "u": ch4096 = self._next() ch256 = self._next() ch16 = self._next() ch1 = self._next() n = 4096 * self._hexDigitToInt(ch4096) n += 256 * self._hexDigitToInt(ch256) n += 16 * self._hexDigitToInt(ch16) n += self._hexDigitToInt(ch1) ch = unichr(n) elif ch not in '"/\\': raise ReadException, "Not a valid escaped JSON character: '%s' in %s" % (ch, self._generator.all()) result = result + ch except StopIteration: raise ReadException, "Not a valid JSON string: '%s'" % self._generator.all() assert self._next() == '"' return result def _hexDigitToInt(self, ch): try: result = self.hex_digits[ch.upper()] except KeyError: try: result = int(ch) except ValueError: raise ReadException, "The character %s is not a hex digit." % ch return result def _readComment(self): assert self._next() == "/" second = self._next() if second == "/": self._readDoubleSolidusComment() elif second == '*': self._readCStyleComment() else: raise ReadException, "Not a valid JSON comment: %s" % self._generator.all() def _readCStyleComment(self): try: done = False while not done: ch = self._next() done = (ch == "*" and self._peek() == "/") if not done and ch == "/" and self._peek() == "*": raise ReadException, "Not a valid JSON comment: %s, '/*' cannot be embedded in the comment." % self._generator.all() self._next() except StopIteration: raise ReadException, "Not a valid JSON comment: %s, expected */" % self._generator.all() def _readDoubleSolidusComment(self): try: ch = self._next() while ch != "\r" and ch != "\n": ch = self._next() except StopIteration: pass def _readArray(self): result = [] assert self._next() == '[' done = self._peek() == ']' while not done: item = self._read() result.append(item) self._eatWhitespace() done = self._peek() == ']' if not done: ch = self._next() if ch != ",": raise ReadException, "Not a valid JSON array: '%s' due to: '%s'" % (self._generator.all(), ch) assert ']' == self._next() return result def _readObject(self): result = {} assert self._next() == '{' done = self._peek() == '}' while not done: key = self._read() if type(key) is not types.StringType: raise ReadException, "Not a valid JSON object key (should be a string): %s" % key self._eatWhitespace() ch = self._next() if ch != ":": raise ReadException, "Not a valid JSON object: '%s' due to: '%s'" % (self._generator.all(), ch) self._eatWhitespace() val = self._read() result[key] = val self._eatWhitespace() done = self._peek() == '}' if not done: ch = self._next() if ch != ",": raise ReadException, "Not a valid JSON array: '%s' due to: '%s'" % (self._generator.all(), ch) assert self._next() == "}" return result def _eatWhitespace(self): p = self._peek() while p is not None and p in string.whitespace or p == '/': if p == '/': self._readComment() else: self._next() p = self._peek() def _peek(self): return self._generator.peek() def _next(self): return self._generator.next() class JsonWriter(object): def _append(self, s): self._results.append(s) def write(self, obj, escaped_forward_slash=False): self._escaped_forward_slash = escaped_forward_slash self._results = [] self._write(obj) return "".join(self._results) def _write(self, obj): ty = type(obj) if ty is types.DictType: n = len(obj) self._append("{") for k, v in obj.items(): self._write(k) self._append(":") self._write(v) n = n - 1 if n > 0: self._append(",") self._append("}") elif ty is types.ListType or ty is types.TupleType: n = len(obj) self._append("[") for item in obj: self._write(item) n = n - 1 if n > 0: self._append(",") self._append("]") elif ty is types.StringType or ty is types.UnicodeType: self._append('"') obj = obj.replace('\\', r'\\') if self._escaped_forward_slash: obj = obj.replace('/', r'\/') obj = obj.replace('"', r'\"') obj = obj.replace('\b', r'\b') obj = obj.replace('\f', r'\f') obj = obj.replace('\n', r'\n') obj = obj.replace('\r', r'\r') obj = obj.replace('\t', r'\t') self._append(obj) self._append('"') elif ty is types.IntType or ty is types.LongType: self._append(str(obj)) elif ty is types.FloatType: self._append("%f" % obj) elif obj is True: self._append("true") elif obj is False: self._append("false") elif obj is None: self._append("null") else: raise WriteException, "Cannot write in JSON: %s" % repr(obj) def write(obj, escaped_forward_slash=False): return JsonWriter().write(obj, escaped_forward_slash) def read(s): return JsonReader().read(s)
Python
""" Rest reporting stuff """ import py import sys from StringIO import StringIO from py.__.test.rsession.reporter import AbstractReporter from py.__.test.rsession import repevent from py.__.rest.rst import * class RestReporter(AbstractReporter): linkwriter = None def __init__(self, *args, **kwargs): super(RestReporter, self).__init__(*args, **kwargs) self.rest = Rest() self.traceback_num = 0 def get_linkwriter(self): if self.linkwriter is None: try: self.linkwriter = self.config.getvalue('linkwriter') except KeyError: print >>sys.stderr, ('no linkwriter configured, using default ' 'one') self.linkwriter = RelLinkWriter() return self.linkwriter def report_unknown(self, what): if self.config.option.verbose: self.add_rest(Paragraph("Unknown report: %s" % what)) def gethost(self, item): if item.channel: return item.channel.gateway.host return self.hosts[0] def report_SendItem(self, item): address = self.gethost(item).hostname if self.config.option.verbose: self.add_rest(Paragraph('sending item %s to %s' % (item.item, address))) def report_HostRSyncing(self, item): self.add_rest(LiteralBlock('%10s: RSYNC ==> %s' % (item.host.hostname[:10], item.host.relpath))) def _host_ready(self, item): self.add_rest(LiteralBlock('%10s: READY' % (item.host.hostname[:10],))) def report_TestStarted(self, event): txt = "Running tests on hosts: %s" % ", ".join([i.hostname for i in event.hosts]) self.add_rest(Title(txt, abovechar='=', belowchar='=')) self.timestart = event.timestart def report_TestFinished(self, item): self.timeend = item.timeend self.summary() return len(self.failed_tests_outcome) > 0 def report_ImmediateFailure(self, item): pass def report_HostGatewayReady(self, item): self.to_rsync[item.host] = len(item.roots) def report_ItemStart(self, event): item = event.item if isinstance(item, py.test.collect.Module): lgt = len(list(item._tryiter())) lns = item.listnames()[1:] name = "/".join(lns) link = self.get_linkwriter().get_link(self.get_rootpath(item), item.fspath) if link: name = Link(name, link) txt = 'Testing module %s (%d items)' % (name, lgt) self.add_rest(Title('Testing module', name, '(%d items)' % (lgt,), belowchar='-')) def get_rootpath(self, item): root = item.parent while root.parent is not None: root = root.parent return root.fspath def print_summary(self, total, skipped_str, failed_str): self.skips() self.failures() txt = "%d tests run%s%s in %.2fs (rsync: %.2f)" % \ (total, skipped_str, failed_str, self.timeend - self.timestart, self.timersync - self.timestart) self.add_rest(Title(txt, belowchar='-')) # since we're rendering each item, the links haven't been rendered # yet self.out.write(self.rest.render_links()) def report_ReceivedItemOutcome(self, event): host = self.gethost(event) if event.outcome.passed: status = [Strong("PASSED")] self.passed[host] += 1 elif event.outcome.skipped: status = [Strong("SKIPPED")] self.skipped_tests_outcome.append(event) self.skipped[host] += 1 else: status = [Strong("FAILED"), InternalLink("traceback%d" % self.traceback_num)] self.traceback_num += 1 self.failed[host] += 1 self.failed_tests_outcome.append(event) # we'll take care of them later itempath = self.get_path_from_item(event.item) status.append(Text(itempath)) hostname = host.hostname self.add_rest(ListItem(Text("%10s:" % (hostname[:10],)), *status)) def skips(self): # XXX hrmph, copied code texts = {} for event in self.skipped_tests_outcome: colitem = event.item if isinstance(event, repevent.ReceivedItemOutcome): outcome = event.outcome text = outcome.skipped itemname = self.get_item_name(event, colitem) elif isinstance(event, repevent.SkippedTryiter): text = str(event.excinfo.value) itemname = "/".join(colitem.listnames()) if text not in texts: texts[text] = [itemname] else: texts[text].append(itemname) if texts: self.add_rest(Title('Reasons for skipped tests:', belowchar='+')) for text, items in texts.items(): for item in items: self.add_rest(ListItem('%s: %s' % (item, text))) def get_host(self, event): try: return event.channel.gateway.host except AttributeError: return None def failures(self): self.traceback_num = 0 tbstyle = self.config.option.tbstyle if self.failed_tests_outcome: self.add_rest(Title('Exceptions:', belowchar='+')) for i, event in enumerate(self.failed_tests_outcome): if i > 0: self.add_rest(Transition()) if isinstance(event, repevent.ReceivedItemOutcome): host = self.get_host(event) itempath = self.get_path_from_item(event.item) root = self.get_rootpath(event.item) link = self.get_linkwriter().get_link(root, event.item.fspath) t = Title(belowchar='+') if link: t.add(Link(itempath, link)) else: t.add(Text(itempath)) if host: t.add(Text('on %s' % (host.hostname,))) self.add_rest(t) if event.outcome.signal: self.repr_signal(event.item, event.outcome) else: self.repr_failure(event.item, event.outcome, tbstyle) else: itempath = self.get_path_from_item(event.item) root = self.get_rootpath(event.item) link = self.get_linkwriter().get_link(root, event.item.fspath) t = Title(abovechar='+', belowchar='+') if link: t.add(Link(itempath, link)) else: t.add(Text(itempath)) out = outcome.Outcome(excinfo=event.excinfo) self.repr_failure(event.item, outcome.ReprOutcome(out.make_repr()), tbstyle) def repr_signal(self, item, outcome): signal = outcome.signal self.add_rest(Title('Received signal: %d' % (outcome.signal,), abovechar='+', belowchar='+')) if outcome.stdout.strip(): self.add_rest(Paragraph('Captured process stdout:')) self.add_rest(LiteralBlock(outcome.stdout)) if outcome.stderr.strip(): self.add_rest(Paragraph('Captured process stderr:')) self.add_rest(LiteralBlock(outcome.stderr)) def repr_failure(self, item, outcome, style): excinfo = outcome.excinfo traceback = excinfo.traceback if not traceback: self.add_rest(Paragraph('empty traceback from item %r' % (item,))) return self.repr_traceback(item, excinfo, traceback, style) if outcome.stdout: self.add_rest(Title('Captured process stdout:', abovechar='+', belowchar='+')) self.add_rest(LiteralBlock(outcome.stdout)) if outcome.stderr: self.add_rest(Title('Captured process stderr:', abovechar='+', belowchar='+')) self.add_rest(LiteralBlock(outcome.stderr)) def repr_traceback(self, item, excinfo, traceback, style): root = self.get_rootpath(item) self.add_rest(LinkTarget('traceback%d' % self.traceback_num, "")) self.traceback_num += 1 if style == 'long': for entry in traceback: link = self.get_linkwriter().get_link(root, py.path.local(entry.path)) if link: self.add_rest(Title(Link(entry.path, link), 'line %d' % (entry.lineno,), belowchar='+', abovechar='+')) else: self.add_rest(Title('%s line %d' % (entry.path, entry.lineno,), belowchar='+', abovechar='+')) self.add_rest(LiteralBlock(self.prepare_source(entry.relline, entry.source))) elif style == 'short': text = [] for entry in traceback: text.append('%s line %d' % (entry.path, entry.lineno)) text.append(' %s' % (entry.source.strip(),)) self.add_rest(LiteralBlock('\n'.join(text))) self.add_rest(Title(excinfo.typename, belowchar='+')) self.add_rest(LiteralBlock(excinfo.value)) def prepare_source(self, relline, source): text = [] for num, line in enumerate(source.split('\n')): if num == relline: text.append('>>> %s' % (line,)) else: text.append(' %s' % (line,)) return '\n'.join(text) def add_rest(self, item): self.rest.add(item) self.out.write('%s\n\n' % (item.text(),)) def get_path_from_item(self, item): lns = item.listnames()[1:] for i, ln in enumerate(lns): if i > 0 and ln != '()': lns[i] = '/%s' % (ln,) itempath = ''.join(lns) return itempath class AbstractLinkWriter(object): def get_link(self, base, path): pass class NoLinkWriter(AbstractLinkWriter): def get_link(self, base, path): return '' class LinkWriter(AbstractLinkWriter): def __init__(self, baseurl): self.baseurl = baseurl def get_link(self, base, path): relpath = path.relto(base) return self.baseurl + relpath class RelLinkWriter(AbstractLinkWriter): def get_link(self, base, path): return path.relto(base)
Python
""" local-only operations """ import py from py.__.test.rsession.executor import BoxExecutor, RunExecutor,\ ApigenExecutor from py.__.test.rsession import repevent from py.__.test.rsession.outcome import ReprOutcome # XXX copied from session.py def startcapture(session): if not session.config.option.nocapture: session._capture = py.io.StdCapture() def finishcapture(session): if hasattr(session, '_capture'): capture = session._capture del session._capture return capture.reset() return "", "" def box_runner(item, session, reporter): r = BoxExecutor(item, config=session.config) return ReprOutcome(r.execute()) def plain_runner(item, session, reporter): r = RunExecutor(item, usepdb=session.config.option.usepdb, reporter=reporter, config=session.config) outcome = r.execute() outcome = ReprOutcome(outcome.make_repr(session.config.option.tbstyle)) return outcome def benchmark_runner(item, session, reporter): raise NotImplementedError() def apigen_runner(item, session, reporter): #retval = plain_runner(item, session, reporter) startcapture(session) r = ApigenExecutor(item, reporter=reporter, config=session.config) outcome = r.execute(session.tracer) outcome = ReprOutcome(outcome.make_repr(session.config.option.tbstyle)) outcome.stdout, outcome.stderr = finishcapture(session) return outcome def exec_runner(item, session, reporter): raise NotImplementedError() # runner interface is here to perform several different types of run #+1. box_runner - for running normal boxed tests #+2. plain_runner - for performing running without boxing (necessary for pdb) # XXX: really? #-3. exec_runner - for running under different interpreter #-4. benchmark_runner - for running with benchmarking #-5. apigen_runner - for running under apigen to generate api out of it. def local_loop(session, reporter, itemgenerator, shouldstop, config, runner=None): assert runner is not None #if runner is None: # if session.config.option.apigen: # runner = apigen_runner # else: # runner = box_runner while 1: try: item = itemgenerator.next() if shouldstop(): return outcome = runner(item, session, reporter) reporter(repevent.ReceivedItemOutcome(None, item, outcome)) except StopIteration: break
Python
""" Reporter classes for showing asynchronous and synchronous status events """ import py import time def basic_report(msg_type, message): print msg_type, message #def report(msg_type, message): # pass ##def report_error(excinfo): ## if isinstance(excinfo, py.test.collect.Item.Skipped): ## # we need to dispatch this info ## report(Skipped(excinfo)) ## else: ## report("itererror", excinfo) def wrapcall(reporter, func, *args, **kwargs): reporter(CallStart(func, args, kwargs)) try: retval = func(*args, **kwargs) except: reporter(CallException(func, args, kwargs)) raise else: reporter(CallFinish(func, args, kwargs)) return retval # ---------------------------------------------------------------------- # Reporting Events # ---------------------------------------------------------------------- class ReportEvent(object): def __repr__(self): l = ["%s=%s" %(key, value) for key, value in self.__dict__.items()] return "<%s %s>" %(self.__class__.__name__, " ".join(l),) class SendItem(ReportEvent): def __init__(self, channel, item): self.item = item self.channel = channel if channel: self.host = channel.gateway.host class ReceivedItemOutcome(ReportEvent): def __init__(self, channel, item, outcome): self.channel = channel if channel: self.host = channel.gateway.host self.item = item self.outcome = outcome class CallEvent(ReportEvent): def __init__(self, func, args, kwargs): self.func = func self.args = args self.kwargs = kwargs def __repr__(self): call = "%s args=%s, kwargs=%s" %(self.func.__name__, self.args, self.kwargs) return '<%s %s>' %(self.__class__.__name__, call) class CallStart(CallEvent): pass class CallException(CallEvent): pass class CallFinish(CallEvent): pass class HostRSyncing(ReportEvent): def __init__(self, host, root, remotepath, synced): self.host = host self.root = root self.remotepath = remotepath self.synced = synced class HostGatewayReady(ReportEvent): def __init__(self, host, roots): self.host = host self.roots = roots class HostRSyncRootReady(ReportEvent): def __init__(self, host, root): self.host = host self.root = root class TestStarted(ReportEvent): def __init__(self, hosts, topdir, roots): self.hosts = hosts self.topdir = topdir self.roots = roots self.timestart = time.time() class TestFinished(ReportEvent): def __init__(self): self.timeend = time.time() class Nodes(ReportEvent): def __init__(self, nodes): self.nodes = nodes class SkippedTryiter(ReportEvent): def __init__(self, excinfo, item): self.excinfo = excinfo self.item = item class FailedTryiter(ReportEvent): def __init__(self, excinfo, item): self.excinfo = excinfo self.item = item class ItemStart(ReportEvent): """ This class shows most of the start stuff, like directory, module, class can be used for containers """ def __init__(self, item): self.item = item class RsyncFinished(ReportEvent): def __init__(self): self.time = time.time() class ImmediateFailure(ReportEvent): def __init__(self, item, outcome): self.item = item self.outcome = outcome class PongReceived(ReportEvent): def __init__(self, hostid, result): self.hostid = hostid self.result = result class InterruptedExecution(ReportEvent): def __init__(self): self.timeend = time.time() class CrashedExecution(ReportEvent): def __init__(self): self.timeend = time.time()
Python
""" boxing - wrapping process with another process so we can run a process inside and see if it crashes """ import py import os import sys import marshal from py.__.test import config as pytestconfig PYTESTSTDOUT = "pyteststdout" PYTESTSTDERR = "pyteststderr" PYTESTRETVAL = "pytestretval" import tempfile import itertools from StringIO import StringIO counter = itertools.count().next class FileBox(object): def __init__(self, fun, args=None, kwargs=None, config=None): if args is None: args = [] if kwargs is None: kwargs = {} self.fun = fun self.config = config assert self.config self.args = args self.kwargs = kwargs def run(self, continuation=False): # XXX we should not use py.test.ensuretemp here count = counter() tempdir = py.test.ensuretemp("box%d" % count) self.tempdir = tempdir self.PYTESTRETVAL = tempdir.join('retval') self.PYTESTSTDOUT = tempdir.join('stdout') self.PYTESTSTDERR = tempdir.join('stderr') nice_level = self.config.getvalue('dist_nicelevel') pid = os.fork() if pid: if not continuation: self.parent(pid) else: return self.parent, pid else: try: outcome = self.children(nice_level) except: excinfo = py.code.ExceptionInfo() x = open("/tmp/traceback", "w") print >>x, "Internal box error" for i in excinfo.traceback: print >>x, str(i)[2:-1] print >>x, excinfo x.close() os._exit(1) os.close(1) os.close(2) os._exit(0) return pid def children(self, nice_level): # right now we need to call a function, but first we need to # map all IO that might happen # make sure sys.stdout points to file descriptor one sys.stdout = stdout = self.PYTESTSTDOUT.open('w') sys.stdout.flush() fdstdout = stdout.fileno() if fdstdout != 1: os.dup2(fdstdout, 1) sys.stderr = stderr = self.PYTESTSTDERR.open('w') fdstderr = stderr.fileno() if fdstderr != 2: os.dup2(fdstderr, 2) retvalf = self.PYTESTRETVAL.open("w") try: if nice_level: os.nice(nice_level) # with fork() we have duplicated py.test's basetemp # directory so we want to set it manually here. # this may be expensive for some test setups, # but that is what you get with boxing. # XXX but we are called in more than strict boxing # mode ("AsyncExecutor") so we can't do the following without # inflicting on --dist speed, hum: # pytestconfig.basetemp = self.tempdir.join("childbasetemp") retval = self.fun(*self.args, **self.kwargs) retvalf.write(marshal.dumps(retval)) finally: stdout.close() stderr.close() retvalf.close() os._exit(0) def parent(self, pid, waiter=os.waitpid): pid, exitstat = waiter(pid, 0) self.signal = exitstat & 0x7f self.exitstat = exitstat & 0xff00 if not exitstat: retval = self.PYTESTRETVAL.open() try: retval_data = retval.read() finally: retval.close() self.retval = marshal.loads(retval_data) else: self.retval = None self.stdoutrepr = self.PYTESTSTDOUT.read() self.stderrrepr = self.PYTESTSTDERR.read() return self.stdoutrepr, self.stderrrepr Box = FileBox
Python
""" some example for running box stuff inside """ import sys import py, os def boxf1(): print "some out" print >>sys.stderr, "some err" return 1 def boxf2(): os.write(1, "someout") os.write(2, "someerr") return 2 def boxseg(): os.kill(os.getpid(), 11) def boxhuge(): os.write(1, " " * 10000) os.write(2, " " * 10000) os.write(1, " " * 10000) os.write(1, " " * 10000) os.write(2, " " * 10000) os.write(2, " " * 10000) os.write(1, " " * 10000) return 3
Python
def f1(): f2() def f2(): pass def g1(): g2() def g2(): raise ValueError()
Python
""" Support module for running tests """ import py def func_source(): import py import time def funcpass(): pass def funcfail(): raise AssertionError("hello world") def funcskip(): py.test.skip("skipped") def funcprint(): print "samfing" def funcprintfail(): print "samfing elz" asddsa def funcoptioncustom(): assert py.test.config.getvalue("custom") def funchang(): import time time.sleep(1000) class BasicRsessionTest(object): def setup_class(cls): tmpdir = py.test.ensuretemp(cls.__name__) source = py.code.Source(func_source)[1:].deindent() testonepath = tmpdir.ensure("test_one.py") testonepath.write(source) cls.config = py.test.config._reparse([tmpdir]) cls.collector_test_one = cls.config._getcollector(testonepath) def getexample(self, name): funcname = "func" + name col = self.collector_test_one.join(funcname) assert col is not None, funcname return col def getmod(self): return self.collector_test_one
Python
#
Python
""" Remote session base class """ import os import py import sys import re import time from py.__.test.rsession import repevent from py.__.test.rsession.master import MasterNode, dispatch_loop, itemgen from py.__.test.rsession.hostmanage import HostInfo, HostManager from py.__.test.rsession.local import local_loop, plain_runner, apigen_runner,\ box_runner from py.__.test.rsession.reporter import LocalReporter, RemoteReporter from py.__.test.session import Session from py.__.test.outcome import Skipped, Failed class AbstractSession(Session): """ An abstract session executes collectors/items through a runner. """ def fixoptions(self): option = self.config.option if option.runbrowser and not option.startserver: #print "--runbrowser implies --startserver" option.startserver = True if self.config.getvalue("dist_boxed"): option.boxed = True super(AbstractSession, self).fixoptions() def init_reporter(self, reporter, hosts, reporter_class, arg=""): """ This initialises so called `reporter` class, which will handle all event presenting to user. Does not get called if main received custom reporter """ startserverflag = self.config.option.startserver restflag = self.config.option.restreport if startserverflag and reporter is None: from py.__.test.rsession.web import start_server, exported_methods if self.config.option.runbrowser: from socket import INADDR_ANY port = INADDR_ANY # pick a random port when starting browser else: port = 8000 # stick to a fixed port otherwise reporter = exported_methods.report httpd = start_server(server_address = ('', port)) port = httpd.server_port if self.config.option.runbrowser: import webbrowser, thread # webbrowser.open() may block until the browser finishes or not url = "http://localhost:%d" % (port,) thread.start_new_thread(webbrowser.open, (url,)) elif reporter is None: if restflag: from py.__.test.rsession.rest import RestReporter reporter_class = RestReporter if arg: reporter_instance = reporter_class(self.config, hosts) else: reporter_instance = reporter_class(self.config, hosts) reporter = reporter_instance.report else: startserverflag = False return reporter, startserverflag def reporterror(reporter, data): excinfo, item = data if excinfo is None: reporter(repevent.ItemStart(item)) elif excinfo.type is Skipped: reporter(repevent.SkippedTryiter(excinfo, item)) else: reporter(repevent.FailedTryiter(excinfo, item)) reporterror = staticmethod(reporterror) def kill_server(self, startserverflag): """ Kill web server """ if startserverflag: from py.__.test.rsession.web import kill_server kill_server() def wrap_reporter(self, reporter): """ We wrap reporter around, which makes it possible to us to track existance of failures """ self.was_failure = False def new_reporter(event): if isinstance(event, repevent.ReceivedItemOutcome) and \ not event.outcome.passed and \ not event.outcome.skipped: self.was_failure = True return reporter(event) checkfun = lambda : self.config.option.exitfirst and \ self.was_failure # for tests self.checkfun = checkfun return new_reporter, checkfun class RSession(AbstractSession): """ Remote version of session """ def fixoptions(self): super(RSession, self).fixoptions() option = self.config.option if option.nocapture: print "Cannot use nocapture with distributed testing" sys.exit(1) config = self.config try: config.getvalue('dist_hosts') except KeyError: print "For running ad-hoc distributed tests you need to specify" print "dist_hosts in a local conftest.py file, for example:" print "for example:" print print " dist_hosts = ['localhost'] * 4 # for 3 processors" print " dist_hosts = ['you@remote.com', '...'] # for testing on ssh accounts" print " # with your remote ssh accounts" print print "see also: http://codespeak.net/py/current/doc/test.html#automated-distributed-testing" raise SystemExit def main(self, reporter=None): """ main loop for running tests. """ args = self.config.args hm = HostManager(self.config) reporter, startserverflag = self.init_reporter(reporter, hm.hosts, RemoteReporter) reporter, checkfun = self.wrap_reporter(reporter) reporter(repevent.TestStarted(hm.hosts, self.config.topdir, hm.roots)) try: nodes = hm.setup_hosts(reporter) reporter(repevent.RsyncFinished()) try: self.dispatch_tests(nodes, reporter, checkfun) except (KeyboardInterrupt, SystemExit): print >>sys.stderr, "C-c pressed waiting for gateways to teardown..." channels = [node.channel for node in nodes] hm.kill_channels(channels) hm.teardown_gateways(reporter, channels) print >>sys.stderr, "... Done" raise channels = [node.channel for node in nodes] hm.teardown_hosts(reporter, channels, nodes, exitfirst=self.config.option.exitfirst) reporter(repevent.Nodes(nodes)) retval = reporter(repevent.TestFinished()) self.kill_server(startserverflag) return retval except (KeyboardInterrupt, SystemExit): reporter(repevent.InterruptedExecution()) self.kill_server(startserverflag) raise except: reporter(repevent.CrashedExecution()) self.kill_server(startserverflag) raise def dispatch_tests(self, nodes, reporter, checkfun): colitems = self.config.getcolitems() keyword = self.config.option.keyword itemgenerator = itemgen(colitems, reporter, keyword, self.reporterror) all_tests = dispatch_loop(nodes, itemgenerator, checkfun) class LSession(AbstractSession): """ Local version of session """ def main(self, reporter=None, runner=None): # check out if used options makes any sense args = self.config.args hm = HostManager(self.config, hosts=[HostInfo('localhost')]) hosts = hm.hosts if not self.config.option.nomagic: py.magic.invoke(assertion=1) reporter, startserverflag = self.init_reporter(reporter, hosts, LocalReporter, args[0]) reporter, checkfun = self.wrap_reporter(reporter) reporter(repevent.TestStarted(hosts, self.config.topdir, [])) colitems = self.config.getcolitems() reporter(repevent.RsyncFinished()) if runner is None: runner = self.init_runner() keyword = self.config.option.keyword itemgenerator = itemgen(colitems, reporter, keyword, self.reporterror) local_loop(self, reporter, itemgenerator, checkfun, self.config, runner=runner) retval = reporter(repevent.TestFinished()) self.kill_server(startserverflag) if not self.config.option.nomagic: py.magic.revoke(assertion=1) self.write_docs() return retval def write_docs(self): if self.config.option.apigen: from py.__.apigen.tracer.docstorage import DocStorageAccessor apigen = py.path.local(self.config.option.apigen).pyimport() if not hasattr(apigen, 'build'): raise NotImplementedError("%s does not contain 'build' " "function" %(apigen,)) print >>sys.stderr, 'building documentation' capture = py.io.StdCaptureFD() try: pkgdir = py.path.local(self.config.args[0]).pypkgpath() apigen.build(pkgdir, DocStorageAccessor(self.docstorage), capture) finally: capture.reset() print >>sys.stderr, '\ndone' def init_runner(self): if self.config.option.apigen: from py.__.apigen.tracer.tracer import Tracer, DocStorage pkgdir = py.path.local(self.config.args[0]).pypkgpath() apigen = py.path.local(self.config.option.apigen).pyimport() if not hasattr(apigen, 'get_documentable_items'): raise NotImplementedError("Provided script does not seem " "to contain get_documentable_items") pkgname, items = apigen.get_documentable_items(pkgdir) self.docstorage = DocStorage().from_dict(items, module_name=pkgname) self.tracer = Tracer(self.docstorage) return apigen_runner elif self.config.option.boxed: return box_runner else: return plain_runner
Python
""" Remote executor """ import py, os, sys from py.__.test.rsession.outcome import Outcome, ReprOutcome from py.__.test.rsession.box import Box from py.__.test.rsession import repevent from py.__.test.outcome import Skipped, Failed class RunExecutor(object): """ Same as in executor, but just running run """ wraps = False def __init__(self, item, usepdb=False, reporter=None, config=None): self.item = item self.usepdb = usepdb self.reporter = reporter self.config = config assert self.config def run(self, capture=True): if capture: self.item.startcapture() try: self.item.run() finally: self.item.finishcapture() else: self.item.run() def execute(self, capture=True): try: self.run(capture) outcome = Outcome() except Skipped, e: outcome = Outcome(skipped=str(e)) except (SystemExit, KeyboardInterrupt): raise except: e = sys.exc_info()[1] if isinstance(e, Failed) and e.excinfo: excinfo = e.excinfo else: excinfo = py.code.ExceptionInfo() if isinstance(self.item, py.test.collect.Function): fun = self.item.obj # hope this is stable code = py.code.Code(fun) excinfo.traceback = excinfo.traceback.cut( path=code.path, firstlineno=code.firstlineno) outcome = Outcome(excinfo=excinfo, setupfailure=False) if self.usepdb: if self.reporter is not None: self.reporter(repevent.ImmediateFailure(self.item, ReprOutcome(outcome.make_repr (self.config.option.tbstyle)))) import pdb pdb.post_mortem(excinfo._excinfo[2]) # XXX hmm, we probably will not like to continue from that # point raise SystemExit() outcome.stdout, outcome.stderr = self.item._getouterr() return outcome class ApigenExecutor(RunExecutor): """ Same as RunExecutor, but takes tracer to trace calls as an argument to execute """ def execute(self, tracer): self.tracer = tracer return super(ApigenExecutor, self).execute() def wrap_underlaying(self, target, *args): try: self.tracer.start_tracing() return target(*args) finally: self.tracer.end_tracing() def run(self, capture): """ We want to trace *only* function objects here. Unsure what to do with custom collectors at all """ if hasattr(self.item, 'obj') and type(self.item) is py.test.collect.Function: self.item.execute = self.wrap_underlaying self.item.run() class BoxExecutor(RunExecutor): """ Same as RunExecutor, but boxes test instead """ wraps = True def execute(self): def fun(): outcome = RunExecutor.execute(self, False) return outcome.make_repr(self.config.option.tbstyle) b = Box(fun, config=self.config) pid = b.run() assert pid if b.retval is not None: passed, setupfailure, excinfo, skipped, critical, _, _, _\ = b.retval return (passed, setupfailure, excinfo, skipped, critical, 0, b.stdoutrepr, b.stderrrepr) else: return (False, False, None, False, False, b.signal, b.stdoutrepr, b.stderrrepr) class AsyncExecutor(RunExecutor): """ same as box executor, but instead it returns function to continue computations (more async mode) """ wraps = True def execute(self): def fun(): outcome = RunExecutor.execute(self, False) return outcome.make_repr(self.config.option.tbstyle) b = Box(fun, config=self.config) parent, pid = b.run(continuation=True) def cont(waiter=os.waitpid): parent(pid, waiter=waiter) if b.retval is not None: passed, setupfailure, excinfo, skipped,\ critical, _, _, _ = b.retval return (passed, setupfailure, excinfo, skipped, critical, 0, b.stdoutrepr, b.stderrrepr) else: return (False, False, None, False, False, b.signal, b.stdoutrepr, b.stderrrepr) return cont, pid
Python
""" Node code for Master. """ import py from py.__.test.rsession.outcome import ReprOutcome from py.__.test.rsession import repevent class MasterNode(object): def __init__(self, channel, reporter): self.channel = channel self.reporter = reporter self.pending = [] channel.setcallback(self._callback) def _callback(self, outcome): item = self.pending.pop() self.receive_result(outcome, item) def receive_result(self, outcomestring, item): repr_outcome = ReprOutcome(outcomestring) # send finish report self.reporter(repevent.ReceivedItemOutcome( self.channel, item, repr_outcome)) def send(self, item): try: if item is StopIteration: self.channel.send(42) else: self.pending.insert(0, item) #itemspec = item.listnames()[1:] self.channel.send(item._get_collector_trail()) # send start report self.reporter(repevent.SendItem(self.channel, item)) except IOError: print "Sending error, channel IOError" print self.channel._getremoteerror() # XXX: this should go as soon as we'll have proper detection # of hanging nodes and such raise def itemgen(colitems, reporter, keyword, reporterror): def rep(x): reporterror(reporter, x) for x in colitems: for y in x._tryiter(reporterror=rep, keyword=keyword): yield y def dispatch_loop(masternodes, itemgenerator, shouldstop, waiter = lambda: py.std.time.sleep(0.1), max_tasks_per_node=None): if not max_tasks_per_node: max_tasks_per_node = py.test.config.getvalue("dist_taskspernode") all_tests = {} while 1: try: for node in masternodes: if len(node.pending) < max_tasks_per_node: item = itemgenerator.next() all_tests[item] = True if shouldstop(): for _node in masternodes: _node.send(StopIteration) # magic connector return None node.send(item) except StopIteration: break waiter() return all_tests
Python
""" Classes for representing outcomes on master and slavenode sides """ # WARNING! is_critical is debugging flag which means something # wrong went on a different level. Usually that means # internal bug. import sys import py class Outcome(object): def __init__(self, setupfailure=False, excinfo=None, skipped=None, is_critical=False): self.passed = not excinfo and not skipped self.skipped = skipped self.setupfailure = setupfailure self.excinfo = excinfo self.is_critical = is_critical self.signal = 0 self.stdout = "" # XXX temporary self.stderr = "" assert bool(self.passed) + bool(excinfo) + bool(skipped) == 1 def make_excinfo_repr(self, tbstyle): if self.excinfo is None: return None excinfo = self.excinfo tb_info = [self.traceback_entry_repr(x, tbstyle) for x in excinfo.traceback] rec_index = excinfo.traceback.recursionindex() if hasattr(excinfo, 'type'): etype = excinfo.type if hasattr(etype, '__name__'): etype = etype.__name__ else: etype = excinfo.typename val = getattr(excinfo, 'value', None) if not val: val = excinfo.exconly() val = str(val) return (etype, val, (tb_info, rec_index)) def traceback_entry_repr(self, tb_entry, tb_style): lineno = tb_entry.lineno relline = lineno - tb_entry.frame.code.firstlineno path = str(tb_entry.path) #try: try: if tb_style == 'long': source = str(tb_entry.getsource()) else: source = str(tb_entry.getsource()).split("\n")[relline] except py.error.ENOENT: source = "[cannot get source]" name = str(tb_entry.frame.code.name) # XXX: Bare except. What can getsource() raise anyway? # SyntaxError, AttributeError, IndentationError for sure, check it #except: # source = "<could not get source>" return (relline, lineno, source, path, name) def make_repr(self, tbstyle="long"): return (self.passed, self.setupfailure, self.make_excinfo_repr(tbstyle), self.skipped, self.is_critical, 0, self.stdout, self.stderr) class TracebackEntryRepr(object): def __init__(self, tbentry): relline, lineno, self.source, self.path, self.name = tbentry self.relline = int(relline) self.path = py.path.local(self.path) self.lineno = int(lineno) self.locals = {} def __repr__(self): return "line %s in %s\n %s" %(self.lineno, self.path, self.source[100:]) def getsource(self): return py.code.Source(self.source).strip() def getfirstlinesource(self): return self.lineno - self.relline class TracebackRepr(list): def recursionindex(self): return self.recursion_index class ExcInfoRepr(object): def __init__(self, excinfo): self.typename, self.value, tb_i = excinfo tb, rec_index = tb_i self.traceback = TracebackRepr([TracebackEntryRepr(x) for x in tb]) self.traceback.recursion_index = rec_index def __repr__(self): l = ["%s=%s" %(x, getattr(self, x)) for x in "typename value traceback".split()] return "<ExcInfoRepr %s>" %(" ".join(l),) def exconly(self, tryshort=False): """ Somehow crippled version of original one """ return "%s: %s" % (self.typename, self.value) def errisinstance(self, exc_t): if not isinstance(exc_t, tuple): exc_t = (exc_t,) for exc in exc_t: if self.typename == str(exc).split('.')[-1]: return True return False class ReprOutcome(object): def __init__(self, repr_tuple): (self.passed, self.setupfailure, excinfo, self.skipped, self.is_critical, self.signal, self.stdout, self.stderr) = repr_tuple if excinfo is None: self.excinfo = None else: self.excinfo = ExcInfoRepr(excinfo) def __repr__(self): l = ["%s=%s" %(x, getattr(self, x)) for x in "signal passed skipped setupfailure excinfo stdout stderr".split()] return "<ReprOutcome %s>" %(" ".join(l),)
Python
#
Python
""" Node code for slaves. """ import py from py.__.test.rsession.executor import RunExecutor, BoxExecutor, AsyncExecutor from py.__.test.rsession.outcome import Outcome from py.__.test.outcome import Skipped import thread import os class SlaveNode(object): def __init__(self, config, executor): #self.rootcollector = rootcollector self.config = config self.executor = executor def execute(self, itemspec): item = self.config._getcollector(itemspec) ex = self.executor(item, config=self.config) return ex.execute() def run(self, itemspec): #outcome = self.execute(itemspec) #return outcome.make_repr() outcome = self.execute(itemspec) if self.executor.wraps: return outcome else: return outcome.make_repr(self.config.option.tbstyle) def slave_main(receive, send, path, config): import os assert os.path.exists(path) path = os.path.abspath(path) nodes = {} def getnode(item): node = nodes.get(item[0], None) if node is not None: return node col = py.test.collect.Directory(str(py.path.local(path).join(item[0]))) if config.option.boxed: executor = BoxExecutor else: executor = RunExecutor node = nodes[item[0]] = SlaveNode(config, executor) return node while 1: nextitem = receive() if nextitem is None: break try: node = getnode(nextitem) res = node.run(nextitem) except Skipped, s: send(Outcome(skipped=str(s)).make_repr()) except: excinfo = py.code.ExceptionInfo() send(Outcome(excinfo=excinfo, is_critical=True).make_repr()) else: if not res[0] and not res[3] and config.option.exitfirst: # we're finished, but need to eat what we can send(res) break send(res) while nextitem is not None: nextitem = receive() defaultconftestnames = ['dist_nicelevel'] def setup_slave(host, config): channel = host.gw.remote_exec(str(py.code.Source(setup, "setup()"))) configrepr = config._makerepr(defaultconftestnames) #print "sending configrepr", configrepr topdir = host.gw_remotepath if topdir is None: assert host.inplacelocal topdir = config.topdir channel.send(str(topdir)) channel.send(configrepr) return channel def setup(): # our current dir is the topdir import os, sys basedir = channel.receive() config_repr = channel.receive() # setup defaults... sys.path.insert(0, basedir) import py config = py.test.config assert not config._initialized config._initdirect(basedir, config_repr) if hasattr(os, 'nice'): nice_level = config.getvalue('dist_nicelevel') os.nice(nice_level) if not config.option.nomagic: py.magic.invoke(assertion=1) from py.__.test.rsession.slave import slave_main slave_main(channel.receive, channel.send, basedir, config) if not config.option.nomagic: py.magic.revoke(assertion=1) channel.close()
Python
from __future__ import generators import py from py.__.test.session import Session from py.__.test.terminal.out import getout from py.__.test.outcome import Failed, Passed, Skipped def checkpyfilechange(rootdir, statcache={}): """ wait until project files are changed. """ def fil(p): return p.ext in ('.py', '.c', '.h') #fil = lambda x: x.check(fnmatch='*.py') def rec(p): return p.check(dotfile=0) changed = False for path in rootdir.visit(fil, rec): oldstat = statcache.get(path, None) try: statcache[path] = curstat = path.stat() except py.error.ENOENT: if oldstat: del statcache[path] print "# WARN: race condition on", path else: if oldstat: if oldstat.mtime != curstat.mtime or \ oldstat.size != curstat.size: changed = True print "# MODIFIED", path else: changed = True return changed def getfailureitems(failures): l = [] for rootpath, names in failures: root = py.path.local(rootpath) if root.check(dir=1): current = py.test.collect.Directory(root).Directory(root) elif root.check(file=1): current = py.test.collect.Module(root).Module(root) # root is fspath of names[0] -> pop names[0] # slicing works with empty lists names = names[1:] while names: name = names.pop(0) try: current = current.join(name) except NameError: print "WARNING: could not find %s on %r" %(name, current) break else: l.append(current) return l class RemoteTerminalSession(Session): def __init__(self, config, file=None): super(RemoteTerminalSession, self).__init__(config=config) self._setexecutable() if file is None: file = py.std.sys.stdout self._file = file self.out = getout(file) def _setexecutable(self): name = self.config.option.executable if name is None: executable = py.std.sys.executable else: executable = py.path.local.sysfind(name) assert executable is not None, executable self.executable = executable def main(self): rootdir = self.config.topdir wasfailing = False failures = [] while 1: if self.config.option.looponfailing and (failures or not wasfailing): while not checkpyfilechange(rootdir): py.std.time.sleep(4.4) wasfailing = len(failures) failures = self.run_remote_session(failures) if not self.config.option.looponfailing: break print "#" * 60 print "# looponfailing: mode: %d failures args" % len(failures) for root, names in failures: name = "/".join(names) # XXX print "Failure at: %r" % (name,) print "# watching py files below %s" % rootdir print "# ", "^" * len(str(rootdir)) return failures def _initslavegateway(self): print "* opening PopenGateway: ", self.executable topdir = self.config.topdir return py.execnet.PopenGateway(self.executable), topdir def run_remote_session(self, failures): gw, topdir = self._initslavegateway() channel = gw.remote_exec(""" from py.__.test.terminal.remote import slaverun_TerminalSession slaverun_TerminalSession(channel) """, stdout=self.out, stderr=self.out) try: print "MASTER: initiated slave terminal session ->" repr = self.config._makerepr(conftestnames=[]) channel.send((str(topdir), repr, failures)) print "MASTER: send start info, topdir=%s" % (topdir,) try: return channel.receive() except channel.RemoteError, e: print "*" * 70 print "ERROR while waiting for proper slave startup" print "*" * 70 print e return [] finally: gw.exit() def slaverun_TerminalSession(channel): """ we run this on the other side. """ print "SLAVE: initializing ..." topdir, repr, failures = channel.receive() print "SLAVE: received configuration, using topdir:", topdir config = py.test.config config._initdirect(topdir, repr, failures) config.option.session = None config.option.looponfailing = False config.option.usepdb = False config.option.executable = None if failures: config.option.verbose = True session = config.initsession() session.shouldclose = channel.isclosed print "SLAVE: starting session.main()" session.main() failures = session.getitemoutcomepairs(Failed) failures = [config.get_collector_trail(item) for item,_ in failures] channel.send(failures)
Python
from __future__ import generators import sys import os import py from py.__.misc import terminal_helper class Out(object): tty = False fullwidth = terminal_helper.terminal_width def __init__(self, file): self.file = py.io.dupfile(file) def sep(self, sepchar, title=None, fullwidth=None): if not fullwidth: fullwidth = self.fullwidth # the goal is to have the line be as long as possible # under the condition that len(line) <= fullwidth if title is not None: # we want 2 + 2*len(fill) + len(title) <= fullwidth # i.e. 2 + 2*len(sepchar)*N + len(title) <= fullwidth # 2*len(sepchar)*N <= fullwidth - len(title) - 2 # N <= (fullwidth - len(title) - 2) // (2*len(sepchar)) N = (fullwidth - len(title) - 2) // (2*len(sepchar)) fill = sepchar * N line = "%s %s %s" % (fill, title, fill) else: # we want len(sepchar)*N <= fullwidth # i.e. N <= fullwidth // len(sepchar) line = sepchar * (fullwidth // len(sepchar)) # in some situations there is room for an extra sepchar at the right, # in particular if we consider that with a sepchar like "_ " the # trailing space is not important at the end of the line if len(line) + len(sepchar.rstrip()) <= fullwidth: line += sepchar.rstrip() self.line(line) class TerminalOut(Out): tty = True def __init__(self, file): super(TerminalOut, self).__init__(file) def sep(self, sepchar, title=None): super(TerminalOut, self).sep(sepchar, title, terminal_helper.get_terminal_width()) def write(self, s): self.file.write(str(s)) self.file.flush() def line(self, s=''): if s: self.file.write(s + '\n') else: self.file.write('\n') self.file.flush() def rewrite(self, s=''): #self.write('\x1b[u%s' % s) - this escape sequence does # strange things, or nothing at all, on various terminals. # XXX what is it supposed to do in the first place?? self.write(s) class FileOut(Out): def write(self, s): self.file.write(str(s)) self.file.flush() def line(self, s=''): if s: self.file.write(str(s) + '\n') else: self.file.write('\n') self.file.flush() def rewrite(self, s=''): self.write(s) def getout(file): # XXX investigate further into terminal output, this is not enough # if file is None: file = py.std.sys.stdout elif hasattr(file, 'send'): file = WriteFile(file.send) elif callable(file): file = WriteFile(file) if hasattr(file, 'isatty') and file.isatty(): return TerminalOut(file) else: return FileOut(file) class WriteFile(object): def __init__(self, writemethod): self.write = writemethod def flush(self): return
Python
import py from time import time as now from py.__.test.terminal.out import getout from py.__.test.representation import Presenter from py.__.test.outcome import Skipped, Passed, Failed def getrelpath(source, dest): base = source.common(dest) if not base: return None # with posix local paths '/' is always a common base relsource = source.relto(base) reldest = dest.relto(base) n = relsource.count(source.sep) target = dest.sep.join(('..', )*n + (reldest, )) return target from py.__.test.session import Session class TerminalSession(Session): def __init__(self, config, file=None): super(TerminalSession, self).__init__(config) if file is None: file = py.std.sys.stdout self._file = file self.out = getout(file) self._opencollectors = [] self.presenter = Presenter(self.out, config) # --------------------- # PROGRESS information # --------------------- def start(self, colitem): super(TerminalSession, self).start(colitem) if self.config.option.collectonly: cols = self._opencollectors self.out.line(' ' * len(cols) + repr(colitem)) cols.append(colitem) else: cls = getattr(colitem, '__class__', None) if cls is None: return if issubclass(cls, py.test.collect.Module): self.start_Module(colitem) elif issubclass(cls, py.test.collect.Item): self.start_Item(colitem) #for typ in py.std.inspect.getmro(cls): # meth = getattr(self, 'start_%s' % typ.__name__, None) # if meth: # meth(colitem) # break colitem.start = py.std.time.time() def start_Module(self, colitem): if self.config.option.verbose == 0: abbrev_fn = getrelpath(py.path.local('.xxx.'), colitem.fspath) self.out.write('%s' % (abbrev_fn, )) else: self.out.line() self.out.line("+ testmodule: %s" % colitem.fspath) def startiteration(self, colitem, subitems): if (isinstance(colitem, py.test.collect.Module) and self.config.option.verbose == 0 and not self.config.option.collectonly): try: sum = 0 for sub in subitems: sum += len(list(colitem.join(sub)._tryiter())) except (SystemExit, KeyboardInterrupt): raise except: self.out.write('[?]') else: self.out.write('[%d] ' % sum) return self.out.line def start_Item(self, colitem): if self.config.option.verbose >= 1: if isinstance(colitem, py.test.collect.Item): realpath, lineno = colitem._getpathlineno() location = "%s:%d" % (realpath.basename, lineno+1) self.out.write("%-20s %s " % (location, colitem._getmodpath())) def finish(self, colitem, outcome): end = now() super(TerminalSession, self).finish(colitem, outcome) if self.config.option.collectonly: cols = self._opencollectors last = cols.pop() #assert last == colitem, "expected %r, got %r" %(last, colitem) return colitem.elapsedtime = end - colitem.start if self.config.option.usepdb: if isinstance(outcome, Failed): print "dispatching to ppdb", colitem self.repr_failure(colitem, outcome) import pdb self.out.write('\n%s\n' % (outcome.excinfo.exconly(),)) pdb.post_mortem(outcome.excinfo._excinfo[2]) if isinstance(colitem, py.test.collect.Module): resultstring = self.repr_progress_module_result(colitem, outcome) if resultstring: self.out.line(" - " + resultstring) if isinstance(colitem, py.test.collect.Item): if self.config.option.verbose >= 1: resultstring = self.repr_progress_long_result(colitem, outcome) resultstring += " (%.2f)" % (colitem.elapsedtime,) self.out.line(resultstring) else: c = self.repr_progress_short_result(colitem, outcome) self.out.write(c) # ------------------- # HEADER information # ------------------- def header(self, colitems): super(TerminalSession, self).header(colitems) self.out.sep("=", "test process starts") option = self.config.option modes = [] for name in 'looponfailing', 'exitfirst', 'nomagic': if getattr(option, name): modes.append(name) #if self._isremoteoption._fromremote: # modes.insert(0, 'child process') #else: # modes.insert(0, 'inprocess') #mode = "/".join(modes) #self.out.line("testing-mode: %s" % mode) self.out.line("executable: %s (%s)" % (py.std.sys.executable, repr_pythonversion())) rev = py.__package__.getrev() self.out.line("using py lib: %s <rev %s>" % ( py.path.local(py.__file__).dirpath(), rev)) if self.config.option.traceconfig or self.config.option.verbose: for x in colitems: self.out.line("test target: %s" %(x.fspath,)) conftestmodules = self.config._conftest.getconftestmodules(None) for i,x in py.builtin.enumerate(conftestmodules): self.out.line("initial conf %d: %s" %(i, x.__file__)) #for i, x in py.builtin.enumerate(py.test.config.configpaths): # self.out.line("initial testconfig %d: %s" %(i, x)) #additional = py.test.config.getfirst('additionalinfo') #if additional: # for key, descr in additional(): # self.out.line("%s: %s" %(key, descr)) self.out.line() self.starttime = now() # ------------------- # FOOTER information # ------------------- def footer(self, colitems): super(TerminalSession, self).footer(colitems) self.endtime = now() self.out.line() self.skippedreasons() self.failures() self.summaryline() # -------------------- # progress information # -------------------- typemap = { Passed: '.', Skipped: 's', Failed: 'F', } namemap = { Passed: 'ok', Skipped: 'SKIP', Failed: 'FAIL', } def repr_progress_short_result(self, item, outcome): for outcometype, char in self.typemap.items(): if isinstance(outcome, outcometype): return char else: #raise TypeError, "not an Outomce instance: %r" % (outcome,) return '?' def repr_progress_long_result(self, item, outcome): for outcometype, char in self.namemap.items(): if isinstance(outcome, outcometype): return char else: #raise TypeError, "not an Outcome instance: %r" % (outcome,) return 'UNKNOWN' def repr_progress_module_result(self, item, outcome): if isinstance(outcome, Failed): return "FAILED TO LOAD MODULE" elif isinstance(outcome, Skipped): return "skipped" elif not isinstance(outcome, (list, Passed)): return "?" # -------------------- # summary information # -------------------- def summaryline(self): outlist = [] sum = 0 for typ in Passed, Failed, Skipped: l = self.getitemoutcomepairs(typ) if l: outlist.append('%d %s' % (len(l), typ.__name__.lower())) sum += len(l) elapsed = self.endtime-self.starttime status = "%s" % ", ".join(outlist) self.out.sep('=', 'tests finished: %s in %4.2f seconds' % (status, elapsed)) def getlastvisible(self, sourcetraceback): traceback = sourcetraceback[:] while traceback: entry = traceback.pop() try: x = entry.frame.eval("__tracebackhide__") except: x = False if not x: return entry else: return sourcetraceback[-1] def skippedreasons(self): texts = {} for colitem, outcome in self.getitemoutcomepairs(Skipped): raisingtb = self.getlastvisible(outcome.excinfo.traceback) fn = raisingtb.frame.code.path lineno = raisingtb.lineno d = texts.setdefault(outcome.excinfo.exconly(), {}) d[(fn,lineno)] = outcome if texts: self.out.line() self.out.sep('_', 'reasons for skipped tests') for text, dict in texts.items(): for (fn, lineno), outcome in dict.items(): self.out.line('Skipped in %s:%d' %(fn, lineno+1)) self.out.line("reason: %s" % text) self.out.line() def failures(self): if self.config.option.tbstyle == 'no': return # skip the detailed failure reports altogether l = self.getitemoutcomepairs(Failed) if l: self.out.sep('_') for colitem, outcome in l: self.repr_failure(colitem, outcome) def repr_failure(self, item, outcome): excinfo = outcome.excinfo traceback = excinfo.traceback #print "repr_failures sees item", item #print "repr_failures sees traceback" #py.std.pprint.pprint(traceback) if item and not self.config.option.fulltrace: path, firstlineno = item._getpathlineno() ntraceback = traceback.cut(path=path, firstlineno=firstlineno) if ntraceback == traceback: ntraceback = ntraceback.cut(path=path) traceback = ntraceback.filter() if not traceback: self.out.line("empty traceback from item %r" % (item,)) return handler = getattr(self.presenter, 'repr_failure_tb%s' % self.config.option.tbstyle) handler(item, excinfo, traceback, lambda : self.repr_out_err(item)) def repr_out_err(self, colitem): for parent in colitem.listchain(): for name, obj in zip(['out', 'err'], parent._getouterr()): if obj: self.out.sep("- ", "%s: recorded std%s" % (parent.name, name)) self.out.line(obj) def repr_pythonversion(): v = py.std.sys.version_info try: return "%s.%s.%s-%s-%s" % v except ValueError: return str(v)
Python
#
Python
from __future__ import generators import py from conftesthandle import Conftest from py.__.test.defaultconftest import adddefaultoptions optparse = py.compat.optparse # XXX move to Config class basetemp = None def ensuretemp(string, dir=1): """ return temporary directory path with the given string as the trailing part. """ global basetemp if basetemp is None: basetemp = py.path.local.make_numbered_dir(prefix='pytest-') return basetemp.ensure(string, dir=dir) class CmdOptions(object): """ pure container instance for holding cmdline options as attributes. """ def __repr__(self): return "<CmdOptions %r>" %(self.__dict__,) class Config(object): """ central hub for dealing with configuration/initialization data. """ Option = optparse.Option def __init__(self): self.option = CmdOptions() self._parser = optparse.OptionParser( usage="usage: %prog [options] [query] [filenames of tests]") self._conftest = Conftest() self._initialized = False def parse(self, args): """ parse cmdline arguments into this config object. Note that this can only be called once per testing process. """ assert not self._initialized, ( "can only parse cmdline args once per Config object") self._initialized = True adddefaultoptions(self) self._conftest.setinitial(args) args = [str(x) for x in args] cmdlineoption, args = self._parser.parse_args(args) self.option.__dict__.update(vars(cmdlineoption)) if not args: args.append(py.std.os.getcwd()) self.topdir = gettopdir(args) self.args = args def _initdirect(self, topdir, repr, coltrails=None): assert not self._initialized self._initialized = True self.topdir = py.path.local(topdir) self._mergerepr(repr) self._coltrails = coltrails def getcolitems(self): """ return initial collectors. """ trails = getattr(self, '_coltrails', None) return [self._getcollector(path) for path in (trails or self.args)] def _getcollector(self, path): if isinstance(path, tuple): relpath, names = path fspath = self.topdir.join(relpath) col = self._getcollector(fspath) else: path = py.path.local(path) assert path.check(), "%s: path does not exist" %(path,) col = self._getrootcollector(path) names = path.relto(col.fspath).split(path.sep) return col._getitembynames(names) def _getrootcollector(self, path): pkgpath = path.pypkgpath() if pkgpath is None: pkgpath = path.check(file=1) and path.dirpath() or path col = self._conftest.rget("Directory", pkgpath)(pkgpath) col._config = self return col def getvalue_pathlist(self, name, path=None): """ return a matching value, which needs to be sequence of filenames that will be returned as a list of Path objects (they can be relative to the location where they were found). """ try: return getattr(self.option, name) except AttributeError: try: mod, relroots = self._conftest.rget_with_confmod(name, path) except KeyError: return None modpath = py.path.local(mod.__file__).dirpath() return [modpath.join(x, abs=True) for x in relroots] def addoptions(self, groupname, *specs): """ add a named group of options to the current testing session. This function gets invoked during testing session initialization. """ for spec in specs: for shortopt in spec._short_opts: if not shortopt.isupper(): raise ValueError( "custom options must be capital letter " "got %r" %(spec,) ) return self._addoptions(groupname, *specs) def _addoptions(self, groupname, *specs): optgroup = optparse.OptionGroup(self._parser, groupname) optgroup.add_options(specs) self._parser.add_option_group(optgroup) for opt in specs: if hasattr(opt, 'default') and opt.dest: setattr(self.option, opt.dest, opt.default) return self.option def getvalue(self, name, path=None): """ return 'name' value looked up from the 'options' and then from the first conftest file found up the path (including the path itself). if path is None, lookup the value in the initial conftest modules found during command line parsing. """ try: return getattr(self.option, name) except AttributeError: return self._conftest.rget(name, path) def initsession(self): """ return an initialized session object. """ cls = self._getsessionclass() session = cls(self) session.fixoptions() return session def _getsessionclass(self): """ return Session class determined from cmdline options and looked up in initial config modules. """ if self.option.session is not None: return self._conftest.rget(self.option.session) else: name = self._getsessionname() try: return self._conftest.rget(name) except KeyError: pass importpath = globals()[name] mod = __import__(importpath, None, None, '__doc__') return getattr(mod, name) def _getsessionname(self): """ return default session name as determined from options. """ name = 'TerminalSession' if self.option.dist: name = 'RSession' else: optnames = 'startserver runbrowser apigen restreport boxed'.split() for opt in optnames: if getattr(self.option, opt, False): name = 'LSession' break else: if self.getvalue('dist_boxed'): name = 'LSession' if self.option.looponfailing: name = 'RemoteTerminalSession' elif self.option.executable: name = 'RemoteTerminalSession' return name def _reparse(self, args): """ this is used from tests that want to re-invoke parse(). """ #assert args # XXX should not be empty global config_per_process oldconfig = py.test.config try: config_per_process = py.test.config = Config() config_per_process.parse(args) return config_per_process finally: config_per_process = py.test.config = oldconfig def _makerepr(self, conftestnames, optnames=None): """ return a marshallable representation of conftest and cmdline options. if optnames is None, all options on self.option will be transferred. """ conftestdict = {} for name in conftestnames: value = self.getvalue(name) checkmarshal(name, value) conftestdict[name] = value cmdlineopts = {} if optnames is None: optnames = dir(self.option) for name in optnames: if not name.startswith("_"): value = getattr(self.option, name) checkmarshal(name, value) cmdlineopts[name] = value l = [] for path in self.args: path = py.path.local(path) l.append(path.relto(self.topdir)) return l, conftestdict, cmdlineopts def _mergerepr(self, repr): """ merge in the conftest and cmdline option values found in the given representation (produced by _makerepr above). The repr-contained conftest values are stored on the default conftest module (last priority) and the cmdline options on self.option. """ class override: def __init__(self, d): self.__dict__.update(d) self.__file__ = "<options from remote>" args, conftestdict, cmdlineopts = repr self.args = [self.topdir.join(x) for x in args] self._conftest.setinitial(self.args) self._conftest._path2confmods[None].append(override(conftestdict)) for name, val in cmdlineopts.items(): setattr(self.option, name, val) def get_collector_trail(self, collector): """ provide a trail relative to the topdir, which can be used to reconstruct the collector (possibly on a different host starting from a different topdir). """ chain = collector.listchain() relpath = chain[0].fspath.relto(self.topdir) if not relpath: if chain[0].fspath == self.topdir: relpath = "." else: raise ValueError("%r not relative to %s" %(chain[0], self.topdir)) return relpath, tuple([x.name for x in chain[1:]]) def _startcapture(self, colitem, path=None): if not self.option.nocapture: assert not hasattr(colitem, '_capture') iocapture = self.getvalue("conf_iocapture", path=path) if iocapture == "fd": capture = py.io.StdCaptureFD() elif iocapture == "sys": capture = py.io.StdCapture() else: raise ValueError("unknown io capturing: " + iocapture) colitem._capture = capture def _finishcapture(self, colitem): if hasattr(colitem, '_capture'): capture = colitem._capture del colitem._capture colitem._captured_out, colitem._captured_err = capture.reset() # this is the one per-process instance of py.test configuration config_per_process = Config() # default import paths for sessions TerminalSession = 'py.__.test.terminal.terminal' RemoteTerminalSession = 'py.__.test.terminal.remote' RSession = 'py.__.test.rsession.rsession' LSession = 'py.__.test.rsession.rsession' # # helpers # def checkmarshal(name, value): try: py.std.marshal.dumps(value) except ValueError: raise ValueError("%s=%r is not marshallable" %(name, value)) def gettopdir(args): """ return the top directory for the given paths. if the common base dir resides in a python package parent directory of the root package is returned. """ args = [py.path.local(arg) for arg in args] p = reduce(py.path.local.common, args) assert p, "cannot determine common basedir of %s" %(args,) pkgdir = p.pypkgpath() if pkgdir is None: return p else: return pkgdir.dirpath()
Python
import py Module = py.test.collect.Module DoctestFile = py.test.collect.DoctestFile Directory = py.test.collect.Directory Class = py.test.collect.Class Generator = py.test.collect.Generator Function = py.test.collect.Function Instance = py.test.collect.Instance conf_iocapture = "fd" # overridable from conftest.py # =================================================== # Distributed testing specific options #dist_hosts: needs to be provided by user #dist_rsync_roots: might be provided by user, if not present or None, # whole pkgdir will be rsynced dist_remotepython = "python" dist_taskspernode = 15 dist_boxed = False if hasattr(py.std.os, 'nice'): dist_nicelevel = py.std.os.nice(0) # nice py.test works else: dist_nicelevel = 0 dist_rsync_ignore = [] # =================================================== def adddefaultoptions(config): Option = config.Option config._addoptions('general options', Option('-v', '--verbose', action="count", dest="verbose", default=0, help="increase verbosity."), Option('-x', '--exitfirst', action="store_true", dest="exitfirst", default=False, help="exit instantly on first error or failed test."), Option('-s', '--nocapture', action="store_true", dest="nocapture", default=False, help="disable catching of sys.stdout/stderr output."), Option('-k', action="store", dest="keyword", default='', help="only run test items matching the given (google-style) " "keyword expression."), Option('-l', '--showlocals', action="store_true", dest="showlocals", default=False, help="show locals in tracebacks (disabled by default)."), Option('', '--pdb', action="store_true", dest="usepdb", default=False, help="start pdb (the Python debugger) on errors."), Option('', '--tb', action="store", dest="tbstyle", default='long', type="choice", choices=['long', 'short', 'no'], help="traceback verboseness (long/short/no)."), Option('', '--fulltrace', action="store_true", dest="fulltrace", default=False, help="don't cut any tracebacks (default is to cut)."), Option('', '--nomagic', action="store_true", dest="nomagic", default=False, help="refrain from using magic as much as possible."), Option('', '--collectonly', action="store_true", dest="collectonly", default=False, help="only collect tests, don't execute them."), Option('', '--traceconfig', action="store_true", dest="traceconfig", default=False, help="trace considerations of conftest.py files."), Option('-f', '--looponfailing', action="store_true", dest="looponfailing", default=False, help="loop on failing test set."), Option('', '--exec', action="store", dest="executable", default=None, help="python executable to run the tests with."), ) config._addoptions('EXPERIMENTAL options', Option('-d', '--dist', action="store_true", dest="dist", default=False, help="ad-hoc distribute tests across machines (requires conftest settings)"), Option('-w', '--startserver', action="store_true", dest="startserver", default=False, help="starts local web server for displaying test progress.", ), Option('-r', '--runbrowser', action="store_true", dest="runbrowser", default=False, help="run browser (implies --startserver)." ), Option('', '--boxed', action="store_true", dest="boxed", default=False, help="box each test run in a separate process"), Option('', '--rest', action='store_true', dest="restreport", default=False, help="restructured text output reporting."), Option('', '--apigen', action="store", dest="apigen", help="generate api documentation while testing (requires " "argument pointing to a script)."), Option('', '--session', action="store", dest="session", default=None, help="lookup given sessioname in conftest.py files and use it."), )
Python
import py defaultconftestpath = py.magic.autopath().dirpath('defaultconftest.py') class Conftest(object): """ the single place for accessing values and interacting towards conftest modules from py.test objects. Note that triggering Conftest instances to import conftest.py files may result in added cmdline options. XXX """ def __init__(self, path=None): self._path2confmods = {} if path is not None: self.setinitial([path]) def setinitial(self, args): """ return a Conftest object initialized with a path obtained from looking at the first (usually cmdline) argument that points to an existing file object. XXX note: conftest files may add command line options and we thus have no completely safe way of determining which parts of the arguments are actually related to options. """ current = py.path.local() for arg in args + [current]: anchor = current.join(arg, abs=1) if anchor.check(): # we found some file object #print >>py.std.sys.stderr, "initializing conftest from", anchor # conftest-lookups without a path actually mean # lookups with our initial path. self._path2confmods[None] = self.getconftestmodules(anchor) #print " -> ", conftest._path2confmods break def getconftestmodules(self, path): """ return a list of imported conftest modules for the given path. """ try: clist = self._path2confmods[path] except KeyError: dp = path.dirpath() if dp == path: return [importconfig(defaultconftestpath)] clist = self.getconftestmodules(dp) conftestpath = path.join("conftest.py") if conftestpath.check(file=1): clist.append(importconfig(conftestpath)) self._path2confmods[path] = clist # be defensive: avoid changes from caller side to # affect us by always returning a copy of the actual list return clist[:] def rget(self, name, path=None): mod, value = self.rget_with_confmod(name, path) return value def rget_with_confmod(self, name, path=None): modules = self.getconftestmodules(path) modules.reverse() for mod in modules: try: return mod, getattr(mod, name) except AttributeError: continue raise KeyError, name def importconfig(configpath): # We could have used caching here, but it's redundant since # they're cached on path anyway, so we use it only when doing rget_path assert configpath.check(), configpath if not configpath.dirpath('__init__.py').check(file=1): # HACK: we don't want any "globally" imported conftest.py, # prone to conflicts and subtle problems modname = str(configpath).replace('.', configpath.sep) mod = configpath.pyimport(modname=modname) else: mod = configpath.pyimport() return mod
Python
import shared_lib
Python
""" Just a dummy module """
Python
from package import shared_lib
Python
#
Python
#
Python
import py def setup_module(mod): mod.datadir = setupdatadir() mod.tmpdir = py.test.ensuretemp(mod.__name__) def setupdatadir(): datadir = py.test.ensuretemp("datadir") names = [x.basename for x in datadir.listdir()] for name, content in namecontent: if name not in names: datadir.join(name).write(content) return datadir namecontent = [ ('syntax_error.py', "this is really not python\n"), ('disabled_module.py', py.code.Source(''' disabled = True def setup_module(mod): raise ValueError class TestClassOne: def test_func(self): raise ValueError class TestClassTwo: def setup_class(cls): raise ValueError def test_func(self): raise ValueError ''')), ('brokenrepr.py', py.code.Source(''' import py class BrokenRepr1: """A broken class with lots of broken methods. Let's try to make the test framework immune to these.""" foo=0 def __repr__(self): raise Exception("Ha Ha fooled you, I'm a broken repr().") class BrokenRepr2: """A broken class with lots of broken methods. Let's try to make the test framework immune to these.""" foo=0 def __repr__(self): raise "Ha Ha fooled you, I'm a broken repr()." class TestBrokenClass: def test_explicit_bad_repr(self): t = BrokenRepr1() py.test.raises(Exception, 'repr(t)') def test_implicit_bad_repr1(self): t = BrokenRepr1() assert t.foo == 1 def test_implicit_bad_repr2(self): t = BrokenRepr2() assert t.foo == 1 ''')), ('failingimport.py', py.code.Source(''' import gruetzelmuetzel ''')), ('filetest.py', py.code.Source(''' def test_one(): assert 42 == 43 class TestClass(object): def test_method_one(self): assert 42 == 43 ''')), ('testspecial_importerror.py', py.code.Source(''' import asdasd ''')), ('disabled.py', py.code.Source(''' class TestDisabled: disabled = True def test_method(self): pass ''')), ]
Python
""" This file intends to gather all methods of representing failures/tracebacks etc. which should be used among all terminal-based reporters. This methods should be general, to allow further use outside the pylib """ import py from py.__.code import safe_repr class Presenter(object): """ Class used for presentation of various objects, sharing common output style """ def __init__(self, out, config): """ out is a file-like object (we can write to it) """ assert hasattr(out, 'write') self.out = out self.config = config def repr_source(self, source, marker=">", marker_location=-1): """ This one represents piece of source with possible marker at requested position """ if isinstance(source, str): # why the hell, string is iterable? source = source.split("\n") if marker_location < 0: marker_location += len(source) if marker_location < 0: marker_location = 0 if marker_location >= len(source): marker_location = len(source) - 1 for i in range(len(source)): if i == marker_location: prefix = marker + " " else: prefix = " " self.out.line(prefix + source[i]) def repr_item_info(self, item): """ This method represents py.test.collect.Item info (path and module) """ root = item.fspath modpath = item._getmodpath() try: fn, lineno = item._getpathlineno() except TypeError: assert isinstance(item.parent, py.test.collect.Generator) # a generative test yielded a non-callable fn, lineno = item.parent._getpathlineno() if root == fn: self.out.sep("_", "entrypoint: %s" %(modpath)) else: self.out.sep("_", "entrypoint: %s %s" %(root.basename, modpath)) def repr_failure_explanation(self, excinfo, source): try: s = str(source.getstatement(len(source)-1)) except KeyboardInterrupt: raise except: s = str(source[-1]) indent = " " * (4 + (len(s) - len(s.lstrip()))) # get the real exception information out lines = excinfo.exconly(tryshort=True).split('\n') self.out.line('>' + indent[:-1] + lines.pop(0)) for x in lines: self.out.line(indent + x) def getentrysource(self, entry): try: source = entry.getsource() except py.error.ENOENT: source = py.code.Source("[failure to get at sourcelines from %r]\n" % entry) return source.deindent() def repr_locals(self, f_locals): if self.config.option.showlocals: self.out.sep('- ', 'locals') for name, value in f_locals.items(): if name == '__builtins__': self.out.line("__builtins__ = <builtins>") else: # This formatting could all be handled by the _repr() function, which is # only repr.Repr in disguise, so is very configurable. str_repr = safe_repr._repr(value) if len(str_repr) < 70 or not isinstance(value, (list, tuple, dict)): self.out.line("%-10s = %s" %(name, str_repr)) else: self.out.line("%-10s =\\" % (name,)) py.std.pprint.pprint(value, stream=self.out) def repr_failure_tblong(self, item, excinfo, traceback, out_err_reporter): if not self.config.option.nomagic and excinfo.errisinstance(RuntimeError): recursionindex = traceback.recursionindex() else: recursionindex = None last = traceback[-1] first = traceback[0] for index, entry in py.builtin.enumerate(traceback): if entry == first: if item: self.repr_item_info(item) self.out.line() else: self.out.line("") source = self.getentrysource(entry) firstsourceline = entry.getfirstlinesource() marker_location = entry.lineno - firstsourceline if entry == last: self.repr_source(source, 'E', marker_location) self.repr_failure_explanation(excinfo, source) else: self.repr_source(source, '>', marker_location) self.out.line("") self.out.line("[%s:%d]" %(entry.path, entry.lineno+1)) self.repr_locals(entry.locals) # trailing info if entry == last: out_err_reporter() self.out.sep("_") else: self.out.sep("_ ") if index == recursionindex: self.out.line("Recursion detected (same locals & position)") self.out.sep("!") break def repr_failure_tbshort(self, item, excinfo, traceback, out_err_reporter): # print a Python-style short traceback if not self.config.option.nomagic and excinfo.errisinstance(RuntimeError): recursionindex = traceback.recursionindex() else: recursionindex = None last = traceback[-1] first = traceback[0] self.out.line() for index, entry in py.builtin.enumerate(traceback): path = entry.path.basename firstsourceline = entry.getfirstlinesource() relline = entry.lineno - firstsourceline self.out.line(' File "%s", line %d, in %s' % ( path, entry.lineno+1, entry.name)) try: source = entry.getsource().lines except py.error.ENOENT: source = ["?"] else: try: if len(source) > 1: source = source[relline] except IndexError: source = [] if entry == last: if source: self.repr_source(source, 'E') self.repr_failure_explanation(excinfo, source) else: if source: self.repr_source(source, ' ') self.repr_locals(entry.locals) # trailing info if entry == last: out_err_reporter() self.out.sep("_") else: if index == recursionindex: self.out.line("Recursion detected (same locals & position)") self.out.sep("!") break # the following is only used by the combination '--pdb --tb=no' repr_failure_tbno = repr_failure_tbshort
Python
""" File defining possible outcomes of running """ class Outcome: def __init__(self, msg=None, excinfo=None): self.msg = msg self.excinfo = excinfo def __repr__(self): if self.msg: return self.msg return "<%s instance>" %(self.__class__.__name__,) __str__ = __repr__ class Passed(Outcome): pass class Failed(Outcome): pass class ExceptionFailure(Failed): def __init__(self, expr, expected, msg=None, excinfo=None): Failed.__init__(self, msg=msg, excinfo=excinfo) self.expr = expr self.expected = expected class Skipped(Outcome): pass
Python
""" versatile unit-testing tool + libraries """
Python
import sys import py from py.__.test.outcome import ExceptionFailure def raises(ExpectedException, *args, **kwargs): """ raise AssertionError, if target code does not raise the expected exception. """ assert args __tracebackhide__ = True if isinstance(args[0], str): expr, = args assert isinstance(expr, str) frame = sys._getframe(1) loc = frame.f_locals.copy() loc.update(kwargs) #print "raises frame scope: %r" % frame.f_locals source = py.code.Source(expr) try: exec source.compile() in frame.f_globals, loc #del __traceback__ # XXX didn'T mean f_globals == f_locals something special? # this is destroyed here ... except ExpectedException: return py.code.ExceptionInfo() else: func = args[0] assert callable try: func(*args[1:], **kwargs) #del __traceback__ except ExpectedException: return py.code.ExceptionInfo() k = ", ".join(["%s=%r" % x for x in kwargs.items()]) if k: k = ', ' + k expr = '%s(%r%s)' %(func.__name__, args, k) raise ExceptionFailure(msg="DID NOT RAISE", expr=args, expected=ExpectedException)
Python
import sys if '_stackless' in sys.builtin_module_names: # when running on top of a pypy with stackless support from _stackless import greenlet else: # regular CPython (or pypy without stackless support, and then crash :-) import py gdir = py.path.local(py.__file__).dirpath() path = gdir.join('c-extension', 'greenlet', 'greenlet.c') greenlet = path._getpymodule().greenlet
Python
from compiler import parse, ast, pycodegen import py import __builtin__, sys passthroughex = (KeyboardInterrupt, SystemExit, MemoryError) class Failure: def __init__(self, node): self.exc, self.value, self.tb = sys.exc_info() self.node = node #import traceback #traceback.print_exc() from py.__.magic.viewtype import View class Interpretable(View): """A parse tree node with a few extra methods.""" explanation = None def is_builtin(self, frame): return False def eval(self, frame): # fall-back for unknown expression nodes try: expr = ast.Expression(self.__obj__) expr.filename = '<eval>' self.__obj__.filename = '<eval>' co = pycodegen.ExpressionCodeGenerator(expr).getCode() result = frame.eval(co) except passthroughex: raise except: raise Failure(self) self.result = result self.explanation = self.explanation or frame.repr(self.result) def run(self, frame): # fall-back for unknown statement nodes try: expr = ast.Module(None, ast.Stmt([self.__obj__])) expr.filename = '<run>' co = pycodegen.ModuleCodeGenerator(expr).getCode() frame.exec_(co) except passthroughex: raise except: raise Failure(self) def nice_explanation(self): # uck! See CallFunc for where \n{ and \n} escape sequences are used raw_lines = (self.explanation or '').split('\n') # escape newlines not followed by { and } lines = [raw_lines[0]] for l in raw_lines[1:]: if l.startswith('{') or l.startswith('}'): lines.append(l) else: lines[-1] += '\\n' + l result = lines[:1] stack = [0] stackcnt = [0] for line in lines[1:]: if line.startswith('{'): if stackcnt[-1]: s = 'and ' else: s = 'where ' stack.append(len(result)) stackcnt[-1] += 1 stackcnt.append(0) result.append(' +' + ' '*(len(stack)-1) + s + line[1:]) else: assert line.startswith('}') stack.pop() stackcnt.pop() result[stack[-1]] += line[1:] assert len(stack) == 1 return '\n'.join(result) class Name(Interpretable): __view__ = ast.Name def is_local(self, frame): co = compile('%r in locals() is not globals()' % self.name, '?', 'eval') try: return frame.is_true(frame.eval(co)) except passthroughex: raise except: return False def is_global(self, frame): co = compile('%r in globals()' % self.name, '?', 'eval') try: return frame.is_true(frame.eval(co)) except passthroughex: raise except: return False def is_builtin(self, frame): co = compile('%r not in locals() and %r not in globals()' % ( self.name, self.name), '?', 'eval') try: return frame.is_true(frame.eval(co)) except passthroughex: raise except: return False def eval(self, frame): super(Name, self).eval(frame) if not self.is_local(frame): self.explanation = self.name class Compare(Interpretable): __view__ = ast.Compare def eval(self, frame): expr = Interpretable(self.expr) expr.eval(frame) for operation, expr2 in self.ops: expr2 = Interpretable(expr2) expr2.eval(frame) self.explanation = "%s %s %s" % ( expr.explanation, operation, expr2.explanation) co = compile("__exprinfo_left %s __exprinfo_right" % operation, '?', 'eval') try: self.result = frame.eval(co, __exprinfo_left=expr.result, __exprinfo_right=expr2.result) except passthroughex: raise except: raise Failure(self) if not frame.is_true(self.result): break expr = expr2 class And(Interpretable): __view__ = ast.And def eval(self, frame): explanations = [] for expr in self.nodes: expr = Interpretable(expr) expr.eval(frame) explanations.append(expr.explanation) self.result = expr.result if not frame.is_true(expr.result): break self.explanation = '(' + ' and '.join(explanations) + ')' class Or(Interpretable): __view__ = ast.Or def eval(self, frame): explanations = [] for expr in self.nodes: expr = Interpretable(expr) expr.eval(frame) explanations.append(expr.explanation) self.result = expr.result if frame.is_true(expr.result): break self.explanation = '(' + ' or '.join(explanations) + ')' # == Unary operations == keepalive = [] for astclass, astpattern in { ast.Not : 'not __exprinfo_expr', ast.Invert : '(~__exprinfo_expr)', }.items(): class UnaryArith(Interpretable): __view__ = astclass def eval(self, frame, astpattern=astpattern, co=compile(astpattern, '?', 'eval')): expr = Interpretable(self.expr) expr.eval(frame) self.explanation = astpattern.replace('__exprinfo_expr', expr.explanation) try: self.result = frame.eval(co, __exprinfo_expr=expr.result) except passthroughex: raise except: raise Failure(self) keepalive.append(UnaryArith) # == Binary operations == for astclass, astpattern in { ast.Add : '(__exprinfo_left + __exprinfo_right)', ast.Sub : '(__exprinfo_left - __exprinfo_right)', ast.Mul : '(__exprinfo_left * __exprinfo_right)', ast.Div : '(__exprinfo_left / __exprinfo_right)', ast.Mod : '(__exprinfo_left % __exprinfo_right)', ast.Power : '(__exprinfo_left ** __exprinfo_right)', }.items(): class BinaryArith(Interpretable): __view__ = astclass def eval(self, frame, astpattern=astpattern, co=compile(astpattern, '?', 'eval')): left = Interpretable(self.left) left.eval(frame) right = Interpretable(self.right) right.eval(frame) self.explanation = (astpattern .replace('__exprinfo_left', left .explanation) .replace('__exprinfo_right', right.explanation)) try: self.result = frame.eval(co, __exprinfo_left=left.result, __exprinfo_right=right.result) except passthroughex: raise except: raise Failure(self) keepalive.append(BinaryArith) class CallFunc(Interpretable): __view__ = ast.CallFunc def is_bool(self, frame): co = compile('isinstance(__exprinfo_value, bool)', '?', 'eval') try: return frame.is_true(frame.eval(co, __exprinfo_value=self.result)) except passthroughex: raise except: return False def eval(self, frame): node = Interpretable(self.node) node.eval(frame) explanations = [] vars = {'__exprinfo_fn': node.result} source = '__exprinfo_fn(' for a in self.args: if isinstance(a, ast.Keyword): keyword = a.name a = a.expr else: keyword = None a = Interpretable(a) a.eval(frame) argname = '__exprinfo_%d' % len(vars) vars[argname] = a.result if keyword is None: source += argname + ',' explanations.append(a.explanation) else: source += '%s=%s,' % (keyword, argname) explanations.append('%s=%s' % (keyword, a.explanation)) if self.star_args: star_args = Interpretable(self.star_args) star_args.eval(frame) argname = '__exprinfo_star' vars[argname] = star_args.result source += '*' + argname + ',' explanations.append('*' + star_args.explanation) if self.dstar_args: dstar_args = Interpretable(self.dstar_args) dstar_args.eval(frame) argname = '__exprinfo_kwds' vars[argname] = dstar_args.result source += '**' + argname + ',' explanations.append('**' + dstar_args.explanation) self.explanation = "%s(%s)" % ( node.explanation, ', '.join(explanations)) if source.endswith(','): source = source[:-1] source += ')' co = compile(source, '?', 'eval') try: self.result = frame.eval(co, **vars) except passthroughex: raise except: raise Failure(self) if not node.is_builtin(frame) or not self.is_bool(frame): r = frame.repr(self.result) self.explanation = '%s\n{%s = %s\n}' % (r, r, self.explanation) class Getattr(Interpretable): __view__ = ast.Getattr def eval(self, frame): expr = Interpretable(self.expr) expr.eval(frame) co = compile('__exprinfo_expr.%s' % self.attrname, '?', 'eval') try: self.result = frame.eval(co, __exprinfo_expr=expr.result) except passthroughex: raise except: raise Failure(self) self.explanation = '%s.%s' % (expr.explanation, self.attrname) # if the attribute comes from the instance, its value is interesting co = compile('hasattr(__exprinfo_expr, "__dict__") and ' '%r in __exprinfo_expr.__dict__' % self.attrname, '?', 'eval') try: from_instance = frame.is_true( frame.eval(co, __exprinfo_expr=expr.result)) except passthroughex: raise except: from_instance = True if from_instance: r = frame.repr(self.result) self.explanation = '%s\n{%s = %s\n}' % (r, r, self.explanation) # == Re-interpretation of full statements == import __builtin__ BuiltinAssertionError = __builtin__.AssertionError class Assert(Interpretable): __view__ = ast.Assert def run(self, frame): test = Interpretable(self.test) test.eval(frame) # simplify 'assert False where False = ...' if (test.explanation.startswith('False\n{False = ') and test.explanation.endswith('\n}')): test.explanation = test.explanation[15:-2] # print the result as 'assert <explanation>' self.result = test.result self.explanation = 'assert ' + test.explanation if not frame.is_true(test.result): try: raise BuiltinAssertionError except passthroughex: raise except: raise Failure(self) class Assign(Interpretable): __view__ = ast.Assign def run(self, frame): expr = Interpretable(self.expr) expr.eval(frame) self.result = expr.result self.explanation = '... = ' + expr.explanation # fall-back-run the rest of the assignment ass = ast.Assign(self.nodes, ast.Name('__exprinfo_expr')) mod = ast.Module(None, ast.Stmt([ass])) mod.filename = '<run>' co = pycodegen.ModuleCodeGenerator(mod).getCode() try: frame.exec_(co, __exprinfo_expr=expr.result) except passthroughex: raise except: raise Failure(self) class Discard(Interpretable): __view__ = ast.Discard def run(self, frame): expr = Interpretable(self.expr) expr.eval(frame) self.result = expr.result self.explanation = expr.explanation class Stmt(Interpretable): __view__ = ast.Stmt def run(self, frame): for stmt in self.nodes: stmt = Interpretable(stmt) stmt.run(frame) def report_failure(e): explanation = e.node.nice_explanation() if explanation: explanation = ", in: " + explanation else: explanation = "" print "%s: %s%s" % (e.exc.__name__, e.value, explanation) def check(s, frame=None): if frame is None: import sys frame = sys._getframe(1) frame = py.code.Frame(frame) expr = parse(s, 'eval') assert isinstance(expr, ast.Expression) node = Interpretable(expr.node) try: node.eval(frame) except passthroughex: raise except Failure, e: report_failure(e) else: if not frame.is_true(node.result): print "assertion failed:", node.nice_explanation() ########################################################### # API / Entry points # ######################################################### def interpret(source, frame, should_fail=False): module = Interpretable(parse(source, 'exec').node) #print "got module", module if isinstance(frame, py.std.types.FrameType): frame = py.code.Frame(frame) try: module.run(frame) except Failure, e: return getfailure(e) except passthroughex: raise except: import traceback traceback.print_exc() if should_fail: return "(inconsistently failed then succeeded)" else: return None def getmsg(excinfo): if isinstance(excinfo, tuple): excinfo = py.code.ExceptionInfo(excinfo) #frame, line = gettbline(tb) #frame = py.code.Frame(frame) #return interpret(line, frame) tb = excinfo.traceback[-1] source = str(tb.statement).strip() x = interpret(source, tb.frame, should_fail=True) if not isinstance(x, str): raise TypeError, "interpret returned non-string %r" % (x,) return x def getfailure(e): explanation = e.node.nice_explanation() if str(e.value): lines = explanation.split('\n') lines[0] += " << %s" % (e.value,) explanation = '\n'.join(lines) text = "%s: %s" % (e.exc.__name__, explanation) if text.startswith('AssertionError: assert '): text = text[16:] return text def run(s, frame=None): if frame is None: import sys frame = sys._getframe(1) frame = py.code.Frame(frame) module = Interpretable(parse(s, 'exec').node) try: module.run(frame) except Failure, e: report_failure(e) if __name__ == '__main__': # example: def f(): return 5 def g(): return 3 def h(x): return 'never' check("f() * g() == 5") check("not f()") check("not (f() and g() or 0)") check("f() == g()") i = 4 check("i == f()") check("len(f()) == 0") check("isinstance(2+3+4, float)") run("x = i") check("x == 5") run("assert not f(), 'oops'") run("a, b, c = 1, 2") run("a, b, c = f()") check("max([f(),g()]) == 4") check("'hello'[g()] == 'h'") run("'guk%d' % h(f())")
Python
import __builtin__, sys import py from py.__.magic import exprinfo BuiltinAssertionError = __builtin__.AssertionError class AssertionError(BuiltinAssertionError): def __init__(self, *args): BuiltinAssertionError.__init__(self, *args) if args: self.msg = str(args[0]) else: f = sys._getframe(1) try: source = py.code.Frame(f).statement source = str(source.deindent()).strip() except py.error.ENOENT: source = None # this can also occur during reinterpretation, when the # co_filename is set to "<run>". if source: self.msg = exprinfo.interpret(source, f, should_fail=True) if not self.args: self.args = (self.msg,) else: self.msg = None def invoke(): py.magic.patch(__builtin__, 'AssertionError', AssertionError) def revoke(): py.magic.revert(__builtin__, 'AssertionError')
Python
import py import __builtin__ as cpy_builtin def invoke(assertion=False, compile=False): """ invoke magic, currently you can specify: assertion patches the builtin AssertionError to try to give more meaningful AssertionErrors, which by means of deploying a mini-interpreter constructs a useful error message. """ if assertion: from py.__.magic import assertion assertion.invoke() if compile: py.magic.patch(cpy_builtin, 'compile', py.code.compile ) def revoke(assertion=False, compile=False): """ revoke previously invoked magic (see invoke()).""" if assertion: from py.__.magic import assertion assertion.revoke() if compile: py.magic.revert(cpy_builtin, 'compile')
Python
#
Python
import os, sys from py.path import local from py.__.path.common import PathStr def autopath(globs=None, basefile='__init__.py'): """ return the (local) path of the "current" file pointed to by globals or - if it is none - alternatively the callers frame globals. the path will always point to a .py file or to None. the path will have the following payload: pkgdir is the last parent directory path containing 'basefile' starting backwards from the current file. """ if globs is None: globs = sys._getframe(1).f_globals try: __file__ = globs['__file__'] except KeyError: if not sys.argv[0]: raise ValueError, "cannot compute autopath in interactive mode" __file__ = os.path.abspath(sys.argv[0]) custom__file__ = isinstance(__file__, PathStr) if custom__file__: ret = __file__.__path__ else: ret = local(__file__) if ret.ext in ('.pyc', '.pyo'): ret = ret.new(ext='.py') current = pkgdir = ret.dirpath() while 1: if basefile in current: pkgdir = current current = current.dirpath() if pkgdir != current: continue elif not custom__file__ and str(current) not in sys.path: sys.path.insert(0, str(current)) break ret.pkgdir = pkgdir return ret
Python
patched = {} def patch(namespace, name, value): """ rebind the 'name' on the 'namespace' to the 'value', possibly and remember the original value. Multiple invocations to the same namespace/name pair will remember a list of old values. """ nref = (namespace, name) orig = getattr(namespace, name) patched.setdefault(nref, []).append(orig) setattr(namespace, name, value) return orig def revert(namespace, name): """ revert to the orginal value the last patch modified. Raise ValueError if no such original value exists. """ nref = (namespace, name) if nref not in patched or not patched[nref]: raise ValueError, "No original value stored for %s.%s" % nref current = getattr(namespace, name) orig = patched[nref].pop() setattr(namespace, name, orig) return current
Python
""" some nice, slightly magic APIs """
Python
""" The View base class for view-based programming. A view of an object is an extension of this existing object. This is useful to *locally* add methods or even attributes to objects that you have obtained from elsewhere. """ from __future__ import generators import inspect class View(object): """View base class. If C is a subclass of View, then C(x) creates a proxy object around the object x. The actual class of the proxy is not C in general, but a *subclass* of C determined by the rules below. To avoid confusion we call view class the class of the proxy (a subclass of C, so of View) and object class the class of x. Attributes and methods not found in the proxy are automatically read on x. Other operations like setting attributes are performed on the proxy, as determined by its view class. The object x is available from the proxy as its __obj__ attribute. The view class selection is determined by the __view__ tuples and the optional __viewkey__ method. By default, the selected view class is the most specific subclass of C whose __view__ mentions the class of x. If no such subclass is found, the search proceeds with the parent object classes. For example, C(True) will first look for a subclass of C with __view__ = (..., bool, ...) and only if it doesn't find any look for one with __view__ = (..., int, ...), and then ..., object,... If everything fails the class C itself is considered to be the default. Alternatively, the view class selection can be driven by another aspect of the object x, instead of the class of x, by overriding __viewkey__. See last example at the end of this module. """ _viewcache = {} __view__ = () def __new__(rootclass, obj, *args, **kwds): self = object.__new__(rootclass) self.__obj__ = obj self.__rootclass__ = rootclass key = self.__viewkey__() try: self.__class__ = self._viewcache[key] except KeyError: self.__class__ = self._selectsubclass(key) return self def __getattr__(self, attr): # attributes not found in the normal hierarchy rooted on View # are looked up in the object's real class return getattr(self.__obj__, attr) def __viewkey__(self): return self.__obj__.__class__ def __matchkey__(self, key, subclasses): if inspect.isclass(key): keys = inspect.getmro(key) else: keys = [key] for key in keys: result = [C for C in subclasses if key in C.__view__] if result: return result return [] def _selectsubclass(self, key): subclasses = list(enumsubclasses(self.__rootclass__)) for C in subclasses: if not isinstance(C.__view__, tuple): C.__view__ = (C.__view__,) choices = self.__matchkey__(key, subclasses) if not choices: return self.__rootclass__ elif len(choices) == 1: return choices[0] else: # combine the multiple choices return type('?', tuple(choices), {}) def __repr__(self): return '%s(%r)' % (self.__rootclass__.__name__, self.__obj__) def enumsubclasses(cls): for subcls in cls.__subclasses__(): for subsubclass in enumsubclasses(subcls): yield subsubclass yield cls
Python
""" Lazy functions in PyPy. To run on top of the thunk object space with the following command-line: py.py -o thunk fibonacci2.py This is a typical Functional Programming Languages demo, computing the Fibonacci sequence as nested 2-tuples. """ import pprint try: from __pypy__ import lazy except ImportError: print __doc__ raise SystemExit(2) @lazy def fibo(a, b): return (a, fibo(b, a + b)) fibonacci = fibo(1, 1) pprint.pprint(fibonacci, depth=10)
Python
""" Standard Library usage demo. Uses urllib and htmllib to download and parse a web page. The purpose of this demo is to remind and show that almost all pure-Python modules of the Standard Library work just fine. """ url = 'http://www.python.org/' html = 'python.html' import urllib content = urllib.urlopen(url).read() file(html, 'w').write(content) import htmllib htmllib.test([html]) import os os.remove(html)
Python
"""This is an example that uses the (prototype) Logic Object Space. To run, you have to set USE_GREENLETS in pypy.objspace.logic to True and do: $ py.py -o logic uthread.py newvar creates a new unbound logical variable. If you try to access an unbound variable, the current uthread is blocked, until the variable is bound. """ X = newvar() Y = newvar() bind(Y, X) # aliasing def f(): print "starting" print is_free(X) if Y: print "ok" return print "false" return def bind(): unify(X, 1) uthread(f) print "afterwards" uthread(bind)
Python
""" Of historical interest: we computed the food bill of our first Gothenburg sprint with PyPy :-) """ slips=[(1, 'Kals MatMarkn', 6150, 'Chutney for Curry', 'dinner Saturday'), (2, 'Kals MatMarkn', 32000, 'Spaghetti, Beer', 'dinner Monday'), (2, 'Kals MatMarkn', -810, 'Deposit on Beer Bottles', 'various'), (3, 'Fram', 7700, 'Rice and Curry Spice', 'dinner Saturday'), (4, 'Kals MatMarkn', 25000, 'Alcohol-Free Beer, sundries', 'various'), (4, 'Kals MatMarkn', -1570, "Michael's toothpaste", 'none'), (4, 'Kals MatMarkn', -1690, "Laura's toothpaste", 'none'), (4, 'Kals MatMarkn', -720, 'Deposit on Beer Bottles', 'various'), (4, 'Kals MatMarkn', -60, 'Deposit on another Beer Bottle', 'various'), (5, 'Kals MatMarkn', 26750, 'lunch bread meat cheese', 'lunch Monday'), (6, 'Kals MatMarkn', 15950, 'various', 'dinner Tuesday and Thursday'), (7, 'Kals MatMarkn', 3650, 'Drottningsylt, etc.', 'dinner Thursday'), (8, 'Kals MatMarkn', 26150, 'Chicken and Mushroom Sauce', 'dinner Wed'), (8, 'Kals MatMarkn', -2490, 'Jacob and Laura -- juice', 'dinner Wed'), (8, 'Kals MatMarkn', -2990, "Chicken we didn't cook", 'dinner Wednesday'), (9, 'Kals MatMarkn', 1380, 'fruit for Curry', 'dinner Saturday'), (9, 'Kals MatMarkn', 1380, 'fruit for Curry', 'dinner Saturday'), (10, 'Kals MatMarkn', 26900, 'Jansons Frestelse', 'dinner Sunday'), (10, 'Kals MatMarkn', -540, 'Deposit on Beer Bottles', 'dinner Sunday'), (11, 'Kals MatMarkn', 22650, 'lunch bread meat cheese', 'lunch Thursday'), (11, 'Kals MatMarkn', -2190, 'Jacob and Laura -- juice', 'lunch Thursday'), (11, 'Kals MatMarkn', -2790, 'Jacob and Laura -- cereal', 'lunch Thurs'), (11, 'Kals MatMarkn', -760, 'Jacob and Laura -- milk', 'lunch Thursday'), (12, 'Kals MatMarkn', 18850, 'lunch bread meat cheese', 'lunch Friday'), (13, 'Kals MatMarkn', 18850, 'lunch bread meat cheese', 'guestimate Sun'), (14, 'Kals MatMarkn', 18850, 'lunch bread meat cheese', 'guestimate Tues'), (15, 'Kals MatMarkn', 20000, 'lunch bread meat cheese', 'guestimate Wed'), (16, 'Kals MatMarkn', 42050, 'grillfest', 'dinner Friday'), (16, 'Kals MatMarkn', -1350, 'Deposit on Beer Bottles', 'dinner Friday'), (17, 'System Bolaget', 15500, 'Cederlunds Caloric', 'dinner Thursday'), (17, 'System Bolaget', 22400, '4 x Farnese Sangiovese 56SEK', 'various'), (17, 'System Bolaget', 22400, '4 x Farnese Sangiovese 56SEK', 'various'), (17, 'System Bolaget', 13800, '2 x Jacobs Creek 69SEK', 'various'), (18, 'J and Ls winecabinet', 10800, '2 x Parrotes 54SEK', 'various'), (18, 'J and Ls winecabinet', 14700, '3 x Saint Paulin 49SEK', 'various'), (18, 'J and Ls winecabinet', 10400, '2 x Farnese Sangioves 52SEK', 'cheaper when we bought it'), (18, 'J and Ls winecabinet', 17800, '2 x Le Poiane 89SEK', 'various'), (18, 'J and Ls winecabinet', 9800, '2 x Something Else 49SEK', 'various'), (19, 'Konsum', 26000, 'Saturday Bread and Fruit', 'Slip MISSING'), (20, 'Konsum', 15245, 'Mooseburgers', 'found slip'), (21, 'Kals MatMarkn', 20650, 'Grilling', 'Friday dinner'), (22, 'J and Ls freezer', 21000, 'Meat for Curry, grilling', ''), (22, 'J and Ls cupboard', 3000, 'Rice', ''), (22, 'J and Ls cupboard', 4000, 'Charcoal', ''), (23, 'Fram', 2975, 'Potatoes', '3.5 kg @ 8.50SEK'), (23, 'Fram', 1421, 'Peas', 'Thursday dinner'), (24, 'Kals MatMarkn', 20650, 'Grilling', 'Friday dinner'), (24, 'Kals MatMarkn', -2990, 'TP', 'None'), (24, 'Kals MatMarkn', -2320, 'T-Gul', 'None') ] print [t[2] for t in slips] print (reduce(lambda x, y: x+y, [t[2] for t in slips], 0))/900
Python
""" An old-time classical example, and one of our first goals. To run on top of PyPy. """ import dis dis.dis(dis.dis)
Python
""" Thunk (a.k.a. lazy objects) in PyPy. To run on top of the thunk object space with the following command-line: py.py -o thunk fibonacci.py This is a typical Functional Programming Languages demo, computing the Fibonacci sequence by using an infinite lazy linked list. """ try: from __pypy__ import thunk # only available in 'py.py -o thunk' except ImportError: print __doc__ raise SystemExit(2) # ____________________________________________________________ class ListNode: def __init__(self, head, tail): self.head = head # the first element of the list self.tail = tail # the sublist of all remaining elements def add_lists(list1, list2): """Compute the linked-list equivalent of the Python expression [a+b for (a,b) in zip(list1,list2)] """ return ListNode(list1.head + list2.head, thunk(add_lists, list1.tail, list2.tail)) # 1, 1, 2, 3, 5, 8, 13, 21, 34, ... Fibonacci = ListNode(1, ListNode(1, None)) Fibonacci.tail.tail = thunk(add_lists, Fibonacci, Fibonacci.tail) if __name__ == '__main__': node = Fibonacci while True: print node.head node = node.tail
Python
"""SQL injection example with holes fixed using the taint space. Needs gadfly (sf.net/projects/gadfly) to be on the python path. Use populate.py to create the example db. Passwords are the reverse of user names :). Query is the number of a calendar month, purchases for the user with the password since including that month are shown. Works with a -otaint --allworkingmodules --oldstyle pypy-c . """ import sys import __pypy__ import gadfly import BaseHTTPServer import cgi import md5 page=""" <html> <head> <title>DEMO</title> </head> <body> <form method="get" action="/"> <label for="pwd">Passwd</label> <input name="pwd" type="text" size="10"></input><br /> <label for="query">Query</label> <input name="query" type="text" size="20"></input><br /> <input type="submit"> </form> <div> %s </div> </body> </html> """ table = """ <table> <th>customer</th> <th>month</th> <th>year</th> <th>prod.</th> <th>qty</th> <th>amount</th> %s </table> """ row = "<tr>"+"<td>%s</td>"*6 +"</tr>" def do_query(query): conn = gadfly.gadfly("db0", "DBS") cursor = conn.cursor() pwd = pypymagic.untaint(str, query['pwd'][0]) pwd = md5.new(pwd).hexdigest() q = pypymagic.untaint(str, query['query'][0]) if not q.isdigit(): return "Wrong query!" sel = ("""select user,month,year,product,qty,amount from purchases where pwd='%s' and month>=%s """ % (pwd, q)) cursor.execute(sel) rows = [] for x in cursor.fetchall(): rows.append(row % x) results = table % ('\n'.join(rows)) conn.close() return results class RequestHandler(BaseHTTPServer.BaseHTTPRequestHandler): def do_GET(self): self.send_response(200, "OK") self.end_headers() parts = self.path.split('?') if len(parts) > 1: _, query = parts query = cgi.parse_qs(query, strict_parsing=True) else: query = None if query is not None: query = pypymagic.taint(query) results = do_query(query) else: results = "no query" self.wfile.write(page % results) if __name__ == '__main__': if len(sys.argv) > 1: port = int(sys.argv[1]) else: port = 8000 server_address = ('', port) httpd = BaseHTTPServer.HTTPServer(server_address, RequestHandler) httpd.serve_forever()
Python
"""SQL injection example Needs gadfly (sf.net/projects/gadfly) to be on the python path. Use populate.py to create the example db. Passwords are the reverse of user names :). Query is the number of a calendar month, purchases for the user with the password since including that month are shown. Works with an --allworkingmodules --oldstyle pypy-c . """ import sys import gadfly import BaseHTTPServer import cgi import md5 page=""" <html> <head> <title>DEMO</title> </head> <body> <form method="get" action="/"> <label for="pwd">Passwd</label> <input name="pwd" type="text" size="10"></input><br /> <label for="query">Query</label> <input name="query" type="text" size="20"></input><br /> <input type="submit"> </form> <div> %s </div> </body> </html> """ table = """ <table> <th>customer</th> <th>month</th> <th>year</th> <th>prod.</th> <th>qty</th> <th>amount</th> %s </table> """ row = "<tr>"+"<td>%s</td>"*6 +"</tr>" def do_query(query): conn = gadfly.gadfly("db0", "DBS") cursor = conn.cursor() pwd = md5.new(query['pwd'][0]).hexdigest() q = query['query'][0] sel = ("""select user,month,year,product,qty,amount from purchases where pwd='%s' and month>=%s """ % (pwd, q)) cursor.execute(sel) rows = [] for x in cursor.fetchall(): rows.append(row % x) results = table % ('\n'.join(rows)) conn.close() return results class RequestHandler(BaseHTTPServer.BaseHTTPRequestHandler): def do_GET(self): self.send_response(200, "OK") self.end_headers() parts = self.path.split('?') if len(parts) > 1: _, query = parts query = cgi.parse_qs(query, strict_parsing=True) else: query = None if query is not None: results = do_query(query) else: results = "no query" self.wfile.write(page % results) if __name__ == '__main__': if len(sys.argv) > 1: port = int(sys.argv[1]) else: port = 8000 server_address = ('', port) httpd = BaseHTTPServer.HTTPServer(server_address, RequestHandler) httpd.serve_forever()
Python