Skip to content

Add 'shortcuts' module. #5

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Feb 7, 2015
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions ppp_libmodule/shortcuts.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
from .simplification import simplify

from ppp_datamodel.communication import TraceItem, Response


def traverse_until_fixpoint(predicate, tree):
"""Traverses the tree again and again until it is not modified."""
old_tree = None
tree = simplify(tree)
while tree and old_tree != tree:
old_tree = tree
tree = tree.traverse(predicate)
if not tree:
return None
tree = simplify(tree)
return tree


def build_answer(request, tree, measures, module_name):
trace = request.trace + [TraceItem(module_name, tree, measures)]
return Response(request.language, tree, measures, trace)

45 changes: 45 additions & 0 deletions tests/test_shortcuts.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
from ppp_libmodule.tests import PPPTestCase
from ppp_libmodule.http import HttpRequestHandler
from ppp_libmodule import shortcuts

from ppp_datamodel.nodes import Triple as T
from ppp_datamodel.nodes import Missing as M
from ppp_datamodel.nodes import Missing as R
from ppp_datamodel.communication import Response, TraceItem

def predicate(node):
if node == T(M(), M(), M()):
return R('foo')
elif node == R('foo'):
return R('bar')
elif node == M():
return node
else:
assert False, node

class RequestHandler:
def __init__(self, request):
self.request = request

def answer(self):
tree = self.request.tree.traverse(predicate)
if tree != self.request.tree:
# If we have modified the tree, it is relevant to return it
return [shortcuts.build_answer(self.request, tree, {}, 'test')]
else:
# Otherwise, we have nothing interesting to say.
return []

def app(environ, start_response):
"""Function called by the WSGI server."""
r = HttpRequestHandler(environ, start_response, RequestHandler).dispatch()
return r

class HttpTest(PPPTestCase(app)):
def testWorking(self):
t = T(M(), M(), M())
q = {'id': '1', 'language': 'en', 'tree': t.as_dict(),
'measures': {}, 'trace': []}
self.assertResponse(q, [Response('en', R('bar'), {},
[TraceItem('test', R('bar'), {})])])