From b4105be21e967f79d819749c44eff6ed4311f65d Mon Sep 17 00:00:00 2001
From: Aldo Cortesi
Date: Sat, 28 Apr 2012 12:42:03 +1200
Subject: Initial checkin.
---
.gitignore | 8 +
libpathod/__init__.py | 23 +
libpathod/contrib/__init__.py | 0
libpathod/contrib/pyparsing.py | 3749 ++++++++++++++++++++++++++++++++++++
libpathod/handlers.py | 45 +
libpathod/http.py | 103 +
libpathod/rparse.py | 429 +++++
libpathod/static/bootstrap.min.css | 543 ++++++
libpathod/templates/frame.html | 41 +
libpathod/templates/help.html | 4 +
libpathod/templates/index.html | 12 +
libpathod/templates/log.html | 5 +
libpathod/utils.py | 31 +
notes | 102 +
pathod | 21 +
test/.pry | 5 +
test/test_rparse.py | 262 +++
test/test_utils.py | 8 +
todo | 6 +
19 files changed, 5397 insertions(+)
create mode 100644 .gitignore
create mode 100644 libpathod/__init__.py
create mode 100644 libpathod/contrib/__init__.py
create mode 100644 libpathod/contrib/pyparsing.py
create mode 100644 libpathod/handlers.py
create mode 100644 libpathod/http.py
create mode 100644 libpathod/rparse.py
create mode 100644 libpathod/static/bootstrap.min.css
create mode 100644 libpathod/templates/frame.html
create mode 100644 libpathod/templates/help.html
create mode 100644 libpathod/templates/index.html
create mode 100644 libpathod/templates/log.html
create mode 100644 libpathod/utils.py
create mode 100644 notes
create mode 100755 pathod
create mode 100644 test/.pry
create mode 100644 test/test_rparse.py
create mode 100644 test/test_utils.py
create mode 100644 todo
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 00000000..08d66342
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,8 @@
+# Python object files
+*.py[cd]
+MANIFEST
+/build
+/dist
+# Vim swap files
+*.swp
+/doc
diff --git a/libpathod/__init__.py b/libpathod/__init__.py
new file mode 100644
index 00000000..e841a6ab
--- /dev/null
+++ b/libpathod/__init__.py
@@ -0,0 +1,23 @@
+from tornado import web, template
+import handlers, utils
+
+class PathodApp(web.Application):
+ def __init__(self, *args, **kwargs):
+ self.templates = template.Loader(utils.data.path("templates"))
+ web.Application.__init__(self, *args, **kwargs)
+
+
+def application(**settings):
+ return PathodApp(
+ [
+ (r"/", handlers.Index),
+ (r"/log", handlers.Log),
+ (r"/help", handlers.Help),
+ (r"/preview", handlers.Preview),
+ (r"/p/.*", handlers.Pathod, settings),
+ ],
+ debug=True,
+ static_path = utils.data.path("static"),
+ template_path = utils.data.path("templates"),
+ )
+
diff --git a/libpathod/contrib/__init__.py b/libpathod/contrib/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/libpathod/contrib/pyparsing.py b/libpathod/contrib/pyparsing.py
new file mode 100644
index 00000000..9be97dc2
--- /dev/null
+++ b/libpathod/contrib/pyparsing.py
@@ -0,0 +1,3749 @@
+# module pyparsing.py
+#
+# Copyright (c) 2003-2011 Paul T. McGuire
+#
+# Permission is hereby granted, free of charge, to any person obtaining
+# a copy of this software and associated documentation files (the
+# "Software"), to deal in the Software without restriction, including
+# without limitation the rights to use, copy, modify, merge, publish,
+# distribute, sublicense, and/or sell copies of the Software, and to
+# permit persons to whom the Software is furnished to do so, subject to
+# the following conditions:
+#
+# The above copyright notice and this permission notice shall be
+# included in all copies or substantial portions of the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+#
+#from __future__ import generators
+
+__doc__ = \
+"""
+pyparsing module - Classes and methods to define and execute parsing grammars
+
+The pyparsing module is an alternative approach to creating and executing simple grammars,
+vs. the traditional lex/yacc approach, or the use of regular expressions. With pyparsing, you
+don't need to learn a new syntax for defining grammars or matching expressions - the parsing module
+provides a library of classes that you use to construct the grammar directly in Python.
+
+Here is a program to parse "Hello, World!" (or any greeting of the form C{", !"})::
+
+ from pyparsing import Word, alphas
+
+ # define grammar of a greeting
+ greet = Word( alphas ) + "," + Word( alphas ) + "!"
+
+ hello = "Hello, World!"
+ print hello, "->", greet.parseString( hello )
+
+The program outputs the following::
+
+ Hello, World! -> ['Hello', ',', 'World', '!']
+
+The Python representation of the grammar is quite readable, owing to the self-explanatory
+class names, and the use of '+', '|' and '^' operators.
+
+The parsed results returned from C{parseString()} can be accessed as a nested list, a dictionary, or an
+object with named attributes.
+
+The pyparsing module handles some of the problems that are typically vexing when writing text parsers:
+ - extra or missing whitespace (the above program will also handle "Hello,World!", "Hello , World !", etc.)
+ - quoted strings
+ - embedded comments
+"""
+
+__version__ = "1.5.6"
+__versionTime__ = "26 June 2011 10:53"
+__author__ = "Paul McGuire "
+
+import string
+from weakref import ref as wkref
+import copy
+import sys
+import warnings
+import re
+import sre_constants
+#~ sys.stderr.write( "testing pyparsing module, version %s, %s\n" % (__version__,__versionTime__ ) )
+
+__all__ = [
+'And', 'CaselessKeyword', 'CaselessLiteral', 'CharsNotIn', 'Combine', 'Dict', 'Each', 'Empty',
+'FollowedBy', 'Forward', 'GoToColumn', 'Group', 'Keyword', 'LineEnd', 'LineStart', 'Literal',
+'MatchFirst', 'NoMatch', 'NotAny', 'OneOrMore', 'OnlyOnce', 'Optional', 'Or',
+'ParseBaseException', 'ParseElementEnhance', 'ParseException', 'ParseExpression', 'ParseFatalException',
+'ParseResults', 'ParseSyntaxException', 'ParserElement', 'QuotedString', 'RecursiveGrammarException',
+'Regex', 'SkipTo', 'StringEnd', 'StringStart', 'Suppress', 'Token', 'TokenConverter', 'Upcase',
+'White', 'Word', 'WordEnd', 'WordStart', 'ZeroOrMore',
+'alphanums', 'alphas', 'alphas8bit', 'anyCloseTag', 'anyOpenTag', 'cStyleComment', 'col',
+'commaSeparatedList', 'commonHTMLEntity', 'countedArray', 'cppStyleComment', 'dblQuotedString',
+'dblSlashComment', 'delimitedList', 'dictOf', 'downcaseTokens', 'empty', 'getTokensEndLoc', 'hexnums',
+'htmlComment', 'javaStyleComment', 'keepOriginalText', 'line', 'lineEnd', 'lineStart', 'lineno',
+'makeHTMLTags', 'makeXMLTags', 'matchOnlyAtCol', 'matchPreviousExpr', 'matchPreviousLiteral',
+'nestedExpr', 'nullDebugAction', 'nums', 'oneOf', 'opAssoc', 'operatorPrecedence', 'printables',
+'punc8bit', 'pythonStyleComment', 'quotedString', 'removeQuotes', 'replaceHTMLEntity',
+'replaceWith', 'restOfLine', 'sglQuotedString', 'srange', 'stringEnd',
+'stringStart', 'traceParseAction', 'unicodeString', 'upcaseTokens', 'withAttribute',
+'indentedBlock', 'originalTextFor',
+]
+
+"""
+Detect if we are running version 3.X and make appropriate changes
+Robert A. Clark
+"""
+_PY3K = sys.version_info[0] > 2
+if _PY3K:
+ _MAX_INT = sys.maxsize
+ basestring = str
+ unichr = chr
+ _ustr = str
+ alphas = string.ascii_lowercase + string.ascii_uppercase
+else:
+ _MAX_INT = sys.maxint
+ range = xrange
+ set = lambda s : dict( [(c,0) for c in s] )
+ alphas = string.lowercase + string.uppercase
+
+ def _ustr(obj):
+ """Drop-in replacement for str(obj) that tries to be Unicode friendly. It first tries
+ str(obj). If that fails with a UnicodeEncodeError, then it tries unicode(obj). It
+ then < returns the unicode object | encodes it with the default encoding | ... >.
+ """
+ if isinstance(obj,unicode):
+ return obj
+
+ try:
+ # If this works, then _ustr(obj) has the same behaviour as str(obj), so
+ # it won't break any existing code.
+ return str(obj)
+
+ except UnicodeEncodeError:
+ # The Python docs (http://docs.python.org/ref/customization.html#l2h-182)
+ # state that "The return value must be a string object". However, does a
+ # unicode object (being a subclass of basestring) count as a "string
+ # object"?
+ # If so, then return a unicode object:
+ return unicode(obj)
+ # Else encode it... but how? There are many choices... :)
+ # Replace unprintables with escape codes?
+ #return unicode(obj).encode(sys.getdefaultencoding(), 'backslashreplace_errors')
+ # Replace unprintables with question marks?
+ #return unicode(obj).encode(sys.getdefaultencoding(), 'replace')
+ # ...
+
+ alphas = string.lowercase + string.uppercase
+
+# build list of single arg builtins, tolerant of Python version, that can be used as parse actions
+singleArgBuiltins = []
+import __builtin__
+for fname in "sum len enumerate sorted reversed list tuple set any all".split():
+ try:
+ singleArgBuiltins.append(getattr(__builtin__,fname))
+ except AttributeError:
+ continue
+
+def _xml_escape(data):
+ """Escape &, <, >, ", ', etc. in a string of data."""
+
+ # ampersand must be replaced first
+ from_symbols = '&><"\''
+ to_symbols = ['&'+s+';' for s in "amp gt lt quot apos".split()]
+ for from_,to_ in zip(from_symbols, to_symbols):
+ data = data.replace(from_, to_)
+ return data
+
+class _Constants(object):
+ pass
+
+nums = string.digits
+hexnums = nums + "ABCDEFabcdef"
+alphanums = alphas + nums
+_bslash = chr(92)
+printables = "".join( [ c for c in string.printable if c not in string.whitespace ] )
+
+class ParseBaseException(Exception):
+ """base exception class for all parsing runtime exceptions"""
+ # Performance tuning: we construct a *lot* of these, so keep this
+ # constructor as small and fast as possible
+ def __init__( self, pstr, loc=0, msg=None, elem=None ):
+ self.loc = loc
+ if msg is None:
+ self.msg = pstr
+ self.pstr = ""
+ else:
+ self.msg = msg
+ self.pstr = pstr
+ self.parserElement = elem
+
+ def __getattr__( self, aname ):
+ """supported attributes by name are:
+ - lineno - returns the line number of the exception text
+ - col - returns the column number of the exception text
+ - line - returns the line containing the exception text
+ """
+ if( aname == "lineno" ):
+ return lineno( self.loc, self.pstr )
+ elif( aname in ("col", "column") ):
+ return col( self.loc, self.pstr )
+ elif( aname == "line" ):
+ return line( self.loc, self.pstr )
+ else:
+ raise AttributeError(aname)
+
+ def __str__( self ):
+ return "%s (at char %d), (line:%d, col:%d)" % \
+ ( self.msg, self.loc, self.lineno, self.column )
+ def __repr__( self ):
+ return _ustr(self)
+ def markInputline( self, markerString = ">!<" ):
+ """Extracts the exception line from the input string, and marks
+ the location of the exception with a special symbol.
+ """
+ line_str = self.line
+ line_column = self.column - 1
+ if markerString:
+ line_str = "".join( [line_str[:line_column],
+ markerString, line_str[line_column:]])
+ return line_str.strip()
+ def __dir__(self):
+ return "loc msg pstr parserElement lineno col line " \
+ "markInputLine __str__ __repr__".split()
+
+class ParseException(ParseBaseException):
+ """exception thrown when parse expressions don't match class;
+ supported attributes by name are:
+ - lineno - returns the line number of the exception text
+ - col - returns the column number of the exception text
+ - line - returns the line containing the exception text
+ """
+ pass
+
+class ParseFatalException(ParseBaseException):
+ """user-throwable exception thrown when inconsistent parse content
+ is found; stops all parsing immediately"""
+ pass
+
+class ParseSyntaxException(ParseFatalException):
+ """just like C{ParseFatalException}, but thrown internally when an
+ C{ErrorStop} ('-' operator) indicates that parsing is to stop immediately because
+ an unbacktrackable syntax error has been found"""
+ def __init__(self, pe):
+ super(ParseSyntaxException, self).__init__(
+ pe.pstr, pe.loc, pe.msg, pe.parserElement)
+
+#~ class ReparseException(ParseBaseException):
+ #~ """Experimental class - parse actions can raise this exception to cause
+ #~ pyparsing to reparse the input string:
+ #~ - with a modified input string, and/or
+ #~ - with a modified start location
+ #~ Set the values of the ReparseException in the constructor, and raise the
+ #~ exception in a parse action to cause pyparsing to use the new string/location.
+ #~ Setting the values as None causes no change to be made.
+ #~ """
+ #~ def __init_( self, newstring, restartLoc ):
+ #~ self.newParseText = newstring
+ #~ self.reparseLoc = restartLoc
+
+class RecursiveGrammarException(Exception):
+ """exception thrown by C{validate()} if the grammar could be improperly recursive"""
+ def __init__( self, parseElementList ):
+ self.parseElementTrace = parseElementList
+
+ def __str__( self ):
+ return "RecursiveGrammarException: %s" % self.parseElementTrace
+
+class _ParseResultsWithOffset(object):
+ def __init__(self,p1,p2):
+ self.tup = (p1,p2)
+ def __getitem__(self,i):
+ return self.tup[i]
+ def __repr__(self):
+ return repr(self.tup)
+ def setOffset(self,i):
+ self.tup = (self.tup[0],i)
+
+class ParseResults(object):
+ """Structured parse results, to provide multiple means of access to the parsed data:
+ - as a list (C{len(results)})
+ - by list index (C{results[0], results[1]}, etc.)
+ - by attribute (C{results.})
+ """
+ #~ __slots__ = ( "__toklist", "__tokdict", "__doinit", "__name", "__parent", "__accumNames", "__weakref__" )
+ def __new__(cls, toklist, name=None, asList=True, modal=True ):
+ if isinstance(toklist, cls):
+ return toklist
+ retobj = object.__new__(cls)
+ retobj.__doinit = True
+ return retobj
+
+ # Performance tuning: we construct a *lot* of these, so keep this
+ # constructor as small and fast as possible
+ def __init__( self, toklist, name=None, asList=True, modal=True, isinstance=isinstance ):
+ if self.__doinit:
+ self.__doinit = False
+ self.__name = None
+ self.__parent = None
+ self.__accumNames = {}
+ if isinstance(toklist, list):
+ self.__toklist = toklist[:]
+ else:
+ self.__toklist = [toklist]
+ self.__tokdict = dict()
+
+ if name is not None and name:
+ if not modal:
+ self.__accumNames[name] = 0
+ if isinstance(name,int):
+ name = _ustr(name) # will always return a str, but use _ustr for consistency
+ self.__name = name
+ if not toklist in (None,'',[]):
+ if isinstance(toklist,basestring):
+ toklist = [ toklist ]
+ if asList:
+ if isinstance(toklist,ParseResults):
+ self[name] = _ParseResultsWithOffset(toklist.copy(),0)
+ else:
+ self[name] = _ParseResultsWithOffset(ParseResults(toklist[0]),0)
+ self[name].__name = name
+ else:
+ try:
+ self[name] = toklist[0]
+ except (KeyError,TypeError,IndexError):
+ self[name] = toklist
+
+ def __getitem__( self, i ):
+ if isinstance( i, (int,slice) ):
+ return self.__toklist[i]
+ else:
+ if i not in self.__accumNames:
+ return self.__tokdict[i][-1][0]
+ else:
+ return ParseResults([ v[0] for v in self.__tokdict[i] ])
+
+ def __setitem__( self, k, v, isinstance=isinstance ):
+ if isinstance(v,_ParseResultsWithOffset):
+ self.__tokdict[k] = self.__tokdict.get(k,list()) + [v]
+ sub = v[0]
+ elif isinstance(k,int):
+ self.__toklist[k] = v
+ sub = v
+ else:
+ self.__tokdict[k] = self.__tokdict.get(k,list()) + [_ParseResultsWithOffset(v,0)]
+ sub = v
+ if isinstance(sub,ParseResults):
+ sub.__parent = wkref(self)
+
+ def __delitem__( self, i ):
+ if isinstance(i,(int,slice)):
+ mylen = len( self.__toklist )
+ del self.__toklist[i]
+
+ # convert int to slice
+ if isinstance(i, int):
+ if i < 0:
+ i += mylen
+ i = slice(i, i+1)
+ # get removed indices
+ removed = list(range(*i.indices(mylen)))
+ removed.reverse()
+ # fixup indices in token dictionary
+ for name in self.__tokdict:
+ occurrences = self.__tokdict[name]
+ for j in removed:
+ for k, (value, position) in enumerate(occurrences):
+ occurrences[k] = _ParseResultsWithOffset(value, position - (position > j))
+ else:
+ del self.__tokdict[i]
+
+ def __contains__( self, k ):
+ return k in self.__tokdict
+
+ def __len__( self ): return len( self.__toklist )
+ def __bool__(self): return len( self.__toklist ) > 0
+ __nonzero__ = __bool__
+ def __iter__( self ): return iter( self.__toklist )
+ def __reversed__( self ): return iter( self.__toklist[::-1] )
+ def keys( self ):
+ """Returns all named result keys."""
+ return self.__tokdict.keys()
+
+ def pop( self, index=-1 ):
+ """Removes and returns item at specified index (default=last).
+ Will work with either numeric indices or dict-key indicies."""
+ ret = self[index]
+ del self[index]
+ return ret
+
+ def get(self, key, defaultValue=None):
+ """Returns named result matching the given key, or if there is no
+ such name, then returns the given C{defaultValue} or C{None} if no
+ C{defaultValue} is specified."""
+ if key in self:
+ return self[key]
+ else:
+ return defaultValue
+
+ def insert( self, index, insStr ):
+ """Inserts new element at location index in the list of parsed tokens."""
+ self.__toklist.insert(index, insStr)
+ # fixup indices in token dictionary
+ for name in self.__tokdict:
+ occurrences = self.__tokdict[name]
+ for k, (value, position) in enumerate(occurrences):
+ occurrences[k] = _ParseResultsWithOffset(value, position + (position > index))
+
+ def items( self ):
+ """Returns all named result keys and values as a list of tuples."""
+ return [(k,self[k]) for k in self.__tokdict]
+
+ def values( self ):
+ """Returns all named result values."""
+ return [ v[-1][0] for v in self.__tokdict.values() ]
+
+ def __getattr__( self, name ):
+ if True: #name not in self.__slots__:
+ if name in self.__tokdict:
+ if name not in self.__accumNames:
+ return self.__tokdict[name][-1][0]
+ else:
+ return ParseResults([ v[0] for v in self.__tokdict[name] ])
+ else:
+ return ""
+ return None
+
+ def __add__( self, other ):
+ ret = self.copy()
+ ret += other
+ return ret
+
+ def __iadd__( self, other ):
+ if other.__tokdict:
+ offset = len(self.__toklist)
+ addoffset = ( lambda a: (a<0 and offset) or (a+offset) )
+ otheritems = other.__tokdict.items()
+ otherdictitems = [(k, _ParseResultsWithOffset(v[0],addoffset(v[1])) )
+ for (k,vlist) in otheritems for v in vlist]
+ for k,v in otherdictitems:
+ self[k] = v
+ if isinstance(v[0],ParseResults):
+ v[0].__parent = wkref(self)
+
+ self.__toklist += other.__toklist
+ self.__accumNames.update( other.__accumNames )
+ return self
+
+ def __radd__(self, other):
+ if isinstance(other,int) and other == 0:
+ return self.copy()
+
+ def __repr__( self ):
+ return "(%s, %s)" % ( repr( self.__toklist ), repr( self.__tokdict ) )
+
+ def __str__( self ):
+ out = "["
+ sep = ""
+ for i in self.__toklist:
+ if isinstance(i, ParseResults):
+ out += sep + _ustr(i)
+ else:
+ out += sep + repr(i)
+ sep = ", "
+ out += "]"
+ return out
+
+ def _asStringList( self, sep='' ):
+ out = []
+ for item in self.__toklist:
+ if out and sep:
+ out.append(sep)
+ if isinstance( item, ParseResults ):
+ out += item._asStringList()
+ else:
+ out.append( _ustr(item) )
+ return out
+
+ def asList( self ):
+ """Returns the parse results as a nested list of matching tokens, all converted to strings."""
+ out = []
+ for res in self.__toklist:
+ if isinstance(res,ParseResults):
+ out.append( res.asList() )
+ else:
+ out.append( res )
+ return out
+
+ def asDict( self ):
+ """Returns the named parse results as dictionary."""
+ return dict( self.items() )
+
+ def copy( self ):
+ """Returns a new copy of a C{ParseResults} object."""
+ ret = ParseResults( self.__toklist )
+ ret.__tokdict = self.__tokdict.copy()
+ ret.__parent = self.__parent
+ ret.__accumNames.update( self.__accumNames )
+ ret.__name = self.__name
+ return ret
+
+ def asXML( self, doctag=None, namedItemsOnly=False, indent="", formatted=True ):
+ """Returns the parse results as XML. Tags are created for tokens and lists that have defined results names."""
+ nl = "\n"
+ out = []
+ namedItems = dict( [ (v[1],k) for (k,vlist) in self.__tokdict.items()
+ for v in vlist ] )
+ nextLevelIndent = indent + " "
+
+ # collapse out indents if formatting is not desired
+ if not formatted:
+ indent = ""
+ nextLevelIndent = ""
+ nl = ""
+
+ selfTag = None
+ if doctag is not None:
+ selfTag = doctag
+ else:
+ if self.__name:
+ selfTag = self.__name
+
+ if not selfTag:
+ if namedItemsOnly:
+ return ""
+ else:
+ selfTag = "ITEM"
+
+ out += [ nl, indent, "<", selfTag, ">" ]
+
+ worklist = self.__toklist
+ for i,res in enumerate(worklist):
+ if isinstance(res,ParseResults):
+ if i in namedItems:
+ out += [ res.asXML(namedItems[i],
+ namedItemsOnly and doctag is None,
+ nextLevelIndent,
+ formatted)]
+ else:
+ out += [ res.asXML(None,
+ namedItemsOnly and doctag is None,
+ nextLevelIndent,
+ formatted)]
+ else:
+ # individual token, see if there is a name for it
+ resTag = None
+ if i in namedItems:
+ resTag = namedItems[i]
+ if not resTag:
+ if namedItemsOnly:
+ continue
+ else:
+ resTag = "ITEM"
+ xmlBodyText = _xml_escape(_ustr(res))
+ out += [ nl, nextLevelIndent, "<", resTag, ">",
+ xmlBodyText,
+ "", resTag, ">" ]
+
+ out += [ nl, indent, "", selfTag, ">" ]
+ return "".join(out)
+
+ def __lookup(self,sub):
+ for k,vlist in self.__tokdict.items():
+ for v,loc in vlist:
+ if sub is v:
+ return k
+ return None
+
+ def getName(self):
+ """Returns the results name for this token expression."""
+ if self.__name:
+ return self.__name
+ elif self.__parent:
+ par = self.__parent()
+ if par:
+ return par.__lookup(self)
+ else:
+ return None
+ elif (len(self) == 1 and
+ len(self.__tokdict) == 1 and
+ self.__tokdict.values()[0][0][1] in (0,-1)):
+ return self.__tokdict.keys()[0]
+ else:
+ return None
+
+ def dump(self,indent='',depth=0):
+ """Diagnostic method for listing out the contents of a C{ParseResults}.
+ Accepts an optional C{indent} argument so that this string can be embedded
+ in a nested display of other data."""
+ out = []
+ out.append( indent+_ustr(self.asList()) )
+ keys = self.items()
+ keys.sort()
+ for k,v in keys:
+ if out:
+ out.append('\n')
+ out.append( "%s%s- %s: " % (indent,(' '*depth), k) )
+ if isinstance(v,ParseResults):
+ if v.keys():
+ out.append( v.dump(indent,depth+1) )
+ else:
+ out.append(_ustr(v))
+ else:
+ out.append(_ustr(v))
+ return "".join(out)
+
+ # add support for pickle protocol
+ def __getstate__(self):
+ return ( self.__toklist,
+ ( self.__tokdict.copy(),
+ self.__parent is not None and self.__parent() or None,
+ self.__accumNames,
+ self.__name ) )
+
+ def __setstate__(self,state):
+ self.__toklist = state[0]
+ (self.__tokdict,
+ par,
+ inAccumNames,
+ self.__name) = state[1]
+ self.__accumNames = {}
+ self.__accumNames.update(inAccumNames)
+ if par is not None:
+ self.__parent = wkref(par)
+ else:
+ self.__parent = None
+
+ def __dir__(self):
+ return dir(super(ParseResults,self)) + self.keys()
+
+def col (loc,strg):
+ """Returns current column within a string, counting newlines as line separators.
+ The first column is number 1.
+
+ Note: the default parsing behavior is to expand tabs in the input string
+ before starting the parsing process. See L{I{ParserElement.parseString}} for more information
+ on parsing strings containing s, and suggested methods to maintain a
+ consistent view of the parsed string, the parse location, and line and column
+ positions within the parsed string.
+ """
+ return (loc} for more information
+ on parsing strings containing s, and suggested methods to maintain a
+ consistent view of the parsed string, the parse location, and line and column
+ positions within the parsed string.
+ """
+ return strg.count("\n",0,loc) + 1
+
+def line( loc, strg ):
+ """Returns the line of text containing loc within a string, counting newlines as line separators.
+ """
+ lastCR = strg.rfind("\n", 0, loc)
+ nextCR = strg.find("\n", loc)
+ if nextCR >= 0:
+ return strg[lastCR+1:nextCR]
+ else:
+ return strg[lastCR+1:]
+
+def _defaultStartDebugAction( instring, loc, expr ):
+ print ("Match " + _ustr(expr) + " at loc " + _ustr(loc) + "(%d,%d)" % ( lineno(loc,instring), col(loc,instring) ))
+
+def _defaultSuccessDebugAction( instring, startloc, endloc, expr, toks ):
+ print ("Matched " + _ustr(expr) + " -> " + str(toks.asList()))
+
+def _defaultExceptionDebugAction( instring, loc, expr, exc ):
+ print ("Exception raised:" + _ustr(exc))
+
+def nullDebugAction(*args):
+ """'Do-nothing' debug action, to suppress debugging output during parsing."""
+ pass
+
+'decorator to trim function calls to match the arity of the target'
+if not _PY3K:
+ def _trim_arity(func, maxargs=2):
+ limit = [0]
+ def wrapper(*args):
+ while 1:
+ try:
+ return func(*args[limit[0]:])
+ except TypeError:
+ if limit[0] <= maxargs:
+ limit[0] += 1
+ continue
+ raise
+ return wrapper
+else:
+ def _trim_arity(func, maxargs=2):
+ limit = maxargs
+ def wrapper(*args):
+ #~ nonlocal limit
+ while 1:
+ try:
+ return func(*args[limit:])
+ except TypeError:
+ if limit:
+ limit -= 1
+ continue
+ raise
+ return wrapper
+
+class ParserElement(object):
+ """Abstract base level parser element class."""
+ DEFAULT_WHITE_CHARS = " \n\t\r"
+ verbose_stacktrace = False
+
+ def setDefaultWhitespaceChars( chars ):
+ """Overrides the default whitespace chars
+ """
+ ParserElement.DEFAULT_WHITE_CHARS = chars
+ setDefaultWhitespaceChars = staticmethod(setDefaultWhitespaceChars)
+
+ def __init__( self, savelist=False ):
+ self.parseAction = list()
+ self.failAction = None
+ #~ self.name = "" # don't define self.name, let subclasses try/except upcall
+ self.strRepr = None
+ self.resultsName = None
+ self.saveAsList = savelist
+ self.skipWhitespace = True
+ self.whiteChars = ParserElement.DEFAULT_WHITE_CHARS
+ self.copyDefaultWhiteChars = True
+ self.mayReturnEmpty = False # used when checking for left-recursion
+ self.keepTabs = False
+ self.ignoreExprs = list()
+ self.debug = False
+ self.streamlined = False
+ self.mayIndexError = True # used to optimize exception handling for subclasses that don't advance parse index
+ self.errmsg = ""
+ self.modalResults = True # used to mark results names as modal (report only last) or cumulative (list all)
+ self.debugActions = ( None, None, None ) #custom debug actions
+ self.re = None
+ self.callPreparse = True # used to avoid redundant calls to preParse
+ self.callDuringTry = False
+
+ def copy( self ):
+ """Make a copy of this C{ParserElement}. Useful for defining different parse actions
+ for the same parsing pattern, using copies of the original parse element."""
+ cpy = copy.copy( self )
+ cpy.parseAction = self.parseAction[:]
+ cpy.ignoreExprs = self.ignoreExprs[:]
+ if self.copyDefaultWhiteChars:
+ cpy.whiteChars = ParserElement.DEFAULT_WHITE_CHARS
+ return cpy
+
+ def setName( self, name ):
+ """Define name for this expression, for use in debugging."""
+ self.name = name
+ self.errmsg = "Expected " + self.name
+ if hasattr(self,"exception"):
+ self.exception.msg = self.errmsg
+ return self
+
+ def setResultsName( self, name, listAllMatches=False ):
+ """Define name for referencing matching tokens as a nested attribute
+ of the returned parse results.
+ NOTE: this returns a *copy* of the original C{ParserElement} object;
+ this is so that the client can define a basic element, such as an
+ integer, and reference it in multiple places with different names.
+
+ You can also set results names using the abbreviated syntax,
+ C{expr("name")} in place of C{expr.setResultsName("name")} -
+ see L{I{__call__}<__call__>}.
+ """
+ newself = self.copy()
+ if name.endswith("*"):
+ name = name[:-1]
+ listAllMatches=True
+ newself.resultsName = name
+ newself.modalResults = not listAllMatches
+ return newself
+
+ def setBreak(self,breakFlag = True):
+ """Method to invoke the Python pdb debugger when this element is
+ about to be parsed. Set C{breakFlag} to True to enable, False to
+ disable.
+ """
+ if breakFlag:
+ _parseMethod = self._parse
+ def breaker(instring, loc, doActions=True, callPreParse=True):
+ import pdb
+ pdb.set_trace()
+ return _parseMethod( instring, loc, doActions, callPreParse )
+ breaker._originalParseMethod = _parseMethod
+ self._parse = breaker
+ else:
+ if hasattr(self._parse,"_originalParseMethod"):
+ self._parse = self._parse._originalParseMethod
+ return self
+
+ def setParseAction( self, *fns, **kwargs ):
+ """Define action to perform when successfully matching parse element definition.
+ Parse action fn is a callable method with 0-3 arguments, called as C{fn(s,loc,toks)},
+ C{fn(loc,toks)}, C{fn(toks)}, or just C{fn()}, where:
+ - s = the original string being parsed (see note below)
+ - loc = the location of the matching substring
+ - toks = a list of the matched tokens, packaged as a ParseResults object
+ If the functions in fns modify the tokens, they can return them as the return
+ value from fn, and the modified list of tokens will replace the original.
+ Otherwise, fn does not need to return any value.
+
+ Note: the default parsing behavior is to expand tabs in the input string
+ before starting the parsing process. See L{I{parseString}} for more information
+ on parsing strings containing s, and suggested methods to maintain a
+ consistent view of the parsed string, the parse location, and line and column
+ positions within the parsed string.
+ """
+ self.parseAction = list(map(_trim_arity, list(fns)))
+ self.callDuringTry = ("callDuringTry" in kwargs and kwargs["callDuringTry"])
+ return self
+
+ def addParseAction( self, *fns, **kwargs ):
+ """Add parse action to expression's list of parse actions. See L{I{setParseAction}}."""
+ self.parseAction += list(map(_trim_arity, list(fns)))
+ self.callDuringTry = self.callDuringTry or ("callDuringTry" in kwargs and kwargs["callDuringTry"])
+ return self
+
+ def setFailAction( self, fn ):
+ """Define action to perform if parsing fails at this expression.
+ Fail acton fn is a callable function that takes the arguments
+ C{fn(s,loc,expr,err)} where:
+ - s = string being parsed
+ - loc = location where expression match was attempted and failed
+ - expr = the parse expression that failed
+ - err = the exception thrown
+ The function returns no value. It may throw C{ParseFatalException}
+ if it is desired to stop parsing immediately."""
+ self.failAction = fn
+ return self
+
+ def _skipIgnorables( self, instring, loc ):
+ exprsFound = True
+ while exprsFound:
+ exprsFound = False
+ for e in self.ignoreExprs:
+ try:
+ while 1:
+ loc,dummy = e._parse( instring, loc )
+ exprsFound = True
+ except ParseException:
+ pass
+ return loc
+
+ def preParse( self, instring, loc ):
+ if self.ignoreExprs:
+ loc = self._skipIgnorables( instring, loc )
+
+ if self.skipWhitespace:
+ wt = self.whiteChars
+ instrlen = len(instring)
+ while loc < instrlen and instring[loc] in wt:
+ loc += 1
+
+ return loc
+
+ def parseImpl( self, instring, loc, doActions=True ):
+ return loc, []
+
+ def postParse( self, instring, loc, tokenlist ):
+ return tokenlist
+
+ #~ @profile
+ def _parseNoCache( self, instring, loc, doActions=True, callPreParse=True ):
+ debugging = ( self.debug ) #and doActions )
+
+ if debugging or self.failAction:
+ #~ print ("Match",self,"at loc",loc,"(%d,%d)" % ( lineno(loc,instring), col(loc,instring) ))
+ if (self.debugActions[0] ):
+ self.debugActions[0]( instring, loc, self )
+ if callPreParse and self.callPreparse:
+ preloc = self.preParse( instring, loc )
+ else:
+ preloc = loc
+ tokensStart = preloc
+ try:
+ try:
+ loc,tokens = self.parseImpl( instring, preloc, doActions )
+ except IndexError:
+ raise ParseException( instring, len(instring), self.errmsg, self )
+ except ParseBaseException:
+ #~ print ("Exception raised:", err)
+ err = None
+ if self.debugActions[2]:
+ err = sys.exc_info()[1]
+ self.debugActions[2]( instring, tokensStart, self, err )
+ if self.failAction:
+ if err is None:
+ err = sys.exc_info()[1]
+ self.failAction( instring, tokensStart, self, err )
+ raise
+ else:
+ if callPreParse and self.callPreparse:
+ preloc = self.preParse( instring, loc )
+ else:
+ preloc = loc
+ tokensStart = preloc
+ if self.mayIndexError or loc >= len(instring):
+ try:
+ loc,tokens = self.parseImpl( instring, preloc, doActions )
+ except IndexError:
+ raise ParseException( instring, len(instring), self.errmsg, self )
+ else:
+ loc,tokens = self.parseImpl( instring, preloc, doActions )
+
+ tokens = self.postParse( instring, loc, tokens )
+
+ retTokens = ParseResults( tokens, self.resultsName, asList=self.saveAsList, modal=self.modalResults )
+ if self.parseAction and (doActions or self.callDuringTry):
+ if debugging:
+ try:
+ for fn in self.parseAction:
+ tokens = fn( instring, tokensStart, retTokens )
+ if tokens is not None:
+ retTokens = ParseResults( tokens,
+ self.resultsName,
+ asList=self.saveAsList and isinstance(tokens,(ParseResults,list)),
+ modal=self.modalResults )
+ except ParseBaseException:
+ #~ print "Exception raised in user parse action:", err
+ if (self.debugActions[2] ):
+ err = sys.exc_info()[1]
+ self.debugActions[2]( instring, tokensStart, self, err )
+ raise
+ else:
+ for fn in self.parseAction:
+ tokens = fn( instring, tokensStart, retTokens )
+ if tokens is not None:
+ retTokens = ParseResults( tokens,
+ self.resultsName,
+ asList=self.saveAsList and isinstance(tokens,(ParseResults,list)),
+ modal=self.modalResults )
+
+ if debugging:
+ #~ print ("Matched",self,"->",retTokens.asList())
+ if (self.debugActions[1] ):
+ self.debugActions[1]( instring, tokensStart, loc, self, retTokens )
+
+ return loc, retTokens
+
+ def tryParse( self, instring, loc ):
+ try:
+ return self._parse( instring, loc, doActions=False )[0]
+ except ParseFatalException:
+ raise ParseException( instring, loc, self.errmsg, self)
+
+ # this method gets repeatedly called during backtracking with the same arguments -
+ # we can cache these arguments and save ourselves the trouble of re-parsing the contained expression
+ def _parseCache( self, instring, loc, doActions=True, callPreParse=True ):
+ lookup = (self,instring,loc,callPreParse,doActions)
+ if lookup in ParserElement._exprArgCache:
+ value = ParserElement._exprArgCache[ lookup ]
+ if isinstance(value, Exception):
+ raise value
+ return (value[0],value[1].copy())
+ else:
+ try:
+ value = self._parseNoCache( instring, loc, doActions, callPreParse )
+ ParserElement._exprArgCache[ lookup ] = (value[0],value[1].copy())
+ return value
+ except ParseBaseException:
+ pe = sys.exc_info()[1]
+ ParserElement._exprArgCache[ lookup ] = pe
+ raise
+
+ _parse = _parseNoCache
+
+ # argument cache for optimizing repeated calls when backtracking through recursive expressions
+ _exprArgCache = {}
+ def resetCache():
+ ParserElement._exprArgCache.clear()
+ resetCache = staticmethod(resetCache)
+
+ _packratEnabled = False
+ def enablePackrat():
+ """Enables "packrat" parsing, which adds memoizing to the parsing logic.
+ Repeated parse attempts at the same string location (which happens
+ often in many complex grammars) can immediately return a cached value,
+ instead of re-executing parsing/validating code. Memoizing is done of
+ both valid results and parsing exceptions.
+
+ This speedup may break existing programs that use parse actions that
+ have side-effects. For this reason, packrat parsing is disabled when
+ you first import pyparsing. To activate the packrat feature, your
+ program must call the class method C{ParserElement.enablePackrat()}. If
+ your program uses C{psyco} to "compile as you go", you must call
+ C{enablePackrat} before calling C{psyco.full()}. If you do not do this,
+ Python will crash. For best results, call C{enablePackrat()} immediately
+ after importing pyparsing.
+ """
+ if not ParserElement._packratEnabled:
+ ParserElement._packratEnabled = True
+ ParserElement._parse = ParserElement._parseCache
+ enablePackrat = staticmethod(enablePackrat)
+
+ def parseString( self, instring, parseAll=False ):
+ """Execute the parse expression with the given string.
+ This is the main interface to the client code, once the complete
+ expression has been built.
+
+ If you want the grammar to require that the entire input string be
+ successfully parsed, then set C{parseAll} to True (equivalent to ending
+ the grammar with C{StringEnd()}).
+
+ Note: C{parseString} implicitly calls C{expandtabs()} on the input string,
+ in order to report proper column numbers in parse actions.
+ If the input string contains tabs and
+ the grammar uses parse actions that use the C{loc} argument to index into the
+ string being parsed, you can ensure you have a consistent view of the input
+ string by:
+ - calling C{parseWithTabs} on your grammar before calling C{parseString}
+ (see L{I{parseWithTabs}})
+ - define your parse action using the full C{(s,loc,toks)} signature, and
+ reference the input string using the parse action's C{s} argument
+ - explictly expand the tabs in your input string before calling
+ C{parseString}
+ """
+ ParserElement.resetCache()
+ if not self.streamlined:
+ self.streamline()
+ #~ self.saveAsList = True
+ for e in self.ignoreExprs:
+ e.streamline()
+ if not self.keepTabs:
+ instring = instring.expandtabs()
+ try:
+ loc, tokens = self._parse( instring, 0 )
+ if parseAll:
+ loc = self.preParse( instring, loc )
+ se = Empty() + StringEnd()
+ se._parse( instring, loc )
+ except ParseBaseException:
+ if ParserElement.verbose_stacktrace:
+ raise
+ else:
+ # catch and re-raise exception from here, clears out pyparsing internal stack trace
+ exc = sys.exc_info()[1]
+ raise exc
+ else:
+ return tokens
+
+ def scanString( self, instring, maxMatches=_MAX_INT, overlap=False ):
+ """Scan the input string for expression matches. Each match will return the
+ matching tokens, start location, and end location. May be called with optional
+ C{maxMatches} argument, to clip scanning after 'n' matches are found. If
+ C{overlap} is specified, then overlapping matches will be reported.
+
+ Note that the start and end locations are reported relative to the string
+ being parsed. See L{I{parseString}} for more information on parsing
+ strings with embedded tabs."""
+ if not self.streamlined:
+ self.streamline()
+ for e in self.ignoreExprs:
+ e.streamline()
+
+ if not self.keepTabs:
+ instring = _ustr(instring).expandtabs()
+ instrlen = len(instring)
+ loc = 0
+ preparseFn = self.preParse
+ parseFn = self._parse
+ ParserElement.resetCache()
+ matches = 0
+ try:
+ while loc <= instrlen and matches < maxMatches:
+ try:
+ preloc = preparseFn( instring, loc )
+ nextLoc,tokens = parseFn( instring, preloc, callPreParse=False )
+ except ParseException:
+ loc = preloc+1
+ else:
+ if nextLoc > loc:
+ matches += 1
+ yield tokens, preloc, nextLoc
+ if overlap:
+ nextloc = preparseFn( instring, loc )
+ if nextloc > loc:
+ loc = nextLoc
+ else:
+ loc += 1
+ else:
+ loc = nextLoc
+ else:
+ loc = preloc+1
+ except ParseBaseException:
+ if ParserElement.verbose_stacktrace:
+ raise
+ else:
+ # catch and re-raise exception from here, clears out pyparsing internal stack trace
+ exc = sys.exc_info()[1]
+ raise exc
+
+ def transformString( self, instring ):
+ """Extension to C{scanString}, to modify matching text with modified tokens that may
+ be returned from a parse action. To use C{transformString}, define a grammar and
+ attach a parse action to it that modifies the returned token list.
+ Invoking C{transformString()} on a target string will then scan for matches,
+ and replace the matched text patterns according to the logic in the parse
+ action. C{transformString()} returns the resulting transformed string."""
+ out = []
+ lastE = 0
+ # force preservation of s, to minimize unwanted transformation of string, and to
+ # keep string locs straight between transformString and scanString
+ self.keepTabs = True
+ try:
+ for t,s,e in self.scanString( instring ):
+ out.append( instring[lastE:s] )
+ if t:
+ if isinstance(t,ParseResults):
+ out += t.asList()
+ elif isinstance(t,list):
+ out += t
+ else:
+ out.append(t)
+ lastE = e
+ out.append(instring[lastE:])
+ out = [o for o in out if o]
+ return "".join(map(_ustr,_flatten(out)))
+ except ParseBaseException:
+ if ParserElement.verbose_stacktrace:
+ raise
+ else:
+ # catch and re-raise exception from here, clears out pyparsing internal stack trace
+ exc = sys.exc_info()[1]
+ raise exc
+
+ def searchString( self, instring, maxMatches=_MAX_INT ):
+ """Another extension to C{scanString}, simplifying the access to the tokens found
+ to match the given parse expression. May be called with optional
+ C{maxMatches} argument, to clip searching after 'n' matches are found.
+ """
+ try:
+ return ParseResults([ t for t,s,e in self.scanString( instring, maxMatches ) ])
+ except ParseBaseException:
+ if ParserElement.verbose_stacktrace:
+ raise
+ else:
+ # catch and re-raise exception from here, clears out pyparsing internal stack trace
+ exc = sys.exc_info()[1]
+ raise exc
+
+ def __add__(self, other ):
+ """Implementation of + operator - returns And"""
+ if isinstance( other, basestring ):
+ other = Literal( other )
+ if not isinstance( other, ParserElement ):
+ warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
+ SyntaxWarning, stacklevel=2)
+ return None
+ return And( [ self, other ] )
+
+ def __radd__(self, other ):
+ """Implementation of + operator when left operand is not a C{ParserElement}"""
+ if isinstance( other, basestring ):
+ other = Literal( other )
+ if not isinstance( other, ParserElement ):
+ warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
+ SyntaxWarning, stacklevel=2)
+ return None
+ return other + self
+
+ def __sub__(self, other):
+ """Implementation of - operator, returns C{And} with error stop"""
+ if isinstance( other, basestring ):
+ other = Literal( other )
+ if not isinstance( other, ParserElement ):
+ warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
+ SyntaxWarning, stacklevel=2)
+ return None
+ return And( [ self, And._ErrorStop(), other ] )
+
+ def __rsub__(self, other ):
+ """Implementation of - operator when left operand is not a C{ParserElement}"""
+ if isinstance( other, basestring ):
+ other = Literal( other )
+ if not isinstance( other, ParserElement ):
+ warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
+ SyntaxWarning, stacklevel=2)
+ return None
+ return other - self
+
+ def __mul__(self,other):
+ """Implementation of * operator, allows use of C{expr * 3} in place of
+ C{expr + expr + expr}. Expressions may also me multiplied by a 2-integer
+ tuple, similar to C{{min,max}} multipliers in regular expressions. Tuples
+ may also include C{None} as in:
+ - C{expr*(n,None)} or C{expr*(n,)} is equivalent
+ to C{expr*n + ZeroOrMore(expr)}
+ (read as "at least n instances of C{expr}")
+ - C{expr*(None,n)} is equivalent to C{expr*(0,n)}
+ (read as "0 to n instances of C{expr}")
+ - C{expr*(None,None)} is equivalent to C{ZeroOrMore(expr)}
+ - C{expr*(1,None)} is equivalent to C{OneOrMore(expr)}
+
+ Note that C{expr*(None,n)} does not raise an exception if
+ more than n exprs exist in the input stream; that is,
+ C{expr*(None,n)} does not enforce a maximum number of expr
+ occurrences. If this behavior is desired, then write
+ C{expr*(None,n) + ~expr}
+
+ """
+ if isinstance(other,int):
+ minElements, optElements = other,0
+ elif isinstance(other,tuple):
+ other = (other + (None, None))[:2]
+ if other[0] is None:
+ other = (0, other[1])
+ if isinstance(other[0],int) and other[1] is None:
+ if other[0] == 0:
+ return ZeroOrMore(self)
+ if other[0] == 1:
+ return OneOrMore(self)
+ else:
+ return self*other[0] + ZeroOrMore(self)
+ elif isinstance(other[0],int) and isinstance(other[1],int):
+ minElements, optElements = other
+ optElements -= minElements
+ else:
+ raise TypeError("cannot multiply 'ParserElement' and ('%s','%s') objects", type(other[0]),type(other[1]))
+ else:
+ raise TypeError("cannot multiply 'ParserElement' and '%s' objects", type(other))
+
+ if minElements < 0:
+ raise ValueError("cannot multiply ParserElement by negative value")
+ if optElements < 0:
+ raise ValueError("second tuple value must be greater or equal to first tuple value")
+ if minElements == optElements == 0:
+ raise ValueError("cannot multiply ParserElement by 0 or (0,0)")
+
+ if (optElements):
+ def makeOptionalList(n):
+ if n>1:
+ return Optional(self + makeOptionalList(n-1))
+ else:
+ return Optional(self)
+ if minElements:
+ if minElements == 1:
+ ret = self + makeOptionalList(optElements)
+ else:
+ ret = And([self]*minElements) + makeOptionalList(optElements)
+ else:
+ ret = makeOptionalList(optElements)
+ else:
+ if minElements == 1:
+ ret = self
+ else:
+ ret = And([self]*minElements)
+ return ret
+
+ def __rmul__(self, other):
+ return self.__mul__(other)
+
+ def __or__(self, other ):
+ """Implementation of | operator - returns C{MatchFirst}"""
+ if isinstance( other, basestring ):
+ other = Literal( other )
+ if not isinstance( other, ParserElement ):
+ warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
+ SyntaxWarning, stacklevel=2)
+ return None
+ return MatchFirst( [ self, other ] )
+
+ def __ror__(self, other ):
+ """Implementation of | operator when left operand is not a C{ParserElement}"""
+ if isinstance( other, basestring ):
+ other = Literal( other )
+ if not isinstance( other, ParserElement ):
+ warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
+ SyntaxWarning, stacklevel=2)
+ return None
+ return other | self
+
+ def __xor__(self, other ):
+ """Implementation of ^ operator - returns C{Or}"""
+ if isinstance( other, basestring ):
+ other = Literal( other )
+ if not isinstance( other, ParserElement ):
+ warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
+ SyntaxWarning, stacklevel=2)
+ return None
+ return Or( [ self, other ] )
+
+ def __rxor__(self, other ):
+ """Implementation of ^ operator when left operand is not a C{ParserElement}"""
+ if isinstance( other, basestring ):
+ other = Literal( other )
+ if not isinstance( other, ParserElement ):
+ warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
+ SyntaxWarning, stacklevel=2)
+ return None
+ return other ^ self
+
+ def __and__(self, other ):
+ """Implementation of & operator - returns C{Each}"""
+ if isinstance( other, basestring ):
+ other = Literal( other )
+ if not isinstance( other, ParserElement ):
+ warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
+ SyntaxWarning, stacklevel=2)
+ return None
+ return Each( [ self, other ] )
+
+ def __rand__(self, other ):
+ """Implementation of & operator when left operand is not a C{ParserElement}"""
+ if isinstance( other, basestring ):
+ other = Literal( other )
+ if not isinstance( other, ParserElement ):
+ warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
+ SyntaxWarning, stacklevel=2)
+ return None
+ return other & self
+
+ def __invert__( self ):
+ """Implementation of ~ operator - returns C{NotAny}"""
+ return NotAny( self )
+
+ def __call__(self, name):
+ """Shortcut for C{setResultsName}, with C{listAllMatches=default}::
+ userdata = Word(alphas).setResultsName("name") + Word(nums+"-").setResultsName("socsecno")
+ could be written as::
+ userdata = Word(alphas)("name") + Word(nums+"-")("socsecno")
+
+ If C{name} is given with a trailing C{'*'} character, then C{listAllMatches} will be
+ passed as C{True}.
+ """
+ return self.setResultsName(name)
+
+ def suppress( self ):
+ """Suppresses the output of this C{ParserElement}; useful to keep punctuation from
+ cluttering up returned output.
+ """
+ return Suppress( self )
+
+ def leaveWhitespace( self ):
+ """Disables the skipping of whitespace before matching the characters in the
+ C{ParserElement}'s defined pattern. This is normally only used internally by
+ the pyparsing module, but may be needed in some whitespace-sensitive grammars.
+ """
+ self.skipWhitespace = False
+ return self
+
+ def setWhitespaceChars( self, chars ):
+ """Overrides the default whitespace chars
+ """
+ self.skipWhitespace = True
+ self.whiteChars = chars
+ self.copyDefaultWhiteChars = False
+ return self
+
+ def parseWithTabs( self ):
+ """Overrides default behavior to expand C{}s to spaces before parsing the input string.
+ Must be called before C{parseString} when the input grammar contains elements that
+ match C{} characters."""
+ self.keepTabs = True
+ return self
+
+ def ignore( self, other ):
+ """Define expression to be ignored (e.g., comments) while doing pattern
+ matching; may be called repeatedly, to define multiple comment or other
+ ignorable patterns.
+ """
+ if isinstance( other, Suppress ):
+ if other not in self.ignoreExprs:
+ self.ignoreExprs.append( other.copy() )
+ else:
+ self.ignoreExprs.append( Suppress( other.copy() ) )
+ return self
+
+ def setDebugActions( self, startAction, successAction, exceptionAction ):
+ """Enable display of debugging messages while doing pattern matching."""
+ self.debugActions = (startAction or _defaultStartDebugAction,
+ successAction or _defaultSuccessDebugAction,
+ exceptionAction or _defaultExceptionDebugAction)
+ self.debug = True
+ return self
+
+ def setDebug( self, flag=True ):
+ """Enable display of debugging messages while doing pattern matching.
+ Set C{flag} to True to enable, False to disable."""
+ if flag:
+ self.setDebugActions( _defaultStartDebugAction, _defaultSuccessDebugAction, _defaultExceptionDebugAction )
+ else:
+ self.debug = False
+ return self
+
+ def __str__( self ):
+ return self.name
+
+ def __repr__( self ):
+ return _ustr(self)
+
+ def streamline( self ):
+ self.streamlined = True
+ self.strRepr = None
+ return self
+
+ def checkRecursion( self, parseElementList ):
+ pass
+
+ def validate( self, validateTrace=[] ):
+ """Check defined expressions for valid structure, check for infinite recursive definitions."""
+ self.checkRecursion( [] )
+
+ def parseFile( self, file_or_filename, parseAll=False ):
+ """Execute the parse expression on the given file or filename.
+ If a filename is specified (instead of a file object),
+ the entire file is opened, read, and closed before parsing.
+ """
+ try:
+ file_contents = file_or_filename.read()
+ except AttributeError:
+ f = open(file_or_filename, "rb")
+ file_contents = f.read()
+ f.close()
+ try:
+ return self.parseString(file_contents, parseAll)
+ except ParseBaseException:
+ # catch and re-raise exception from here, clears out pyparsing internal stack trace
+ exc = sys.exc_info()[1]
+ raise exc
+
+ def getException(self):
+ return ParseException("",0,self.errmsg,self)
+
+ def __getattr__(self,aname):
+ if aname == "myException":
+ self.myException = ret = self.getException();
+ return ret;
+ else:
+ raise AttributeError("no such attribute " + aname)
+
+ def __eq__(self,other):
+ if isinstance(other, ParserElement):
+ return self is other or self.__dict__ == other.__dict__
+ elif isinstance(other, basestring):
+ try:
+ self.parseString(_ustr(other), parseAll=True)
+ return True
+ except ParseBaseException:
+ return False
+ else:
+ return super(ParserElement,self)==other
+
+ def __ne__(self,other):
+ return not (self == other)
+
+ def __hash__(self):
+ return hash(id(self))
+
+ def __req__(self,other):
+ return self == other
+
+ def __rne__(self,other):
+ return not (self == other)
+
+
+class Token(ParserElement):
+ """Abstract C{ParserElement} subclass, for defining atomic matching patterns."""
+ def __init__( self ):
+ super(Token,self).__init__( savelist=False )
+
+ def setName(self, name):
+ s = super(Token,self).setName(name)
+ self.errmsg = "Expected " + self.name
+ return s
+
+
+class Empty(Token):
+ """An empty token, will always match."""
+ def __init__( self ):
+ super(Empty,self).__init__()
+ self.name = "Empty"
+ self.mayReturnEmpty = True
+ self.mayIndexError = False
+
+
+class NoMatch(Token):
+ """A token that will never match."""
+ def __init__( self ):
+ super(NoMatch,self).__init__()
+ self.name = "NoMatch"
+ self.mayReturnEmpty = True
+ self.mayIndexError = False
+ self.errmsg = "Unmatchable token"
+
+ def parseImpl( self, instring, loc, doActions=True ):
+ exc = self.myException
+ exc.loc = loc
+ exc.pstr = instring
+ raise exc
+
+
+class Literal(Token):
+ """Token to exactly match a specified string."""
+ def __init__( self, matchString ):
+ super(Literal,self).__init__()
+ self.match = matchString
+ self.matchLen = len(matchString)
+ try:
+ self.firstMatchChar = matchString[0]
+ except IndexError:
+ warnings.warn("null string passed to Literal; use Empty() instead",
+ SyntaxWarning, stacklevel=2)
+ self.__class__ = Empty
+ self.name = '"%s"' % _ustr(self.match)
+ self.errmsg = "Expected " + self.name
+ self.mayReturnEmpty = False
+ self.mayIndexError = False
+
+ # Performance tuning: this routine gets called a *lot*
+ # if this is a single character match string and the first character matches,
+ # short-circuit as quickly as possible, and avoid calling startswith
+ #~ @profile
+ def parseImpl( self, instring, loc, doActions=True ):
+ if (instring[loc] == self.firstMatchChar and
+ (self.matchLen==1 or instring.startswith(self.match,loc)) ):
+ return loc+self.matchLen, self.match
+ #~ raise ParseException( instring, loc, self.errmsg )
+ exc = self.myException
+ exc.loc = loc
+ exc.pstr = instring
+ raise exc
+_L = Literal
+
+class Keyword(Token):
+ """Token to exactly match a specified string as a keyword, that is, it must be
+ immediately followed by a non-keyword character. Compare with C{Literal}::
+ Literal("if") will match the leading C{'if'} in C{'ifAndOnlyIf'}.
+ Keyword("if") will not; it will only match the leading C{'if'} in C{'if x=1'}, or C{'if(y==2)'}
+ Accepts two optional constructor arguments in addition to the keyword string:
+ C{identChars} is a string of characters that would be valid identifier characters,
+ defaulting to all alphanumerics + "_" and "$"; C{caseless} allows case-insensitive
+ matching, default is C{False}.
+ """
+ DEFAULT_KEYWORD_CHARS = alphanums+"_$"
+
+ def __init__( self, matchString, identChars=DEFAULT_KEYWORD_CHARS, caseless=False ):
+ super(Keyword,self).__init__()
+ self.match = matchString
+ self.matchLen = len(matchString)
+ try:
+ self.firstMatchChar = matchString[0]
+ except IndexError:
+ warnings.warn("null string passed to Keyword; use Empty() instead",
+ SyntaxWarning, stacklevel=2)
+ self.name = '"%s"' % self.match
+ self.errmsg = "Expected " + self.name
+ self.mayReturnEmpty = False
+ self.mayIndexError = False
+ self.caseless = caseless
+ if caseless:
+ self.caselessmatch = matchString.upper()
+ identChars = identChars.upper()
+ self.identChars = set(identChars)
+
+ def parseImpl( self, instring, loc, doActions=True ):
+ if self.caseless:
+ if ( (instring[ loc:loc+self.matchLen ].upper() == self.caselessmatch) and
+ (loc >= len(instring)-self.matchLen or instring[loc+self.matchLen].upper() not in self.identChars) and
+ (loc == 0 or instring[loc-1].upper() not in self.identChars) ):
+ return loc+self.matchLen, self.match
+ else:
+ if (instring[loc] == self.firstMatchChar and
+ (self.matchLen==1 or instring.startswith(self.match,loc)) and
+ (loc >= len(instring)-self.matchLen or instring[loc+self.matchLen] not in self.identChars) and
+ (loc == 0 or instring[loc-1] not in self.identChars) ):
+ return loc+self.matchLen, self.match
+ #~ raise ParseException( instring, loc, self.errmsg )
+ exc = self.myException
+ exc.loc = loc
+ exc.pstr = instring
+ raise exc
+
+ def copy(self):
+ c = super(Keyword,self).copy()
+ c.identChars = Keyword.DEFAULT_KEYWORD_CHARS
+ return c
+
+ def setDefaultKeywordChars( chars ):
+ """Overrides the default Keyword chars
+ """
+ Keyword.DEFAULT_KEYWORD_CHARS = chars
+ setDefaultKeywordChars = staticmethod(setDefaultKeywordChars)
+
+class CaselessLiteral(Literal):
+ """Token to match a specified string, ignoring case of letters.
+ Note: the matched results will always be in the case of the given
+ match string, NOT the case of the input text.
+ """
+ def __init__( self, matchString ):
+ super(CaselessLiteral,self).__init__( matchString.upper() )
+ # Preserve the defining literal.
+ self.returnString = matchString
+ self.name = "'%s'" % self.returnString
+ self.errmsg = "Expected " + self.name
+
+ def parseImpl( self, instring, loc, doActions=True ):
+ if instring[ loc:loc+self.matchLen ].upper() == self.match:
+ return loc+self.matchLen, self.returnString
+ #~ raise ParseException( instring, loc, self.errmsg )
+ exc = self.myException
+ exc.loc = loc
+ exc.pstr = instring
+ raise exc
+
+class CaselessKeyword(Keyword):
+ def __init__( self, matchString, identChars=Keyword.DEFAULT_KEYWORD_CHARS ):
+ super(CaselessKeyword,self).__init__( matchString, identChars, caseless=True )
+
+ def parseImpl( self, instring, loc, doActions=True ):
+ if ( (instring[ loc:loc+self.matchLen ].upper() == self.caselessmatch) and
+ (loc >= len(instring)-self.matchLen or instring[loc+self.matchLen].upper() not in self.identChars) ):
+ return loc+self.matchLen, self.match
+ #~ raise ParseException( instring, loc, self.errmsg )
+ exc = self.myException
+ exc.loc = loc
+ exc.pstr = instring
+ raise exc
+
+class Word(Token):
+ """Token for matching words composed of allowed character sets.
+ Defined with string containing all allowed initial characters,
+ an optional string containing allowed body characters (if omitted,
+ defaults to the initial character set), and an optional minimum,
+ maximum, and/or exact length. The default value for C{min} is 1 (a
+ minimum value < 1 is not valid); the default values for C{max} and C{exact}
+ are 0, meaning no maximum or exact length restriction. An optional
+ C{exclude} parameter can list characters that might be found in
+ the input C{bodyChars} string; useful to define a word of all printables
+ except for one or two characters, for instance.
+ """
+ def __init__( self, initChars, bodyChars=None, min=1, max=0, exact=0, asKeyword=False, excludeChars=None ):
+ super(Word,self).__init__()
+ if excludeChars:
+ initChars = ''.join([c for c in initChars if c not in excludeChars])
+ if bodyChars:
+ bodyChars = ''.join([c for c in bodyChars if c not in excludeChars])
+ self.initCharsOrig = initChars
+ self.initChars = set(initChars)
+ if bodyChars :
+ self.bodyCharsOrig = bodyChars
+ self.bodyChars = set(bodyChars)
+ else:
+ self.bodyCharsOrig = initChars
+ self.bodyChars = set(initChars)
+
+ self.maxSpecified = max > 0
+
+ if min < 1:
+ raise ValueError("cannot specify a minimum length < 1; use Optional(Word()) if zero-length word is permitted")
+
+ self.minLen = min
+
+ if max > 0:
+ self.maxLen = max
+ else:
+ self.maxLen = _MAX_INT
+
+ if exact > 0:
+ self.maxLen = exact
+ self.minLen = exact
+
+ self.name = _ustr(self)
+ self.errmsg = "Expected " + self.name
+ self.mayIndexError = False
+ self.asKeyword = asKeyword
+
+ if ' ' not in self.initCharsOrig+self.bodyCharsOrig and (min==1 and max==0 and exact==0):
+ if self.bodyCharsOrig == self.initCharsOrig:
+ self.reString = "[%s]+" % _escapeRegexRangeChars(self.initCharsOrig)
+ elif len(self.bodyCharsOrig) == 1:
+ self.reString = "%s[%s]*" % \
+ (re.escape(self.initCharsOrig),
+ _escapeRegexRangeChars(self.bodyCharsOrig),)
+ else:
+ self.reString = "[%s][%s]*" % \
+ (_escapeRegexRangeChars(self.initCharsOrig),
+ _escapeRegexRangeChars(self.bodyCharsOrig),)
+ if self.asKeyword:
+ self.reString = r"\b"+self.reString+r"\b"
+ try:
+ self.re = re.compile( self.reString )
+ except:
+ self.re = None
+
+ def parseImpl( self, instring, loc, doActions=True ):
+ if self.re:
+ result = self.re.match(instring,loc)
+ if not result:
+ exc = self.myException
+ exc.loc = loc
+ exc.pstr = instring
+ raise exc
+
+ loc = result.end()
+ return loc, result.group()
+
+ if not(instring[ loc ] in self.initChars):
+ #~ raise ParseException( instring, loc, self.errmsg )
+ exc = self.myException
+ exc.loc = loc
+ exc.pstr = instring
+ raise exc
+ start = loc
+ loc += 1
+ instrlen = len(instring)
+ bodychars = self.bodyChars
+ maxloc = start + self.maxLen
+ maxloc = min( maxloc, instrlen )
+ while loc < maxloc and instring[loc] in bodychars:
+ loc += 1
+
+ throwException = False
+ if loc - start < self.minLen:
+ throwException = True
+ if self.maxSpecified and loc < instrlen and instring[loc] in bodychars:
+ throwException = True
+ if self.asKeyword:
+ if (start>0 and instring[start-1] in bodychars) or (loc4:
+ return s[:4]+"..."
+ else:
+ return s
+
+ if ( self.initCharsOrig != self.bodyCharsOrig ):
+ self.strRepr = "W:(%s,%s)" % ( charsAsStr(self.initCharsOrig), charsAsStr(self.bodyCharsOrig) )
+ else:
+ self.strRepr = "W:(%s)" % charsAsStr(self.initCharsOrig)
+
+ return self.strRepr
+
+
+class Regex(Token):
+ """Token for matching strings that match a given regular expression.
+ Defined with string specifying the regular expression in a form recognized by the inbuilt Python re module.
+ """
+ compiledREtype = type(re.compile("[A-Z]"))
+ def __init__( self, pattern, flags=0):
+ """The parameters C{pattern} and C{flags} are passed to the C{re.compile()} function as-is. See the Python C{re} module for an explanation of the acceptable patterns and flags."""
+ super(Regex,self).__init__()
+
+ if isinstance(pattern, basestring):
+ if len(pattern) == 0:
+ warnings.warn("null string passed to Regex; use Empty() instead",
+ SyntaxWarning, stacklevel=2)
+
+ self.pattern = pattern
+ self.flags = flags
+
+ try:
+ self.re = re.compile(self.pattern, self.flags)
+ self.reString = self.pattern
+ except sre_constants.error:
+ warnings.warn("invalid pattern (%s) passed to Regex" % pattern,
+ SyntaxWarning, stacklevel=2)
+ raise
+
+ elif isinstance(pattern, Regex.compiledREtype):
+ self.re = pattern
+ self.pattern = \
+ self.reString = str(pattern)
+ self.flags = flags
+
+ else:
+ raise ValueError("Regex may only be constructed with a string or a compiled RE object")
+
+ self.name = _ustr(self)
+ self.errmsg = "Expected " + self.name
+ self.mayIndexError = False
+ self.mayReturnEmpty = True
+
+ def parseImpl( self, instring, loc, doActions=True ):
+ result = self.re.match(instring,loc)
+ if not result:
+ exc = self.myException
+ exc.loc = loc
+ exc.pstr = instring
+ raise exc
+
+ loc = result.end()
+ d = result.groupdict()
+ ret = ParseResults(result.group())
+ if d:
+ for k in d:
+ ret[k] = d[k]
+ return loc,ret
+
+ def __str__( self ):
+ try:
+ return super(Regex,self).__str__()
+ except:
+ pass
+
+ if self.strRepr is None:
+ self.strRepr = "Re:(%s)" % repr(self.pattern)
+
+ return self.strRepr
+
+
+class QuotedString(Token):
+ """Token for matching strings that are delimited by quoting characters.
+ """
+ def __init__( self, quoteChar, escChar=None, escQuote=None, multiline=False, unquoteResults=True, endQuoteChar=None):
+ """
+ Defined with the following parameters:
+ - quoteChar - string of one or more characters defining the quote delimiting string
+ - escChar - character to escape quotes, typically backslash (default=None)
+ - escQuote - special quote sequence to escape an embedded quote string (such as SQL's "" to escape an embedded ") (default=None)
+ - multiline - boolean indicating whether quotes can span multiple lines (default=False)
+ - unquoteResults - boolean indicating whether the matched text should be unquoted (default=True)
+ - endQuoteChar - string of one or more characters defining the end of the quote delimited string (default=None => same as quoteChar)
+ """
+ super(QuotedString,self).__init__()
+
+ # remove white space from quote chars - wont work anyway
+ quoteChar = quoteChar.strip()
+ if len(quoteChar) == 0:
+ warnings.warn("quoteChar cannot be the empty string",SyntaxWarning,stacklevel=2)
+ raise SyntaxError()
+
+ if endQuoteChar is None:
+ endQuoteChar = quoteChar
+ else:
+ endQuoteChar = endQuoteChar.strip()
+ if len(endQuoteChar) == 0:
+ warnings.warn("endQuoteChar cannot be the empty string",SyntaxWarning,stacklevel=2)
+ raise SyntaxError()
+
+ self.quoteChar = quoteChar
+ self.quoteCharLen = len(quoteChar)
+ self.firstQuoteChar = quoteChar[0]
+ self.endQuoteChar = endQuoteChar
+ self.endQuoteCharLen = len(endQuoteChar)
+ self.escChar = escChar
+ self.escQuote = escQuote
+ self.unquoteResults = unquoteResults
+
+ if multiline:
+ self.flags = re.MULTILINE | re.DOTALL
+ self.pattern = r'%s(?:[^%s%s]' % \
+ ( re.escape(self.quoteChar),
+ _escapeRegexRangeChars(self.endQuoteChar[0]),
+ (escChar is not None and _escapeRegexRangeChars(escChar) or '') )
+ else:
+ self.flags = 0
+ self.pattern = r'%s(?:[^%s\n\r%s]' % \
+ ( re.escape(self.quoteChar),
+ _escapeRegexRangeChars(self.endQuoteChar[0]),
+ (escChar is not None and _escapeRegexRangeChars(escChar) or '') )
+ if len(self.endQuoteChar) > 1:
+ self.pattern += (
+ '|(?:' + ')|(?:'.join(["%s[^%s]" % (re.escape(self.endQuoteChar[:i]),
+ _escapeRegexRangeChars(self.endQuoteChar[i]))
+ for i in range(len(self.endQuoteChar)-1,0,-1)]) + ')'
+ )
+ if escQuote:
+ self.pattern += (r'|(?:%s)' % re.escape(escQuote))
+ if escChar:
+ self.pattern += (r'|(?:%s.)' % re.escape(escChar))
+ charset = ''.join(set(self.quoteChar[0]+self.endQuoteChar[0])).replace('^',r'\^').replace('-',r'\-')
+ self.escCharReplacePattern = re.escape(self.escChar)+("([%s])" % charset)
+ self.pattern += (r')*%s' % re.escape(self.endQuoteChar))
+
+ try:
+ self.re = re.compile(self.pattern, self.flags)
+ self.reString = self.pattern
+ except sre_constants.error:
+ warnings.warn("invalid pattern (%s) passed to Regex" % self.pattern,
+ SyntaxWarning, stacklevel=2)
+ raise
+
+ self.name = _ustr(self)
+ self.errmsg = "Expected " + self.name
+ self.mayIndexError = False
+ self.mayReturnEmpty = True
+
+ def parseImpl( self, instring, loc, doActions=True ):
+ result = instring[loc] == self.firstQuoteChar and self.re.match(instring,loc) or None
+ if not result:
+ exc = self.myException
+ exc.loc = loc
+ exc.pstr = instring
+ raise exc
+
+ loc = result.end()
+ ret = result.group()
+
+ if self.unquoteResults:
+
+ # strip off quotes
+ ret = ret[self.quoteCharLen:-self.endQuoteCharLen]
+
+ if isinstance(ret,basestring):
+ # replace escaped characters
+ if self.escChar:
+ ret = re.sub(self.escCharReplacePattern,"\g<1>",ret)
+
+ # replace escaped quotes
+ if self.escQuote:
+ ret = ret.replace(self.escQuote, self.endQuoteChar)
+
+ return loc, ret
+
+ def __str__( self ):
+ try:
+ return super(QuotedString,self).__str__()
+ except:
+ pass
+
+ if self.strRepr is None:
+ self.strRepr = "quoted string, starting with %s ending with %s" % (self.quoteChar, self.endQuoteChar)
+
+ return self.strRepr
+
+
+class CharsNotIn(Token):
+ """Token for matching words composed of characters *not* in a given set.
+ Defined with string containing all disallowed characters, and an optional
+ minimum, maximum, and/or exact length. The default value for C{min} is 1 (a
+ minimum value < 1 is not valid); the default values for C{max} and C{exact}
+ are 0, meaning no maximum or exact length restriction.
+ """
+ def __init__( self, notChars, min=1, max=0, exact=0 ):
+ super(CharsNotIn,self).__init__()
+ self.skipWhitespace = False
+ self.notChars = notChars
+
+ if min < 1:
+ raise ValueError("cannot specify a minimum length < 1; use Optional(CharsNotIn()) if zero-length char group is permitted")
+
+ self.minLen = min
+
+ if max > 0:
+ self.maxLen = max
+ else:
+ self.maxLen = _MAX_INT
+
+ if exact > 0:
+ self.maxLen = exact
+ self.minLen = exact
+
+ self.name = _ustr(self)
+ self.errmsg = "Expected " + self.name
+ self.mayReturnEmpty = ( self.minLen == 0 )
+ self.mayIndexError = False
+
+ def parseImpl( self, instring, loc, doActions=True ):
+ if instring[loc] in self.notChars:
+ #~ raise ParseException( instring, loc, self.errmsg )
+ exc = self.myException
+ exc.loc = loc
+ exc.pstr = instring
+ raise exc
+
+ start = loc
+ loc += 1
+ notchars = self.notChars
+ maxlen = min( start+self.maxLen, len(instring) )
+ while loc < maxlen and \
+ (instring[loc] not in notchars):
+ loc += 1
+
+ if loc - start < self.minLen:
+ #~ raise ParseException( instring, loc, self.errmsg )
+ exc = self.myException
+ exc.loc = loc
+ exc.pstr = instring
+ raise exc
+
+ return loc, instring[start:loc]
+
+ def __str__( self ):
+ try:
+ return super(CharsNotIn, self).__str__()
+ except:
+ pass
+
+ if self.strRepr is None:
+ if len(self.notChars) > 4:
+ self.strRepr = "!W:(%s...)" % self.notChars[:4]
+ else:
+ self.strRepr = "!W:(%s)" % self.notChars
+
+ return self.strRepr
+
+class White(Token):
+ """Special matching class for matching whitespace. Normally, whitespace is ignored
+ by pyparsing grammars. This class is included when some whitespace structures
+ are significant. Define with a string containing the whitespace characters to be
+ matched; default is C{" \\t\\r\\n"}. Also takes optional C{min}, C{max}, and C{exact} arguments,
+ as defined for the C{Word} class."""
+ whiteStrs = {
+ " " : "",
+ "\t": "",
+ "\n": "",
+ "\r": "",
+ "\f": "",
+ }
+ def __init__(self, ws=" \t\r\n", min=1, max=0, exact=0):
+ super(White,self).__init__()
+ self.matchWhite = ws
+ self.setWhitespaceChars( "".join([c for c in self.whiteChars if c not in self.matchWhite]) )
+ #~ self.leaveWhitespace()
+ self.name = ("".join([White.whiteStrs[c] for c in self.matchWhite]))
+ self.mayReturnEmpty = True
+ self.errmsg = "Expected " + self.name
+
+ self.minLen = min
+
+ if max > 0:
+ self.maxLen = max
+ else:
+ self.maxLen = _MAX_INT
+
+ if exact > 0:
+ self.maxLen = exact
+ self.minLen = exact
+
+ def parseImpl( self, instring, loc, doActions=True ):
+ if not(instring[ loc ] in self.matchWhite):
+ #~ raise ParseException( instring, loc, self.errmsg )
+ exc = self.myException
+ exc.loc = loc
+ exc.pstr = instring
+ raise exc
+ start = loc
+ loc += 1
+ maxloc = start + self.maxLen
+ maxloc = min( maxloc, len(instring) )
+ while loc < maxloc and instring[loc] in self.matchWhite:
+ loc += 1
+
+ if loc - start < self.minLen:
+ #~ raise ParseException( instring, loc, self.errmsg )
+ exc = self.myException
+ exc.loc = loc
+ exc.pstr = instring
+ raise exc
+
+ return loc, instring[start:loc]
+
+
+class _PositionToken(Token):
+ def __init__( self ):
+ super(_PositionToken,self).__init__()
+ self.name=self.__class__.__name__
+ self.mayReturnEmpty = True
+ self.mayIndexError = False
+
+class GoToColumn(_PositionToken):
+ """Token to advance to a specific column of input text; useful for tabular report scraping."""
+ def __init__( self, colno ):
+ super(GoToColumn,self).__init__()
+ self.col = colno
+
+ def preParse( self, instring, loc ):
+ if col(loc,instring) != self.col:
+ instrlen = len(instring)
+ if self.ignoreExprs:
+ loc = self._skipIgnorables( instring, loc )
+ while loc < instrlen and instring[loc].isspace() and col( loc, instring ) != self.col :
+ loc += 1
+ return loc
+
+ def parseImpl( self, instring, loc, doActions=True ):
+ thiscol = col( loc, instring )
+ if thiscol > self.col:
+ raise ParseException( instring, loc, "Text not in expected column", self )
+ newloc = loc + self.col - thiscol
+ ret = instring[ loc: newloc ]
+ return newloc, ret
+
+class LineStart(_PositionToken):
+ """Matches if current position is at the beginning of a line within the parse string"""
+ def __init__( self ):
+ super(LineStart,self).__init__()
+ self.setWhitespaceChars( ParserElement.DEFAULT_WHITE_CHARS.replace("\n","") )
+ self.errmsg = "Expected start of line"
+
+ def preParse( self, instring, loc ):
+ preloc = super(LineStart,self).preParse(instring,loc)
+ if instring[preloc] == "\n":
+ loc += 1
+ return loc
+
+ def parseImpl( self, instring, loc, doActions=True ):
+ if not( loc==0 or
+ (loc == self.preParse( instring, 0 )) or
+ (instring[loc-1] == "\n") ): #col(loc, instring) != 1:
+ #~ raise ParseException( instring, loc, "Expected start of line" )
+ exc = self.myException
+ exc.loc = loc
+ exc.pstr = instring
+ raise exc
+ return loc, []
+
+class LineEnd(_PositionToken):
+ """Matches if current position is at the end of a line within the parse string"""
+ def __init__( self ):
+ super(LineEnd,self).__init__()
+ self.setWhitespaceChars( ParserElement.DEFAULT_WHITE_CHARS.replace("\n","") )
+ self.errmsg = "Expected end of line"
+
+ def parseImpl( self, instring, loc, doActions=True ):
+ if loc len(instring):
+ return loc, []
+ else:
+ exc = self.myException
+ exc.loc = loc
+ exc.pstr = instring
+ raise exc
+
+class WordStart(_PositionToken):
+ """Matches if the current position is at the beginning of a Word, and
+ is not preceded by any character in a given set of C{wordChars}
+ (default=C{printables}). To emulate the C{\b} behavior of regular expressions,
+ use C{WordStart(alphanums)}. C{WordStart} will also match at the beginning of
+ the string being parsed, or at the beginning of a line.
+ """
+ def __init__(self, wordChars = printables):
+ super(WordStart,self).__init__()
+ self.wordChars = set(wordChars)
+ self.errmsg = "Not at the start of a word"
+
+ def parseImpl(self, instring, loc, doActions=True ):
+ if loc != 0:
+ if (instring[loc-1] in self.wordChars or
+ instring[loc] not in self.wordChars):
+ exc = self.myException
+ exc.loc = loc
+ exc.pstr = instring
+ raise exc
+ return loc, []
+
+class WordEnd(_PositionToken):
+ """Matches if the current position is at the end of a Word, and
+ is not followed by any character in a given set of C{wordChars}
+ (default=C{printables}). To emulate the C{\b} behavior of regular expressions,
+ use C{WordEnd(alphanums)}. C{WordEnd} will also match at the end of
+ the string being parsed, or at the end of a line.
+ """
+ def __init__(self, wordChars = printables):
+ super(WordEnd,self).__init__()
+ self.wordChars = set(wordChars)
+ self.skipWhitespace = False
+ self.errmsg = "Not at the end of a word"
+
+ def parseImpl(self, instring, loc, doActions=True ):
+ instrlen = len(instring)
+ if instrlen>0 and loc maxExcLoc:
+ maxException = err
+ maxExcLoc = err.loc
+ except IndexError:
+ if len(instring) > maxExcLoc:
+ maxException = ParseException(instring,len(instring),e.errmsg,self)
+ maxExcLoc = len(instring)
+ else:
+ if loc2 > maxMatchLoc:
+ maxMatchLoc = loc2
+ maxMatchExp = e
+
+ if maxMatchLoc < 0:
+ if maxException is not None:
+ raise maxException
+ else:
+ raise ParseException(instring, loc, "no defined alternatives to match", self)
+
+ return maxMatchExp._parse( instring, loc, doActions )
+
+ def __ixor__(self, other ):
+ if isinstance( other, basestring ):
+ other = Literal( other )
+ return self.append( other ) #Or( [ self, other ] )
+
+ def __str__( self ):
+ if hasattr(self,"name"):
+ return self.name
+
+ if self.strRepr is None:
+ self.strRepr = "{" + " ^ ".join( [ _ustr(e) for e in self.exprs ] ) + "}"
+
+ return self.strRepr
+
+ def checkRecursion( self, parseElementList ):
+ subRecCheckList = parseElementList[:] + [ self ]
+ for e in self.exprs:
+ e.checkRecursion( subRecCheckList )
+
+
+class MatchFirst(ParseExpression):
+ """Requires that at least one C{ParseExpression} is found.
+ If two expressions match, the first one listed is the one that will match.
+ May be constructed using the C{'|'} operator.
+ """
+ def __init__( self, exprs, savelist = False ):
+ super(MatchFirst,self).__init__(exprs, savelist)
+ if exprs:
+ self.mayReturnEmpty = False
+ for e in self.exprs:
+ if e.mayReturnEmpty:
+ self.mayReturnEmpty = True
+ break
+ else:
+ self.mayReturnEmpty = True
+
+ def parseImpl( self, instring, loc, doActions=True ):
+ maxExcLoc = -1
+ maxException = None
+ for e in self.exprs:
+ try:
+ ret = e._parse( instring, loc, doActions )
+ return ret
+ except ParseException, err:
+ if err.loc > maxExcLoc:
+ maxException = err
+ maxExcLoc = err.loc
+ except IndexError:
+ if len(instring) > maxExcLoc:
+ maxException = ParseException(instring,len(instring),e.errmsg,self)
+ maxExcLoc = len(instring)
+
+ # only got here if no expression matched, raise exception for match that made it the furthest
+ else:
+ if maxException is not None:
+ raise maxException
+ else:
+ raise ParseException(instring, loc, "no defined alternatives to match", self)
+
+ def __ior__(self, other ):
+ if isinstance( other, basestring ):
+ other = Literal( other )
+ return self.append( other ) #MatchFirst( [ self, other ] )
+
+ def __str__( self ):
+ if hasattr(self,"name"):
+ return self.name
+
+ if self.strRepr is None:
+ self.strRepr = "{" + " | ".join( [ _ustr(e) for e in self.exprs ] ) + "}"
+
+ return self.strRepr
+
+ def checkRecursion( self, parseElementList ):
+ subRecCheckList = parseElementList[:] + [ self ]
+ for e in self.exprs:
+ e.checkRecursion( subRecCheckList )
+
+
+class Each(ParseExpression):
+ """Requires all given C{ParseExpression}s to be found, but in any order.
+ Expressions may be separated by whitespace.
+ May be constructed using the C{'&'} operator.
+ """
+ def __init__( self, exprs, savelist = True ):
+ super(Each,self).__init__(exprs, savelist)
+ self.mayReturnEmpty = True
+ for e in self.exprs:
+ if not e.mayReturnEmpty:
+ self.mayReturnEmpty = False
+ break
+ self.skipWhitespace = True
+ self.initExprGroups = True
+
+ def parseImpl( self, instring, loc, doActions=True ):
+ if self.initExprGroups:
+ opt1 = [ e.expr for e in self.exprs if isinstance(e,Optional) ]
+ opt2 = [ e for e in self.exprs if e.mayReturnEmpty and e not in opt1 ]
+ self.optionals = opt1 + opt2
+ self.multioptionals = [ e.expr for e in self.exprs if isinstance(e,ZeroOrMore) ]
+ self.multirequired = [ e.expr for e in self.exprs if isinstance(e,OneOrMore) ]
+ self.required = [ e for e in self.exprs if not isinstance(e,(Optional,ZeroOrMore,OneOrMore)) ]
+ self.required += self.multirequired
+ self.initExprGroups = False
+ tmpLoc = loc
+ tmpReqd = self.required[:]
+ tmpOpt = self.optionals[:]
+ matchOrder = []
+
+ keepMatching = True
+ while keepMatching:
+ tmpExprs = tmpReqd + tmpOpt + self.multioptionals + self.multirequired
+ failed = []
+ for e in tmpExprs:
+ try:
+ tmpLoc = e.tryParse( instring, tmpLoc )
+ except ParseException:
+ failed.append(e)
+ else:
+ matchOrder.append(e)
+ if e in tmpReqd:
+ tmpReqd.remove(e)
+ elif e in tmpOpt:
+ tmpOpt.remove(e)
+ if len(failed) == len(tmpExprs):
+ keepMatching = False
+
+ if tmpReqd:
+ missing = ", ".join( [ _ustr(e) for e in tmpReqd ] )
+ raise ParseException(instring,loc,"Missing one or more required elements (%s)" % missing )
+
+ # add any unmatched Optionals, in case they have default values defined
+ matchOrder += [e for e in self.exprs if isinstance(e,Optional) and e.expr in tmpOpt]
+
+ resultlist = []
+ for e in matchOrder:
+ loc,results = e._parse(instring,loc,doActions)
+ resultlist.append(results)
+
+ finalResults = ParseResults([])
+ for r in resultlist:
+ dups = {}
+ for k in r.keys():
+ if k in finalResults.keys():
+ tmp = ParseResults(finalResults[k])
+ tmp += ParseResults(r[k])
+ dups[k] = tmp
+ finalResults += ParseResults(r)
+ for k,v in dups.items():
+ finalResults[k] = v
+ return loc, finalResults
+
+ def __str__( self ):
+ if hasattr(self,"name"):
+ return self.name
+
+ if self.strRepr is None:
+ self.strRepr = "{" + " & ".join( [ _ustr(e) for e in self.exprs ] ) + "}"
+
+ return self.strRepr
+
+ def checkRecursion( self, parseElementList ):
+ subRecCheckList = parseElementList[:] + [ self ]
+ for e in self.exprs:
+ e.checkRecursion( subRecCheckList )
+
+
+class ParseElementEnhance(ParserElement):
+ """Abstract subclass of C{ParserElement}, for combining and post-processing parsed tokens."""
+ def __init__( self, expr, savelist=False ):
+ super(ParseElementEnhance,self).__init__(savelist)
+ if isinstance( expr, basestring ):
+ expr = Literal(expr)
+ self.expr = expr
+ self.strRepr = None
+ if expr is not None:
+ self.mayIndexError = expr.mayIndexError
+ self.mayReturnEmpty = expr.mayReturnEmpty
+ self.setWhitespaceChars( expr.whiteChars )
+ self.skipWhitespace = expr.skipWhitespace
+ self.saveAsList = expr.saveAsList
+ self.callPreparse = expr.callPreparse
+ self.ignoreExprs.extend(expr.ignoreExprs)
+
+ def parseImpl( self, instring, loc, doActions=True ):
+ if self.expr is not None:
+ return self.expr._parse( instring, loc, doActions, callPreParse=False )
+ else:
+ raise ParseException("",loc,self.errmsg,self)
+
+ def leaveWhitespace( self ):
+ self.skipWhitespace = False
+ self.expr = self.expr.copy()
+ if self.expr is not None:
+ self.expr.leaveWhitespace()
+ return self
+
+ def ignore( self, other ):
+ if isinstance( other, Suppress ):
+ if other not in self.ignoreExprs:
+ super( ParseElementEnhance, self).ignore( other )
+ if self.expr is not None:
+ self.expr.ignore( self.ignoreExprs[-1] )
+ else:
+ super( ParseElementEnhance, self).ignore( other )
+ if self.expr is not None:
+ self.expr.ignore( self.ignoreExprs[-1] )
+ return self
+
+ def streamline( self ):
+ super(ParseElementEnhance,self).streamline()
+ if self.expr is not None:
+ self.expr.streamline()
+ return self
+
+ def checkRecursion( self, parseElementList ):
+ if self in parseElementList:
+ raise RecursiveGrammarException( parseElementList+[self] )
+ subRecCheckList = parseElementList[:] + [ self ]
+ if self.expr is not None:
+ self.expr.checkRecursion( subRecCheckList )
+
+ def validate( self, validateTrace=[] ):
+ tmp = validateTrace[:]+[self]
+ if self.expr is not None:
+ self.expr.validate(tmp)
+ self.checkRecursion( [] )
+
+ def __str__( self ):
+ try:
+ return super(ParseElementEnhance,self).__str__()
+ except:
+ pass
+
+ if self.strRepr is None and self.expr is not None:
+ self.strRepr = "%s:(%s)" % ( self.__class__.__name__, _ustr(self.expr) )
+ return self.strRepr
+
+
+class FollowedBy(ParseElementEnhance):
+ """Lookahead matching of the given parse expression. C{FollowedBy}
+ does *not* advance the parsing position within the input string, it only
+ verifies that the specified parse expression matches at the current
+ position. C{FollowedBy} always returns a null token list."""
+ def __init__( self, expr ):
+ super(FollowedBy,self).__init__(expr)
+ self.mayReturnEmpty = True
+
+ def parseImpl( self, instring, loc, doActions=True ):
+ self.expr.tryParse( instring, loc )
+ return loc, []
+
+
+class NotAny(ParseElementEnhance):
+ """Lookahead to disallow matching with the given parse expression. C{NotAny}
+ does *not* advance the parsing position within the input string, it only
+ verifies that the specified parse expression does *not* match at the current
+ position. Also, C{NotAny} does *not* skip over leading whitespace. C{NotAny}
+ always returns a null token list. May be constructed using the '~' operator."""
+ def __init__( self, expr ):
+ super(NotAny,self).__init__(expr)
+ #~ self.leaveWhitespace()
+ self.skipWhitespace = False # do NOT use self.leaveWhitespace(), don't want to propagate to exprs
+ self.mayReturnEmpty = True
+ self.errmsg = "Found unwanted token, "+_ustr(self.expr)
+
+ def parseImpl( self, instring, loc, doActions=True ):
+ try:
+ self.expr.tryParse( instring, loc )
+ except (ParseException,IndexError):
+ pass
+ else:
+ #~ raise ParseException(instring, loc, self.errmsg )
+ exc = self.myException
+ exc.loc = loc
+ exc.pstr = instring
+ raise exc
+ return loc, []
+
+ def __str__( self ):
+ if hasattr(self,"name"):
+ return self.name
+
+ if self.strRepr is None:
+ self.strRepr = "~{" + _ustr(self.expr) + "}"
+
+ return self.strRepr
+
+
+class ZeroOrMore(ParseElementEnhance):
+ """Optional repetition of zero or more of the given expression."""
+ def __init__( self, expr ):
+ super(ZeroOrMore,self).__init__(expr)
+ self.mayReturnEmpty = True
+
+ def parseImpl( self, instring, loc, doActions=True ):
+ tokens = []
+ try:
+ loc, tokens = self.expr._parse( instring, loc, doActions, callPreParse=False )
+ hasIgnoreExprs = ( len(self.ignoreExprs) > 0 )
+ while 1:
+ if hasIgnoreExprs:
+ preloc = self._skipIgnorables( instring, loc )
+ else:
+ preloc = loc
+ loc, tmptokens = self.expr._parse( instring, preloc, doActions )
+ if tmptokens or tmptokens.keys():
+ tokens += tmptokens
+ except (ParseException,IndexError):
+ pass
+
+ return loc, tokens
+
+ def __str__( self ):
+ if hasattr(self,"name"):
+ return self.name
+
+ if self.strRepr is None:
+ self.strRepr = "[" + _ustr(self.expr) + "]..."
+
+ return self.strRepr
+
+ def setResultsName( self, name, listAllMatches=False ):
+ ret = super(ZeroOrMore,self).setResultsName(name,listAllMatches)
+ ret.saveAsList = True
+ return ret
+
+
+class OneOrMore(ParseElementEnhance):
+ """Repetition of one or more of the given expression."""
+ def parseImpl( self, instring, loc, doActions=True ):
+ # must be at least one
+ loc, tokens = self.expr._parse( instring, loc, doActions, callPreParse=False )
+ try:
+ hasIgnoreExprs = ( len(self.ignoreExprs) > 0 )
+ while 1:
+ if hasIgnoreExprs:
+ preloc = self._skipIgnorables( instring, loc )
+ else:
+ preloc = loc
+ loc, tmptokens = self.expr._parse( instring, preloc, doActions )
+ if tmptokens or tmptokens.keys():
+ tokens += tmptokens
+ except (ParseException,IndexError):
+ pass
+
+ return loc, tokens
+
+ def __str__( self ):
+ if hasattr(self,"name"):
+ return self.name
+
+ if self.strRepr is None:
+ self.strRepr = "{" + _ustr(self.expr) + "}..."
+
+ return self.strRepr
+
+ def setResultsName( self, name, listAllMatches=False ):
+ ret = super(OneOrMore,self).setResultsName(name,listAllMatches)
+ ret.saveAsList = True
+ return ret
+
+class _NullToken(object):
+ def __bool__(self):
+ return False
+ __nonzero__ = __bool__
+ def __str__(self):
+ return ""
+
+_optionalNotMatched = _NullToken()
+class Optional(ParseElementEnhance):
+ """Optional matching of the given expression.
+ A default return string can also be specified, if the optional expression
+ is not found.
+ """
+ def __init__( self, exprs, default=_optionalNotMatched ):
+ super(Optional,self).__init__( exprs, savelist=False )
+ self.defaultValue = default
+ self.mayReturnEmpty = True
+
+ def parseImpl( self, instring, loc, doActions=True ):
+ try:
+ loc, tokens = self.expr._parse( instring, loc, doActions, callPreParse=False )
+ except (ParseException,IndexError):
+ if self.defaultValue is not _optionalNotMatched:
+ if self.expr.resultsName:
+ tokens = ParseResults([ self.defaultValue ])
+ tokens[self.expr.resultsName] = self.defaultValue
+ else:
+ tokens = [ self.defaultValue ]
+ else:
+ tokens = []
+ return loc, tokens
+
+ def __str__( self ):
+ if hasattr(self,"name"):
+ return self.name
+
+ if self.strRepr is None:
+ self.strRepr = "[" + _ustr(self.expr) + "]"
+
+ return self.strRepr
+
+
+class SkipTo(ParseElementEnhance):
+ """Token for skipping over all undefined text until the matched expression is found.
+ If C{include} is set to true, the matched expression is also parsed (the skipped text
+ and matched expression are returned as a 2-element list). The C{ignore}
+ argument is used to define grammars (typically quoted strings and comments) that
+ might contain false matches.
+ """
+ def __init__( self, other, include=False, ignore=None, failOn=None ):
+ super( SkipTo, self ).__init__( other )
+ self.ignoreExpr = ignore
+ self.mayReturnEmpty = True
+ self.mayIndexError = False
+ self.includeMatch = include
+ self.asList = False
+ if failOn is not None and isinstance(failOn, basestring):
+ self.failOn = Literal(failOn)
+ else:
+ self.failOn = failOn
+ self.errmsg = "No match found for "+_ustr(self.expr)
+
+ def parseImpl( self, instring, loc, doActions=True ):
+ startLoc = loc
+ instrlen = len(instring)
+ expr = self.expr
+ failParse = False
+ while loc <= instrlen:
+ try:
+ if self.failOn:
+ try:
+ self.failOn.tryParse(instring, loc)
+ except ParseBaseException:
+ pass
+ else:
+ failParse = True
+ raise ParseException(instring, loc, "Found expression " + str(self.failOn))
+ failParse = False
+ if self.ignoreExpr is not None:
+ while 1:
+ try:
+ loc = self.ignoreExpr.tryParse(instring,loc)
+ # print "found ignoreExpr, advance to", loc
+ except ParseBaseException:
+ break
+ expr._parse( instring, loc, doActions=False, callPreParse=False )
+ skipText = instring[startLoc:loc]
+ if self.includeMatch:
+ loc,mat = expr._parse(instring,loc,doActions,callPreParse=False)
+ if mat:
+ skipRes = ParseResults( skipText )
+ skipRes += mat
+ return loc, [ skipRes ]
+ else:
+ return loc, [ skipText ]
+ else:
+ return loc, [ skipText ]
+ except (ParseException,IndexError):
+ if failParse:
+ raise
+ else:
+ loc += 1
+ exc = self.myException
+ exc.loc = loc
+ exc.pstr = instring
+ raise exc
+
+class Forward(ParseElementEnhance):
+ """Forward declaration of an expression to be defined later -
+ used for recursive grammars, such as algebraic infix notation.
+ When the expression is known, it is assigned to the C{Forward} variable using the '<<' operator.
+
+ Note: take care when assigning to C{Forward} not to overlook precedence of operators.
+ Specifically, '|' has a lower precedence than '<<', so that::
+ fwdExpr << a | b | c
+ will actually be evaluated as::
+ (fwdExpr << a) | b | c
+ thereby leaving b and c out as parseable alternatives. It is recommended that you
+ explicitly group the values inserted into the C{Forward}::
+ fwdExpr << (a | b | c)
+ """
+ def __init__( self, other=None ):
+ super(Forward,self).__init__( other, savelist=False )
+
+ def __lshift__( self, other ):
+ if isinstance( other, basestring ):
+ other = Literal(other)
+ self.expr = other
+ self.mayReturnEmpty = other.mayReturnEmpty
+ self.strRepr = None
+ self.mayIndexError = self.expr.mayIndexError
+ self.mayReturnEmpty = self.expr.mayReturnEmpty
+ self.setWhitespaceChars( self.expr.whiteChars )
+ self.skipWhitespace = self.expr.skipWhitespace
+ self.saveAsList = self.expr.saveAsList
+ self.ignoreExprs.extend(self.expr.ignoreExprs)
+ return None
+
+ def leaveWhitespace( self ):
+ self.skipWhitespace = False
+ return self
+
+ def streamline( self ):
+ if not self.streamlined:
+ self.streamlined = True
+ if self.expr is not None:
+ self.expr.streamline()
+ return self
+
+ def validate( self, validateTrace=[] ):
+ if self not in validateTrace:
+ tmp = validateTrace[:]+[self]
+ if self.expr is not None:
+ self.expr.validate(tmp)
+ self.checkRecursion([])
+
+ def __str__( self ):
+ if hasattr(self,"name"):
+ return self.name
+
+ self._revertClass = self.__class__
+ self.__class__ = _ForwardNoRecurse
+ try:
+ if self.expr is not None:
+ retString = _ustr(self.expr)
+ else:
+ retString = "None"
+ finally:
+ self.__class__ = self._revertClass
+ return self.__class__.__name__ + ": " + retString
+
+ def copy(self):
+ if self.expr is not None:
+ return super(Forward,self).copy()
+ else:
+ ret = Forward()
+ ret << self
+ return ret
+
+class _ForwardNoRecurse(Forward):
+ def __str__( self ):
+ return "..."
+
+class TokenConverter(ParseElementEnhance):
+ """Abstract subclass of C{ParseExpression}, for converting parsed results."""
+ def __init__( self, expr, savelist=False ):
+ super(TokenConverter,self).__init__( expr )#, savelist )
+ self.saveAsList = False
+
+class Upcase(TokenConverter):
+ """Converter to upper case all matching tokens."""
+ def __init__(self, *args):
+ super(Upcase,self).__init__(*args)
+ warnings.warn("Upcase class is deprecated, use upcaseTokens parse action instead",
+ DeprecationWarning,stacklevel=2)
+
+ def postParse( self, instring, loc, tokenlist ):
+ return list(map( string.upper, tokenlist ))
+
+
+class Combine(TokenConverter):
+ """Converter to concatenate all matching tokens to a single string.
+ By default, the matching patterns must also be contiguous in the input string;
+ this can be disabled by specifying C{'adjacent=False'} in the constructor.
+ """
+ def __init__( self, expr, joinString="", adjacent=True ):
+ super(Combine,self).__init__( expr )
+ # suppress whitespace-stripping in contained parse expressions, but re-enable it on the Combine itself
+ if adjacent:
+ self.leaveWhitespace()
+ self.adjacent = adjacent
+ self.skipWhitespace = True
+ self.joinString = joinString
+ self.callPreparse = True
+
+ def ignore( self, other ):
+ if self.adjacent:
+ ParserElement.ignore(self, other)
+ else:
+ super( Combine, self).ignore( other )
+ return self
+
+ def postParse( self, instring, loc, tokenlist ):
+ retToks = tokenlist.copy()
+ del retToks[:]
+ retToks += ParseResults([ "".join(tokenlist._asStringList(self.joinString)) ], modal=self.modalResults)
+
+ if self.resultsName and len(retToks.keys())>0:
+ return [ retToks ]
+ else:
+ return retToks
+
+class Group(TokenConverter):
+ """Converter to return the matched tokens as a list - useful for returning tokens of C{ZeroOrMore} and C{OneOrMore} expressions."""
+ def __init__( self, expr ):
+ super(Group,self).__init__( expr )
+ self.saveAsList = True
+
+ def postParse( self, instring, loc, tokenlist ):
+ return [ tokenlist ]
+
+class Dict(TokenConverter):
+ """Converter to return a repetitive expression as a list, but also as a dictionary.
+ Each element can also be referenced using the first token in the expression as its key.
+ Useful for tabular report scraping when the first column can be used as a item key.
+ """
+ def __init__( self, exprs ):
+ super(Dict,self).__init__( exprs )
+ self.saveAsList = True
+
+ def postParse( self, instring, loc, tokenlist ):
+ for i,tok in enumerate(tokenlist):
+ if len(tok) == 0:
+ continue
+ ikey = tok[0]
+ if isinstance(ikey,int):
+ ikey = _ustr(tok[0]).strip()
+ if len(tok)==1:
+ tokenlist[ikey] = _ParseResultsWithOffset("",i)
+ elif len(tok)==2 and not isinstance(tok[1],ParseResults):
+ tokenlist[ikey] = _ParseResultsWithOffset(tok[1],i)
+ else:
+ dictvalue = tok.copy() #ParseResults(i)
+ del dictvalue[0]
+ if len(dictvalue)!= 1 or (isinstance(dictvalue,ParseResults) and dictvalue.keys()):
+ tokenlist[ikey] = _ParseResultsWithOffset(dictvalue,i)
+ else:
+ tokenlist[ikey] = _ParseResultsWithOffset(dictvalue[0],i)
+
+ if self.resultsName:
+ return [ tokenlist ]
+ else:
+ return tokenlist
+
+
+class Suppress(TokenConverter):
+ """Converter for ignoring the results of a parsed expression."""
+ def postParse( self, instring, loc, tokenlist ):
+ return []
+
+ def suppress( self ):
+ return self
+
+
+class OnlyOnce(object):
+ """Wrapper for parse actions, to ensure they are only called once."""
+ def __init__(self, methodCall):
+ self.callable = _trim_arity(methodCall)
+ self.called = False
+ def __call__(self,s,l,t):
+ if not self.called:
+ results = self.callable(s,l,t)
+ self.called = True
+ return results
+ raise ParseException(s,l,"")
+ def reset(self):
+ self.called = False
+
+def traceParseAction(f):
+ """Decorator for debugging parse actions."""
+ f = _trim_arity(f)
+ def z(*paArgs):
+ thisFunc = f.func_name
+ s,l,t = paArgs[-3:]
+ if len(paArgs)>3:
+ thisFunc = paArgs[0].__class__.__name__ + '.' + thisFunc
+ sys.stderr.write( ">>entering %s(line: '%s', %d, %s)\n" % (thisFunc,line(l,s),l,t) )
+ try:
+ ret = f(*paArgs)
+ except Exception:
+ exc = sys.exc_info()[1]
+ sys.stderr.write( "<", "|".join( [ _escapeRegexChars(sym) for sym in symbols] ))
+ try:
+ if len(symbols)==len("".join(symbols)):
+ return Regex( "[%s]" % "".join( [ _escapeRegexRangeChars(sym) for sym in symbols] ) )
+ else:
+ return Regex( "|".join( [ re.escape(sym) for sym in symbols] ) )
+ except:
+ warnings.warn("Exception creating Regex for oneOf, building MatchFirst",
+ SyntaxWarning, stacklevel=2)
+
+
+ # last resort, just use MatchFirst
+ return MatchFirst( [ parseElementClass(sym) for sym in symbols ] )
+
+def dictOf( key, value ):
+ """Helper to easily and clearly define a dictionary by specifying the respective patterns
+ for the key and value. Takes care of defining the C{Dict}, C{ZeroOrMore}, and C{Group} tokens
+ in the proper order. The key pattern can include delimiting markers or punctuation,
+ as long as they are suppressed, thereby leaving the significant key text. The value
+ pattern can include named results, so that the C{Dict} results can include named token
+ fields.
+ """
+ return Dict( ZeroOrMore( Group ( key + value ) ) )
+
+def originalTextFor(expr, asString=True):
+ """Helper to return the original, untokenized text for a given expression. Useful to
+ restore the parsed fields of an HTML start tag into the raw tag text itself, or to
+ revert separate tokens with intervening whitespace back to the original matching
+ input text. Simpler to use than the parse action C{L{keepOriginalText}}, and does not
+ require the inspect module to chase up the call stack. By default, returns a
+ string containing the original parsed text.
+
+ If the optional C{asString} argument is passed as C{False}, then the return value is a
+ C{ParseResults} containing any results names that were originally matched, and a
+ single token containing the original matched text from the input string. So if
+ the expression passed to C{L{originalTextFor}} contains expressions with defined
+ results names, you must set C{asString} to C{False} if you want to preserve those
+ results name values."""
+ locMarker = Empty().setParseAction(lambda s,loc,t: loc)
+ endlocMarker = locMarker.copy()
+ endlocMarker.callPreparse = False
+ matchExpr = locMarker("_original_start") + expr + endlocMarker("_original_end")
+ if asString:
+ extractText = lambda s,l,t: s[t._original_start:t._original_end]
+ else:
+ def extractText(s,l,t):
+ del t[:]
+ t.insert(0, s[t._original_start:t._original_end])
+ del t["_original_start"]
+ del t["_original_end"]
+ matchExpr.setParseAction(extractText)
+ return matchExpr
+
+def ungroup(expr):
+ """Helper to undo pyparsing's default grouping of And expressions, even
+ if all but one are non-empty."""
+ return TokenConverter(expr).setParseAction(lambda t:t[0])
+
+# convenience constants for positional expressions
+empty = Empty().setName("empty")
+lineStart = LineStart().setName("lineStart")
+lineEnd = LineEnd().setName("lineEnd")
+stringStart = StringStart().setName("stringStart")
+stringEnd = StringEnd().setName("stringEnd")
+
+_escapedPunc = Word( _bslash, r"\[]-*.$+^?()~ ", exact=2 ).setParseAction(lambda s,l,t:t[0][1])
+_printables_less_backslash = "".join([ c for c in printables if c not in r"\]" ])
+_escapedHexChar = Regex(r"\\0?[xX][0-9a-fA-F]+").setParseAction(lambda s,l,t:unichr(int(t[0][1:],16)))
+_escapedOctChar = Regex(r"\\0[0-7]+").setParseAction(lambda s,l,t:unichr(int(t[0][1:],8)))
+_singleChar = _escapedPunc | _escapedHexChar | _escapedOctChar | Word(_printables_less_backslash,exact=1)
+_charRange = Group(_singleChar + Suppress("-") + _singleChar)
+_reBracketExpr = Literal("[") + Optional("^").setResultsName("negate") + Group( OneOrMore( _charRange | _singleChar ) ).setResultsName("body") + "]"
+
+_expanded = lambda p: (isinstance(p,ParseResults) and ''.join([ unichr(c) for c in range(ord(p[0]),ord(p[1])+1) ]) or p)
+
+def srange(s):
+ r"""Helper to easily define string ranges for use in Word construction. Borrows
+ syntax from regexp '[]' string range definitions::
+ srange("[0-9]") -> "0123456789"
+ srange("[a-z]") -> "abcdefghijklmnopqrstuvwxyz"
+ srange("[a-z$_]") -> "abcdefghijklmnopqrstuvwxyz$_"
+ The input string must be enclosed in []'s, and the returned string is the expanded
+ character set joined into a single string.
+ The values enclosed in the []'s may be::
+ a single character
+ an escaped character with a leading backslash (such as \- or \])
+ an escaped hex character with a leading '\x' (\x21, which is a '!' character)
+ (\0x## is also supported for backwards compatibility)
+ an escaped octal character with a leading '\0' (\041, which is a '!' character)
+ a range of any of the above, separated by a dash ('a-z', etc.)
+ any combination of the above ('aeiouy', 'a-zA-Z0-9_$', etc.)
+ """
+ try:
+ return "".join([_expanded(part) for part in _reBracketExpr.parseString(s).body])
+ except:
+ return ""
+
+def matchOnlyAtCol(n):
+ """Helper method for defining parse actions that require matching at a specific
+ column in the input text.
+ """
+ def verifyCol(strg,locn,toks):
+ if col(locn,strg) != n:
+ raise ParseException(strg,locn,"matched token not at column %d" % n)
+ return verifyCol
+
+def replaceWith(replStr):
+ """Helper method for common parse actions that simply return a literal value. Especially
+ useful when used with C{transformString()}.
+ """
+ def _replFunc(*args):
+ return [replStr]
+ return _replFunc
+
+def removeQuotes(s,l,t):
+ """Helper parse action for removing quotation marks from parsed quoted strings.
+ To use, add this parse action to quoted string using::
+ quotedString.setParseAction( removeQuotes )
+ """
+ return t[0][1:-1]
+
+def upcaseTokens(s,l,t):
+ """Helper parse action to convert tokens to upper case."""
+ return [ tt.upper() for tt in map(_ustr,t) ]
+
+def downcaseTokens(s,l,t):
+ """Helper parse action to convert tokens to lower case."""
+ return [ tt.lower() for tt in map(_ustr,t) ]
+
+def keepOriginalText(s,startLoc,t):
+ """DEPRECATED - use new helper method C{originalTextFor}.
+ Helper parse action to preserve original parsed text,
+ overriding any nested parse actions."""
+ try:
+ endloc = getTokensEndLoc()
+ except ParseException:
+ raise ParseFatalException("incorrect usage of keepOriginalText - may only be called as a parse action")
+ del t[:]
+ t += ParseResults(s[startLoc:endloc])
+ return t
+
+def getTokensEndLoc():
+ """Method to be called from within a parse action to determine the end
+ location of the parsed tokens."""
+ import inspect
+ fstack = inspect.stack()
+ try:
+ # search up the stack (through intervening argument normalizers) for correct calling routine
+ for f in fstack[2:]:
+ if f[3] == "_parseNoCache":
+ endloc = f[0].f_locals["loc"]
+ return endloc
+ else:
+ raise ParseFatalException("incorrect usage of getTokensEndLoc - may only be called from within a parse action")
+ finally:
+ del fstack
+
+def _makeTags(tagStr, xml):
+ """Internal helper to construct opening and closing tag expressions, given a tag name"""
+ if isinstance(tagStr,basestring):
+ resname = tagStr
+ tagStr = Keyword(tagStr, caseless=not xml)
+ else:
+ resname = tagStr.name
+
+ tagAttrName = Word(alphas,alphanums+"_-:")
+ if (xml):
+ tagAttrValue = dblQuotedString.copy().setParseAction( removeQuotes )
+ openTag = Suppress("<") + tagStr("tag") + \
+ Dict(ZeroOrMore(Group( tagAttrName + Suppress("=") + tagAttrValue ))) + \
+ Optional("/",default=[False]).setResultsName("empty").setParseAction(lambda s,l,t:t[0]=='/') + Suppress(">")
+ else:
+ printablesLessRAbrack = "".join( [ c for c in printables if c not in ">" ] )
+ tagAttrValue = quotedString.copy().setParseAction( removeQuotes ) | Word(printablesLessRAbrack)
+ openTag = Suppress("<") + tagStr("tag") + \
+ Dict(ZeroOrMore(Group( tagAttrName.setParseAction(downcaseTokens) + \
+ Optional( Suppress("=") + tagAttrValue ) ))) + \
+ Optional("/",default=[False]).setResultsName("empty").setParseAction(lambda s,l,t:t[0]=='/') + Suppress(">")
+ closeTag = Combine(_L("") + tagStr + ">")
+
+ openTag = openTag.setResultsName("start"+"".join(resname.replace(":"," ").title().split())).setName("<%s>" % tagStr)
+ closeTag = closeTag.setResultsName("end"+"".join(resname.replace(":"," ").title().split())).setName("%s>" % tagStr)
+ openTag.tag = resname
+ closeTag.tag = resname
+ return openTag, closeTag
+
+def makeHTMLTags(tagStr):
+ """Helper to construct opening and closing tag expressions for HTML, given a tag name"""
+ return _makeTags( tagStr, False )
+
+def makeXMLTags(tagStr):
+ """Helper to construct opening and closing tag expressions for XML, given a tag name"""
+ return _makeTags( tagStr, True )
+
+def withAttribute(*args,**attrDict):
+ """Helper to create a validating parse action to be used with start tags created
+ with C{makeXMLTags} or C{makeHTMLTags}. Use C{withAttribute} to qualify a starting tag
+ with a required attribute value, to avoid false matches on common tags such as
+ C{
{% end %}
diff --git a/libpathod/templates/onelog.html b/libpathod/templates/onelog.html
new file mode 100644
index 00000000..378bac32
--- /dev/null
+++ b/libpathod/templates/onelog.html
@@ -0,0 +1,10 @@
+{% extends frame.html %}
+{% block body %}
+
Log entry {{ lid }}
+
+
+{{ alog }}
+
+
+{% end %}
+
diff --git a/test/test_app.py b/test/test_app.py
index 721b36d7..8f9738db 100644
--- a/test/test_app.py
+++ b/test/test_app.py
@@ -27,6 +27,11 @@ class uApplication(libpry.AutoTree):
assert a.log[0]["id"] == 3
assert a.log[-1]["id"] == 1
+ assert a.log_by_id(1)["id"] == 1
+ assert not a.log_by_id(0)
+
+
+
class uPages(libpry.AutoTree):
def dummy_page(self, path):
# A hideous, hideous kludge, but Tornado seems to have no more sensible
--
cgit v1.2.3
From 5650086ca1927fd7aa21d102048c790d5a28b729 Mon Sep 17 00:00:00 2001
From: Aldo Cortesi
Date: Sun, 29 Apr 2012 17:37:47 +1200
Subject: First pass at a README.
---
README | 140 ++++++++++++++++++++++++++++++++++++++++++++++++++++
libpathod/rparse.py | 10 ++--
notes | 42 ----------------
pathod | 2 +-
todo | 4 +-
5 files changed, 149 insertions(+), 49 deletions(-)
create mode 100644 README
delete mode 100644 notes
diff --git a/README b/README
new file mode 100644
index 00000000..3e25d581
--- /dev/null
+++ b/README
@@ -0,0 +1,140 @@
+
+Pathod
+======
+
+Pathod is a pathological HTTP/S daemon, useful for testing and torturing client
+software. At Pathod's core is a small, terse language for crafting HTTP
+responses. The simplest way to use Pathod is to fire up the daemon, and specify
+the respnse behaviour you want in the request URL, like this:
+
+ http://localhost:9999/p/200
+
+Everything below the magic "/p/" path component is a response specifier - in
+this case we're just specifying a vanilly 200 OK response, see the docs below
+to get fancier. You can also add anchors to the Pathod server that serve a
+fixed response whenever a path matching a specified URL is requested:
+
+ pathod --anchor /foo=200
+
+Here, the part before the "=" is a regex specifying the anchor path, and the
+part after is again a response specifier.
+
+Pathod has a nifty web interface built in, which exposes activity logs, online
+help and various other goodies. Try it by visiting the server root:
+
+ http://localhost:9999
+
+
+
+Specifying Responses
+====================
+
+The general form of a response is as follows:
+
+ code[MESSAGE]:[colon-separated list of features]
+
+Here's the simplest possible response specification, returning just an HTTP 200
+OK message with no headers and no content:
+
+ 200
+
+We can embellish this a bit by specifying an optional custom HTTP response
+message. By default for a 200 response code, this is just "OK", but we can
+change it like this:
+
+ 200"YAY"
+
+The quoted string above is an example of a value specifier, a syntax that is
+used pervasively in the Pathod response specification language. In this case,
+we're specifying a literal string, but there are many other fun things we can
+do. For example, we can tell Pathod to generate 100k of random ASCII letters
+instead:
+
+ 200@100k,ascii_letters
+
+Full documentation on the value specification syntax can be found below.
+
+Following the response code specifier is a colon-separateed list of features.
+For instance, this specifies a response with a body consisting of 1 megabyte of
+random data:
+
+ 200:b@1m
+
+And this is the same response with an ETag header added:
+
+ 200:b@1m:h"Etag"="foo"
+
+Both the header name and the header value are full value specifiers. Here's the
+same response again, but with a 1k randomly generated header name:
+
+ 200:b@1m:h@1k,ascii_letters="foo"
+
+A few specific headers have shortcuts, because they're used so often. The
+shorcut for the content-type header is "c":
+
+ 200:b@1m:c"text/json"
+
+That's it for the basic response definition. Now we can start mucking with the
+responses to break clients. One common hard-to-test circumstance is hangs or
+slow responses. Pathod has a pause operator that you can use to define
+precisely when and how long the server should hang. Here, for instance, we hang
+for 120 seconds after sending 50 bytes (counted from the first byte of the HTTP
+response):
+
+ 200:b@1m:p120,50
+
+If that's not long enough, we can tell Pathod to hang forever:
+
+ 200:b@1m:p120,f
+
+Or to send all data, and then hang without disconnecting:
+
+ 200:b@1m:p120,a
+
+We can also ask Pathod to hang randomly:
+
+ 200:b@1m:pr,a
+
+Pathod has a similar mechanism for simply dropping a connection mid-response.
+So we can tell Pathod to disconnect after sending 50 bytes:
+
+ 200:b@1m:d50
+
+Or randomly:
+
+ 200:b@1m:dr
+
+All of these features can be combined. Here's a response that pauses twice,
+then hangs:
+
+ 200:b@1m:p10,10:p20,10:d5000
+
+
+Features
+========
+
+ hVALUE=VALUE Set header
+ bVALUE Set body
+ cVALUE Set Content-Type header
+ lVALUE Set Location header
+
+ dOFF|r Disconnect after OFF bytes, measured from the beginning of the response.
+ pNUM|f,OFF|r|a Pause for NUM seconds after OFF bytes.
+
+
+Value Specifiers
+----------------
+
+ @500k - 500k of random data
+ @500k,utf8 - 500k of utf8. Other specifiers: utf8,alphanum,alpha,printable
+ "foo" - literal
+
Date: Sun, 29 Apr 2012 17:38:41 +1200
Subject: README -> README.mkd
---
README | 140 -------------------------------------------------------------
README.mkd | 140 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
2 files changed, 140 insertions(+), 140 deletions(-)
delete mode 100644 README
create mode 100644 README.mkd
diff --git a/README b/README
deleted file mode 100644
index 3e25d581..00000000
--- a/README
+++ /dev/null
@@ -1,140 +0,0 @@
-
-Pathod
-======
-
-Pathod is a pathological HTTP/S daemon, useful for testing and torturing client
-software. At Pathod's core is a small, terse language for crafting HTTP
-responses. The simplest way to use Pathod is to fire up the daemon, and specify
-the respnse behaviour you want in the request URL, like this:
-
- http://localhost:9999/p/200
-
-Everything below the magic "/p/" path component is a response specifier - in
-this case we're just specifying a vanilly 200 OK response, see the docs below
-to get fancier. You can also add anchors to the Pathod server that serve a
-fixed response whenever a path matching a specified URL is requested:
-
- pathod --anchor /foo=200
-
-Here, the part before the "=" is a regex specifying the anchor path, and the
-part after is again a response specifier.
-
-Pathod has a nifty web interface built in, which exposes activity logs, online
-help and various other goodies. Try it by visiting the server root:
-
- http://localhost:9999
-
-
-
-Specifying Responses
-====================
-
-The general form of a response is as follows:
-
- code[MESSAGE]:[colon-separated list of features]
-
-Here's the simplest possible response specification, returning just an HTTP 200
-OK message with no headers and no content:
-
- 200
-
-We can embellish this a bit by specifying an optional custom HTTP response
-message. By default for a 200 response code, this is just "OK", but we can
-change it like this:
-
- 200"YAY"
-
-The quoted string above is an example of a value specifier, a syntax that is
-used pervasively in the Pathod response specification language. In this case,
-we're specifying a literal string, but there are many other fun things we can
-do. For example, we can tell Pathod to generate 100k of random ASCII letters
-instead:
-
- 200@100k,ascii_letters
-
-Full documentation on the value specification syntax can be found below.
-
-Following the response code specifier is a colon-separateed list of features.
-For instance, this specifies a response with a body consisting of 1 megabyte of
-random data:
-
- 200:b@1m
-
-And this is the same response with an ETag header added:
-
- 200:b@1m:h"Etag"="foo"
-
-Both the header name and the header value are full value specifiers. Here's the
-same response again, but with a 1k randomly generated header name:
-
- 200:b@1m:h@1k,ascii_letters="foo"
-
-A few specific headers have shortcuts, because they're used so often. The
-shorcut for the content-type header is "c":
-
- 200:b@1m:c"text/json"
-
-That's it for the basic response definition. Now we can start mucking with the
-responses to break clients. One common hard-to-test circumstance is hangs or
-slow responses. Pathod has a pause operator that you can use to define
-precisely when and how long the server should hang. Here, for instance, we hang
-for 120 seconds after sending 50 bytes (counted from the first byte of the HTTP
-response):
-
- 200:b@1m:p120,50
-
-If that's not long enough, we can tell Pathod to hang forever:
-
- 200:b@1m:p120,f
-
-Or to send all data, and then hang without disconnecting:
-
- 200:b@1m:p120,a
-
-We can also ask Pathod to hang randomly:
-
- 200:b@1m:pr,a
-
-Pathod has a similar mechanism for simply dropping a connection mid-response.
-So we can tell Pathod to disconnect after sending 50 bytes:
-
- 200:b@1m:d50
-
-Or randomly:
-
- 200:b@1m:dr
-
-All of these features can be combined. Here's a response that pauses twice,
-then hangs:
-
- 200:b@1m:p10,10:p20,10:d5000
-
-
-Features
-========
-
- hVALUE=VALUE Set header
- bVALUE Set body
- cVALUE Set Content-Type header
- lVALUE Set Location header
-
- dOFF|r Disconnect after OFF bytes, measured from the beginning of the response.
- pNUM|f,OFF|r|a Pause for NUM seconds after OFF bytes.
-
-
-Value Specifiers
-----------------
-
- @500k - 500k of random data
- @500k,utf8 - 500k of utf8. Other specifiers: utf8,alphanum,alpha,printable
- "foo" - literal
-
Date: Sun, 29 Apr 2012 18:28:46 +1200
Subject: Feature specification documentation.
---
README.mkd | 88 +++++++++++++++++++++++++++++++++++++++++++-------------------
1 file changed, 62 insertions(+), 26 deletions(-)
diff --git a/README.mkd b/README.mkd
index 3e25d581..01f88ef5 100644
--- a/README.mkd
+++ b/README.mkd
@@ -5,22 +5,23 @@ Pathod
Pathod is a pathological HTTP/S daemon, useful for testing and torturing client
software. At Pathod's core is a small, terse language for crafting HTTP
responses. The simplest way to use Pathod is to fire up the daemon, and specify
-the respnse behaviour you want in the request URL, like this:
+the respnse behaviour you want using this language in the request URL. Here's a
+minimal example:
http://localhost:9999/p/200
Everything below the magic "/p/" path component is a response specifier - in
-this case we're just specifying a vanilly 200 OK response, see the docs below
-to get fancier. You can also add anchors to the Pathod server that serve a
-fixed response whenever a path matching a specified URL is requested:
+this case just a vanilla 200 OK response. See the docs below to get (much)
+fancier. You can also add anchors to the Pathod server that serve a fixed
+response whenever a matching URL is requested:
- pathod --anchor /foo=200
+ pathod --anchor "/foo=200"
Here, the part before the "=" is a regex specifying the anchor path, and the
-part after is again a response specifier.
+part after is a response specifier.
-Pathod has a nifty web interface built in, which exposes activity logs, online
-help and various other goodies. Try it by visiting the server root:
+Pathod also has a nifty built-in web interface, which exposes activity logs,
+online help and various other goodies. Try it by visiting the server root:
http://localhost:9999
@@ -39,20 +40,22 @@ OK message with no headers and no content:
200
We can embellish this a bit by specifying an optional custom HTTP response
-message. By default for a 200 response code, this is just "OK", but we can
-change it like this:
+message (if we don't, Pathod automatically creates an appropriate one). By
+default for a 200 response code the message is "OK", but we can change it like
+this:
200"YAY"
-The quoted string above is an example of a value specifier, a syntax that is
-used pervasively in the Pathod response specification language. In this case,
-we're specifying a literal string, but there are many other fun things we can
-do. For example, we can tell Pathod to generate 100k of random ASCII letters
-instead:
+The quoted string here is an example of a Value Specifier, a syntax that is
+used throughout the Pathod response specification language. In this case, the
+quotes mean we're specifying a literal string, but there are many other fun
+things we can do. For example, we can tell Pathod to generate 100k of random
+ASCII letters instead:
200@100k,ascii_letters
-Full documentation on the value specification syntax can be found below.
+Full documentation on the value specification syntax can be found in the next
+section.
Following the response code specifier is a colon-separateed list of features.
For instance, this specifies a response with a body consisting of 1 megabyte of
@@ -95,8 +98,8 @@ We can also ask Pathod to hang randomly:
200:b@1m:pr,a
-Pathod has a similar mechanism for simply dropping a connection mid-response.
-So we can tell Pathod to disconnect after sending 50 bytes:
+There is a similar mechanism for dropping connections mid-response. So, we can
+tell Pathod to disconnect after sending 50 bytes:
200:b@1m:d50
@@ -105,7 +108,7 @@ Or randomly:
200:b@1m:dr
All of these features can be combined. Here's a response that pauses twice,
-then hangs:
+once at 10 bytes and once at 20, then disconnects at 5000:
200:b@1m:p10,10:p20,10:d5000
@@ -113,17 +116,50 @@ then hangs:
Features
========
- hVALUE=VALUE Set header
- bVALUE Set body
- cVALUE Set Content-Type header
- lVALUE Set Location header
+_h_KEY=VALUE
+------------
- dOFF|r Disconnect after OFF bytes, measured from the beginning of the response.
- pNUM|f,OFF|r|a Pause for NUM seconds after OFF bytes.
+Set a header. Both KEY and VALUE are full _Value Specifiers_.
+
+
+_b_VALUE
+--------
+
+Set the body. VALUE is a _Value Specifier_. When the body is set, Pathod will
+automatically set the appropriate Content-Length header.
+
+_c_VALUE
+--------
+
+A shortcut for setting the Content-Type header. Equivalent to:
+
+ h"Content-Type"=VALUE
+
+_l_VALUE
+--------
+
+A shortcut for setting the Location header. Equivalent to:
+
+ h"Content-Type"=VALUE
+
+
+_d_OFFSET
+---------
+
+Disconnect after OFFSET bytes. The offset can also be "r", in which case Pathod
+will disconnect at a random point in the response.
+
+
+_p_SECONDS,OFFSET
+-----------------
+
+Pause for SECONDS seconds after OFFSET bytes. SECONDS can also be "f" to pause
+forever. OFFSET can also be "r" to generate a random offset, or "a" for an
+offset just after all data has been sent.
Value Specifiers
-----------------
+================
@500k - 500k of random data
@500k,utf8 - 500k of utf8. Other specifiers: utf8,alphanum,alpha,printable
--
cgit v1.2.3
From e7ed79e38b5f7f782f392a56c9925dad82ea2881 Mon Sep 17 00:00:00 2001
From: Aldo Cortesi
Date: Sun, 29 Apr 2012 18:42:06 +1200
Subject: Docs for Value Specifiers.
---
README.mkd | 100 ++++++++++++++++++++++++++++++++++++++++++++++++++-----------
1 file changed, 83 insertions(+), 17 deletions(-)
diff --git a/README.mkd b/README.mkd
index 01f88ef5..76ad9246 100644
--- a/README.mkd
+++ b/README.mkd
@@ -116,42 +116,36 @@ once at 10 bytes and once at 20, then disconnects at 5000:
Features
========
-_h_KEY=VALUE
-------------
+### _h_KEY=VALUE
Set a header. Both KEY and VALUE are full _Value Specifiers_.
-_b_VALUE
---------
+### _b_VALUE
Set the body. VALUE is a _Value Specifier_. When the body is set, Pathod will
automatically set the appropriate Content-Length header.
-_c_VALUE
---------
+### _c_VALUE
A shortcut for setting the Content-Type header. Equivalent to:
h"Content-Type"=VALUE
-_l_VALUE
---------
+### _l_VALUE
A shortcut for setting the Location header. Equivalent to:
h"Content-Type"=VALUE
-_d_OFFSET
----------
+### _d_OFFSET
Disconnect after OFFSET bytes. The offset can also be "r", in which case Pathod
will disconnect at a random point in the response.
-_p_SECONDS,OFFSET
------------------
+### _p_SECONDS,OFFSET
Pause for SECONDS seconds after OFFSET bytes. SECONDS can also be "f" to pause
forever. OFFSET can also be "r" to generate a random offset, or "a" for an
@@ -161,11 +155,83 @@ offset just after all data has been sent.
Value Specifiers
================
- @500k - 500k of random data
- @500k,utf8 - 500k of utf8. Other specifiers: utf8,alphanum,alpha,printable
- "foo" - literal
-
Date: Sun, 29 Apr 2012 18:46:12 +1200
Subject: Doc tweaks.
There will be a lot of these, because the only way to see how things render on
Github is to upload a new README...
---
README.mkd | 21 ++++++---------------
1 file changed, 6 insertions(+), 15 deletions(-)
diff --git a/README.mkd b/README.mkd
index 76ad9246..9c333a40 100644
--- a/README.mkd
+++ b/README.mkd
@@ -116,36 +116,36 @@ once at 10 bytes and once at 20, then disconnects at 5000:
Features
========
-### _h_KEY=VALUE
+#### hKEY=VALUE
Set a header. Both KEY and VALUE are full _Value Specifiers_.
-### _b_VALUE
+#### bVALUE
Set the body. VALUE is a _Value Specifier_. When the body is set, Pathod will
automatically set the appropriate Content-Length header.
-### _c_VALUE
+#### cVALUE
A shortcut for setting the Content-Type header. Equivalent to:
h"Content-Type"=VALUE
-### _l_VALUE
+#### lVALUE
A shortcut for setting the Location header. Equivalent to:
h"Content-Type"=VALUE
-### _d_OFFSET
+#### dOFFSET
Disconnect after OFFSET bytes. The offset can also be "r", in which case Pathod
will disconnect at a random point in the response.
-### _p_SECONDS,OFFSET
+#### pSECONDS,OFFSET
Pause for SECONDS seconds after OFFSET bytes. SECONDS can also be "f" to pause
forever. OFFSET can also be "r" to generate a random offset, or "a" for an
@@ -231,12 +231,3 @@ Supported data types are:
whitespace
ascii
bytes
-
-
-
-Anchors
-=======
-
- Passed on command-line:
- -a "/foo/bar=200:!/foo"
-
--
cgit v1.2.3
From 37e880b3990e2729d857b0f3a24f80d45116b7f0 Mon Sep 17 00:00:00 2001
From: Aldo Cortesi
Date: Sun, 29 Apr 2012 18:56:49 +1200
Subject: Add a rendered version of the docs to the web app.
---
README.mkd | 2 +
libpathod/templates/help.html | 252 +++++++++++++++++++++++++++++++++++++++++-
todo | 3 +-
3 files changed, 254 insertions(+), 3 deletions(-)
diff --git a/README.mkd b/README.mkd
index 9c333a40..ecbf3210 100644
--- a/README.mkd
+++ b/README.mkd
@@ -126,12 +126,14 @@ Set a header. Both KEY and VALUE are full _Value Specifiers_.
Set the body. VALUE is a _Value Specifier_. When the body is set, Pathod will
automatically set the appropriate Content-Length header.
+
#### cVALUE
A shortcut for setting the Content-Type header. Equivalent to:
h"Content-Type"=VALUE
+
#### lVALUE
A shortcut for setting the Location header. Equivalent to:
diff --git a/libpathod/templates/help.html b/libpathod/templates/help.html
index 20d884c5..3ab48c95 100644
--- a/libpathod/templates/help.html
+++ b/libpathod/templates/help.html
@@ -1,4 +1,254 @@
{% extends frame.html %}
{% block body %}
-
Help
+
+
+
Pathod
+
+
Pathod is a pathological HTTP/S daemon, useful for testing and torturing client
+software. At Pathod's core is a small, terse language for crafting HTTP
+responses. The simplest way to use Pathod is to fire up the daemon, and specify
+the respnse behaviour you want using this language in the request URL. Here's a
+minimal example:
+
+
http://localhost:9999/p/200
+
+
+
Everything below the magic "/p/" path component is a response specifier - in
+this case just a vanilla 200 OK response. See the docs below to get (much)
+fancier. You can also add anchors to the Pathod server that serve a fixed
+response whenever a matching URL is requested:
+
+
pathod --anchor "/foo=200"
+
+
+
Here, the part before the "=" is a regex specifying the anchor path, and the
+part after is a response specifier.
+
+
Pathod also has a nifty built-in web interface, which exposes activity logs,
+online help and various other goodies. Try it by visiting the server root:
+
+
http://localhost:9999
+
+
+
Specifying Responses
+
+
The general form of a response is as follows:
+
+
code[MESSAGE]:[colon-separated list of features]
+
+
+
Here's the simplest possible response specification, returning just an HTTP 200
+OK message with no headers and no content:
+
+
200
+
+
+
We can embellish this a bit by specifying an optional custom HTTP response
+message (if we don't, Pathod automatically creates an appropriate one). By
+default for a 200 response code the message is "OK", but we can change it like
+this:
+
+
200"YAY"
+
+
+
The quoted string here is an example of a Value Specifier, a syntax that is
+used throughout the Pathod response specification language. In this case, the
+quotes mean we're specifying a literal string, but there are many other fun
+things we can do. For example, we can tell Pathod to generate 100k of random
+ASCII letters instead:
+
+
200@100k,ascii_letters
+
+
+
Full documentation on the value specification syntax can be found in the next
+section.
+
+
Following the response code specifier is a colon-separateed list of features.
+For instance, this specifies a response with a body consisting of 1 megabyte of
+random data:
+
+
200:b@1m
+
+
+
And this is the same response with an ETag header added:
+
+
200:b@1m:h"Etag"="foo"
+
+
+
Both the header name and the header value are full value specifiers. Here's the
+same response again, but with a 1k randomly generated header name:
+
+
200:b@1m:h@1k,ascii_letters="foo"
+
+
+
A few specific headers have shortcuts, because they're used so often. The
+shorcut for the content-type header is "c":
+
+
200:b@1m:c"text/json"
+
+
+
That's it for the basic response definition. Now we can start mucking with the
+responses to break clients. One common hard-to-test circumstance is hangs or
+slow responses. Pathod has a pause operator that you can use to define
+precisely when and how long the server should hang. Here, for instance, we hang
+for 120 seconds after sending 50 bytes (counted from the first byte of the HTTP
+response):
+
+
200:b@1m:p120,50
+
+
+
If that's not long enough, we can tell Pathod to hang forever:
+
+
200:b@1m:p120,f
+
+
+
Or to send all data, and then hang without disconnecting:
+
+
200:b@1m:p120,a
+
+
+
We can also ask Pathod to hang randomly:
+
+
200:b@1m:pr,a
+
+
+
There is a similar mechanism for dropping connections mid-response. So, we can
+tell Pathod to disconnect after sending 50 bytes:
+
+
200:b@1m:d50
+
+
+
Or randomly:
+
+
200:b@1m:dr
+
+
+
All of these features can be combined. Here's a response that pauses twice,
+once at 10 bytes and once at 20, then disconnects at 5000:
+
+
200:b@1m:p10,10:p20,10:d5000
+
+
+
Features
+
+
hKEY=VALUE
+
+
Set a header. Both KEY and VALUE are full Value Specifiers.
+
+
bVALUE
+
+
Set the body. VALUE is a Value Specifier. When the body is set, Pathod will
+automatically set the appropriate Content-Length header.
+
+
cVALUE
+
+
A shortcut for setting the Content-Type header. Equivalent to:
+
+
h"Content-Type"=VALUE
+
+
+
lVALUE
+
+
A shortcut for setting the Location header. Equivalent to:
+
+
h"Content-Type"=VALUE
+
+
+
dOFFSET
+
+
Disconnect after OFFSET bytes. The offset can also be "r", in which case Pathod
+will disconnect at a random point in the response.
+
+
pSECONDS,OFFSET
+
+
Pause for SECONDS seconds after OFFSET bytes. SECONDS can also be "f" to pause
+forever. OFFSET can also be "r" to generate a random offset, or "a" for an
+offset just after all data has been sent.
+
+
Value Specifiers
+
+
There are three different flavours of value specification.
+
+
Literal
+
+
Literal values are specified as a quoted strings:
+
+
"foo"
+
+
+
Either single or double quotes are accepted, and quotes can be escaped with
+backslashes within the string:
+
+
'fo\'o'
+
+
+
Files
+
+
You can load a value from a specified file path. To do so, you have to specify
+a staticdir option to Pathod on the command-line, like so:
+
+
pathod -d ~/myassets
+
+
+
All paths are relative paths under this directory. File loads are indicated by
+starting the value specifier with the left angle bracket:
+
+
<my/path
+
+
+
The path value can also be a quoted string, with the same syntax as literals:
+
+
<"my/path"
+
+
+
Generated values
+
+
An @-symbol lead-in specifies that generated data should be used. There are two
+components to a generator specification - a size, and a data type. By default
+Pathod assumes a data type of "bytes".
+
+
Here's a value specifier for generating 100 bytes:
+
+
@100
+
+
+
You can use standard suffixes to indicate larger values. Here, for instance, is
+a specifier for generating 100 megabytes:
Tools for testing and torturing HTTP clients, servers and proxies.
+
+
+
+
+
+
pathod
+
+ A pathological web daemon.
+
+
+
+
+
+
pathoc
+
+ A perverse HTTP client.
+
+
+
+
+
+
libpathod.test
+
+ Use pathod and pathoc in your unit tests.
+
+
+
+
diff --git a/doc-src/index.py b/doc-src/index.py
new file mode 100644
index 00000000..85d3e339
--- /dev/null
+++ b/doc-src/index.py
@@ -0,0 +1,18 @@
+from countershape import widgets, layout, html, blog, markup, sitemap
+from countershape.doc import *
+
+ns.foot = "Copyright 2012 Aldo Cortesi"
+this.markup = markup.Markdown(extras=dict(footnotes=True))
+this.layout = layout.FileLayout("_layout_full.html")
+this.titlePrefix = ""
+this.site_url = "http://corte.si"
+pages = [
+ Page("index.html", "overview", namespace=dict(section="index")),
+ Page("docs.html", "docs", namespace=dict(section="docs")),
+ sitemap.Sitemap("sitemap.xml")
+]
+ns.sidebar = widgets.SiblingPageIndex(
+ pages[0],
+ depth=1,
+ divclass="sidebarmenu"
+ )
diff --git a/doc-src/start_quote.png b/doc-src/start_quote.png
new file mode 100644
index 00000000..8090f6e8
Binary files /dev/null and b/doc-src/start_quote.png differ
--
cgit v1.2.3
From 6d0b49dfef9c3a047127de5f56660da49f3e65af Mon Sep 17 00:00:00 2001
From: Aldo Cortesi
Date: Sun, 24 Jun 2012 10:54:37 +1200
Subject: Documentation.
---
README.mkd | 300 ----------------------------------------
README.txt | 30 ++--
doc-src/_layout_full.html | 6 +-
doc-src/docs.html | 5 -
doc-src/index.py | 9 +-
doc-src/pathoc.html | 5 +
doc-src/pathod.html | 338 ++++++++++++++++++++++++++++++++++++++++++++++
doc-src/test.html | 5 +
8 files changed, 366 insertions(+), 332 deletions(-)
delete mode 100644 doc-src/docs.html
create mode 100644 doc-src/pathoc.html
create mode 100644 doc-src/pathod.html
create mode 100644 doc-src/test.html
diff --git a/README.mkd b/README.mkd
index 9920ec8b..6feb5c3c 100644
--- a/README.mkd
+++ b/README.mkd
@@ -1,4 +1,3 @@
-
__pathod__ is a collection of pathological tools for testing and torturing HTTP
clients and servers. The project has three components:
@@ -7,304 +6,6 @@ clients and servers. The project has three components:
- __libpathod.test__, an API for easily using __pathod__ and __pathoc__ in unit tests.
-# pathod
-
-At __pathod__'s heart is a tiny, terse language for crafting HTTP responses.
-The simplest way to use __pathod__ is to fire up the daemon, and specify the
-response behaviour you want using this language in the request URL. Here's a
-minimal example:
-
- http://localhost:9999/p/200
-
-Everything after the "/p/" path component is a response specifier - in this
-case just a vanilla 200 OK response. See the docs below to get (much) fancier.
-You can also add anchors to the __pathod__ server that serve a fixed response
-whenever a matching URL is requested:
-
- pathod --anchor "/foo=200"
-
-Here, "/foo" a regex specifying the anchor path, and the part after the "=" is
-a response specifier.
-
-__pathod__ also has a nifty built-in web interface, which lets you play with
-the language by previewing responses, exposes activity logs, online help and
-various other goodies. Try it by visiting the server root:
-
- http://localhost:9999
-
-
-
-## Specifying Responses
-
-The general form of a response is as follows:
-
- code[MESSAGE]:[colon-separated list of features]
-
-Here's the simplest possible response specification, returning just an HTTP 200
-OK message with no headers and no content:
-
- 200
-
-We can embellish this a bit by specifying an optional custom HTTP response
-message (if we don't, __pathod__ automatically creates an appropriate one). By
-default for a 200 response code the message is "OK", but we can change it like
-this:
-
- 200"YAY"
-
-The quoted string here is an example of a Value Specifier, a syntax that is
-used throughout the __pathod__ response specification language. In this case, the
-quotes mean we're specifying a literal string, but there are many other fun
-things we can do. For example, we can tell __pathod__ to generate 100k of random
-ASCII letters instead:
-
- 200@100k,ascii_letters
-
-Full documentation on the value specification syntax can be found in the next
-section.
-
-Following the response code specifier is a colon-separated list of features.
-For instance, this specifies a response with a body consisting of 1 megabyte of
-random data:
-
- 200:b@1m
-
-And this is the same response with an ETag header added:
-
- 200:b@1m:h"Etag"="foo"
-
-Both the header name and the header value are full value specifiers. Here's the
-same response again, but with a 1k randomly generated header name:
-
- 200:b@1m:h@1k,ascii_letters="foo"
-
-A few specific headers have shortcuts, because they're used so often. The
-shortcut for the content-type header is "c":
-
- 200:b@1m:c"text/json"
-
-That's it for the basic response definition. Now we can start mucking with the
-responses to break clients. One common hard-to-test circumstance is hangs or
-slow responses. __pathod__ has a pause operator that you can use to define
-precisely when and how long the server should hang. Here, for instance, we hang
-for 120 seconds after sending 50 bytes (counted from the first byte of the HTTP
-response):
-
- 200:b@1m:p120,50
-
-If that's not long enough, we can tell __pathod__ to hang forever:
-
- 200:b@1m:p120,f
-
-Or to send all data, and then hang without disconnecting:
-
- 200:b@1m:p120,a
-
-We can also ask __pathod__ to hang randomly:
-
- 200:b@1m:pr,a
-
-There is a similar mechanism for dropping connections mid-response. So, we can
-tell __pathod__ to disconnect after sending 50 bytes:
-
- 200:b@1m:d50
-
-Or randomly:
-
- 200:b@1m:dr
-
-All of these features can be combined. Here's a response that pauses twice,
-once at 10 bytes and once at 20, then disconnects at 5000:
-
- 200:b@1m:p10,10:p20,10:d5000
-
-
-## Features
-
-
-#### hKEY=VALUE
-
-Set a header. Both KEY and VALUE are full _Value Specifiers_.
-
-
-#### bVALUE
-
-Set the body. VALUE is a _Value Specifier_. When the body is set, __pathod__ will
-automatically set the appropriate Content-Length header.
-
-
-#### cVALUE
-
-A shortcut for setting the Content-Type header. Equivalent to:
-
- h"Content-Type"=VALUE
-
-
-#### lVALUE
-
-A shortcut for setting the Location header. Equivalent to:
-
- h"Content-Type"=VALUE
-
-
-#### dOFFSET
-
-Disconnect after OFFSET bytes. The offset can also be "r", in which case __pathod__
-will disconnect at a random point in the response.
-
-
-#### pSECONDS,OFFSET
-
-Pause for SECONDS seconds after OFFSET bytes. SECONDS can also be "f" to pause
-forever. OFFSET can also be "r" to generate a random offset, or "a" for an
-offset just after all data has been sent.
-
-
-
-
-## Value Specifiers
-
-There are three different flavours of value specification.
-
-### Literal
-
-Literal values are specified as a quoted strings:
-
- "foo"
-
-Either single or double quotes are accepted, and quotes can be escaped with
-backslashes within the string:
-
- 'fo\'o'
-
-
-### Files
-
-You can load a value from a specified file path. To do so, you have to specify
-a _staticdir_ option to __pathod__ on the command-line, like so:
-
- pathod -d ~/myassets
-
-All paths are relative paths under this directory. File loads are indicated by
-starting the value specifier with the left angle bracket:
-
-
diff --git a/doc-src/docs.html b/doc-src/docs.html
deleted file mode 100644
index fe11ed3f..00000000
--- a/doc-src/docs.html
+++ /dev/null
@@ -1,5 +0,0 @@
-
-Test.
-
-
-
diff --git a/doc-src/index.py b/doc-src/index.py
index 85d3e339..de392004 100644
--- a/doc-src/index.py
+++ b/doc-src/index.py
@@ -8,11 +8,8 @@ this.titlePrefix = ""
this.site_url = "http://corte.si"
pages = [
Page("index.html", "overview", namespace=dict(section="index")),
- Page("docs.html", "docs", namespace=dict(section="docs")),
+ Page("pathod.html", "pathod", namespace=dict(section="docs")),
+ Page("pathoc.html", "pathoc", namespace=dict(section="docs")),
+ Page("test.html", "libpathod.test", namespace=dict(section="docs")),
sitemap.Sitemap("sitemap.xml")
]
-ns.sidebar = widgets.SiblingPageIndex(
- pages[0],
- depth=1,
- divclass="sidebarmenu"
- )
diff --git a/doc-src/pathoc.html b/doc-src/pathoc.html
new file mode 100644
index 00000000..fe11ed3f
--- /dev/null
+++ b/doc-src/pathoc.html
@@ -0,0 +1,5 @@
+
+Test.
+
+
+
diff --git a/doc-src/pathod.html b/doc-src/pathod.html
new file mode 100644
index 00000000..01cfca30
--- /dev/null
+++ b/doc-src/pathod.html
@@ -0,0 +1,338 @@
+# pathod
+
+At __pathod__'s heart is a tiny, terse language for crafting HTTP responses,
+designed to be easy to specify in a request URL. The simplest way to use
+__pathod__ is to fire up the daemon, and specify the response behaviour you
+want using this language in the request URL. Here's a minimal example:
+
+ http://localhost:9999/p/200
+
+Everything after the "/p/" path component is a response specifier - in this
+case just a vanilla 200 OK response. See the docs below to get (much) fancier.
+You can also add anchors to the __pathod__ server that serve a fixed response
+whenever a matching URL is requested:
+
+ pathod --anchor "/foo=200"
+
+Here, "/foo" a regex specifying the anchor path, and the part after the "=" is
+a response specifier.
+
+__pathod__ also has a nifty built-in web interface, which lets you play with
+the language by previewing responses, exposes activity logs, online help and
+various other goodies. Try it by visiting the server root:
+
+ http://localhost:9999
+
+
+
+# Specifying Responses
+
+The general form of a response is as follows:
+
+ code[MESSAGE]:[colon-separated list of features]
+
+Here's the simplest possible response specification, returning just an HTTP 200
+OK message with no headers and no content:
+
+ 200
+
+We can embellish this a bit by specifying an optional custom HTTP response
+message (if we don't, __pathod__ automatically creates an appropriate one). By
+default for a 200 response code the message is "OK", but we can change it like
+this:
+
+ 200"YAY"
+
+The quoted string here is an example of a Value
+Specifier, a syntax that is used throughout the __pathod__ response
+specification language. In this case, the quotes mean we're specifying a
+literal string, but there are many other fun things we can do. For example, we
+can tell __pathod__ to generate 100k of random ASCII letters instead:
+
+ 200@100k,ascii_letters
+
+Full documentation on the value specification syntax can be found in the next
+section.
+
+Following the response code specifier is a colon-separated list of features.
+For instance, this specifies a response with a body consisting of 1 megabyte of
+random data:
+
+ 200:b@1m
+
+And this is the same response with an ETag header added:
+
+ 200:b@1m:h"Etag"="foo"
+
+Both the header name and the header value are full value specifiers. Here's the
+same response again, but with a 1k randomly generated header name:
+
+ 200:b@1m:h@1k,ascii_letters="foo"
+
+A few specific headers have shortcuts, because they're used so often. The
+shortcut for the content-type header is "c":
+
+ 200:b@1m:c"text/json"
+
+That's it for the basic response definition. Now we can start mucking with the
+responses to break clients. One common hard-to-test circumstance is hangs or
+slow responses. __pathod__ has a pause operator that you can use to define
+precisely when and how long the server should hang. Here, for instance, we hang
+for 120 seconds after sending 50 bytes (counted from the first byte of the HTTP
+response):
+
+ 200:b@1m:p120,50
+
+If that's not long enough, we can tell __pathod__ to hang forever:
+
+ 200:b@1m:p120,f
+
+Or to send all data, and then hang without disconnecting:
+
+ 200:b@1m:p120,a
+
+We can also ask __pathod__ to hang randomly:
+
+ 200:b@1m:pr,a
+
+There is a similar mechanism for dropping connections mid-response. So, we can
+tell __pathod__ to disconnect after sending 50 bytes:
+
+ 200:b@1m:d50
+
+Or randomly:
+
+ 200:b@1m:dr
+
+All of these features can be combined. Here's a response that pauses twice,
+once at 10 bytes and once at 20, then disconnects at 5000:
+
+ 200:b@1m:p10,10:p20,10:d5000
+
+
+## Response Features
+
+
+ Set the body. VALUE is a Value
+ Specifier. When the body is set, __pathod__ will
+ automatically set the appropriate Content-Length header.
+
+
+
+
+
+ cVALUE
+
+
+ A shortcut for setting the Content-Type header. Equivalent to:
+
+
h"Content-Type"=VALUE
+
+
+
+
+
+
+ lVALUE
+
+
+ A shortcut for setting the Location header. Equivalent to:
+
+
h"Content-Type"=VALUE
+
+
+
+
+
+
+
+ dOFFSET
+
+
+ Disconnect after OFFSET bytes. The offset can also be "r", in which case __pathod__
+ will disconnect at a random point in the response.
+
+
+
+
+
+ pSECONDS,OFFSET
+
+
+ Pause for SECONDS seconds after OFFSET bytes. SECONDS can also be "f" to pause
+ forever. OFFSET can also be "r" to generate a random offset, or "a" for an
+ offset just after all data has been sent.
+
+
+
+
+
+
+## VALUE Specifiers
+
+There are three different flavours of value specification.
+
+### Literal
+
+Literal values are specified as a quoted strings:
+
+ "foo"
+
+Either single or double quotes are accepted, and quotes can be escaped with
+backslashes within the string:
+
+ 'fo\'o'
+
+
+### Files
+
+You can load a value from a specified file path. To do so, you have to specify
+a _staticdir_ option to __pathod__ on the command-line, like so:
+
+ pathod -d ~/myassets
+
+All paths are relative paths under this directory. File loads are indicated by
+starting the value specifier with the left angle bracket:
+
+
+
+
+
b
1024**0 (bytes)
+
+
+
k
1024**1 (kilobytes)
+
+
+
m
1024**2 (megabytes)
+
+
+
g
1024**3 (gigabytes)
+
+
+
t
1024**4 (terabytes)
+
+
+
+
+Data types are separated from the size specification by a comma. This
+specification generates 100mb of ASCII:
+
+ @100m,ascii
+
+Supported data types are:
+
+
+- ascii_letters
+- ascii_lowercase
+- ascii_uppercase
+- digits
+- hexdigits
+- letters
+- lowercase
+- octdigits
+- printable
+- punctuation
+- uppercase
+- whitespace
+- ascii
+- bytes
+
+
+# API
+
+__pathod__ exposes a simple API, intended to make it possible to drive and
+inspect the daemon remotely for use in unit testing and the like.
+
+### /api/log
+
+Returns the current log buffer. At the moment the buffer size is 500 entries -
+when the log grows larger than this, older entries are discarded. The returned
+data is a JSON dictionary, with the form:
+
+ {
+ 'logs': [ ENTRIES ]
+ }
+
+Where each entry looks like this:
+
+ {
+ # Record of actions taken at specified byte offsets
+ 'actions': [(200, 'disconnect'), (10, 'pause', 1)],
+ # HTTP return code
+ 'code': 200,
+ # Request duration in seconds
+ 'duration': 0.00020599365234375,
+ # ID unique to this invocation of pathod
+ 'id': 2,
+ # The request that triggered the response
+ 'request': {
+ 'full_url': 'http://testing:9999/p/200:b@1000:p1,10:d200',
+ 'headers': {
+ 'Accept': '*/*',
+ 'Host': 'localhost:9999',
+ 'User-Agent': 'curl/7.21.4'
+ },
+ 'host': 'localhost:9999',
+ 'method': 'POST',
+ 'path': '/p/200:b@1000:p1,10:d200',
+ 'protocol': 'http',
+ 'query': '',
+ 'remote_address': ('10.0.0.234', 63448),
+ 'uri': '/p/200:b@1000:p1,10:d200',
+ 'version': 'HTTP/1.1'
+ },
+ # The response spec that was served. You can re-parse this to get full
+ # details on the response.
+ 'spec': '200:b@1000:p1,10:d200',
+ # Time at which response startd.
+ 'started': 1335735586.469218
+ }
+
+You can preview the JSON data returned for a log entry through the built-in web
+interface.
+
+
+### /api/log/clear
+
+A POST to this URL clears the log buffer.
diff --git a/doc-src/test.html b/doc-src/test.html
new file mode 100644
index 00000000..fe11ed3f
--- /dev/null
+++ b/doc-src/test.html
@@ -0,0 +1,5 @@
+
+Test.
+
+
+
--
cgit v1.2.3
From b71e2f6f2bbc3ecaa1e463bae0cc6fd4762c6b8a Mon Sep 17 00:00:00 2001
From: Aldo Cortesi
Date: Sun, 24 Jun 2012 11:14:54 +1200
Subject: More doc refinement.
---
doc-src/index.html | 9 +++--
doc-src/pathoc.html | 8 +++--
doc-src/pathod.html | 100 ++++++++++++++++++++++++----------------------------
doc-src/test.html | 11 +++---
libpathod/app.py | 8 ++---
5 files changed, 66 insertions(+), 70 deletions(-)
diff --git a/doc-src/index.html b/doc-src/index.html
index acd389f9..30405375 100644
--- a/doc-src/index.html
+++ b/doc-src/index.html
@@ -1,4 +1,3 @@
-
Tools for testing and torturing HTTP clients, servers and proxies.
diff --git a/doc-src/pathod.html b/doc-src/pathod.html
index 01cfca30..6cb28734 100644
--- a/doc-src/pathod.html
+++ b/doc-src/pathod.html
@@ -1,6 +1,11 @@
-# pathod
-
-At __pathod__'s heart is a tiny, terse language for crafting HTTP responses,
+
+
+ pathod
+ A pathological web daemon.
+
+
+
+At __pathod__'s heart is a small, terse language for crafting HTTP responses,
designed to be easy to specify in a request URL. The simplest way to use
__pathod__ is to fire up the daemon, and specify the response behaviour you
want using this language in the request URL. Here's a minimal example:
@@ -284,55 +289,42 @@ Supported data types are:
__pathod__ exposes a simple API, intended to make it possible to drive and
inspect the daemon remotely for use in unit testing and the like.
-### /api/log
-Returns the current log buffer. At the moment the buffer size is 500 entries -
-when the log grows larger than this, older entries are discarded. The returned
-data is a JSON dictionary, with the form:
-
- {
- 'logs': [ ENTRIES ]
- }
-
-Where each entry looks like this:
-
- {
- # Record of actions taken at specified byte offsets
- 'actions': [(200, 'disconnect'), (10, 'pause', 1)],
- # HTTP return code
- 'code': 200,
- # Request duration in seconds
- 'duration': 0.00020599365234375,
- # ID unique to this invocation of pathod
- 'id': 2,
- # The request that triggered the response
- 'request': {
- 'full_url': 'http://testing:9999/p/200:b@1000:p1,10:d200',
- 'headers': {
- 'Accept': '*/*',
- 'Host': 'localhost:9999',
- 'User-Agent': 'curl/7.21.4'
- },
- 'host': 'localhost:9999',
- 'method': 'POST',
- 'path': '/p/200:b@1000:p1,10:d200',
- 'protocol': 'http',
- 'query': '',
- 'remote_address': ('10.0.0.234', 63448),
- 'uri': '/p/200:b@1000:p1,10:d200',
- 'version': 'HTTP/1.1'
- },
- # The response spec that was served. You can re-parse this to get full
- # details on the response.
- 'spec': '200:b@1000:p1,10:d200',
- # Time at which response startd.
- 'started': 1335735586.469218
- }
-
-You can preview the JSON data returned for a log entry through the built-in web
-interface.
-
-
-### /api/log/clear
-
-A POST to this URL clears the log buffer.
+
+
+
+
+ /api/clear_log
+
+
+ A POST to this URL clears the log buffer.
+
+
+
+
+ /api/info
+
+
+ Basic version and configuration info.
+
+
+
+
+ /api/log
+
+
+ Returns the current log buffer. At the moment the buffer size is 500 entries -
+ when the log grows larger than this, older entries are discarded. The returned
+ data is a JSON dictionary, with the form:
+
+
+ {
+ 'log': [ ENTRIES ]
+ }
+
+ You can preview the JSON data returned for a log entry through the built-in web
+ interface.
+
+pathoc hostname get:/foo/bar:h"foo"="bar" get:/wah:b@1m
-
+pathoc --ssl hostname get:/foo/bar:h"foo"="bar" get:/wah:b@1m
diff --git a/libpathod/pathod.py b/libpathod/pathod.py
index aed95675..ef37d5ad 100644
--- a/libpathod/pathod.py
+++ b/libpathod/pathod.py
@@ -26,7 +26,7 @@ class PathodHandler(tcp.BaseHandler):
if path.startswith(self.server.prefix):
spec = urllib.unquote(path)[len(self.server.prefix):]
try:
- presp = rparse.parse({}, spec)
+ presp = rparse.parse(self.server.request_settings, spec)
except rparse.ParseException, v:
presp = rparse.InternalResponse(
800,
@@ -34,8 +34,7 @@ class PathodHandler(tcp.BaseHandler):
)
ret = presp.serve(self.wfile)
if ret["disconnect"]:
- self.close()
-
+ self.finish()
ret["request"] = dict(
path = path,
method = method,
@@ -65,6 +64,7 @@ class Pathod(tcp.TCPServer):
def __init__(self, addr, ssloptions=None, prefix="/p/", staticdir=None, anchors=None):
tcp.TCPServer.__init__(self, addr)
self.ssloptions = ssloptions
+ self.staticdir = staticdir
self.prefix = prefix
self.app = app.app
self.app.config["pathod"] = self
@@ -73,7 +73,9 @@ class Pathod(tcp.TCPServer):
@property
def request_settings(self):
- return {}
+ return dict(
+ staticdir = self.staticdir
+ )
def handle_connection(self, request, client_address):
PathodHandler(request, client_address, self)
diff --git a/libpathod/rparse.py b/libpathod/rparse.py
index 92d0a54b..8a407388 100644
--- a/libpathod/rparse.py
+++ b/libpathod/rparse.py
@@ -2,8 +2,6 @@ import operator, string, random, mmap, os, time
import contrib.pyparsing as pp
from netlib import http_status
-TESTING = False
-
class ParseException(Exception):
def __init__(self, msg, s, col):
Exception.__init__(self)
diff --git a/test/test_test.py b/test/test_test.py
index 36d77fd5..7053bd73 100644
--- a/test/test_test.py
+++ b/test/test_test.py
@@ -44,12 +44,28 @@ class TestDaemon:
def tearDownAll(self):
self.d.shutdown()
+ def setUp(self):
+ self.d.clear_log()
+
+ def get(self, spec):
+ return requests.get("http://localhost:%s/p/%s"%(self.d.port, spec))
+
def test_info(self):
assert tuple(self.d.info()["version"]) == version.IVERSION
def test_logs(self):
- rsp = requests.get("http://localhost:%s/p/202"%self.d.port)
+ rsp = self.get("202")
assert len(self.d.log()) == 1
assert self.d.clear_log()
assert len(self.d.log()) == 0
+ def test_disconnect(self):
+ rsp = self.get("202:b@100k:d200")
+ assert len(rsp.content) < 200
+
+ def test_parserr(self):
+ rsp = self.get("400:msg,b:")
+ assert rsp.status_code == 800
+
+
+
--
cgit v1.2.3
From 877b5a2d116c1ee0a8eb26191a65ff87f7146ae0 Mon Sep 17 00:00:00 2001
From: Aldo Cortesi
Date: Sun, 24 Jun 2012 15:12:31 +1200
Subject: Add staticdir to test.Test.
---
libpathod/test.py | 13 ++++++++-----
test/data/file | 1 +
test/test_test.py | 7 ++++++-
3 files changed, 15 insertions(+), 6 deletions(-)
create mode 100644 test/data/file
diff --git a/libpathod/test.py b/libpathod/test.py
index 943fe3c0..cb1b9745 100644
--- a/libpathod/test.py
+++ b/libpathod/test.py
@@ -8,7 +8,7 @@ IFACE = "127.0.0.1"
class Daemon:
def __init__(self, staticdir=None, anchors=(), ssl=None):
self.q = Queue.Queue()
- self.thread = PaThread(self.q, ssl)
+ self.thread = PaThread(self.q, ssl, staticdir)
self.thread.start()
self.port = self.q.get(True, 5)
self.urlbase = "%s://%s:%s"%("https" if ssl else "http", IFACE, self.port)
@@ -43,9 +43,9 @@ class Daemon:
class PaThread(threading.Thread):
- def __init__(self, q, ssl):
+ def __init__(self, q, ssl, staticdir):
threading.Thread.__init__(self)
- self.q, self.ssl = q, ssl
+ self.q, self.ssl, self.staticdir = q, ssl, staticdir
self.port = None
def run(self):
@@ -56,7 +56,10 @@ class PaThread(threading.Thread):
)
else:
ssloptions = self.ssl
- self.server = pathod.Pathod((IFACE, 0), ssloptions=ssloptions)
- #self.server, self.port = pathod.make_server(self.app, 0, IFACE, ssloptions)
+ self.server = pathod.Pathod(
+ (IFACE, 0),
+ ssloptions = ssloptions,
+ staticdir = self.staticdir
+ )
self.q.put(self.server.port)
self.server.serve_forever()
diff --git a/test/data/file b/test/data/file
new file mode 100644
index 00000000..26918572
--- /dev/null
+++ b/test/data/file
@@ -0,0 +1 @@
+testfile
diff --git a/test/test_test.py b/test/test_test.py
index 7053bd73..b9a9cfac 100644
--- a/test/test_test.py
+++ b/test/test_test.py
@@ -38,7 +38,7 @@ class TestDaemonManual:
class TestDaemon:
@classmethod
def setUpAll(self):
- self.d = test.Daemon()
+ self.d = test.Daemon(staticdir=tutils.test_data.path("data"))
@classmethod
def tearDownAll(self):
@@ -67,5 +67,10 @@ class TestDaemon:
rsp = self.get("400:msg,b:")
assert rsp.status_code == 800
+ def test_static(self):
+ rsp = self.get("200:b
Date: Sun, 24 Jun 2012 16:20:50 +1200
Subject: Re-enable anchors.
---
libpathod/pathod.py | 31 ++++++++++++++++++++++++++-----
libpathod/test.py | 8 ++++----
test/test_pathod.py | 6 +++++-
test/test_test.py | 12 ++++++++++--
4 files changed, 45 insertions(+), 12 deletions(-)
diff --git a/libpathod/pathod.py b/libpathod/pathod.py
index ef37d5ad..1491072c 100644
--- a/libpathod/pathod.py
+++ b/libpathod/pathod.py
@@ -1,4 +1,4 @@
-import urllib, threading
+import urllib, threading, re
from netlib import tcp, http, odict, wsgi
import version, app, rparse
@@ -23,16 +23,23 @@ class PathodHandler(tcp.BaseHandler):
self.rfile, self.wfile, headers, httpversion, None
)
- if path.startswith(self.server.prefix):
+ crafted = None
+ for i in self.server.anchors:
+ if i[0].match(path):
+ crafted = i[1]
+
+ if not crafted and path.startswith(self.server.prefix):
spec = urllib.unquote(path)[len(self.server.prefix):]
try:
- presp = rparse.parse(self.server.request_settings, spec)
+ crafted = rparse.parse(self.server.request_settings, spec)
except rparse.ParseException, v:
- presp = rparse.InternalResponse(
+ crafted = rparse.InternalResponse(
800,
"Error parsing response spec: %s\n"%v.msg + v.marked()
)
- ret = presp.serve(self.wfile)
+
+ if crafted:
+ ret = crafted.serve(self.wfile)
if ret["disconnect"]:
self.finish()
ret["request"] = dict(
@@ -62,6 +69,14 @@ class PathodHandler(tcp.BaseHandler):
class Pathod(tcp.TCPServer):
LOGBUF = 500
def __init__(self, addr, ssloptions=None, prefix="/p/", staticdir=None, anchors=None):
+ """
+ addr: (address, port) tuple. If port is 0, a free port will be
+ automatically chosen.
+ ssloptions: a dictionary containing certfile and keyfile specifications.
+ prefix: string specifying the prefix at which to anchor response generation.
+ staticdir: path to a directory of static resources, or None.
+ anchors: A list of (regex, spec) tuples, or None.
+ """
tcp.TCPServer.__init__(self, addr)
self.ssloptions = ssloptions
self.staticdir = staticdir
@@ -70,6 +85,12 @@ class Pathod(tcp.TCPServer):
self.app.config["pathod"] = self
self.log = []
self.logid = 0
+ self.anchors = []
+ if anchors:
+ for i in anchors:
+ arex = re.compile(i[0])
+ aresp = rparse.parse(self.request_settings, i[1])
+ self.anchors.append((arex, aresp))
@property
def request_settings(self):
diff --git a/libpathod/test.py b/libpathod/test.py
index cb1b9745..00e03823 100644
--- a/libpathod/test.py
+++ b/libpathod/test.py
@@ -8,7 +8,7 @@ IFACE = "127.0.0.1"
class Daemon:
def __init__(self, staticdir=None, anchors=(), ssl=None):
self.q = Queue.Queue()
- self.thread = PaThread(self.q, ssl, staticdir)
+ self.thread = PaThread(self.q, staticdir, anchors, ssl)
self.thread.start()
self.port = self.q.get(True, 5)
self.urlbase = "%s://%s:%s"%("https" if ssl else "http", IFACE, self.port)
@@ -43,10 +43,9 @@ class Daemon:
class PaThread(threading.Thread):
- def __init__(self, q, ssl, staticdir):
+ def __init__(self, q, staticdir, anchors, ssl):
threading.Thread.__init__(self)
- self.q, self.ssl, self.staticdir = q, ssl, staticdir
- self.port = None
+ self.q, self.staticdir, self.anchors, self.ssl = q, staticdir, anchors, ssl
def run(self):
if self.ssl is True:
@@ -59,6 +58,7 @@ class PaThread(threading.Thread):
self.server = pathod.Pathod(
(IFACE, 0),
ssloptions = ssloptions,
+ anchors = self.anchors,
staticdir = self.staticdir
)
self.q.put(self.server.port)
diff --git a/test/test_pathod.py b/test/test_pathod.py
index 966ae12e..e00694cd 100644
--- a/test/test_pathod.py
+++ b/test/test_pathod.py
@@ -15,7 +15,11 @@ class _TestApplication:
class TestPathod:
def test_instantiation(self):
- p = pathod.Pathod(("127.0.0.1", 0))
+ p = pathod.Pathod(
+ ("127.0.0.1", 0),
+ anchors = [(".*", "200")]
+ )
+ assert p.anchors
def test_logging(self):
p = pathod.Pathod(("127.0.0.1", 0))
diff --git a/test/test_test.py b/test/test_test.py
index b9a9cfac..dcf980bc 100644
--- a/test/test_test.py
+++ b/test/test_test.py
@@ -38,7 +38,10 @@ class TestDaemonManual:
class TestDaemon:
@classmethod
def setUpAll(self):
- self.d = test.Daemon(staticdir=tutils.test_data.path("data"))
+ self.d = test.Daemon(
+ staticdir=tutils.test_data.path("data"),
+ anchors=[("/anchor/.*", "202")]
+ )
@classmethod
def tearDownAll(self):
@@ -47,6 +50,9 @@ class TestDaemon:
def setUp(self):
self.d.clear_log()
+ def getpath(self, path):
+ return requests.get("http://localhost:%s/%s"%(self.d.port, path))
+
def get(self, spec):
return requests.get("http://localhost:%s/p/%s"%(self.d.port, spec))
@@ -72,5 +78,7 @@ class TestDaemon:
assert rsp.status_code == 200
assert rsp.content.strip() == "testfile"
-
+ def test_anchor(self):
+ rsp = self.getpath("anchor/foo")
+ assert rsp.status_code == 202
--
cgit v1.2.3
From 4fc64ac04ffbec8e3a51ea3f7a129f17530ee3ef Mon Sep 17 00:00:00 2001
From: Aldo Cortesi
Date: Sun, 24 Jun 2012 16:38:32 +1200
Subject: Enable anchors on command line.
---
doc-src/pathod.html | 2 +-
libpathod/pathod.py | 14 +++++++++++---
libpathod/utils.py | 21 ++++-----------------
pathod | 24 +++++++++++++++++-------
test/test_pathod.py | 3 +++
test/test_utils.py | 6 ++----
6 files changed, 38 insertions(+), 32 deletions(-)
diff --git a/doc-src/pathod.html b/doc-src/pathod.html
index 6cb28734..31fd0bbe 100644
--- a/doc-src/pathod.html
+++ b/doc-src/pathod.html
@@ -17,7 +17,7 @@ case just a vanilla 200 OK response. See the docs below to get (much) fancier.
You can also add anchors to the __pathod__ server that serve a fixed response
whenever a matching URL is requested:
- pathod --anchor "/foo=200"
+ pathod -a "/foo=200"
Here, "/foo" a regex specifying the anchor path, and the part after the "=" is
a response specifier.
diff --git a/libpathod/pathod.py b/libpathod/pathod.py
index 1491072c..ba537768 100644
--- a/libpathod/pathod.py
+++ b/libpathod/pathod.py
@@ -2,6 +2,8 @@ import urllib, threading, re
from netlib import tcp, http, odict, wsgi
import version, app, rparse
+class PathodError(Exception): pass
+
class PathodHandler(tcp.BaseHandler):
def handle(self):
@@ -73,7 +75,7 @@ class Pathod(tcp.TCPServer):
addr: (address, port) tuple. If port is 0, a free port will be
automatically chosen.
ssloptions: a dictionary containing certfile and keyfile specifications.
- prefix: string specifying the prefix at which to anchor response generation.
+ prefix: string specifying the prefix at which to anchor response generation.
staticdir: path to a directory of static resources, or None.
anchors: A list of (regex, spec) tuples, or None.
"""
@@ -88,8 +90,14 @@ class Pathod(tcp.TCPServer):
self.anchors = []
if anchors:
for i in anchors:
- arex = re.compile(i[0])
- aresp = rparse.parse(self.request_settings, i[1])
+ try:
+ arex = re.compile(i[0])
+ except re.error:
+ raise PathodError("Invalid regex in anchor: %s"%i[0])
+ try:
+ aresp = rparse.parse(self.request_settings, i[1])
+ except rparse.ParseException, v:
+ raise PathodError("Invalid page spec in anchor: '%s', %s"%(i[1], str(v)))
self.anchors.append((arex, aresp))
@property
diff --git a/libpathod/utils.py b/libpathod/utils.py
index f421b8a6..39732849 100644
--- a/libpathod/utils.py
+++ b/libpathod/utils.py
@@ -1,27 +1,14 @@
import os, re
import rparse
-class AnchorError(Exception): pass
-
-def parse_anchor_spec(s, settings):
+def parse_anchor_spec(s):
"""
- For now, this is very simple, and you can't have an '=' in your regular
- expression.
+ Return a tuple, or None on error.
"""
if not "=" in s:
- raise AnchorError("Invalid anchor definition: %s"%s)
- rex, spec = s.split("=", 1)
- try:
- re.compile(rex)
- except re.error:
- raise AnchorError("Invalid regex in anchor: %s"%s)
- try:
- rparse.parse(settings, spec)
- except rparse.ParseException, v:
- raise AnchorError("Invalid page spec in anchor: '%s', %s"%(s, str(v)))
-
- return rex, spec
+ return None
+ return tuple(s.split("=", 1))
class Data:
diff --git a/pathod b/pathod
index 6b5f6d96..3c8cc08d 100755
--- a/pathod
+++ b/pathod
@@ -7,7 +7,7 @@ if __name__ == "__main__":
parser.add_argument("-p", dest='port', default=9999, type=int, help='Port. Specify 0 to pick an arbitrary empty port.')
parser.add_argument("-l", dest='address', default="0.0.0.0", type=str, help='Listening address.')
parser.add_argument(
- "-a", dest='anchors', default=[], type=str, action="append",
+ "-a", dest='anchors', default=[], type=str, action="append", metavar="ANCHOR",
help='Add an anchor. Specified as a string with the form pattern=pagespec'
)
parser.add_argument(
@@ -43,12 +43,22 @@ if __name__ == "__main__":
else:
ssl = None
- pd = pathod.Pathod(
- (args.address, args.port),
- ssloptions = ssl,
- staticdir = args.staticdir,
- anchors = args.anchors
- )
+ alst = []
+ for i in args.anchors:
+ parts = utils.parse_anchor_spec(i)
+ if not parts:
+ parser.error("Invalid anchor specification: %s"%i)
+ alst.append(parts)
+
+ try:
+ pd = pathod.Pathod(
+ (args.address, args.port),
+ ssloptions = ssl,
+ staticdir = args.staticdir,
+ anchors = alst
+ )
+ except pathod.PathodError, v:
+ parser.error(str(v))
try:
print "%s listening on port %s"%(version.NAMEVERSION, pd.port)
pd.serve_forever()
diff --git a/test/test_pathod.py b/test/test_pathod.py
index e00694cd..4073926f 100644
--- a/test/test_pathod.py
+++ b/test/test_pathod.py
@@ -1,4 +1,5 @@
from libpathod import pathod
+import tutils
class _TestApplication:
def test_anchors(self):
@@ -20,6 +21,8 @@ class TestPathod:
anchors = [(".*", "200")]
)
assert p.anchors
+ tutils.raises("invalid regex", pathod.Pathod, ("127.0.0.1", 0), anchors=[("*", "200")])
+ tutils.raises("invalid page spec", pathod.Pathod, ("127.0.0.1", 0), anchors=[("foo", "bar")])
def test_logging(self):
p = pathod.Pathod(("127.0.0.1", 0))
diff --git a/test/test_utils.py b/test/test_utils.py
index 5cd0fd3d..72c892f0 100644
--- a/test/test_utils.py
+++ b/test/test_utils.py
@@ -3,10 +3,8 @@ import tutils
def test_parse_anchor_spec():
- assert utils.parse_anchor_spec("foo=200", {}) == ("foo", "200")
- tutils.raises(utils.AnchorError, utils.parse_anchor_spec, "foobar", {})
- tutils.raises(utils.AnchorError, utils.parse_anchor_spec, "*=200", {})
- tutils.raises(utils.AnchorError, utils.parse_anchor_spec, "foo=bar", {})
+ assert utils.parse_anchor_spec("foo=200") == ("foo", "200")
+ assert utils.parse_anchor_spec("foo") == None
def test_data_path():
--
cgit v1.2.3
From 05f5e772c3f59c9be40132eb7afd4f049ced140a Mon Sep 17 00:00:00 2001
From: Aldo Cortesi
Date: Sun, 24 Jun 2012 16:47:44 +1200
Subject: Document our use of the 800 response code.
---
doc-src/pathod.html | 21 +++++++++++++++++++--
1 file changed, 19 insertions(+), 2 deletions(-)
diff --git a/doc-src/pathod.html b/doc-src/pathod.html
index 31fd0bbe..b73918a1 100644
--- a/doc-src/pathod.html
+++ b/doc-src/pathod.html
@@ -30,7 +30,9 @@ various other goodies. Try it by visiting the server root:
-# Specifying Responses
+
+
Specifying Responses
+
The general form of a response is as follows:
@@ -284,7 +286,9 @@ Supported data types are:
- bytes
-# API
+
+
API
+
__pathod__ exposes a simple API, intended to make it possible to drive and
inspect the daemon remotely for use in unit testing and the like.
@@ -328,3 +332,16 @@ inspect the daemon remotely for use in unit testing and the like.
+
+
+
Error Responses
+
+
+To let users distinguish crafted responses from internal pathod responses,
+pathod uses the non-standard 800 response code to indicate errors. For example,
+a request to:
+
+ http://localhost:9999/p/foo
+
+... will return an 800 response, because "foo" is not a valid page specifier.
+
--
cgit v1.2.3
From d4ad3f0b2cc5ae878108e13e86679fac2abaedb2 Mon Sep 17 00:00:00 2001
From: Aldo Cortesi
Date: Sun, 24 Jun 2012 17:01:04 +1200
Subject: Refactor to extract ready_actions and write_values.
---
libpathod/pathod.py | 4 +-
libpathod/rparse.py | 95 ++++++++++++++++++++++--------------------
test/test_rparse.py | 116 +++++++++++++++++++++++++---------------------------
3 files changed, 109 insertions(+), 106 deletions(-)
diff --git a/libpathod/pathod.py b/libpathod/pathod.py
index ba537768..c84be420 100644
--- a/libpathod/pathod.py
+++ b/libpathod/pathod.py
@@ -33,7 +33,7 @@ class PathodHandler(tcp.BaseHandler):
if not crafted and path.startswith(self.server.prefix):
spec = urllib.unquote(path)[len(self.server.prefix):]
try:
- crafted = rparse.parse(self.server.request_settings, spec)
+ crafted = rparse.parse_response(self.server.request_settings, spec)
except rparse.ParseException, v:
crafted = rparse.InternalResponse(
800,
@@ -95,7 +95,7 @@ class Pathod(tcp.TCPServer):
except re.error:
raise PathodError("Invalid regex in anchor: %s"%i[0])
try:
- aresp = rparse.parse(self.request_settings, i[1])
+ aresp = rparse.parse_response(self.request_settings, i[1])
except rparse.ParseException, v:
raise PathodError("Invalid page spec in anchor: '%s', %s"%(i[1], str(v)))
self.anchors.append((arex, aresp))
diff --git a/libpathod/rparse.py b/libpathod/rparse.py
index 8a407388..91ba6356 100644
--- a/libpathod/rparse.py
+++ b/libpathod/rparse.py
@@ -2,6 +2,8 @@ import operator, string, random, mmap, os, time
import contrib.pyparsing as pp
from netlib import http_status
+BLOCKSIZE = 1024
+
class ParseException(Exception):
def __init__(self, msg, s, col):
Exception.__init__(self)
@@ -19,6 +21,52 @@ class ParseException(Exception):
class ServerError(Exception): pass
+def ready_actions(l, lst):
+ ret = []
+ for i in lst:
+ itms = list(i)
+ if i[0] == "r":
+ itms[0] = random.randrange(l)
+ if i[0] == "a":
+ itms[0] = l+1
+ ret.append(tuple(itms))
+ ret.sort()
+ return ret
+
+
+def write_values(fp, vals, actions, sofar=0, skip=0, blocksize=BLOCKSIZE):
+ """
+ vals: A list of values, which may be strings or Value objects.
+ actions: A list of (offset, action, arg) tuples. Action may be "pause" or "disconnect".
+
+ Return True if connection should disconnect.
+ """
+ while vals:
+ part = vals.pop()
+ for i in range(skip, len(part), blocksize):
+ d = part[i:i+blocksize]
+ if actions and actions[-1][0] < (sofar + len(d)):
+ p = actions.pop()
+ offset = p[0]-sofar
+ vals.append(part)
+ if p[1] == "pause":
+ fp.write(d[:offset])
+ time.sleep(p[2])
+ return write_values(
+ fp, vals, actions,
+ sofar=sofar+offset,
+ skip=i+offset,
+ blocksize=blocksize
+ )
+ elif p[1] == "disconnect":
+ fp.write(d[:offset])
+ return True
+ fp.write(d)
+ sofar += len(d)
+ skip = 0
+
+
+
DATATYPES = dict(
ascii_letters = string.ascii_letters,
ascii_lowercase = string.ascii_lowercase,
@@ -328,7 +376,6 @@ class Code:
return e.setParseAction(lambda x: klass(*x))
-BLOCKSIZE = 1024
class Response:
comps = (
Body,
@@ -375,46 +422,6 @@ class Response:
l += len(self.body)
return l
- def ready_actions(self, l, lst):
- ret = []
- for i in lst:
- itms = list(i)
- if i[0] == "r":
- itms[0] = random.randrange(l)
- if i[0] == "a":
- itms[0] = l+1
- ret.append(tuple(itms))
- ret.sort()
- return ret
-
- def write_values(self, fp, vals, actions, sofar=0, skip=0, blocksize=BLOCKSIZE):
- """
- Return True if connection should disconnect.
- """
- while vals:
- part = vals.pop()
- for i in range(skip, len(part), blocksize):
- d = part[i:i+blocksize]
- if actions and actions[-1][0] < (sofar + len(d)):
- p = actions.pop()
- offset = p[0]-sofar
- vals.append(part)
- if p[1] == "pause":
- fp.write(d[:offset])
- time.sleep(p[2])
- return self.write_values(
- fp, vals, actions,
- sofar=sofar+offset,
- skip=i+offset,
- blocksize=blocksize
- )
- elif p[1] == "disconnect":
- fp.write(d[:offset])
- return True
- fp.write(d)
- sofar += len(d)
- skip = 0
-
def serve(self, fp):
started = time.time()
if self.body and not self.get_header("Content-Length"):
@@ -443,9 +450,9 @@ class Response:
if self.body:
vals.append(self.body)
vals.reverse()
- actions = self.ready_actions(self.length(), self.actions)
+ actions = ready_actions(self.length(), self.actions)
actions.reverse()
- disconnect = self.write_values(fp, vals, actions[:])
+ disconnect = write_values(fp, vals, actions[:])
duration = time.time() - started
return dict(
disconnect = disconnect,
@@ -498,7 +505,7 @@ class InternalResponse(Response):
return d
-def parse(settings, s):
+def parse_response(settings, s):
try:
return CraftedResponse(settings, s, Response.expr().parseString(s, parseAll=True))
except pp.ParseException, v:
diff --git a/test/test_rparse.py b/test/test_rparse.py
index 0813f22e..727a89f6 100644
--- a/test/test_rparse.py
+++ b/test/test_rparse.py
@@ -137,9 +137,9 @@ class TestMisc:
class TestDisconnects:
- def test_parse(self):
- assert (0, "disconnect") in rparse.parse({}, "400:d0").actions
- assert ("r", "disconnect") in rparse.parse({}, "400:dr").actions
+ def test_parse_response(self):
+ assert (0, "disconnect") in rparse.parse_response({}, "400:d0").actions
+ assert ("r", "disconnect") in rparse.parse_response({}, "400:dr").actions
def test_at(self):
e = rparse.DisconnectAt.expr()
@@ -156,13 +156,13 @@ class TestDisconnects:
class TestShortcuts:
- def test_parse(self):
- assert rparse.parse({}, "400:c'foo'").headers[0][0][:] == "Content-Type"
- assert rparse.parse({}, "400:l'foo'").headers[0][0][:] == "Location"
+ def test_parse_response(self):
+ assert rparse.parse_response({}, "400:c'foo'").headers[0][0][:] == "Content-Type"
+ assert rparse.parse_response({}, "400:l'foo'").headers[0][0][:] == "Location"
class TestPauses:
- def test_parse(self):
+ def test_parse_response(self):
e = rparse.PauseAt.expr()
v = e.parseString("p10,10")[0]
assert v.seconds == 10
@@ -178,109 +178,105 @@ class TestPauses:
assert v.offset == "a"
def test_request(self):
- r = rparse.parse({}, '400:p10,10')
+ r = rparse.parse_response({}, '400:p10,10')
assert r.actions[0] == (10, "pause", 10)
class TestParse:
def test_parse_err(self):
- tutils.raises(rparse.ParseException, rparse.parse, {}, "400:msg,b:")
+ tutils.raises(rparse.ParseException, rparse.parse_response, {}, "400:msg,b:")
try:
- rparse.parse({}, "400'msg':b:")
+ rparse.parse_response({}, "400'msg':b:")
except rparse.ParseException, v:
assert v.marked()
assert str(v)
def test_parse_header(self):
- r = rparse.parse({}, '400:h"foo"="bar"')
+ r = rparse.parse_response({}, '400:h"foo"="bar"')
assert r.get_header("foo") == "bar"
def test_parse_pause_before(self):
- r = rparse.parse({}, "400:p10,0")
+ r = rparse.parse_response({}, "400:p10,0")
assert (0, "pause", 10) in r.actions
def test_parse_pause_after(self):
- r = rparse.parse({}, "400:p10,a")
+ r = rparse.parse_response({}, "400:p10,a")
assert ("a", "pause", 10) in r.actions
def test_parse_pause_random(self):
- r = rparse.parse({}, "400:p10,r")
+ r = rparse.parse_response({}, "400:p10,r")
assert ("r", "pause", 10) in r.actions
def test_parse_stress(self):
- r = rparse.parse({}, "400:b@100g")
+ r = rparse.parse_response({}, "400:b@100g")
assert r.length()
-class TestResponse:
- def dummy_response(self):
- return rparse.parse({}, "400'msg'")
-
- def test_response(self):
- r = rparse.parse({}, "400'msg'")
- assert r.code == 400
- assert r.msg == "msg"
-
- r = rparse.parse({}, "400'msg':b@100b")
- assert r.msg == "msg"
- assert r.body[:]
- assert str(r)
-
- def test_ready_actions(self):
- r = rparse.parse({}, "400'msg'")
-
- x = [(0, 5)]
- assert r.ready_actions(100, x) == x
-
- x = [("r", 5)]
- ret = r.ready_actions(100, x)
- assert 0 <= ret[0][0] < 100
-
- x = [("a", "pause", 5)]
- ret = r.ready_actions(100, x)
- assert ret[0][0] > 100
-
- x = [(1, 5), (0, 5)]
- assert r.ready_actions(100, x) == sorted(x)
-
+class TestWriteValues:
def test_write_values_disconnects(self):
- r = self.dummy_response()
s = cStringIO.StringIO()
tst = "foo"*100
- r.write_values(s, [tst], [(0, "disconnect")], blocksize=5)
+ rparse.write_values(s, [tst], [(0, "disconnect")], blocksize=5)
assert not s.getvalue()
def test_write_values(self):
tst = "foo"*1025
- r = rparse.parse({}, "400'msg'")
-
s = cStringIO.StringIO()
- r.write_values(s, [tst], [])
+ rparse.write_values(s, [tst], [])
assert s.getvalue() == tst
def test_write_values_pauses(self):
tst = "".join(str(i) for i in range(10))
- r = rparse.parse({}, "400'msg'")
-
for i in range(2, 10):
s = cStringIO.StringIO()
- r.write_values(s, [tst], [(2, "pause", 0), (1, "pause", 0)], blocksize=i)
+ rparse.write_values(s, [tst], [(2, "pause", 0), (1, "pause", 0)], blocksize=i)
assert s.getvalue() == tst
for i in range(2, 10):
s = cStringIO.StringIO()
- r.write_values(s, [tst], [(1, "pause", 0)], blocksize=i)
+ rparse.write_values(s, [tst], [(1, "pause", 0)], blocksize=i)
assert s.getvalue() == tst
tst = ["".join(str(i) for i in range(10))]*5
for i in range(2, 10):
s = cStringIO.StringIO()
- r.write_values(s, tst[:], [(1, "pause", 0)], blocksize=i)
+ rparse.write_values(s, tst[:], [(1, "pause", 0)], blocksize=i)
assert s.getvalue() == "".join(tst)
+
+def test_ready_actions():
+ x = [(0, 5)]
+ assert rparse.ready_actions(100, x) == x
+
+ x = [("r", 5)]
+ ret = rparse.ready_actions(100, x)
+ assert 0 <= ret[0][0] < 100
+
+ x = [("a", "pause", 5)]
+ ret = rparse.ready_actions(100, x)
+ assert ret[0][0] > 100
+
+ x = [(1, 5), (0, 5)]
+ assert rparse.ready_actions(100, x) == sorted(x)
+
+
+class TestResponse:
+ def dummy_response(self):
+ return rparse.parse_response({}, "400'msg'")
+
+ def test_response(self):
+ r = rparse.parse_response({}, "400'msg'")
+ assert r.code == 400
+ assert r.msg == "msg"
+
+ r = rparse.parse_response({}, "400'msg':b@100b")
+ assert r.msg == "msg"
+ assert r.body[:]
+ assert str(r)
+
def test_render(self):
s = cStringIO.StringIO()
- r = rparse.parse({}, "400'msg'")
+ r = rparse.parse_response({}, "400'msg'")
assert r.serve(s)
def test_length(self):
@@ -288,6 +284,6 @@ class TestResponse:
s = cStringIO.StringIO()
x.serve(s)
assert x.length() == len(s.getvalue())
- testlen(rparse.parse({}, "400'msg'"))
- testlen(rparse.parse({}, "400'msg':h'foo'='bar'"))
- testlen(rparse.parse({}, "400'msg':h'foo'='bar':b@100b"))
+ testlen(rparse.parse_response({}, "400'msg'"))
+ testlen(rparse.parse_response({}, "400'msg':h'foo'='bar'"))
+ testlen(rparse.parse_response({}, "400'msg':h'foo'='bar':b@100b"))
--
cgit v1.2.3
From 75f06d56cd87c9458a758277bdc1905d0637a532 Mon Sep 17 00:00:00 2001
From: Aldo Cortesi
Date: Sun, 24 Jun 2012 17:23:37 +1200
Subject: Request method parsing.
---
libpathod/rparse.py | 56 ++++++++++++++++++++++++++++++++++++++++-------------
test/test_rparse.py | 6 ++++++
2 files changed, 49 insertions(+), 13 deletions(-)
diff --git a/libpathod/rparse.py b/libpathod/rparse.py
index 91ba6356..3824406d 100644
--- a/libpathod/rparse.py
+++ b/libpathod/rparse.py
@@ -21,14 +21,14 @@ class ParseException(Exception):
class ServerError(Exception): pass
-def ready_actions(l, lst):
+def ready_actions(length, lst):
ret = []
for i in lst:
itms = list(i)
if i[0] == "r":
- itms[0] = random.randrange(l)
+ itms[0] = random.randrange(length)
if i[0] == "a":
- itms[0] = l+1
+ itms[0] = length+1
ret.append(tuple(itms))
ret.sort()
return ret
@@ -66,7 +66,6 @@ def write_values(fp, vals, actions, sofar=0, skip=0, blocksize=BLOCKSIZE):
skip = 0
-
DATATYPES = dict(
ascii_letters = string.ascii_letters,
ascii_lowercase = string.ascii_lowercase,
@@ -241,7 +240,7 @@ class ShortcutContentType:
def __init__(self, value):
self.value = value
- def mod_response(self, settings, r):
+ def accept(self, settings, r):
r.headers.append(
(
LiteralGenerator("Content-Type"),
@@ -261,7 +260,7 @@ class ShortcutLocation:
def __init__(self, value):
self.value = value
- def mod_response(self, settings, r):
+ def accept(self, settings, r):
r.headers.append(
(
LiteralGenerator("Location"),
@@ -280,7 +279,7 @@ class Body:
def __init__(self, value):
self.value = value
- def mod_response(self, settings, r):
+ def accept(self, settings, r):
r.body = self.value.get_generator(settings)
@classmethod
@@ -290,6 +289,37 @@ class Body:
return e.setParseAction(lambda x: klass(*x))
+class Method:
+ methods = [
+ "get",
+ "head",
+ "post",
+ "put",
+ "delete",
+ "options",
+ "trace",
+ "connect",
+ ]
+ def __init__(self, value):
+ # If it's a string, we were passed one of the methods, so we upper-case
+ # it to be canonical. The user can specify a different case by using a
+ # string value literal.
+ if isinstance(value, basestring):
+ value = value.upper()
+ self.value = value
+
+ def accept(self, settings, r):
+ r.method = self.value.get_generator(settings)
+
+ @classmethod
+ def expr(klass):
+ parts = [pp.CaselessLiteral(i) for i in klass.methods]
+ m = pp.MatchFirst(parts)
+ spec = m | Value.copy()
+ spec = spec.setParseAction(lambda x: klass(*x))
+ return spec
+
+
class PauseAt:
def __init__(self, seconds, offset):
self.seconds, self.offset = seconds, offset
@@ -297,7 +327,7 @@ class PauseAt:
@classmethod
def expr(klass):
e = pp.Literal("p").suppress()
- e +=pp.MatchFirst(
+ e += pp.MatchFirst(
[
v_integer,
pp.Literal("f")
@@ -313,7 +343,7 @@ class PauseAt:
)
return e.setParseAction(lambda x: klass(*x))
- def mod_response(self, settings, r):
+ def accept(self, settings, r):
r.actions.append((self.offset, "pause", self.seconds))
@@ -321,7 +351,7 @@ class DisconnectAt:
def __init__(self, value):
self.value = value
- def mod_response(self, settings, r):
+ def accept(self, settings, r):
r.actions.append((self.value, "disconnect"))
@classmethod
@@ -340,7 +370,7 @@ class Header:
def __init__(self, key, value):
self.key, self.value = key, value
- def mod_response(self, settings, r):
+ def accept(self, settings, r):
r.headers.append(
(
self.key.get_generator(settings),
@@ -363,7 +393,7 @@ class Code:
if msg is None:
self.msg = ValueLiteral(http_status.RESPONSES.get(self.code, "Unknown code"))
- def mod_response(self, settings, r):
+ def accept(self, settings, r):
r.code = self.code
r.msg = self.msg.get_generator(settings)
@@ -474,7 +504,7 @@ class CraftedResponse(Response):
Response.__init__(self)
self.spec, self.tokens = spec, tokens
for i in tokens:
- i.mod_response(settings, self)
+ i.accept(settings, self)
def serve(self, fp):
d = Response.serve(self, fp)
diff --git a/test/test_rparse.py b/test/test_rparse.py
index 727a89f6..2b8543a2 100644
--- a/test/test_rparse.py
+++ b/test/test_rparse.py
@@ -88,6 +88,12 @@ class TestMisc:
assert rparse.Value.parseString('"val"')[0].val == "val"
assert rparse.Value.parseString('"\'val\'"')[0].val == "'val'"
+ def test_method(self):
+ e = rparse.Method.expr()
+ assert e.parseString("get")[0].value == "GET"
+ assert e.parseString("'foo'")[0].value.val == "foo"
+ assert e.parseString("'get'")[0].value.val == "get"
+
def test_body(self):
e = rparse.Body.expr()
v = e.parseString("b'foo'")[0]
--
cgit v1.2.3
From f8622ea914b506013625c539388349d53b4a7e58 Mon Sep 17 00:00:00 2001
From: Aldo Cortesi
Date: Sun, 24 Jun 2012 17:47:55 +1200
Subject: Simple request spec parsing.
---
libpathod/rparse.py | 58 +++++++++++++++++++++++++++++++++++++++++++++--------
libpathod/utils.py | 9 +++++++++
test/test_rparse.py | 10 +++++++--
3 files changed, 67 insertions(+), 10 deletions(-)
diff --git a/libpathod/rparse.py b/libpathod/rparse.py
index 3824406d..50ae9804 100644
--- a/libpathod/rparse.py
+++ b/libpathod/rparse.py
@@ -1,6 +1,7 @@
import operator, string, random, mmap, os, time
import contrib.pyparsing as pp
from netlib import http_status
+import utils
BLOCKSIZE = 1024
@@ -305,7 +306,7 @@ class Method:
# it to be canonical. The user can specify a different case by using a
# string value literal.
if isinstance(value, basestring):
- value = value.upper()
+ value = ValueLiteral(value.upper())
self.value = value
def accept(self, settings, r):
@@ -406,6 +407,46 @@ class Code:
return e.setParseAction(lambda x: klass(*x))
+class Request:
+ comps = (
+ Body,
+ Header,
+ PauseAt,
+ DisconnectAt,
+ ShortcutContentType,
+ )
+ version = "HTTP/1.1"
+ body = LiteralGenerator("")
+ def __init__(self):
+ self.headers = []
+ self.actions = []
+
+ @classmethod
+ def expr(klass):
+ parts = [i.expr() for i in klass.comps]
+ atom = pp.MatchFirst(parts)
+ resp = pp.And(
+ [
+ Method.expr(),
+ pp.ZeroOrMore(pp.Literal(":").suppress() + atom)
+ ]
+ )
+ return resp
+
+
+class CraftedRequest(Request):
+ def __init__(self, settings, spec, tokens):
+ Request.__init__(self)
+ self.spec, self.tokens = spec, tokens
+ for i in tokens:
+ i.accept(settings, self)
+
+ def serve(self, fp):
+ d = Request.serve(self, fp)
+ d["spec"] = self.spec
+ return d
+
+
class Response:
comps = (
Body,
@@ -423,12 +464,6 @@ class Response:
self.headers = []
self.actions = []
- def get_header(self, hdr):
- for k, v in self.headers:
- if k[:len(hdr)].lower() == hdr:
- return v
- return None
-
@classmethod
def expr(klass):
parts = [i.expr() for i in klass.comps]
@@ -454,7 +489,7 @@ class Response:
def serve(self, fp):
started = time.time()
- if self.body and not self.get_header("Content-Length"):
+ if self.body and not utils.get_header("Content-Length", self.headers):
self.headers.append(
(
LiteralGenerator("Content-Length"),
@@ -540,3 +575,10 @@ def parse_response(settings, s):
return CraftedResponse(settings, s, Response.expr().parseString(s, parseAll=True))
except pp.ParseException, v:
raise ParseException(v.msg, v.line, v.col)
+
+
+def parse_request(settings, s):
+ try:
+ return CraftedRequest(settings, s, Request.expr().parseString(s, parseAll=True))
+ except pp.ParseException, v:
+ raise ParseException(v.msg, v.line, v.col)
diff --git a/libpathod/utils.py b/libpathod/utils.py
index 39732849..c656a0d0 100644
--- a/libpathod/utils.py
+++ b/libpathod/utils.py
@@ -1,6 +1,15 @@
import os, re
import rparse
+def get_header(val, headers):
+ """
+ Header keys may be Values, so we have to "generate" them as we try the match.
+ """
+ for k, v in headers:
+ if len(k) == len(val) and k[:].lower() == val:
+ return v
+ return None
+
def parse_anchor_spec(s):
"""
diff --git a/test/test_rparse.py b/test/test_rparse.py
index 2b8543a2..2a76c3e8 100644
--- a/test/test_rparse.py
+++ b/test/test_rparse.py
@@ -188,7 +188,13 @@ class TestPauses:
assert r.actions[0] == (10, "pause", 10)
-class TestParse:
+class TestParseRequest:
+ def test_simple(self):
+ r = rparse.parse_request({}, "GET")
+ assert r.method == "GET"
+
+
+class TestParseResponse:
def test_parse_err(self):
tutils.raises(rparse.ParseException, rparse.parse_response, {}, "400:msg,b:")
try:
@@ -199,7 +205,7 @@ class TestParse:
def test_parse_header(self):
r = rparse.parse_response({}, '400:h"foo"="bar"')
- assert r.get_header("foo") == "bar"
+ assert utils.get_header("foo", r.headers)
def test_parse_pause_before(self):
r = rparse.parse_response({}, "400:p10,0")
--
cgit v1.2.3
From 2ac84be7cb0e4a17fd39c6155074a37161662593 Mon Sep 17 00:00:00 2001
From: Aldo Cortesi
Date: Sun, 24 Jun 2012 18:38:22 +1200
Subject: Add Path specification to request parser.
---
doc-src/pathoc.html | 4 ++--
libpathod/rparse.py | 20 +++++++++++++++++++-
test/test_rparse.py | 12 ++++++++++--
3 files changed, 31 insertions(+), 5 deletions(-)
diff --git a/doc-src/pathoc.html b/doc-src/pathoc.html
index 6f25e19d..a330343a 100644
--- a/doc-src/pathoc.html
+++ b/doc-src/pathoc.html
@@ -5,6 +5,6 @@
-At __pathod__'s heart is a small, terse language for crafting HTTP responses,
+At pathod's heart is a small, terse language for crafting HTTP responses,
designed to be easy to specify in a request URL. The simplest way to use
-__pathod__ is to fire up the daemon, and specify the response behaviour you
+pathod is to fire up the daemon, and specify the response behaviour you
want using this language in the request URL. Here's a minimal example:
http://localhost:9999/p/200
Everything after the "/p/" path component is a response specifier - in this
case just a vanilla 200 OK response. See the docs below to get (much) fancier.
-You can also add anchors to the __pathod__ server that serve a fixed response
+You can also add anchors to the pathod server that serve a fixed response
whenever a matching URL is requested:
pathod -a "/foo=200"
@@ -22,7 +22,7 @@ whenever a matching URL is requested:
Here, "/foo" a regex specifying the anchor path, and the part after the "=" is
a response specifier.
-__pathod__ also has a nifty built-in web interface, which lets you play with
+pathod also has a nifty built-in web interface, which lets you play with
the language by previewing responses, exposes activity logs, online help and
various other goodies. Try it by visiting the server root:
@@ -44,17 +44,17 @@ OK message with no headers and no content:
200
We can embellish this a bit by specifying an optional custom HTTP response
-message (if we don't, __pathod__ automatically creates an appropriate one). By
+message (if we don't, pathod automatically creates an appropriate one). By
default for a 200 response code the message is "OK", but we can change it like
this:
200"YAY"
The quoted string here is an example of a Value
-Specifier, a syntax that is used throughout the __pathod__ response
+Specifier, a syntax that is used throughout the pathod response
specification language. In this case, the quotes mean we're specifying a
literal string, but there are many other fun things we can do. For example, we
-can tell __pathod__ to generate 100k of random ASCII letters instead:
+can tell pathod to generate 100k of random ASCII letters instead:
200@100k,ascii_letters
@@ -83,14 +83,14 @@ shortcut for the content-type header is "c":
That's it for the basic response definition. Now we can start mucking with the
responses to break clients. One common hard-to-test circumstance is hangs or
-slow responses. __pathod__ has a pause operator that you can use to define
+slow responses. pathod has a pause operator that you can use to define
precisely when and how long the server should hang. Here, for instance, we hang
for 120 seconds after sending 50 bytes (counted from the first byte of the HTTP
response):
200:b@1m:p120,50
-If that's not long enough, we can tell __pathod__ to hang forever:
+If that's not long enough, we can tell pathod to hang forever:
200:b@1m:p120,f
@@ -98,12 +98,12 @@ Or to send all data, and then hang without disconnecting:
200:b@1m:p120,a
-We can also ask __pathod__ to hang randomly:
+We can also ask pathod to hang randomly:
200:b@1m:pr,a
There is a similar mechanism for dropping connections mid-response. So, we can
-tell __pathod__ to disconnect after sending 50 bytes:
+tell pathod to disconnect after sending 50 bytes:
200:b@1m:d50
@@ -136,7 +136,7 @@ once at 10 bytes and once at 20, then disconnects at 5000:
Set the body. VALUE is a Value
- Specifier. When the body is set, __pathod__ will
+ Specifier. When the body is set, pathod will
automatically set the appropriate Content-Length header.
@@ -171,7 +171,7 @@ once at 10 bytes and once at 20, then disconnects at 5000:
dOFFSET
- Disconnect after OFFSET bytes. The offset can also be "r", in which case __pathod__
+ Disconnect after OFFSET bytes. The offset can also be "r", in which case pathod
will disconnect at a random point in the response.
@@ -209,7 +209,7 @@ backslashes within the string:
### Files
You can load a value from a specified file path. To do so, you have to specify
-a _staticdir_ option to __pathod__ on the command-line, like so:
+a _staticdir_ option to pathod on the command-line, like so:
pathod -d ~/myassets
@@ -227,7 +227,7 @@ The path value can also be a quoted string, with the same syntax as literals:
An @-symbol lead-in specifies that generated data should be used. There are two
components to a generator specification - a size, and a data type. By default
-__pathod__ assumes a data type of "bytes".
+pathod assumes a data type of "bytes".
Here's a value specifier for generating 100 bytes:
@@ -239,7 +239,7 @@ a specifier for generating 100 megabytes:
@100m
Data is generated and served efficiently - if you really want to send a
-terabyte of data to a client, __pathod__ can do it. The supported suffixes are:
+terabyte of data to a client, pathod can do it. The supported suffixes are:
@@ -290,7 +290,7 @@ Supported data types are:
API
-__pathod__ exposes a simple API, intended to make it possible to drive and
+pathod exposes a simple API, intended to make it possible to drive and
inspect the daemon remotely for use in unit testing and the like.
@@ -321,11 +321,8 @@ inspect the daemon remotely for use in unit testing and the like.
when the log grows larger than this, older entries are discarded. The returned
data is a JSON dictionary, with the form:
-
-
-At pathod's heart is a small, terse language for crafting HTTP responses,
-designed to be easy to specify in a request URL. The simplest way to use
-pathod is to fire up the daemon, and specify the response behaviour you
-want using this language in the request URL. Here's a minimal example:
-
- http://localhost:9999/p/200
-
-Everything after the "/p/" path component is a response specifier - in this
-case just a vanilla 200 OK response. See the docs below to get (much) fancier.
-You can also add anchors to the pathod server that serve a fixed response
-whenever a matching URL is requested:
-
- pathod -a "/foo=200"
-
-Here, "/foo" a regex specifying the anchor path, and the part after the "=" is
-a response specifier.
-
-pathod also has a nifty built-in web interface, which lets you play with
-the language by previewing responses, exposes activity logs, online help and
-various other goodies. Try it by visiting the server root:
-
- http://localhost:9999
-
-
-
-
-
Specifying Responses
-
-
-The general form of a response is as follows:
-
- code[MESSAGE]:[colon-separated list of features]
-
-Here's the simplest possible response specification, returning just an HTTP 200
-OK message with no headers and no content:
-
- 200
-
-We can embellish this a bit by specifying an optional custom HTTP response
-message (if we don't, pathod automatically creates an appropriate one). By
-default for a 200 response code the message is "OK", but we can change it like
-this:
-
- 200"YAY"
-
-The quoted string here is an example of a Value
-Specifier, a syntax that is used throughout the pathod response
-specification language. In this case, the quotes mean we're specifying a
-literal string, but there are many other fun things we can do. For example, we
-can tell pathod to generate 100k of random ASCII letters instead:
-
- 200@100k,ascii_letters
-
-Full documentation on the value specification syntax can be found in the next
-section.
-
-Following the response code specifier is a colon-separated list of features.
-For instance, this specifies a response with a body consisting of 1 megabyte of
-random data:
-
- 200:b@1m
-
-And this is the same response with an ETag header added:
-
- 200:b@1m:h"Etag"="foo"
-
-Both the header name and the header value are full value specifiers. Here's the
-same response again, but with a 1k randomly generated header name:
-
- 200:b@1m:h@1k,ascii_letters="foo"
-
-A few specific headers have shortcuts, because they're used so often. The
-shortcut for the content-type header is "c":
-
- 200:b@1m:c"text/json"
-
-That's it for the basic response definition. Now we can start mucking with the
-responses to break clients. One common hard-to-test circumstance is hangs or
-slow responses. pathod has a pause operator that you can use to define
-precisely when and how long the server should hang. Here, for instance, we hang
-for 120 seconds after sending 50 bytes (counted from the first byte of the HTTP
-response):
-
- 200:b@1m:p120,50
-
-If that's not long enough, we can tell pathod to hang forever:
-
- 200:b@1m:p120,f
-
-Or to send all data, and then hang without disconnecting:
-
- 200:b@1m:p120,a
-
-We can also ask pathod to hang randomly:
-
- 200:b@1m:pr,a
-
-There is a similar mechanism for dropping connections mid-response. So, we can
-tell pathod to disconnect after sending 50 bytes:
-
- 200:b@1m:d50
-
-Or randomly:
-
- 200:b@1m:dr
-
-All of these features can be combined. Here's a response that pauses twice,
-once at 10 bytes and once at 20, then disconnects at 5000:
-
- 200:b@1m:p10,10:p20,10:d5000
-
-
-## Response Features
-
-
- Set the body. VALUE is a Value
- Specifier. When the body is set, pathod will
- automatically set the appropriate Content-Length header.
-
-
-
-
-
- cVALUE
-
-
- A shortcut for setting the Content-Type header. Equivalent to:
-
-
h"Content-Type"=VALUE
-
-
-
-
-
-
- lVALUE
-
-
- A shortcut for setting the Location header. Equivalent to:
-
-
h"Content-Type"=VALUE
-
-
-
-
-
-
-
- dOFFSET
-
-
- Disconnect after OFFSET bytes. The offset can also be "r", in which case pathod
- will disconnect at a random point in the response.
-
-
-
-
-
- pSECONDS,OFFSET
-
-
- Pause for SECONDS seconds after OFFSET bytes. SECONDS can also be "f" to pause
- forever. OFFSET can also be "r" to generate a random offset, or "a" for an
- offset just after all data has been sent.
-
-
-
-
-
-
-## VALUE Specifiers
-
-There are three different flavours of value specification.
-
-### Literal
-
-Literal values are specified as a quoted strings:
-
- "foo"
-
-Either single or double quotes are accepted, and quotes can be escaped with
-backslashes within the string:
-
- 'fo\'o'
-
-
-### Files
-
-You can load a value from a specified file path. To do so, you have to specify
-a _staticdir_ option to pathod on the command-line, like so:
-
- pathod -d ~/myassets
-
-All paths are relative paths under this directory. File loads are indicated by
-starting the value specifier with the left angle bracket:
-
-
-
-
-
b
1024**0 (bytes)
-
-
-
k
1024**1 (kilobytes)
-
-
-
m
1024**2 (megabytes)
-
-
-
g
1024**3 (gigabytes)
-
-
-
t
1024**4 (terabytes)
-
-
-
-
-Data types are separated from the size specification by a comma. This
-specification generates 100mb of ASCII:
-
- @100m,ascii
-
-Supported data types are:
-
-
-- ascii_letters
-- ascii_lowercase
-- ascii_uppercase
-- digits
-- hexdigits
-- letters
-- lowercase
-- octdigits
-- printable
-- punctuation
-- uppercase
-- whitespace
-- ascii
-- bytes
-
-
-
-
API
-
-
-pathod exposes a simple API, intended to make it possible to drive and
-inspect the daemon remotely for use in unit testing and the like.
-
-
-
-
-
-
- /api/clear_log
-
-
- A POST to this URL clears the log buffer.
-
-
-
-
- /api/info
-
-
- Basic version and configuration info.
-
-
-
-
- /api/log
-
-
- Returns the current log buffer. At the moment the buffer size is 500 entries -
- when the log grows larger than this, older entries are discarded. The returned
- data is a JSON dictionary, with the form:
-
-
{ 'log': [ ENTRIES ] }
-
- You can preview the JSON data returned for a log entry through the built-in web
- interface.
-
-
-
-
-
-
-
Error Responses
-
-
-To let users distinguish crafted responses from internal pathod responses,
-pathod uses the non-standard 800 response code to indicate errors. For example,
-a request to:
-
- http://localhost:9999/p/foo
-
-... will return an 800 response, because "foo" is not a valid page specifier.
-
diff --git a/doc-src/start_quote.png b/doc-src/start_quote.png
deleted file mode 100644
index 8090f6e8..00000000
Binary files a/doc-src/start_quote.png and /dev/null differ
diff --git a/doc-src/test.html b/doc-src/test.html
deleted file mode 100644
index 045b1f78..00000000
--- a/doc-src/test.html
+++ /dev/null
@@ -1,6 +0,0 @@
-
-
- libpathod.test
- Using pathod and pathoc in your unit tests.
-
+
+At pathod's heart is a small, terse language for crafting HTTP responses,
+designed to be easy to specify in a request URL. The simplest way to use
+pathod is to fire up the daemon, and specify the response behaviour you
+want using this language in the request URL. Here's a minimal example:
+
+ http://localhost:9999/p/200
+
+Everything after the "/p/" path component is a response specifier - in this
+case just a vanilla 200 OK response. See the docs below to get (much) fancier.
+You can also add anchors to the pathod server that serve a fixed response
+whenever a matching URL is requested:
+
+ pathod -a "/foo=200"
+
+Here, "/foo" a regex specifying the anchor path, and the part after the "=" is
+a response specifier.
+
+pathod also has a nifty built-in web interface, which lets you play with
+the language by previewing responses, exposes activity logs, online help and
+various other goodies. Try it by visiting the server root:
+
+ http://localhost:9999
+
+
+
+
+
Specifying Responses
+
+
+The general form of a response is as follows:
+
+ code[MESSAGE]:[colon-separated list of features]
+
+Here's the simplest possible response specification, returning just an HTTP 200
+OK message with no headers and no content:
+
+ 200
+
+We can embellish this a bit by specifying an optional custom HTTP response
+message (if we don't, pathod automatically creates an appropriate one). By
+default for a 200 response code the message is "OK", but we can change it like
+this:
+
+ 200"YAY"
+
+The quoted string here is an example of a Value
+Specifier, a syntax that is used throughout the pathod response
+specification language. In this case, the quotes mean we're specifying a
+literal string, but there are many other fun things we can do. For example, we
+can tell pathod to generate 100k of random ASCII letters instead:
+
+ 200@100k,ascii_letters
+
+Full documentation on the value specification syntax can be found in the next
+section.
+
+Following the response code specifier is a colon-separated list of features.
+For instance, this specifies a response with a body consisting of 1 megabyte of
+random data:
+
+ 200:b@1m
+
+And this is the same response with an ETag header added:
+
+ 200:b@1m:h"Etag"="foo"
+
+Both the header name and the header value are full value specifiers. Here's the
+same response again, but with a 1k randomly generated header name:
+
+ 200:b@1m:h@1k,ascii_letters="foo"
+
+A few specific headers have shortcuts, because they're used so often. The
+shortcut for the content-type header is "c":
+
+ 200:b@1m:c"text/json"
+
+That's it for the basic response definition. Now we can start mucking with the
+responses to break clients. One common hard-to-test circumstance is hangs or
+slow responses. pathod has a pause operator that you can use to define
+precisely when and how long the server should hang. Here, for instance, we hang
+for 120 seconds after sending 50 bytes (counted from the first byte of the HTTP
+response):
+
+ 200:b@1m:p120,50
+
+If that's not long enough, we can tell pathod to hang forever:
+
+ 200:b@1m:p120,f
+
+Or to send all data, and then hang without disconnecting:
+
+ 200:b@1m:p120,a
+
+We can also ask pathod to hang randomly:
+
+ 200:b@1m:pr,a
+
+There is a similar mechanism for dropping connections mid-response. So, we can
+tell pathod to disconnect after sending 50 bytes:
+
+ 200:b@1m:d50
+
+Or randomly:
+
+ 200:b@1m:dr
+
+All of these features can be combined. Here's a response that pauses twice,
+once at 10 bytes and once at 20, then disconnects at 5000:
+
+ 200:b@1m:p10,10:p20,10:d5000
+
+
+## Response Features
+
+
+ Set the body. VALUE is a Value
+ Specifier. When the body is set, pathod will
+ automatically set the appropriate Content-Length header.
+
+
+
+
+
+ cVALUE
+
+
+ A shortcut for setting the Content-Type header. Equivalent to:
+
+
h"Content-Type"=VALUE
+
+
+
+
+
+
+ lVALUE
+
+
+ A shortcut for setting the Location header. Equivalent to:
+
+
h"Content-Type"=VALUE
+
+
+
+
+
+
+
+ dOFFSET
+
+
+ Disconnect after OFFSET bytes. The offset can also be "r", in which case pathod
+ will disconnect at a random point in the response.
+
+
+
+
+
+ pSECONDS,OFFSET
+
+
+ Pause for SECONDS seconds after OFFSET bytes. SECONDS can also be "f" to pause
+ forever. OFFSET can also be "r" to generate a random offset, or "a" for an
+ offset just after all data has been sent.
+
+
+
+
+
+
+## VALUE Specifiers
+
+There are three different flavours of value specification.
+
+### Literal
+
+Literal values are specified as a quoted strings:
+
+ "foo"
+
+Either single or double quotes are accepted, and quotes can be escaped with
+backslashes within the string:
+
+ 'fo\'o'
+
+
+### Files
+
+You can load a value from a specified file path. To do so, you have to specify
+a _staticdir_ option to pathod on the command-line, like so:
+
+ pathod -d ~/myassets
+
+All paths are relative paths under this directory. File loads are indicated by
+starting the value specifier with the left angle bracket:
+
+
+
+
+
b
1024**0 (bytes)
+
+
+
k
1024**1 (kilobytes)
+
+
+
m
1024**2 (megabytes)
+
+
+
g
1024**3 (gigabytes)
+
+
+
t
1024**4 (terabytes)
+
+
+
+
+Data types are separated from the size specification by a comma. This
+specification generates 100mb of ASCII:
+
+ @100m,ascii
+
+Supported data types are:
+
+
+- ascii_letters
+- ascii_lowercase
+- ascii_uppercase
+- digits
+- hexdigits
+- letters
+- lowercase
+- octdigits
+- printable
+- punctuation
+- uppercase
+- whitespace
+- ascii
+- bytes
+
+
+
+
API
+
+
+pathod exposes a simple API, intended to make it possible to drive and
+inspect the daemon remotely for use in unit testing and the like.
+
+
+
+
+
+
+ /api/clear_log
+
+
+ A POST to this URL clears the log buffer.
+
+
+
+
+ /api/info
+
+
+ Basic version and configuration info.
+
+
+
+
+ /api/log
+
+
+ Returns the current log buffer. At the moment the buffer size is 500 entries -
+ when the log grows larger than this, older entries are discarded. The returned
+ data is a JSON dictionary, with the form:
+
+
{ 'log': [ ENTRIES ] }
+
+ You can preview the JSON data returned for a log entry through the built-in web
+ interface.
+
+
+
+
+
+
+
Error Responses
+
+
+To let users distinguish crafted responses from internal pathod responses,
+pathod uses the non-standard 800 response code to indicate errors. For example,
+a request to:
+
+ http://localhost:9999/p/foo
+
+... will return an 800 response, because "foo" is not a valid page specifier.
+{% endblock %}
diff --git a/libpathod/templates/docs_test.html b/libpathod/templates/docs_test.html
new file mode 100644
index 00000000..27129f1c
--- /dev/null
+++ b/libpathod/templates/docs_test.html
@@ -0,0 +1,9 @@
+{% extends "frame.html" %}
+{% block body %}
+
+
+ libpathod.test
+ Using pathod and pathoc in your unit tests.
+
+
+ Using pathod and pathoc in your unit tests.
+
+
+
+
+
+
{% endblock %}
--
cgit v1.2.3
From 2cb55ee0f5b00c2c3f4f6d9ba9360c31b82b095c Mon Sep 17 00:00:00 2001
From: Aldo Cortesi
Date: Sat, 30 Jun 2012 10:51:13 +1200
Subject: Factor out request printing in to a method, and test it.
---
libpathod/pathoc.py | 28 ++++++++++++++++++++++++----
libpathod/pathod.py | 2 +-
pathoc | 20 ++++++--------------
test/test_pathoc.py | 20 ++++++++++++++++++--
4 files changed, 49 insertions(+), 21 deletions(-)
diff --git a/libpathod/pathoc.py b/libpathod/pathoc.py
index 9320b1c5..3791c116 100644
--- a/libpathod/pathoc.py
+++ b/libpathod/pathoc.py
@@ -1,3 +1,4 @@
+import sys
from netlib import tcp, http
import rparse
@@ -16,16 +17,35 @@ def print_full(fp, httpversion, code, msg, headers, content):
class Pathoc(tcp.TCPClient):
def __init__(self, host, port):
- try:
- tcp.TCPClient.__init__(self, host, port)
- except tcp.NetLibError, v:
- raise PathocError(v)
+ tcp.TCPClient.__init__(self, host, port)
def request(self, spec):
"""
Return an (httpversion, code, msg, headers, content) tuple.
+
+ May raise rparse.ParseException and netlib.http.HttpError.
"""
r = rparse.parse_request({}, spec)
r.serve(self.wfile)
self.wfile.flush()
return http.read_response(self.rfile, r.method, None)
+
+ def print_requests(self, reqs, verbose, fp=sys.stdout):
+ """
+ Performs a series of requests, and prints results to the specified
+ file pointer.
+ """
+ for i in reqs:
+ try:
+ ret = self.request(i)
+ except rparse.ParseException, v:
+ print >> fp, "Error parsing request spec: %s"%v.msg
+ print >> fp, v.marked()
+ return
+ except http.HttpError, v:
+ print >> fp, v.msg
+ return
+ if verbose:
+ print_full(fp, *ret)
+ else:
+ print_short(fp, *ret)
diff --git a/libpathod/pathod.py b/libpathod/pathod.py
index 2d3264f8..50e30c45 100644
--- a/libpathod/pathod.py
+++ b/libpathod/pathod.py
@@ -124,7 +124,7 @@ class Pathod(tcp.TCPServer):
def handle_connection(self, request, client_address):
h = PathodHandler(request, client_address, self)
- h.handle()
+ h.handle()
h.finish()
def add_log(self, d):
diff --git a/pathoc b/pathoc
index 9dc87c03..e5cc9bf4 100755
--- a/pathoc
+++ b/pathoc
@@ -1,6 +1,7 @@
#!/usr/bin/env python
import argparse, sys
from libpathod import pathoc, version, rparse
+from netlib import tcp
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='A perverse HTTP client.')
@@ -18,21 +19,12 @@ if __name__ == "__main__":
else:
port = args.port
+ p = pathoc.Pathoc(args.host, port)
try:
- p = pathoc.Pathoc(args.host, port)
p.connect()
- if args.ssl:
- p.convert_to_ssl(sni=args.sni)
- for i in args.request:
- ret = p.request(i)
- if args.verbose:
- pathoc.print_full(sys.stdout, *ret)
- else:
- pathoc.print_short(sys.stdout, *ret)
- except pathoc.PathocError, v:
+ except tcp.NetLibError, v:
print >> sys.stderr, str(v)
sys.exit(1)
- except rparse.ParseException, v:
- print >> sys.stderr, "Error parsing request spec: %s"%v.msg
- print >> sys.stderr, v.marked()
- sys.exit(1)
+ if args.ssl:
+ p.convert_to_ssl(sni=args.sni)
+ p.print_requests(args.request, args.verbose)
diff --git a/test/test_pathoc.py b/test/test_pathoc.py
index c6128e22..a9c38870 100644
--- a/test/test_pathoc.py
+++ b/test/test_pathoc.py
@@ -1,9 +1,8 @@
-import json
+import json, cStringIO
from libpathod import pathoc, test, version
import tutils
-
class TestDaemon:
@classmethod
def setUpAll(self):
@@ -25,3 +24,20 @@ class TestDaemon:
_, _, _, _, content = c.request("get:/api/info")
assert tuple(json.loads(content)["version"]) == version.IVERSION
+ def tval(self, requests, verbose=False):
+ c = pathoc.Pathoc("127.0.0.1", self.d.port)
+ c.connect()
+ s = cStringIO.StringIO()
+ c.print_requests(requests, verbose, s)
+ return s.getvalue()
+
+ def test_print_requests(self):
+ reqs = [ "get:/api/info", "get:/api/info" ]
+ assert self.tval(reqs, False).count("200") == 2
+ assert self.tval(reqs, True).count("Date") == 2
+
+ def test_parse_err(self):
+ assert "Error parsing" in self.tval(["foo"])
+
+ def test_conn_err(self):
+ assert "Invalid server response" in self.tval(["get:'/p/200:d2'"])
--
cgit v1.2.3
From 1bb93176dafc19fc71fde10174ccb00ce7421cb7 Mon Sep 17 00:00:00 2001
From: Aldo Cortesi
Date: Mon, 9 Jul 2012 11:09:37 +1200
Subject: Handle NetLibDisconnect error.
---
libpathod/rparse.py | 51 +++++++++++++++++++++++++++------------------------
1 file changed, 27 insertions(+), 24 deletions(-)
diff --git a/libpathod/rparse.py b/libpathod/rparse.py
index e08da49f..570ee904 100644
--- a/libpathod/rparse.py
+++ b/libpathod/rparse.py
@@ -1,6 +1,6 @@
import operator, string, random, mmap, os, time
import contrib.pyparsing as pp
-from netlib import http_status
+from netlib import http_status, tcp
import utils
BLOCKSIZE = 1024
@@ -43,29 +43,32 @@ def write_values(fp, vals, actions, sofar=0, skip=0, blocksize=BLOCKSIZE):
Return True if connection should disconnect.
"""
- while vals:
- part = vals.pop()
- for i in range(skip, len(part), blocksize):
- d = part[i:i+blocksize]
- if actions and actions[-1][0] < (sofar + len(d)):
- p = actions.pop()
- offset = p[0]-sofar
- vals.append(part)
- if p[1] == "pause":
- fp.write(d[:offset])
- time.sleep(p[2])
- return write_values(
- fp, vals, actions,
- sofar=sofar+offset,
- skip=i+offset,
- blocksize=blocksize
- )
- elif p[1] == "disconnect":
- fp.write(d[:offset])
- return True
- fp.write(d)
- sofar += len(d)
- skip = 0
+ try:
+ while vals:
+ part = vals.pop()
+ for i in range(skip, len(part), blocksize):
+ d = part[i:i+blocksize]
+ if actions and actions[-1][0] < (sofar + len(d)):
+ p = actions.pop()
+ offset = p[0]-sofar
+ vals.append(part)
+ if p[1] == "pause":
+ fp.write(d[:offset])
+ time.sleep(p[2])
+ return write_values(
+ fp, vals, actions,
+ sofar=sofar+offset,
+ skip=i+offset,
+ blocksize=blocksize
+ )
+ elif p[1] == "disconnect":
+ fp.write(d[:offset])
+ return True
+ fp.write(d)
+ sofar += len(d)
+ skip = 0
+ except tcp.NetLibDisconnect:
+ return True
DATATYPES = dict(
--
cgit v1.2.3
From 76f0c3ea783dbb46540a3b77b13f7700e9639ea4 Mon Sep 17 00:00:00 2001
From: Aldo Cortesi
Date: Fri, 20 Jul 2012 11:40:37 +1200
Subject: Handle invalid first line errors, add an error log buffer type.
---
libpathod/pathod.py | 43 ++++++++++++++++++++++++++++++++-----------
test/test_pathod.py | 13 ++++++++++++-
2 files changed, 44 insertions(+), 12 deletions(-)
diff --git a/libpathod/pathod.py b/libpathod/pathod.py
index 50e30c45..1f4ff760 100644
--- a/libpathod/pathod.py
+++ b/libpathod/pathod.py
@@ -12,6 +12,9 @@ class PathodHandler(tcp.BaseHandler):
def debug(self, s):
logging.debug("%s:%s: %s"%(self.client_address[0], self.client_address[1], str(s)))
+ def info(self, s):
+ logging.info("%s:%s: %s"%(self.client_address[0], self.client_address[1], str(s)))
+
def handle_sni(self, connection):
self.sni = connection.get_servername()
@@ -23,7 +26,7 @@ class PathodHandler(tcp.BaseHandler):
self.server.ssloptions["keyfile"],
)
except tcp.NetLibError, v:
- self.debug(v)
+ self.info(v)
self.finish()
while not self.finished:
@@ -36,7 +39,19 @@ class PathodHandler(tcp.BaseHandler):
if line == "":
return None
- method, path, httpversion = http.parse_init_http(line)
+ parts = http.parse_init_http(line)
+ if not parts:
+ s = "Invalid first line: %s"%line.rstrip()
+ self.info(s)
+ self.server.add_log(
+ dict(
+ type = "error",
+ msg = s
+ )
+ )
+ return None
+ method, path, httpversion = parts
+
headers = http.read_headers(self.rfile)
content = http.read_http_body_request(
self.rfile, self.wfile, headers, httpversion, None
@@ -57,19 +72,25 @@ class PathodHandler(tcp.BaseHandler):
"Error parsing response spec: %s\n"%v.msg + v.marked()
)
+ request_log = dict(
+ path = path,
+ method = method,
+ headers = headers.lst,
+ sni = self.sni,
+ remote_address = self.client_address,
+ httpversion = httpversion,
+ )
if crafted:
response_log = crafted.serve(self.wfile)
if response_log["disconnect"]:
self.finish()
- request_log = dict(
- path = path,
- method = method,
- headers = headers.lst,
- sni = self.sni,
- remote_address = self.client_address,
- httpversion = httpversion,
+ self.server.add_log(
+ dict(
+ type = "crafted",
+ request=request_log,
+ response=response_log
+ )
)
- self.server.add_log(dict(request=request_log, response=response_log))
else:
cc = wsgi.ClientConn(self.client_address)
req = wsgi.Request(cc, "http", method, path, headers, content)
@@ -124,7 +145,7 @@ class Pathod(tcp.TCPServer):
def handle_connection(self, request, client_address):
h = PathodHandler(request, client_address, self)
- h.handle()
+ h.handle()
h.finish()
def add_log(self, d):
diff --git a/test/test_pathod.py b/test/test_pathod.py
index bf15bc23..902074b7 100644
--- a/test/test_pathod.py
+++ b/test/test_pathod.py
@@ -1,5 +1,6 @@
import requests
from libpathod import pathod, test, version
+from netlib import tcp
import tutils
class _TestApplication:
@@ -60,12 +61,22 @@ class TestDaemon:
def get(self, spec):
return requests.get("http://localhost:%s/p/%s"%(self.d.port, spec))
+ def test_invalid_first_line(self):
+ c = tcp.TCPClient("localhost", self.d.port)
+ c.connect()
+ c.wfile.write("foo\n\n\n")
+ c.wfile.flush()
+ l = self.d.log()[0]
+ assert l["type"] == "error"
+ assert "foo" in l["msg"]
+
def test_info(self):
assert tuple(self.d.info()["version"]) == version.IVERSION
def test_logs(self):
+ l = len(self.d.log())
rsp = self.get("202")
- assert len(self.d.log()) == 1
+ assert len(self.d.log()) == l+1
assert self.d.clear_log()
assert len(self.d.log()) == 0
--
cgit v1.2.3
From 03f4dcc02b87db6f881f7d334d64a2bd4dcad04c Mon Sep 17 00:00:00 2001
From: Aldo Cortesi
Date: Fri, 20 Jul 2012 13:21:33 +1200
Subject: Extend test suite to cover SSL. Log SSL connection errors.
---
libpathod/pathod.py | 9 ++++++++-
test/test_pathod.py | 55 ++++++++++++++++++++++++++++++++++++++++-------------
2 files changed, 50 insertions(+), 14 deletions(-)
diff --git a/libpathod/pathod.py b/libpathod/pathod.py
index 1f4ff760..5eb91f7a 100644
--- a/libpathod/pathod.py
+++ b/libpathod/pathod.py
@@ -26,7 +26,14 @@ class PathodHandler(tcp.BaseHandler):
self.server.ssloptions["keyfile"],
)
except tcp.NetLibError, v:
- self.info(v)
+ s = str(v)
+ self.server.add_log(
+ dict(
+ type = "error",
+ msg = s
+ )
+ )
+ self.info(s)
self.finish()
while not self.finished:
diff --git a/test/test_pathod.py b/test/test_pathod.py
index 902074b7..9f01b25c 100644
--- a/test/test_pathod.py
+++ b/test/test_pathod.py
@@ -40,12 +40,13 @@ class TestPathod:
assert len(p.get_log()) <= p.LOGBUF
-class TestDaemon:
+class _DaemonTests:
@classmethod
def setUpAll(self):
self.d = test.Daemon(
staticdir=tutils.test_data.path("data"),
- anchors=[("/anchor/.*", "202")]
+ anchors=[("/anchor/.*", "202")],
+ ssl = self.SSL
)
@classmethod
@@ -56,19 +57,12 @@ class TestDaemon:
self.d.clear_log()
def getpath(self, path):
- return requests.get("http://localhost:%s/%s"%(self.d.port, path))
+ scheme = "https" if self.SSL else "http"
+ return requests.get("%s://localhost:%s/%s"%(scheme, self.d.port, path), verify=False)
def get(self, spec):
- return requests.get("http://localhost:%s/p/%s"%(self.d.port, spec))
-
- def test_invalid_first_line(self):
- c = tcp.TCPClient("localhost", self.d.port)
- c.connect()
- c.wfile.write("foo\n\n\n")
- c.wfile.flush()
- l = self.d.log()[0]
- assert l["type"] == "error"
- assert "foo" in l["msg"]
+ scheme = "https" if self.SSL else "http"
+ return requests.get("%s://localhost:%s/p/%s"%(scheme, self.d.port, spec), verify=False)
def test_info(self):
assert tuple(self.d.info()["version"]) == version.IVERSION
@@ -96,3 +90,38 @@ class TestDaemon:
def test_anchor(self):
rsp = self.getpath("anchor/foo")
assert rsp.status_code == 202
+
+ def test_invalid_first_line(self):
+ c = tcp.TCPClient("localhost", self.d.port)
+ c.connect()
+ if self.SSL:
+ c.convert_to_ssl()
+ c.wfile.write("foo\n\n\n")
+ c.wfile.flush()
+ l = self.d.log()[0]
+ assert l["type"] == "error"
+ assert "foo" in l["msg"]
+
+
+class TestDaemon(_DaemonTests):
+ SSL = False
+
+
+class TestDaemonSSL(_DaemonTests):
+ SSL = True
+ def test_ssl_conn_failure(self):
+ c = tcp.TCPClient("localhost", self.d.port)
+ c.rbufsize = 0
+ c.wbufsize = 0
+ c.connect()
+ try:
+ while 1:
+ c.wfile.write("\r\n\r\n\r\n")
+ except:
+ pass
+ l = self.d.log()[0]
+ assert l["type"] == "error"
+ assert "SSL" in l["msg"]
+
+
+
--
cgit v1.2.3
From 3d9e8b2dbf7057fdcc72c74e1ffa265631750c98 Mon Sep 17 00:00:00 2001
From: Aldo Cortesi
Date: Fri, 20 Jul 2012 15:21:36 +1200
Subject: We shouldn't ever get a socket error emanating from netlib.
---
libpathod/pathod.py | 5 +----
1 file changed, 1 insertion(+), 4 deletions(-)
diff --git a/libpathod/pathod.py b/libpathod/pathod.py
index 5eb91f7a..44bcadb7 100644
--- a/libpathod/pathod.py
+++ b/libpathod/pathod.py
@@ -37,10 +37,7 @@ class PathodHandler(tcp.BaseHandler):
self.finish()
while not self.finished:
- try:
- line = self.rfile.readline()
- except socket.error:
- return None
+ line = self.rfile.readline()
if line == "\r\n" or line == "\n": # Possible leftover from previous message
line = self.rfile.readline()
if line == "":
--
cgit v1.2.3
From 21ef35fd281a3f0783b08276db8407b12f33ae5d Mon Sep 17 00:00:00 2001
From: Aldo Cortesi
Date: Fri, 20 Jul 2012 20:14:35 +1200
Subject: Much simpler rewrite of inner data sending loop.
We don't have to do the asynchronous code contortion anymore.
---
libpathod/rparse.py | 49 ++++++++++++++++++++++++++-----------------------
test/test_rparse.py | 20 +++++++++++++++++++-
2 files changed, 45 insertions(+), 24 deletions(-)
diff --git a/libpathod/rparse.py b/libpathod/rparse.py
index 570ee904..e3136b7b 100644
--- a/libpathod/rparse.py
+++ b/libpathod/rparse.py
@@ -36,37 +36,40 @@ def ready_actions(length, lst):
return ret
+def send_chunk(fp, val, blocksize, start, end):
+ """
+ (start, end): Inclusive lower bound, exclusive upper bound.
+ """
+ for i in range(start, end, blocksize):
+ fp.write(
+ val[i:min(i+blocksize, end)]
+ )
+ return end-start
+
+
def write_values(fp, vals, actions, sofar=0, skip=0, blocksize=BLOCKSIZE):
"""
- vals: A list of values, which may be strings or Value objects.
+ vals: A list of values, which may be strings or Value objects.
actions: A list of (offset, action, arg) tuples. Action may be "pause" or "disconnect".
+ Both vals and actions are in reverse order, with the first items last.
+
Return True if connection should disconnect.
"""
+ sofar = 0
try:
while vals:
- part = vals.pop()
- for i in range(skip, len(part), blocksize):
- d = part[i:i+blocksize]
- if actions and actions[-1][0] < (sofar + len(d)):
- p = actions.pop()
- offset = p[0]-sofar
- vals.append(part)
- if p[1] == "pause":
- fp.write(d[:offset])
- time.sleep(p[2])
- return write_values(
- fp, vals, actions,
- sofar=sofar+offset,
- skip=i+offset,
- blocksize=blocksize
- )
- elif p[1] == "disconnect":
- fp.write(d[:offset])
- return True
- fp.write(d)
- sofar += len(d)
- skip = 0
+ v = vals.pop()
+ offset = 0
+ while actions and actions[-1][0] < (sofar + len(v)):
+ a = actions.pop()
+ offset += send_chunk(fp, v, blocksize, offset, a[0]-sofar-offset)
+ if a[1] == "pause":
+ time.sleep(a[2])
+ elif a[1] == "disconnect":
+ return True
+ send_chunk(fp, v, blocksize, offset, len(v))
+ sofar += len(v)
except tcp.NetLibDisconnect:
return True
diff --git a/test/test_rparse.py b/test/test_rparse.py
index cb1076c2..f4b408b2 100644
--- a/test/test_rparse.py
+++ b/test/test_rparse.py
@@ -250,6 +250,18 @@ class TestParseResponse:
class TestWriteValues:
+ def test_send_chunk(self):
+ v = "foobarfoobar"
+ for bs in range(1, len(v)+2):
+ s = cStringIO.StringIO()
+ rparse.send_chunk(s, v, bs, 0, len(v))
+ assert s.getvalue() == v
+ for start in range(len(v)):
+ for end in range(len(v)):
+ s = cStringIO.StringIO()
+ rparse.send_chunk(s, v, bs, start, end)
+ assert s.getvalue() == v[start:end]
+
def test_write_values_disconnects(self):
s = cStringIO.StringIO()
tst = "foo"*100
@@ -257,11 +269,17 @@ class TestWriteValues:
assert not s.getvalue()
def test_write_values(self):
- tst = "foo"*1025
+ tst = "foobarvoing"
s = cStringIO.StringIO()
rparse.write_values(s, [tst], [])
assert s.getvalue() == tst
+ for bs in range(1, len(tst) + 2):
+ for off in range(len(tst)):
+ s = cStringIO.StringIO()
+ rparse.write_values(s, [tst], [(off, "disconnect")], blocksize=bs)
+ assert s.getvalue() == tst[:off]
+
def test_write_values_pauses(self):
tst = "".join(str(i) for i in range(10))
for i in range(2, 10):
--
cgit v1.2.3
From 2bdbbaa8afb80ff1a59542f011fa87ffdfaf7b16 Mon Sep 17 00:00:00 2001
From: Aldo Cortesi
Date: Fri, 20 Jul 2012 23:19:58 +1200
Subject: Convert documentation to HTML, fix styling.
---
libpathod/static/pathod.css | 19 ++
libpathod/templates/docs_pathod.html | 536 ++++++++++++++++++-----------------
libpathod/templates/frame.html | 1 +
3 files changed, 293 insertions(+), 263 deletions(-)
create mode 100644 libpathod/static/pathod.css
diff --git a/libpathod/static/pathod.css b/libpathod/static/pathod.css
new file mode 100644
index 00000000..3e24dd7d
--- /dev/null
+++ b/libpathod/static/pathod.css
@@ -0,0 +1,19 @@
+
+
+section {
+ margin-top: 50px;
+
+}
+
+.example {
+ margin-top: 10px;
+ margin-bottom: 10px;
+
+}
+
+.terminal {
+ margin-top: 10px;
+ margin-bottom: 10px;
+ background: #000;
+ color: #fff;
+}
diff --git a/libpathod/templates/docs_pathod.html b/libpathod/templates/docs_pathod.html
index f3dabd5e..1527f851 100644
--- a/libpathod/templates/docs_pathod.html
+++ b/libpathod/templates/docs_pathod.html
@@ -1,5 +1,6 @@
{% extends "frame.html" %}
{% block body %}
+
pathod
@@ -7,340 +8,349 @@
-At pathod's heart is a small, terse language for crafting HTTP responses,
+
At pathod's heart is a small, terse language for crafting HTTP responses,
designed to be easy to specify in a request URL. The simplest way to use
pathod is to fire up the daemon, and specify the response behaviour you
-want using this language in the request URL. Here's a minimal example:
+want using this language in the request URL. Here's a minimal example:
- http://localhost:9999/p/200
+
http://localhost:9999/p/200
-Everything after the "/p/" path component is a response specifier - in this
+
Everything after the "/p/" path component is a response specifier - in this
case just a vanilla 200 OK response. See the docs below to get (much) fancier.
You can also add anchors to the pathod server that serve a fixed response
-whenever a matching URL is requested:
+whenever a matching URL is requested:
- pathod -a "/foo=200"
+
pathod -a "/foo=200"
-Here, "/foo" a regex specifying the anchor path, and the part after the "=" is
-a response specifier.
+
Here, "/foo" a regex specifying the anchor path, and the part after the "=" is
+a response specifier.
-pathod also has a nifty built-in web interface, which lets you play with
+
pathod also has a nifty built-in web interface, which lets you play with
the language by previewing responses, exposes activity logs, online help and
-various other goodies. Try it by visiting the server root:
-
- http://localhost:9999
-
+various other goodies. Try it by visiting the server root:
+
http://localhost:9999
-
-
Specifying Responses
-
-
-The general form of a response is as follows:
-
- code[MESSAGE]:[colon-separated list of features]
-Here's the simplest possible response specification, returning just an HTTP 200
-OK message with no headers and no content:
-
- 200
+
-We can embellish this a bit by specifying an optional custom HTTP response
-message (if we don't, pathod automatically creates an appropriate one). By
-default for a 200 response code the message is "OK", but we can change it like
-this:
+
+
Specifying Responses
+
- 200"YAY"
+
The general form of a response is as follows:
+
+
code[MESSAGE]:[colon-separated list of features]
-The quoted string here is an example of a Value
-Specifier, a syntax that is used throughout the pathod response
-specification language. In this case, the quotes mean we're specifying a
-literal string, but there are many other fun things we can do. For example, we
-can tell pathod to generate 100k of random ASCII letters instead:
+
Here's the simplest possible response specification, returning just an HTTP 200
+ OK message with no headers and no content:
+
+
200
- 200@100k,ascii_letters
+
We can embellish this a bit by specifying an optional custom HTTP response
+ message (if we don't, pathod automatically creates an appropriate one). By
+ default for a 200 response code the message is "OK", but we can change it like
+ this:
-Full documentation on the value specification syntax can be found in the next
-section.
-
-Following the response code specifier is a colon-separated list of features.
-For instance, this specifies a response with a body consisting of 1 megabyte of
-random data:
+
200"YAY"
- 200:b@1m
+
The quoted string here is an example of a Value
+ Specifier, a syntax that is used throughout the pathod response
+ specification language. In this case, the quotes mean we're specifying a
+ literal string, but there are many other fun things we can do. For example, we
+ can tell pathod to generate 100k of random ASCII letters instead:
-And this is the same response with an ETag header added:
+
200@100k,ascii_letters
- 200:b@1m:h"Etag"="foo"
+
Full documentation on the value specification syntax can be found in the next
+ section.
+
+ Following the response code specifier is a colon-separated list of features.
+ For instance, this specifies a response with a body consisting of 1 megabyte of
+ random data:
-Both the header name and the header value are full value specifiers. Here's the
-same response again, but with a 1k randomly generated header name:
+
200:b@1m
- 200:b@1m:h@1k,ascii_letters="foo"
+
And this is the same response with an ETag header added:
-A few specific headers have shortcuts, because they're used so often. The
-shortcut for the content-type header is "c":
+
200:b@1m:h"Etag"="foo"
- 200:b@1m:c"text/json"
+
Both the header name and the header value are full value specifiers. Here's the
+ same response again, but with a 1k randomly generated header name:
-That's it for the basic response definition. Now we can start mucking with the
-responses to break clients. One common hard-to-test circumstance is hangs or
-slow responses. pathod has a pause operator that you can use to define
-precisely when and how long the server should hang. Here, for instance, we hang
-for 120 seconds after sending 50 bytes (counted from the first byte of the HTTP
-response):
+
200:b@1m:h@1k,ascii_letters="foo"
- 200:b@1m:p120,50
+
A few specific headers have shortcuts, because they're used so often. The
+ shortcut for the content-type header is "c":
-If that's not long enough, we can tell pathod to hang forever:
+
200:b@1m:c"text/json"
- 200:b@1m:p120,f
+
That's it for the basic response definition. Now we can start mucking with the
+ responses to break clients. One common hard-to-test circumstance is hangs or
+ slow responses. pathod has a pause operator that you can use to define
+ precisely when and how long the server should hang. Here, for instance, we hang
+ for 120 seconds after sending 50 bytes (counted from the first byte of the HTTP
+ response):
-Or to send all data, and then hang without disconnecting:
+
200:b@1m:p120,50
- 200:b@1m:p120,a
+
If that's not long enough, we can tell pathod to hang forever:
-We can also ask pathod to hang randomly:
+
200:b@1m:p120,f
- 200:b@1m:pr,a
+
Or to send all data, and then hang without disconnecting:
-There is a similar mechanism for dropping connections mid-response. So, we can
-tell pathod to disconnect after sending 50 bytes:
+
200:b@1m:p120,a
- 200:b@1m:d50
+
We can also ask pathod to hang randomly:
-Or randomly:
+
200:b@1m:pr,a
- 200:b@1m:dr
+
There is a similar mechanism for dropping connections mid-response. So, we can
+ tell pathod to disconnect after sending 50 bytes:
-All of these features can be combined. Here's a response that pauses twice,
-once at 10 bytes and once at 20, then disconnects at 5000:
+
200:b@1m:d50
- 200:b@1m:p10,10:p20,10:d5000
+
Or randomly:
+
200:b@1m:dr
-## Response Features
+
All of these features can be combined. Here's a response that pauses twice,
+ once at 10 bytes and once at 20, then disconnects at 5000:
+ Set the body. VALUE is a Value
+ Specifier. When the body is set, pathod will
+ automatically set the appropriate Content-Length header.
+
+
-
-
- lVALUE
-
-
- A shortcut for setting the Location header. Equivalent to:
+
+
+ cVALUE
+
+
+ A shortcut for setting the Content-Type header. Equivalent to:
h"Content-Type"=VALUE
-
-
-
-
-
-
- dOFFSET
-
-
- Disconnect after OFFSET bytes. The offset can also be "r", in which case pathod
- will disconnect at a random point in the response.
-
-
-
-
-
- pSECONDS,OFFSET
-
-
- Pause for SECONDS seconds after OFFSET bytes. SECONDS can also be "f" to pause
- forever. OFFSET can also be "r" to generate a random offset, or "a" for an
- offset just after all data has been sent.
-
-
-
-
-
-
-## VALUE Specifiers
-
-There are three different flavours of value specification.
-
-### Literal
+
+
-Literal values are specified as a quoted strings:
+
+
+ lVALUE
+
+
+ A shortcut for setting the Location header. Equivalent to:
- "foo"
+
h"Location"=VALUE
-Either single or double quotes are accepted, and quotes can be escaped with
-backslashes within the string:
+
+
- 'fo\'o'
+
+
+ dOFFSET
+
+
+ Disconnect after OFFSET bytes. The offset can also be "r", in which case pathod
+ will disconnect at a random point in the response.
+
+
-### Files
+
+
+ pSECONDS,OFFSET
+
+
+ Pause for SECONDS seconds after OFFSET bytes. SECONDS can also be "f" to pause
+ forever. OFFSET can also be "r" to generate a random offset, or "a" for an
+ offset just after all data has been sent.
+
+
+
+
-You can load a value from a specified file path. To do so, you have to specify
-a _staticdir_ option to pathod on the command-line, like so:
+
+
VALUE Specifiers
- pathod -d ~/myassets
+
Literals
-All paths are relative paths under this directory. File loads are indicated by
-starting the value specifier with the left angle bracket:
-
- Literal values are specified as a quoted strings:
-The path value can also be a quoted string, with the same syntax as literals:
+
"foo"
- <"my/path"
+
Either single or double quotes are accepted, and quotes can be escaped with
+ backslashes within the string:
+
'fo\'o'
-### Generated values
-An @-symbol lead-in specifies that generated data should be used. There are two
-components to a generator specification - a size, and a data type. By default
-pathod assumes a data type of "bytes".
+
Files
-Here's a value specifier for generating 100 bytes:
-
- @100
+
You can load a value from a specified file path. To do so, you have to specify
+ a _staticdir_ option to pathod on the command-line, like so:
-You can use standard suffixes to indicate larger values. Here, for instance, is
-a specifier for generating 100 megabytes:
+
pathod -d ~/myassets
- @100m
+
All paths are relative paths under this directory. File loads are indicated by
+ starting the value specifier with the left angle bracket:
+
+
<my/path
+
+
The path value can also be a quoted string, with the same syntax as literals:
+
+
<"my/path"
+
+
+
Generated values
+
+
An @-symbol lead-in specifies that generated data should be used. There are two
+ components to a generator specification - a size, and a data type. By default
+ pathod assumes a data type of "bytes".
+
+
Here's a value specifier for generating 100 bytes:
+
+
@100
+
+
You can use standard suffixes to indicate larger values. Here, for instance, is
+ a specifier for generating 100 megabytes:
+
+
@100m
+
+
Data is generated and served efficiently - if you really want to send a
+ terabyte of data to a client, pathod can do it. The supported suffixes are:
+
+
+
+
+
+
b
1024**0 (bytes)
+
+
+
k
1024**1 (kilobytes)
+
+
+
m
1024**2 (megabytes)
+
+
+
g
1024**3 (gigabytes)
+
+
+
t
1024**4 (terabytes)
+
+
+
+
+
Data types are separated from the size specification by a comma. This
+ specification generates 100mb of ASCII:
+
+
@100m,ascii
+
+
Supported data types are:
+
+
+
+
ascii_letters
+
ascii_lowercase
+
ascii_uppercase
+
digits
+
hexdigits
+
letters
+
lowercase
+
octdigits
+
printable
+
punctuation
+
uppercase
+
whitespace
+
ascii
+
bytes
+
-Data is generated and served efficiently - if you really want to send a
-terabyte of data to a client, pathod can do it. The supported suffixes are:
+
-
-
-
-
b
1024**0 (bytes)
-
-
-
k
1024**1 (kilobytes)
-
-
-
m
1024**2 (megabytes)
-
-
-
g
1024**3 (gigabytes)
-
-
-
t
1024**4 (terabytes)
-
-
-
-
-Data types are separated from the size specification by a comma. This
-specification generates 100mb of ASCII:
-
- @100m,ascii
-
-Supported data types are:
-
-
-- ascii_letters
-- ascii_lowercase
-- ascii_uppercase
-- digits
-- hexdigits
-- letters
-- lowercase
-- octdigits
-- printable
-- punctuation
-- uppercase
-- whitespace
-- ascii
-- bytes
-
-
-
-
API
-
-
-pathod exposes a simple API, intended to make it possible to drive and
-inspect the daemon remotely for use in unit testing and the like.
-
-
-
-
-
-
- /api/clear_log
-
-
- A POST to this URL clears the log buffer.
-
-
-
-
- /api/info
-
-
- Basic version and configuration info.
-
-
-
-
- /api/log
-
-
- Returns the current log buffer. At the moment the buffer size is 500 entries -
- when the log grows larger than this, older entries are discarded. The returned
- data is a JSON dictionary, with the form:
-
-
{ 'log': [ ENTRIES ] }
-
- You can preview the JSON data returned for a log entry through the built-in web
- interface.
-
-
-
-
-
-
-
Error Responses
-
+
+
+
API
+
-To let users distinguish crafted responses from internal pathod responses,
-pathod uses the non-standard 800 response code to indicate errors. For example,
-a request to:
+
pathod exposes a simple API, intended to make it possible to drive and
+ inspect the daemon remotely for use in unit testing and the like.
- http://localhost:9999/p/foo
-... will return an 800 response, because "foo" is not a valid page specifier.
+
+
+
+
+ /api/clear_log
+
+
+ A POST to this URL clears the log buffer.
+
+
+
+
+ /api/info
+
+
+ Basic version and configuration info.
+
+
+
+
+ /api/log
+
+
+ Returns the current log buffer. At the moment the buffer size is 500 entries -
+ when the log grows larger than this, older entries are discarded. The returned
+ data is a JSON dictionary, with the form:
+
+
{ 'log': [ ENTRIES ] }
+
+ You can preview the JSON data returned for a log entry through the built-in web
+ interface.
+
+
+
+
+
+
+
+
+
Error Responses
+
+
+
To let users distinguish crafted responses from internal pathod responses,
+ pathod uses the non-standard 800 response code to indicate errors. For example,
+ a request to:
+
+
http://localhost:9999/p/foo
+
+
... will return an 800 response, because "foo" is not a valid page specifier.
+
+
+
{% endblock %}
diff --git a/libpathod/templates/frame.html b/libpathod/templates/frame.html
index a83f8f38..daf3e2ae 100644
--- a/libpathod/templates/frame.html
+++ b/libpathod/templates/frame.html
@@ -4,6 +4,7 @@
pathod
+
--
cgit v1.2.3
From d7841898e39b7bb1854f7c066ccccaaa84ab2f2c Mon Sep 17 00:00:00 2001
From: Aldo Cortesi
Date: Fri, 20 Jul 2012 23:36:39 +1200
Subject: Add an injection operator.
---
libpathod/rparse.py | 29 +++++++++++++++++++++++++++--
test/test_rparse.py | 32 ++++++++++++++++++++++++++++++++
2 files changed, 59 insertions(+), 2 deletions(-)
diff --git a/libpathod/rparse.py b/libpathod/rparse.py
index e3136b7b..5a2f84b1 100644
--- a/libpathod/rparse.py
+++ b/libpathod/rparse.py
@@ -49,10 +49,10 @@ def send_chunk(fp, val, blocksize, start, end):
def write_values(fp, vals, actions, sofar=0, skip=0, blocksize=BLOCKSIZE):
"""
- vals: A list of values, which may be strings or Value objects.
+ vals: A list of values, which may be strings or Value objects.
actions: A list of (offset, action, arg) tuples. Action may be "pause" or "disconnect".
- Both vals and actions are in reverse order, with the first items last.
+ Both vals and actions are in reverse order, with the first items last.
Return True if connection should disconnect.
"""
@@ -66,6 +66,8 @@ def write_values(fp, vals, actions, sofar=0, skip=0, blocksize=BLOCKSIZE):
offset += send_chunk(fp, v, blocksize, offset, a[0]-sofar-offset)
if a[1] == "pause":
time.sleep(a[2])
+ elif a[1] == "inject":
+ send_chunk(fp, a[2], blocksize, 0, len(a[2]))
elif a[1] == "disconnect":
return True
send_chunk(fp, v, blocksize, offset, len(v))
@@ -409,6 +411,27 @@ class DisconnectAt:
return e.setParseAction(lambda x: klass(*x))
+class InjectAt:
+ def __init__(self, offset, value):
+ self.offset, self.value = offset, value
+
+ @classmethod
+ def expr(klass):
+ e = pp.Literal("i").suppress()
+ e = e + pp.MatchFirst(
+ [
+ v_integer,
+ pp.Literal("r")
+ ]
+ )
+ e += pp.Literal(",").suppress()
+ e += Value
+ return e.setParseAction(lambda x: klass(*x))
+
+ def accept(self, settings, r):
+ r.actions.append((self.offset, "inject", self.value))
+
+
class Header:
def __init__(self, key, value):
self.key, self.value = key, value
@@ -512,6 +535,7 @@ class Response(Message):
Header,
PauseAt,
DisconnectAt,
+ InjectAt,
ShortcutContentType,
ShortcutLocation,
)
@@ -551,6 +575,7 @@ class Request(Message):
Header,
PauseAt,
DisconnectAt,
+ InjectAt,
ShortcutContentType,
)
logattrs = ["method", "path"]
diff --git a/test/test_rparse.py b/test/test_rparse.py
index f4b408b2..04a4972f 100644
--- a/test/test_rparse.py
+++ b/test/test_rparse.py
@@ -169,6 +169,23 @@ class TestDisconnects:
assert v.value == "r"
+class TestInject:
+ def test_parse_response(self):
+ a = rparse.parse_response({}, "400:ir,@100").actions[0]
+ assert a[0] == "r"
+ assert a[1] == "inject"
+
+ def test_at(self):
+ e = rparse.InjectAt.expr()
+ v = e.parseString("i0,'foo'")[0]
+ assert v.value.val == "foo"
+ assert v.offset == 0
+ assert isinstance(v, rparse.InjectAt)
+
+ v = e.parseString("ir,'foo'")[0]
+ assert v.offset == "r"
+
+
class TestShortcuts:
def test_parse_response(self):
assert rparse.parse_response({}, "400:c'foo'").headers[0][0][:] == "Content-Type"
@@ -262,6 +279,21 @@ class TestWriteValues:
rparse.send_chunk(s, v, bs, start, end)
assert s.getvalue() == v[start:end]
+ def test_write_values_inject(self):
+ tst = "foo"
+
+ s = cStringIO.StringIO()
+ rparse.write_values(s, [tst], [(0, "inject", "aaa")], blocksize=5)
+ assert s.getvalue() == "aaafoo"
+
+ s = cStringIO.StringIO()
+ rparse.write_values(s, [tst], [(1, "inject", "aaa")], blocksize=5)
+ assert s.getvalue() == "faaaoo"
+
+ s = cStringIO.StringIO()
+ rparse.write_values(s, [tst], [(1, "inject", "aaa")], blocksize=5)
+ assert s.getvalue() == "faaaoo"
+
def test_write_values_disconnects(self):
s = cStringIO.StringIO()
tst = "foo"*100
--
cgit v1.2.3
From 8e0c01ae39f2f1f80ad0d372119e8654de21d29c Mon Sep 17 00:00:00 2001
From: Aldo Cortesi
Date: Fri, 20 Jul 2012 23:47:34 +1200
Subject: Fine-tuning for injection: docs, bugfixes.
---
libpathod/rparse.py | 11 +++++++++--
libpathod/templates/docs_pathod.html | 11 +++++++++++
test/test_rparse.py | 9 +++++++++
3 files changed, 29 insertions(+), 2 deletions(-)
diff --git a/libpathod/rparse.py b/libpathod/rparse.py
index 5a2f84b1..e71265ea 100644
--- a/libpathod/rparse.py
+++ b/libpathod/rparse.py
@@ -421,7 +421,8 @@ class InjectAt:
e = e + pp.MatchFirst(
[
v_integer,
- pp.Literal("r")
+ pp.Literal("r"),
+ pp.Literal("a")
]
)
e += pp.Literal(",").suppress()
@@ -429,7 +430,13 @@ class InjectAt:
return e.setParseAction(lambda x: klass(*x))
def accept(self, settings, r):
- r.actions.append((self.offset, "inject", self.value))
+ r.actions.append(
+ (
+ self.offset,
+ "inject",
+ self.value.get_generator(settings)
+ )
+ )
class Header:
diff --git a/libpathod/templates/docs_pathod.html b/libpathod/templates/docs_pathod.html
index 1527f851..8fc062ca 100644
--- a/libpathod/templates/docs_pathod.html
+++ b/libpathod/templates/docs_pathod.html
@@ -157,6 +157,17 @@ various other goodies. Try it by visiting the server root:
+
+
+ iOFFSET,VALUE
+
+
+ Inject the specified value at the offset. OFFSET can be an
+ integer, or "r" to generate a random offset or "a" for an
+ offset just after all data has been sent.
+
+
+
lVALUE
diff --git a/test/test_rparse.py b/test/test_rparse.py
index 04a4972f..dfc8c758 100644
--- a/test/test_rparse.py
+++ b/test/test_rparse.py
@@ -175,6 +175,10 @@ class TestInject:
assert a[0] == "r"
assert a[1] == "inject"
+ a = rparse.parse_response({}, "400:ia,@100").actions[0]
+ assert a[0] == "a"
+ assert a[1] == "inject"
+
def test_at(self):
e = rparse.InjectAt.expr()
v = e.parseString("i0,'foo'")[0]
@@ -185,6 +189,11 @@ class TestInject:
v = e.parseString("ir,'foo'")[0]
assert v.offset == "r"
+ def test_serve(self):
+ s = cStringIO.StringIO()
+ r = rparse.parse_response({}, "400:i0,'foo'")
+ assert r.serve(s)
+
class TestShortcuts:
def test_parse_response(self):
--
cgit v1.2.3
From 8ec44c627770e5a41faabbf724ad54ed518e08f6 Mon Sep 17 00:00:00 2001
From: Aldo Cortesi
Date: Sat, 21 Jul 2012 14:12:45 +1200
Subject: Allow Python string escape sequences in value literals.
---
libpathod/rparse.py | 2 +-
test/test_rparse.py | 6 +++++-
2 files changed, 6 insertions(+), 2 deletions(-)
diff --git a/libpathod/rparse.py b/libpathod/rparse.py
index e71265ea..9d0f7e79 100644
--- a/libpathod/rparse.py
+++ b/libpathod/rparse.py
@@ -165,7 +165,7 @@ class FileGenerator:
class _Value:
def __init__(self, val):
- self.val = val
+ self.val = val.decode("string_escape")
def get_generator(self, settings):
return LiteralGenerator(self.val)
diff --git a/test/test_rparse.py b/test/test_rparse.py
index dfc8c758..11c831c6 100644
--- a/test/test_rparse.py
+++ b/test/test_rparse.py
@@ -40,7 +40,11 @@ class TestMisc:
def test_valueliteral(self):
v = rparse.ValueLiteral("foo")
assert v.expr()
- assert str(v)
+ assert v.val == "foo"
+
+ v = rparse.ValueLiteral(r"foo\n")
+ assert v.expr()
+ assert v.val == "foo\n"
def test_valuenakedliteral(self):
v = rparse.ValueNakedLiteral("foo")
--
cgit v1.2.3
From 5577d85ce6835fddce6e0eaf98b241e42e959a25 Mon Sep 17 00:00:00 2001
From: Aldo Cortesi
Date: Sat, 21 Jul 2012 14:14:31 +1200
Subject: Use injection to test a corner case in pathod daemon.
---
test/test_pathod.py | 13 ++++++++++++-
1 file changed, 12 insertions(+), 1 deletion(-)
diff --git a/test/test_pathod.py b/test/test_pathod.py
index 9f01b25c..a23b7c71 100644
--- a/test/test_pathod.py
+++ b/test/test_pathod.py
@@ -1,5 +1,5 @@
import requests
-from libpathod import pathod, test, version
+from libpathod import pathod, test, version, pathoc
from netlib import tcp
import tutils
@@ -64,6 +64,17 @@ class _DaemonTests:
scheme = "https" if self.SSL else "http"
return requests.get("%s://localhost:%s/p/%s"%(scheme, self.d.port, spec), verify=False)
+ def pathoc(self, spec):
+ c = pathoc.Pathoc("localhost", self.d.port)
+ c.connect()
+ if self.SSL:
+ c.convert_to_ssl()
+ return c.request(spec)
+
+ def test_preline(self):
+ v = self.pathoc(r"get:'/p/200':i0,'\r\n'")
+ assert v[1] == 200
+
def test_info(self):
assert tuple(self.d.info()["version"]) == version.IVERSION
--
cgit v1.2.3
From 3e6f440b8d19ffd2658229e8a23ed8d558390da2 Mon Sep 17 00:00:00 2001
From: Aldo Cortesi
Date: Sat, 21 Jul 2012 14:17:41 +1200
Subject: Document Python-style string escaping.
---
libpathod/templates/docs_pathod.html | 8 ++++++--
1 file changed, 6 insertions(+), 2 deletions(-)
diff --git a/libpathod/templates/docs_pathod.html b/libpathod/templates/docs_pathod.html
index 8fc062ca..3b10b212 100644
--- a/libpathod/templates/docs_pathod.html
+++ b/libpathod/templates/docs_pathod.html
@@ -218,6 +218,10 @@ various other goodies. Try it by visiting the server root:
'fo\'o'
+
Literal values can contain Python-style backslash escape sequences:
+
+
'foo\r\nbar'
+
Files
@@ -284,9 +288,11 @@ various other goodies. Try it by visiting the server root:
+
ascii
ascii_letters
ascii_lowercase
ascii_uppercase
+
bytes
digits
hexdigits
letters
@@ -296,8 +302,6 @@ various other goodies. Try it by visiting the server root:
punctuation
uppercase
whitespace
-
ascii
-
bytes
--
cgit v1.2.3
From 72e30d4712886ed06e8f8287ee7c6933e6e68d4b Mon Sep 17 00:00:00 2001
From: Aldo Cortesi
Date: Sat, 21 Jul 2012 15:15:10 +1200
Subject: Add an -n argument to pathoc, to repeat the specified requests N
times.
---
pathoc | 53 ++++++++++++++++++++++++++++++++++++++---------------
todo | 11 -----------
2 files changed, 38 insertions(+), 26 deletions(-)
delete mode 100644 todo
diff --git a/pathoc b/pathoc
index e5cc9bf4..7f555566 100755
--- a/pathoc
+++ b/pathoc
@@ -5,12 +5,34 @@ from netlib import tcp
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='A perverse HTTP client.')
- parser.add_argument('--port', "-p", type=int, default=None, help="Port. Defaults to 80, or 443 if SSL is active.")
- parser.add_argument('--ssl', "-s", action="store_true", default=False, help="Connect with SSL.")
- parser.add_argument('--sni', "-n", type=str, default=False, help="SSL Server Name Indication.")
- parser.add_argument('--verbose', '-v', action='count')
- parser.add_argument('host', type=str, help='Host to connect to')
- parser.add_argument('request', type=str, nargs="+", help='Request specification')
+ parser.add_argument(
+ "-n", dest='repeat', default=1, type=int, metavar="N",
+ help='Repeat requests N times.'
+ )
+ parser.add_argument(
+ "-p", dest="port", type=int, default=None,
+ help="Port. Defaults to 80, or 443 if SSL is active."
+ )
+ parser.add_argument(
+ "-s", dest="ssl", action="store_true", default=False,
+ help="Connect with SSL."
+ )
+ parser.add_argument(
+ "-i", dest="sni", type=str, default=False,
+ help="SSL Server Name Indication."
+ )
+ parser.add_argument(
+ "-v", dest="verbose", action='count',
+ help="Increase verbosity."
+ )
+ parser.add_argument(
+ 'host', type=str,
+ help='Host to connect to'
+ )
+ parser.add_argument(
+ 'request', type=str, nargs="+",
+ help='Request specification'
+ )
args = parser.parse_args()
@@ -19,12 +41,13 @@ if __name__ == "__main__":
else:
port = args.port
- p = pathoc.Pathoc(args.host, port)
- try:
- p.connect()
- except tcp.NetLibError, v:
- print >> sys.stderr, str(v)
- sys.exit(1)
- if args.ssl:
- p.convert_to_ssl(sni=args.sni)
- p.print_requests(args.request, args.verbose)
+ for i in range(args.repeat):
+ p = pathoc.Pathoc(args.host, port)
+ try:
+ p.connect()
+ except tcp.NetLibError, v:
+ print >> sys.stderr, str(v)
+ sys.exit(1)
+ if args.ssl:
+ p.convert_to_ssl(sni=args.sni)
+ p.print_requests(args.request, args.verbose)
diff --git a/todo b/todo
deleted file mode 100644
index 98e4790c..00000000
--- a/todo
+++ /dev/null
@@ -1,11 +0,0 @@
-
-0.2:
- - API
- - Anchor management
- - Client library
- - Unit testing examples
- - Specify if server should add Server and Date headers
- - Shortcuts for cookies, auth
- - Various SSL errors (expired certs, etc.)
- - Muck with caching
-
--
cgit v1.2.3
From 059a2329035b916c8762b58a385556266abb4629 Mon Sep 17 00:00:00 2001
From: Aldo Cortesi
Date: Sat, 21 Jul 2012 16:19:44 +1200
Subject: Add support for client timeout to pathoc.
---
libpathod/pathoc.py | 9 ++++++---
pathoc | 10 ++++++++--
2 files changed, 14 insertions(+), 5 deletions(-)
diff --git a/libpathod/pathoc.py b/libpathod/pathoc.py
index 3791c116..f79ed3af 100644
--- a/libpathod/pathoc.py
+++ b/libpathod/pathoc.py
@@ -45,7 +45,10 @@ class Pathoc(tcp.TCPClient):
except http.HttpError, v:
print >> fp, v.msg
return
- if verbose:
- print_full(fp, *ret)
+ except tcp.NetLibTimeout:
+ print >> fp, "Timeout"
else:
- print_short(fp, *ret)
+ if verbose:
+ print_full(fp, *ret)
+ else:
+ print_short(fp, *ret)
diff --git a/pathoc b/pathoc
index 7f555566..93da3798 100755
--- a/pathoc
+++ b/pathoc
@@ -5,6 +5,10 @@ from netlib import tcp
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='A perverse HTTP client.')
+ parser.add_argument(
+ "-i", dest="sni", type=str, default=False,
+ help="SSL Server Name Indication."
+ )
parser.add_argument(
"-n", dest='repeat', default=1, type=int, metavar="N",
help='Repeat requests N times.'
@@ -18,8 +22,8 @@ if __name__ == "__main__":
help="Connect with SSL."
)
parser.add_argument(
- "-i", dest="sni", type=str, default=False,
- help="SSL Server Name Indication."
+ "-t", dest="timeout", type=int, default=None,
+ help="Connection timeout."
)
parser.add_argument(
"-v", dest="verbose", action='count',
@@ -50,4 +54,6 @@ if __name__ == "__main__":
sys.exit(1)
if args.ssl:
p.convert_to_ssl(sni=args.sni)
+ if args.timeout:
+ p.settimeout(args.timeout)
p.print_requests(args.request, args.verbose)
--
cgit v1.2.3
From 86fe199988801232f209b7e39a2910065bf5db5f Mon Sep 17 00:00:00 2001
From: Aldo Cortesi
Date: Sat, 21 Jul 2012 20:20:37 +1200
Subject: pathoc: add a flag to dump request information.
---
libpathod/pathoc.py | 26 ++++++++++++++++++--------
libpathod/rparse.py | 17 ++++++++++++-----
pathoc | 6 +++++-
test/test_pathoc.py | 4 ++--
test/test_rparse.py | 4 +++-
5 files changed, 40 insertions(+), 17 deletions(-)
diff --git a/libpathod/pathoc.py b/libpathod/pathoc.py
index f79ed3af..7af5a288 100644
--- a/libpathod/pathoc.py
+++ b/libpathod/pathoc.py
@@ -6,11 +6,11 @@ class PathocError(Exception): pass
def print_short(fp, httpversion, code, msg, headers, content):
- print >> fp, "%s %s: %s bytes"%(code, msg, len(content))
+ print >> fp, "<< %s %s: %s bytes"%(code, msg, len(content))
def print_full(fp, httpversion, code, msg, headers, content):
- print >> fp, "HTTP%s/%s %s %s"%(httpversion[0], httpversion[1], code, msg)
+ print >> fp, "<< HTTP%s/%s %s %s"%(httpversion[0], httpversion[1], code, msg)
print >> fp, headers
print >> fp, content
@@ -26,18 +26,28 @@ class Pathoc(tcp.TCPClient):
May raise rparse.ParseException and netlib.http.HttpError.
"""
r = rparse.parse_request({}, spec)
- r.serve(self.wfile)
+ ret = r.serve(self.wfile)
self.wfile.flush()
return http.read_response(self.rfile, r.method, None)
- def print_requests(self, reqs, verbose, fp=sys.stdout):
+ def print_requests(self, reqs, respdump, reqdump, fp=sys.stdout):
"""
Performs a series of requests, and prints results to the specified
file pointer.
"""
for i in reqs:
try:
- ret = self.request(i)
+ r = rparse.parse_request({}, i)
+ req = r.serve(self.wfile)
+ if reqdump:
+ print >> fp, ">>", req["method"], req["path"]
+ for a in req["actions"]:
+ print >> fp, "\t",
+ for x in a:
+ print x,
+ print
+ self.wfile.flush()
+ resp = self.request(i)
except rparse.ParseException, v:
print >> fp, "Error parsing request spec: %s"%v.msg
print >> fp, v.marked()
@@ -48,7 +58,7 @@ class Pathoc(tcp.TCPClient):
except tcp.NetLibTimeout:
print >> fp, "Timeout"
else:
- if verbose:
- print_full(fp, *ret)
+ if respdump:
+ print_full(fp, *resp)
else:
- print_short(fp, *ret)
+ print_short(fp, *resp)
diff --git a/libpathod/rparse.py b/libpathod/rparse.py
index 9d0f7e79..6eb7d5a4 100644
--- a/libpathod/rparse.py
+++ b/libpathod/rparse.py
@@ -130,21 +130,28 @@ class LiteralGenerator:
def __getslice__(self, a, b):
return self.s.__getslice__(a, b)
+ def __repr__(self):
+ return '"%s"'%self.s
+
class RandomGenerator:
- def __init__(self, chars, length):
- self.chars = chars
+ def __init__(self, dtype, length):
+ self.dtype = dtype
self.length = length
def __len__(self):
return self.length
def __getitem__(self, x):
- return random.choice(self.chars)
+ return random.choice(DATATYPES[self.dtype])
def __getslice__(self, a, b):
b = min(b, self.length)
- return "".join(random.choice(self.chars) for x in range(a, b))
+ chars = DATATYPES[self.dtype]
+ return "".join(random.choice(chars) for x in range(a, b))
+
+ def __repr__(self):
+ return "%s random from %s"%(self.length, self.dtype)
class FileGenerator:
@@ -205,7 +212,7 @@ class ValueGenerate:
return self.usize * self.UNITS[self.unit]
def get_generator(self, settings):
- return RandomGenerator(DATATYPES[self.datatype], self.bytes())
+ return RandomGenerator(self.datatype, self.bytes())
@classmethod
def expr(klass):
diff --git a/pathoc b/pathoc
index 93da3798..fc76cfc8 100755
--- a/pathoc
+++ b/pathoc
@@ -17,6 +17,10 @@ if __name__ == "__main__":
"-p", dest="port", type=int, default=None,
help="Port. Defaults to 80, or 443 if SSL is active."
)
+ parser.add_argument(
+ "-d", dest="reqdump", action="store_true", default=False,
+ help="Print request record before each response."
+ )
parser.add_argument(
"-s", dest="ssl", action="store_true", default=False,
help="Connect with SSL."
@@ -56,4 +60,4 @@ if __name__ == "__main__":
p.convert_to_ssl(sni=args.sni)
if args.timeout:
p.settimeout(args.timeout)
- p.print_requests(args.request, args.verbose)
+ p.print_requests(args.request, args.verbose, args.reqdump)
diff --git a/test/test_pathoc.py b/test/test_pathoc.py
index a9c38870..310d75f6 100644
--- a/test/test_pathoc.py
+++ b/test/test_pathoc.py
@@ -28,11 +28,11 @@ class TestDaemon:
c = pathoc.Pathoc("127.0.0.1", self.d.port)
c.connect()
s = cStringIO.StringIO()
- c.print_requests(requests, verbose, s)
+ c.print_requests(requests, verbose, True, s)
return s.getvalue()
def test_print_requests(self):
- reqs = [ "get:/api/info", "get:/api/info" ]
+ reqs = [ "get:/api/info:p0,0", "get:/api/info:p0,0" ]
assert self.tval(reqs, False).count("200") == 2
assert self.tval(reqs, True).count("Date") == 2
diff --git a/test/test_rparse.py b/test/test_rparse.py
index 11c831c6..1527bddf 100644
--- a/test/test_rparse.py
+++ b/test/test_rparse.py
@@ -12,7 +12,8 @@ class TestMisc:
assert g[:] == "val"
def test_randomgenerator(self):
- g = rparse.RandomGenerator("one", 100)
+ g = rparse.RandomGenerator("bytes", 100)
+ assert repr(g)
assert len(g[:10]) == 10
assert len(g[1:10]) == 9
assert len(g[:1000]) == 100
@@ -21,6 +22,7 @@ class TestMisc:
def test_literalgenerator(self):
g = rparse.LiteralGenerator("one")
+ assert repr(g)
assert g == "one"
assert g[:] == "one"
assert g[1] == "n"
--
cgit v1.2.3
From 7a49cdfef3d9f5eeaecf6d6c8938f0bb8da7c15d Mon Sep 17 00:00:00 2001
From: Aldo Cortesi
Date: Sat, 21 Jul 2012 20:50:41 +1200
Subject: More robust response handling.
---
libpathod/pathoc.py | 12 ++---
libpathod/pathod.py | 150 +++++++++++++++++++++++++++++-----------------------
test/test_pathod.py | 5 +-
3 files changed, 94 insertions(+), 73 deletions(-)
diff --git a/libpathod/pathoc.py b/libpathod/pathoc.py
index 7af5a288..793135e7 100644
--- a/libpathod/pathoc.py
+++ b/libpathod/pathoc.py
@@ -40,23 +40,23 @@ class Pathoc(tcp.TCPClient):
r = rparse.parse_request({}, i)
req = r.serve(self.wfile)
if reqdump:
- print >> fp, ">>", req["method"], req["path"]
+ print >> fp, "\n>>", req["method"], req["path"]
for a in req["actions"]:
print >> fp, "\t",
for x in a:
- print x,
- print
+ print >> fp, x,
+ print >> fp
self.wfile.flush()
- resp = self.request(i)
+ resp = http.read_response(self.rfile, r.method, None)
except rparse.ParseException, v:
print >> fp, "Error parsing request spec: %s"%v.msg
print >> fp, v.marked()
return
except http.HttpError, v:
- print >> fp, v.msg
+ print >> fp, "<<", v.msg
return
except tcp.NetLibTimeout:
- print >> fp, "Timeout"
+ print >> fp, "<<", "Timeout"
else:
if respdump:
print_full(fp, *resp)
diff --git a/libpathod/pathod.py b/libpathod/pathod.py
index 44bcadb7..026986bb 100644
--- a/libpathod/pathod.py
+++ b/libpathod/pathod.py
@@ -18,6 +18,82 @@ class PathodHandler(tcp.BaseHandler):
def handle_sni(self, connection):
self.sni = connection.get_servername()
+ def handle_request(self):
+ """
+ Returns True if handling should continue.
+ """
+ line = self.rfile.readline()
+ if line == "\r\n" or line == "\n": # Possible leftover from previous message
+ line = self.rfile.readline()
+ if line == "":
+ return
+
+ parts = http.parse_init_http(line)
+ if not parts:
+ s = "Invalid first line: %s"%line.rstrip()
+ self.info(s)
+ self.server.add_log(
+ dict(
+ type = "error",
+ msg = s
+ )
+ )
+ return
+ method, path, httpversion = parts
+
+ headers = http.read_headers(self.rfile)
+ content = http.read_http_body_request(
+ self.rfile, self.wfile, headers, httpversion, None
+ )
+
+ crafted = None
+ for i in self.server.anchors:
+ if i[0].match(path):
+ crafted = i[1]
+
+ if not crafted and path.startswith(self.server.prefix):
+ spec = urllib.unquote(path)[len(self.server.prefix):]
+ try:
+ crafted = rparse.parse_response(self.server.request_settings, spec)
+ except rparse.ParseException, v:
+ crafted = rparse.InternalResponse(
+ 800,
+ "Error parsing response spec: %s\n"%v.msg + v.marked()
+ )
+
+ request_log = dict(
+ path = path,
+ method = method,
+ headers = headers.lst,
+ sni = self.sni,
+ remote_address = self.client_address,
+ httpversion = httpversion,
+ )
+ if crafted:
+ response_log = crafted.serve(self.wfile)
+ if response_log["disconnect"]:
+ return
+ self.server.add_log(
+ dict(
+ type = "crafted",
+ request=request_log,
+ response=response_log
+ )
+ )
+ else:
+ cc = wsgi.ClientConn(self.client_address)
+ req = wsgi.Request(cc, "http", method, path, headers, content)
+ sn = self.connection.getsockname()
+ app = wsgi.WSGIAdaptor(
+ self.server.app,
+ sn[0],
+ self.server.port,
+ version.NAMEVERSION
+ )
+ app.serve(req, self.wfile)
+ self.debug("%s %s"%(method, path))
+ return True
+
def handle(self):
if self.server.ssloptions:
try:
@@ -34,79 +110,21 @@ class PathodHandler(tcp.BaseHandler):
)
)
self.info(s)
- self.finish()
+ return
while not self.finished:
- line = self.rfile.readline()
- if line == "\r\n" or line == "\n": # Possible leftover from previous message
- line = self.rfile.readline()
- if line == "":
- return None
-
- parts = http.parse_init_http(line)
- if not parts:
- s = "Invalid first line: %s"%line.rstrip()
- self.info(s)
+ try:
+ if not self.handle_request():
+ return
+ except tcp.NetLibDisconnect:
+ self.info("Disconnect")
self.server.add_log(
dict(
type = "error",
- msg = s
+ msg = "Disconnect"
)
)
- return None
- method, path, httpversion = parts
-
- headers = http.read_headers(self.rfile)
- content = http.read_http_body_request(
- self.rfile, self.wfile, headers, httpversion, None
- )
-
- crafted = None
- for i in self.server.anchors:
- if i[0].match(path):
- crafted = i[1]
-
- if not crafted and path.startswith(self.server.prefix):
- spec = urllib.unquote(path)[len(self.server.prefix):]
- try:
- crafted = rparse.parse_response(self.server.request_settings, spec)
- except rparse.ParseException, v:
- crafted = rparse.InternalResponse(
- 800,
- "Error parsing response spec: %s\n"%v.msg + v.marked()
- )
-
- request_log = dict(
- path = path,
- method = method,
- headers = headers.lst,
- sni = self.sni,
- remote_address = self.client_address,
- httpversion = httpversion,
- )
- if crafted:
- response_log = crafted.serve(self.wfile)
- if response_log["disconnect"]:
- self.finish()
- self.server.add_log(
- dict(
- type = "crafted",
- request=request_log,
- response=response_log
- )
- )
- else:
- cc = wsgi.ClientConn(self.client_address)
- req = wsgi.Request(cc, "http", method, path, headers, content)
- sn = self.connection.getsockname()
- app = wsgi.WSGIAdaptor(
- self.server.app,
- sn[0],
- self.server.port,
- version.NAMEVERSION
- )
- app.serve(req, self.wfile)
- self.debug("%s %s"%(method, path))
+ return
class Pathod(tcp.TCPServer):
diff --git a/test/test_pathod.py b/test/test_pathod.py
index a23b7c71..1484efcd 100644
--- a/test/test_pathod.py
+++ b/test/test_pathod.py
@@ -64,11 +64,13 @@ class _DaemonTests:
scheme = "https" if self.SSL else "http"
return requests.get("%s://localhost:%s/p/%s"%(scheme, self.d.port, spec), verify=False)
- def pathoc(self, spec):
+ def pathoc(self, spec, timeout=None):
c = pathoc.Pathoc("localhost", self.d.port)
c.connect()
if self.SSL:
c.convert_to_ssl()
+ if timeout:
+ c.settimeout(timeout)
return c.request(spec)
def test_preline(self):
@@ -114,6 +116,7 @@ class _DaemonTests:
assert "foo" in l["msg"]
+
class TestDaemon(_DaemonTests):
SSL = False
--
cgit v1.2.3
From 8d8ede7e265591e94f6e2db5bf79f6b85e822912 Mon Sep 17 00:00:00 2001
From: Aldo Cortesi
Date: Sun, 22 Jul 2012 12:30:10 +1200
Subject: Handle invalid content length headers.
---
libpathod/pathod.py | 15 +++++++++++++--
test/test_pathod.py | 8 +++++++-
2 files changed, 20 insertions(+), 3 deletions(-)
diff --git a/libpathod/pathod.py b/libpathod/pathod.py
index 026986bb..e4a14193 100644
--- a/libpathod/pathod.py
+++ b/libpathod/pathod.py
@@ -42,9 +42,20 @@ class PathodHandler(tcp.BaseHandler):
method, path, httpversion = parts
headers = http.read_headers(self.rfile)
- content = http.read_http_body_request(
- self.rfile, self.wfile, headers, httpversion, None
+ try:
+ content = http.read_http_body_request(
+ self.rfile, self.wfile, headers, httpversion, None
+ )
+ except http.HttpError, s:
+ s = str(s)
+ self.info(s)
+ self.server.add_log(
+ dict(
+ type = "error",
+ msg = s
)
+ )
+ return
crafted = None
for i in self.server.anchors:
diff --git a/test/test_pathod.py b/test/test_pathod.py
index 1484efcd..86f37f01 100644
--- a/test/test_pathod.py
+++ b/test/test_pathod.py
@@ -1,6 +1,6 @@
import requests
from libpathod import pathod, test, version, pathoc
-from netlib import tcp
+from netlib import tcp, http
import tutils
class _TestApplication:
@@ -115,6 +115,12 @@ class _DaemonTests:
assert l["type"] == "error"
assert "foo" in l["msg"]
+ def test_invalid_body(self):
+ tutils.raises(http.HttpError, self.pathoc, "get:/:h'content-length'='foo'")
+ l = self.d.log()[0]
+ assert l["type"] == "error"
+ assert "Invalid" in l["msg"]
+
class TestDaemon(_DaemonTests):
--
cgit v1.2.3
From 1e93e42883ba43642b4e2bfb231ee74a323706c7 Mon Sep 17 00:00:00 2001
From: Aldo Cortesi
Date: Sun, 22 Jul 2012 12:40:27 +1200
Subject: Escape special characters in first line error log.
---
libpathod/pathod.py | 2 +-
test/test_pathod.py | 1 -
2 files changed, 1 insertion(+), 2 deletions(-)
diff --git a/libpathod/pathod.py b/libpathod/pathod.py
index e4a14193..9d155301 100644
--- a/libpathod/pathod.py
+++ b/libpathod/pathod.py
@@ -30,7 +30,7 @@ class PathodHandler(tcp.BaseHandler):
parts = http.parse_init_http(line)
if not parts:
- s = "Invalid first line: %s"%line.rstrip()
+ s = "Invalid first line: %s"%repr(line)
self.info(s)
self.server.add_log(
dict(
diff --git a/test/test_pathod.py b/test/test_pathod.py
index 86f37f01..4a8d90d5 100644
--- a/test/test_pathod.py
+++ b/test/test_pathod.py
@@ -122,7 +122,6 @@ class _DaemonTests:
assert "Invalid" in l["msg"]
-
class TestDaemon(_DaemonTests):
SSL = False
--
cgit v1.2.3
From 30a69883925a4ee01b6eb0586e8295fa72458b16 Mon Sep 17 00:00:00 2001
From: Aldo Cortesi
Date: Sun, 22 Jul 2012 12:49:59 +1200
Subject: pathod: handle keyboard interrupts and SSL errors.
---
pathoc | 33 +++++++++++++++++++++------------
1 file changed, 21 insertions(+), 12 deletions(-)
diff --git a/pathoc b/pathoc
index fc76cfc8..70105ced 100755
--- a/pathoc
+++ b/pathoc
@@ -49,15 +49,24 @@ if __name__ == "__main__":
else:
port = args.port
- for i in range(args.repeat):
- p = pathoc.Pathoc(args.host, port)
- try:
- p.connect()
- except tcp.NetLibError, v:
- print >> sys.stderr, str(v)
- sys.exit(1)
- if args.ssl:
- p.convert_to_ssl(sni=args.sni)
- if args.timeout:
- p.settimeout(args.timeout)
- p.print_requests(args.request, args.verbose, args.reqdump)
+ try:
+ for i in range(args.repeat):
+ p = pathoc.Pathoc(args.host, port)
+ try:
+ p.connect()
+ except tcp.NetLibError, v:
+ print >> sys.stderr, str(v)
+ sys.exit(1)
+ if args.ssl:
+ try:
+ p.convert_to_ssl(sni=args.sni)
+ except tcp.NetLibError, v:
+ print "\n>> %s"%v
+ continue
+ if args.timeout:
+ p.settimeout(args.timeout)
+ p.print_requests(args.request, args.verbose, args.reqdump)
+ sys.stdout.flush()
+ except KeyboardInterrupt:
+ pass
+
--
cgit v1.2.3
From 817e550aa1da0eab8b9116f46f8d65a80fcb46e2 Mon Sep 17 00:00:00 2001
From: Aldo Cortesi
Date: Sun, 22 Jul 2012 15:26:05 +1200
Subject: Multiline specifications for pathod and pathoc.
---
libpathod/pathoc.py | 2 +-
libpathod/rparse.py | 16 +++++++++-------
test/test_rparse.py | 28 ++++++++++++++++++++++++++++
3 files changed, 38 insertions(+), 8 deletions(-)
diff --git a/libpathod/pathoc.py b/libpathod/pathoc.py
index 793135e7..9970ffd9 100644
--- a/libpathod/pathoc.py
+++ b/libpathod/pathoc.py
@@ -40,7 +40,7 @@ class Pathoc(tcp.TCPClient):
r = rparse.parse_request({}, i)
req = r.serve(self.wfile)
if reqdump:
- print >> fp, "\n>>", req["method"], req["path"]
+ print >> fp, "\n>>", req["method"], repr(req["path"])
for a in req["actions"]:
print >> fp, "\t",
for x in a:
diff --git a/libpathod/rparse.py b/libpathod/rparse.py
index 6eb7d5a4..17e1ebd4 100644
--- a/libpathod/rparse.py
+++ b/libpathod/rparse.py
@@ -17,7 +17,7 @@ class ParseException(Exception):
return "%s\n%s"%(self.s, " "*(self.col-1) + "^")
def __str__(self):
- return self.msg
+ return "%s at offset %s of %s"%(self.msg, self.col, repr(self.s))
class ServerError(Exception): pass
@@ -101,15 +101,15 @@ v_integer = pp.Regex(r"[+-]?\d+")\
v_literal = pp.MatchFirst(
[
- pp.QuotedString("\"", escChar="\\", unquoteResults=True),
- pp.QuotedString("'", escChar="\\", unquoteResults=True),
+ pp.QuotedString("\"", escChar="\\", unquoteResults=True, multiline=True),
+ pp.QuotedString("'", escChar="\\", unquoteResults=True, multiline=True),
]
)
v_naked_literal = pp.MatchFirst(
[
v_literal,
- pp.Word("".join(i for i in pp.printables if i not in ",:"))
+ pp.Word("".join(i for i in pp.printables if i not in ",:\n"))
]
)
@@ -543,6 +543,8 @@ class Message:
return ret
+Sep = pp.Optional(pp.Literal(":")).suppress()
+
class Response(Message):
comps = (
Body,
@@ -571,7 +573,7 @@ class Response(Message):
resp = pp.And(
[
Code.expr(),
- pp.ZeroOrMore(pp.Literal(":").suppress() + atom)
+ pp.ZeroOrMore(Sep + atom)
]
)
return resp
@@ -610,9 +612,9 @@ class Request(Message):
resp = pp.And(
[
Method.expr(),
- pp.Literal(":").suppress(),
+ Sep,
Path.expr(),
- pp.ZeroOrMore(pp.Literal(":").suppress() + atom)
+ pp.ZeroOrMore(Sep + atom)
]
)
return resp
diff --git a/test/test_rparse.py b/test/test_rparse.py
index 1527bddf..8d157a10 100644
--- a/test/test_rparse.py
+++ b/test/test_rparse.py
@@ -250,6 +250,34 @@ class TestParseRequest:
r = rparse.parse_request({}, 'GET:"/foo"')
assert str(r)
+ def test_multiline(self):
+ l = """
+ GET
+ "/foo"
+ ir,@1
+ """
+ r = rparse.parse_request({}, l)
+ assert r.method == "GET"
+ assert r.path == "/foo"
+ assert r.actions
+
+
+ l = """
+ GET
+
+ "/foo
+
+
+
+ bar"
+
+ ir,@1
+ """
+ r = rparse.parse_request({}, l)
+ assert r.method == "GET"
+ assert r.path.s.endswith("bar")
+ assert r.actions
+
class TestParseResponse:
def test_parse_err(self):
--
cgit v1.2.3
From 33208b87205e08b97af07ed6a55c999990a1b8dc Mon Sep 17 00:00:00 2001
From: Aldo Cortesi
Date: Sun, 22 Jul 2012 22:24:16 +1200
Subject: Doc reorg.
---
libpathod/app.py | 5 +
libpathod/templates/docs_lang.html | 220 +++++++++++++++++++++++++++++++++++
libpathod/templates/docs_pathod.html | 195 +------------------------------
libpathod/templates/frame.html | 1 +
4 files changed, 232 insertions(+), 189 deletions(-)
create mode 100644 libpathod/templates/docs_lang.html
diff --git a/libpathod/app.py b/libpathod/app.py
index fd742ce7..21ae9e0d 100644
--- a/libpathod/app.py
+++ b/libpathod/app.py
@@ -36,6 +36,11 @@ def docs_pathod():
return render_template("docs_pathod.html", section="docs")
+@app.route('/docs/language')
+def docs_language():
+ return render_template("docs_lang.html", section="docs")
+
+
@app.route('/docs/pathoc')
def docs_pathoc():
return render_template("docs_pathoc.html", section="docs")
diff --git a/libpathod/templates/docs_lang.html b/libpathod/templates/docs_lang.html
new file mode 100644
index 00000000..11a489b0
--- /dev/null
+++ b/libpathod/templates/docs_lang.html
@@ -0,0 +1,220 @@
+{% extends "frame.html" %}
+{% block body %}
+
+
+
+ Language Spec
+ The mini-language at the heart of pathoc and pathod.
+
+ Set the body. VALUE is a Value
+ Specifier. When the body is set, pathod will
+ automatically set the appropriate Content-Length header.
+
+
+
+
+
+ cVALUE
+
+
+ A shortcut for setting the Content-Type header. Equivalent to:
+
+
h"Content-Type"=VALUE
+
+
+
+
+
+
+ iOFFSET,VALUE
+
+
+ Inject the specified value at the offset. OFFSET can be an
+ integer, or "r" to generate a random offset or "a" for an
+ offset just after all data has been sent.
+
+
+
+
+
+ lVALUE
+
+
+ A shortcut for setting the Location header. Equivalent to:
+
+
h"Location"=VALUE
+
+
+
+
+
+
+
+ dOFFSET
+
+
+ Disconnect after OFFSET bytes. The offset can also be "r", in which case pathod
+ will disconnect at a random point in the response.
+
+
+
+
+
+ pSECONDS,OFFSET
+
+
+ Pause for SECONDS seconds after OFFSET bytes. SECONDS can also be "f" to pause
+ forever. OFFSET can also be "r" to generate a random offset, or "a" for an
+ offset just after all data has been sent.
+
+
+
+
+
+
+
+
Requests
+
+
+
+
+
Executing specs from file
+
+
+
=./path/to/spec
+
+
+
+
Components
+
+
+
+
VALUEs
+
+
Literals
+
+
Literal values are specified as a quoted strings:
+
+
"foo"
+
+
Either single or double quotes are accepted, and quotes can be escaped with
+ backslashes within the string:
+
+
'fo\'o'
+
+
Literal values can contain Python-style backslash escape sequences:
+
+
'foo\r\nbar'
+
+
+
Files
+
+
You can load a value from a specified file path. To do so, you have to specify
+ a _staticdir_ option to pathod on the command-line, like so:
+
+
pathod -d ~/myassets
+
+
All paths are relative paths under this directory. File loads are indicated by
+ starting the value specifier with the left angle bracket:
+
+
<my/path
+
+
The path value can also be a quoted string, with the same syntax as literals:
+
+
<"my/path"
+
+
+
Generated values
+
+
An @-symbol lead-in specifies that generated data should be used. There are two
+ components to a generator specification - a size, and a data type. By default
+ pathod assumes a data type of "bytes".
+
+
Here's a value specifier for generating 100 bytes:
+
+
@100
+
+
You can use standard suffixes to indicate larger values. Here, for instance, is
+ a specifier for generating 100 megabytes:
+
+
@100m
+
+
Data is generated and served efficiently - if you really want to send a
+ terabyte of data to a client, pathod can do it. The supported suffixes are:
+
+
+
+
+
+
b
1024**0 (bytes)
+
+
+
k
1024**1 (kilobytes)
+
+
+
m
1024**2 (megabytes)
+
+
+
g
1024**3 (gigabytes)
+
+
+
t
1024**4 (terabytes)
+
+
+
+
+
Data types are separated from the size specification by a comma. This
+ specification generates 100mb of ASCII:
+
+
@100m,ascii
+
+
Supported data types are:
+
+
+
+
ascii
+
ascii_letters
+
ascii_lowercase
+
ascii_uppercase
+
bytes
+
digits
+
hexdigits
+
letters
+
lowercase
+
octdigits
+
printable
+
punctuation
+
uppercase
+
whitespace
+
+
+
+{% endblock %}
diff --git a/libpathod/templates/docs_pathod.html b/libpathod/templates/docs_pathod.html
index 3b10b212..96866579 100644
--- a/libpathod/templates/docs_pathod.html
+++ b/libpathod/templates/docs_pathod.html
@@ -60,7 +60,7 @@ various other goodies. Try it by visiting the server root:
literal string, but there are many other fun things we can do. For example, we
can tell pathod to generate 100k of random ASCII letters instead:
-
200@100k,ascii_letters
+
200:@100k,ascii_letters
Full documentation on the value specification syntax can be found in the next
section.
@@ -121,190 +121,6 @@ various other goodies. Try it by visiting the server root:
- Set the body. VALUE is a Value
- Specifier. When the body is set, pathod will
- automatically set the appropriate Content-Length header.
-
-
-
-
-
- cVALUE
-
-
- A shortcut for setting the Content-Type header. Equivalent to:
-
-
h"Content-Type"=VALUE
-
-
-
-
-
-
- iOFFSET,VALUE
-
-
- Inject the specified value at the offset. OFFSET can be an
- integer, or "r" to generate a random offset or "a" for an
- offset just after all data has been sent.
-
-
-
-
-
- lVALUE
-
-
- A shortcut for setting the Location header. Equivalent to:
-
-
h"Location"=VALUE
-
-
-
-
-
-
-
- dOFFSET
-
-
- Disconnect after OFFSET bytes. The offset can also be "r", in which case pathod
- will disconnect at a random point in the response.
-
-
-
-
-
- pSECONDS,OFFSET
-
-
- Pause for SECONDS seconds after OFFSET bytes. SECONDS can also be "f" to pause
- forever. OFFSET can also be "r" to generate a random offset, or "a" for an
- offset just after all data has been sent.
-
-
-
-
-
-
-
VALUE Specifiers
-
-
Literals
-
-
Literal values are specified as a quoted strings:
-
-
"foo"
-
-
Either single or double quotes are accepted, and quotes can be escaped with
- backslashes within the string:
-
-
'fo\'o'
-
-
Literal values can contain Python-style backslash escape sequences:
-
-
'foo\r\nbar'
-
-
-
Files
-
-
You can load a value from a specified file path. To do so, you have to specify
- a _staticdir_ option to pathod on the command-line, like so:
-
-
pathod -d ~/myassets
-
-
All paths are relative paths under this directory. File loads are indicated by
- starting the value specifier with the left angle bracket:
-
-
<my/path
-
-
The path value can also be a quoted string, with the same syntax as literals:
-
-
<"my/path"
-
-
-
Generated values
-
-
An @-symbol lead-in specifies that generated data should be used. There are two
- components to a generator specification - a size, and a data type. By default
- pathod assumes a data type of "bytes".
-
-
Here's a value specifier for generating 100 bytes:
-
-
@100
-
-
You can use standard suffixes to indicate larger values. Here, for instance, is
- a specifier for generating 100 megabytes:
-
-
@100m
-
-
Data is generated and served efficiently - if you really want to send a
- terabyte of data to a client, pathod can do it. The supported suffixes are:
-
-
-
-
-
-
b
1024**0 (bytes)
-
-
-
k
1024**1 (kilobytes)
-
-
-
m
1024**2 (megabytes)
-
-
-
g
1024**3 (gigabytes)
-
-
-
t
1024**4 (terabytes)
-
-
-
-
-
Data types are separated from the size specification by a comma. This
- specification generates 100mb of ASCII:
-
-
@100m,ascii
-
-
Supported data types are:
-
-
-
-
ascii
-
ascii_letters
-
ascii_lowercase
-
ascii_uppercase
-
bytes
-
digits
-
hexdigits
-
letters
-
lowercase
-
octdigits
-
printable
-
punctuation
-
uppercase
-
whitespace
-
-
-
@@ -358,13 +174,14 @@ various other goodies. Try it by visiting the server root:
Error Responses
-
To let users distinguish crafted responses from internal pathod responses,
- pathod uses the non-standard 800 response code to indicate errors. For example,
- a request to:
+
Pathod uses the non-standard 800 response code to indicate internal
+ errors, to distinguish them from crafted responses. For example, a request
+ to:
http://localhost:9999/p/foo
-
... will return an 800 response, because "foo" is not a valid page specifier.
+
... will return an 800 response because "foo" is not a valid page
+ specifier.
- Set the body. VALUE is a Value
- Specifier. When the body is set, pathod will
+ Set the body. When the body is set, pathod will
automatically set the appropriate Content-Length header.
- Inject the specified value at the offset. OFFSET can be an
- integer, or "r" to generate a random offset or "a" for an
- offset just after all data has been sent.
+ Inject the specified value at the offset.
- Disconnect after OFFSET bytes. The offset can also be "r", in which case pathod
- will disconnect at a random point in the response.
+ Disconnect after OFFSET bytes.
- Pause for SECONDS seconds after OFFSET bytes. SECONDS can also be "f" to pause
- forever. OFFSET can also be "r" to generate a random offset, or "a" for an
- offset just after all data has been sent.
+ Pause for SECONDS seconds after OFFSET bytes. SECONDS can
+ be an integer or "f" to pause forever.
+
-
-
Requests
-
-
-
-
-
Executing specs from file
-
-
-
+./path/to/spec
-
-
-
-
Components
-
-
-
-
VALUEs
-
-
Literals
-
-
Literal values are specified as a quoted strings:
-
-
"foo"
-
-
Either single or double quotes are accepted, and quotes can be escaped with
- backslashes within the string:
-
-
'fo\'o'
-
-
Literal values can contain Python-style backslash escape sequences:
-
-
'foo\r\nbar'
-
-
-
Files
-
-
You can load a value from a specified file path. To do so, you have to specify
- a _staticdir_ option to pathod on the command-line, like so:
-
-
pathod -d ~/myassets
-
-
All paths are relative paths under this directory. File loads are indicated by
- starting the value specifier with the left angle bracket:
-
-
<my/path
-
-
The path value can also be a quoted string, with the same syntax as literals:
-
-
<"my/path"
-
+
+
+
Requests
+
+
-
Generated values
-
An @-symbol lead-in specifies that generated data should be used. There are two
- components to a generator specification - a size, and a data type. By default
- pathod assumes a data type of "bytes".
+
+
+
Executing specs from file
+
-
Here's a value specifier for generating 100 bytes:
-
-
@100
+
+./path/to/spec
-
You can use standard suffixes to indicate larger values. Here, for instance, is
- a specifier for generating 100 megabytes:
+
-
@100m
+
+
+
Features
+
-
Data is generated and served efficiently - if you really want to send a
- terabyte of data to a client, pathod can do it. The supported suffixes are:
+
+
OFFSET
+
Offsets are calculated relative to the base message, before any
+ injections or other transforms are applied. They have 3 flavors:
-
-
-
-
b
1024**0 (bytes)
-
-
-
k
1024**1 (kilobytes)
-
-
-
m
1024**2 (megabytes)
-
-
-
g
1024**3 (gigabytes)
-
-
-
t
1024**4 (terabytes)
-
-
-
+
+
An integer byte offset
+
r for a random location
+
a for the end of the message
+
-
Data types are separated from the size specification by a comma. This
- specification generates 100mb of ASCII:
+
+
VALUE
-
@100m,ascii
+
Literals
-
Supported data types are:
+
Literal values are specified as a quoted strings:
+
"foo"
-
-
ascii
-
ascii_letters
-
ascii_lowercase
-
ascii_uppercase
-
bytes
-
digits
-
hexdigits
-
letters
-
lowercase
-
octdigits
-
printable
-
punctuation
-
uppercase
-
whitespace
-
+
Either single or double quotes are accepted, and quotes can be escaped with
+ backslashes within the string:
+
'fo\'o'
+
+
Literal values can contain Python-style backslash escape sequences:
+
+
'foo\r\nbar'
+
+
+
Files
+
+
You can load a value from a specified file path. To do so, you have to specify
+ a _staticdir_ option to pathod on the command-line, like so:
+
+
pathod -d ~/myassets
+
+
All paths are relative paths under this directory. File loads are indicated by
+ starting the value specifier with the left angle bracket:
+
+
<my/path
+
+
The path value can also be a quoted string, with the same syntax as literals:
+
+
<"my/path"
+
+
+
Generated values
+
+
An @-symbol lead-in specifies that generated data should be used. There are two
+ components to a generator specification - a size, and a data type. By default
+ pathod assumes a data type of "bytes".
+
+
Here's a value specifier for generating 100 bytes:
+
+
@100
+
+
You can use standard suffixes to indicate larger values. Here, for instance, is
+ a specifier for generating 100 megabytes:
+
+
@100m
+
+
Data is generated and served efficiently - if you really want to send a
+ terabyte of data to a client, pathod can do it. The supported suffixes are:
+
+
+
+
+
+
b
1024**0 (bytes)
+
+
+
k
1024**1 (kilobytes)
+
+
+
m
1024**2 (megabytes)
+
+
+
g
1024**3 (gigabytes)
+
+
+
t
1024**4 (terabytes)
+
+
+
+
+
Data types are separated from the size specification by a comma. This
+ specification generates 100mb of ASCII:
+
+
@100m,ascii
+
+
Supported data types are:
+
+
+
+
+
ascii
+
All ASCII characters
+
+
+
ascii_letters
+
A-Za-z
+
+
+
ascii_lowercase
+
a-z
+
+
+
ascii_uppercase
+
A-Z
+
+
+
bytes
+
All 256 byte values
+
+
+
digits
+
0-9
+
+
+
hexdigits
+
0-f
+
+
+
octdigits
+
0-8
+
+
+
punctuation
+
+
!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~
+
+
+
+
whitespace
+
+
\t\n\x0b\x0c\r and space
+
+
+
+
+
{% endblock %}
--
cgit v1.2.3
From c1f75dd5a3857b3e426ed5d47b9164e71a4eed73 Mon Sep 17 00:00:00 2001
From: Aldo Cortesi
Date: Mon, 23 Jul 2012 17:30:50 +1200
Subject: Use local scrolling with a JQuery module, because anchor jumps are
braindead.
---
libpathod/static/jquery.localscroll-min.js | 9 +++++++++
libpathod/static/jquery.scrollTo-min.js | 11 +++++++++++
libpathod/templates/frame.html | 12 ++++++++++++
3 files changed, 32 insertions(+)
create mode 100644 libpathod/static/jquery.localscroll-min.js
create mode 100644 libpathod/static/jquery.scrollTo-min.js
diff --git a/libpathod/static/jquery.localscroll-min.js b/libpathod/static/jquery.localscroll-min.js
new file mode 100644
index 00000000..3f8d64cc
--- /dev/null
+++ b/libpathod/static/jquery.localscroll-min.js
@@ -0,0 +1,9 @@
+/**
+ * jQuery.LocalScroll - Animated scrolling navigation, using anchors.
+ * Copyright (c) 2007-2009 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com
+ * Dual licensed under MIT and GPL.
+ * Date: 3/11/2009
+ * @author Ariel Flesler
+ * @version 1.2.7
+ **/
+;(function($){var l=location.href.replace(/#.*/,'');var g=$.localScroll=function(a){$('body').localScroll(a)};g.defaults={duration:1e3,axis:'y',event:'click',stop:true,target:window,reset:true};g.hash=function(a){if(location.hash){a=$.extend({},g.defaults,a);a.hash=false;if(a.reset){var e=a.duration;delete a.duration;$(a.target).scrollTo(0,a);a.duration=e}i(0,location,a)}};$.fn.localScroll=function(b){b=$.extend({},g.defaults,b);return b.lazy?this.bind(b.event,function(a){var e=$([a.target,a.target.parentNode]).filter(d)[0];if(e)i(a,e,b)}):this.find('a,area').filter(d).bind(b.event,function(a){i(a,this,b)}).end().end();function d(){return!!this.href&&!!this.hash&&this.href.replace(this.hash,'')==l&&(!b.filter||$(this).is(b.filter))}};function i(a,e,b){var d=e.hash.slice(1),f=document.getElementById(d)||document.getElementsByName(d)[0];if(!f)return;if(a)a.preventDefault();var h=$(b.target);if(b.lock&&h.is(':animated')||b.onBefore&&b.onBefore.call(b,a,f,h)===false)return;if(b.stop)h.stop(true);if(b.hash){var j=f.id==d?'id':'name',k=$('').attr(j,d).css({position:'absolute',top:$(window).scrollTop(),left:$(window).scrollLeft()});f[j]='';$('body').prepend(k);location=e.hash;k.remove();f[j]=d}h.scrollTo(f,b).trigger('notify.serialScroll',[f])}})(jQuery);
\ No newline at end of file
diff --git a/libpathod/static/jquery.scrollTo-min.js b/libpathod/static/jquery.scrollTo-min.js
new file mode 100644
index 00000000..7d4001dc
--- /dev/null
+++ b/libpathod/static/jquery.scrollTo-min.js
@@ -0,0 +1,11 @@
+/**
+ * jQuery.ScrollTo - Easy element scrolling using jQuery.
+ * Copyright (c) 2007-2009 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com
+ * Dual licensed under MIT and GPL.
+ * Date: 3/9/2009
+ * @author Ariel Flesler
+ * @version 1.4.1
+ *
+ * http://flesler.blogspot.com/2007/10/jqueryscrollto.html
+ */
+;(function($){var m=$.scrollTo=function(b,h,f){$(window).scrollTo(b,h,f)};m.defaults={axis:'xy',duration:parseFloat($.fn.jquery)>=1.3?0:1};m.window=function(b){return $(window).scrollable()};$.fn.scrollable=function(){return this.map(function(){var b=this,h=!b.nodeName||$.inArray(b.nodeName.toLowerCase(),['iframe','#document','html','body'])!=-1;if(!h)return b;var f=(b.contentWindow||b).document||b.ownerDocument||b;return $.browser.safari||f.compatMode=='BackCompat'?f.body:f.documentElement})};$.fn.scrollTo=function(l,j,a){if(typeof j=='object'){a=j;j=0}if(typeof a=='function')a={onAfter:a};if(l=='max')l=9e9;a=$.extend({},m.defaults,a);j=j||a.speed||a.duration;a.queue=a.queue&&a.axis.length>1;if(a.queue)j/=2;a.offset=n(a.offset);a.over=n(a.over);return this.scrollable().each(function(){var k=this,o=$(k),d=l,p,g={},q=o.is('html,body');switch(typeof d){case'number':case'string':if(/^([+-]=)?\d+(\.\d+)?(px)?$/.test(d)){d=n(d);break}d=$(d,this);case'object':if(d.is||d.style)p=(d=$(d)).offset()}$.each(a.axis.split(''),function(b,h){var f=h=='x'?'Left':'Top',i=f.toLowerCase(),c='scroll'+f,r=k[c],s=h=='x'?'Width':'Height';if(p){g[c]=p[i]+(q?0:r-o.offset()[i]);if(a.margin){g[c]-=parseInt(d.css('margin'+f))||0;g[c]-=parseInt(d.css('border'+f+'Width'))||0}g[c]+=a.offset[i]||0;if(a.over[i])g[c]+=d[s.toLowerCase()]()*a.over[i]}else g[c]=d[i];if(/^\d+$/.test(g[c]))g[c]=g[c]<=0?0:Math.min(g[c],u(s));if(!b&&a.queue){if(r!=g[c])t(a.onAfterFirst);delete g[c]}});t(a.onAfter);function t(b){o.animate(g,j,a.easing,b&&function(){b.call(this,l,a)})};function u(b){var h='scroll'+b;if(!q)return k[h];var f='client'+b,i=k.ownerDocument.documentElement,c=k.ownerDocument.body;return Math.max(i[h],c[h])-Math.min(i[f],c[f])}}).end()};function n(b){return typeof b=='object'?b:{top:b,left:b}}})(jQuery);
\ No newline at end of file
diff --git a/libpathod/templates/frame.html b/libpathod/templates/frame.html
index 9c437eba..f176b15d 100644
--- a/libpathod/templates/frame.html
+++ b/libpathod/templates/frame.html
@@ -7,6 +7,8 @@
+
+
@@ -68,4 +70,14 @@
+