http://git-wip-us.apache.org/repos/asf/incubator-slider/blob/4156c1c3/slider-agent/src/main/python/jinja2/examples/bench.py ---------------------------------------------------------------------- diff --git a/slider-agent/src/main/python/jinja2/examples/bench.py b/slider-agent/src/main/python/jinja2/examples/bench.py deleted file mode 100644 index c648dc6..0000000 --- a/slider-agent/src/main/python/jinja2/examples/bench.py +++ /dev/null @@ -1,433 +0,0 @@ -"""\ - This benchmark compares some python templating engines with Jinja 2 so - that we get a picture of how fast Jinja 2 is for a semi real world - template. If a template engine is not installed the test is skipped.\ -""" -import sys -import cgi -from timeit import Timer -from jinja2 import Environment as JinjaEnvironment - -context = { - 'page_title': 'mitsuhiko\'s benchmark', - 'table': [dict(a=1,b=2,c=3,d=4,e=5,f=6,g=7,h=8,i=9,j=10) for x in range(1000)] -} - -jinja_template = JinjaEnvironment( - line_statement_prefix='%', - variable_start_string="${", - variable_end_string="}" -).from_string("""\ -<!doctype html> -<html> - <head> - <title>${page_title|e}</title> - </head> - <body> - <div class="header"> - <h1>${page_title|e}</h1> - </div> - <ul class="navigation"> - % for href, caption in [ - ('index.html', 'Index'), - ('downloads.html', 'Downloads'), - ('products.html', 'Products') - ] - <li><a href="${href|e}">${caption|e}</a></li> - % endfor - </ul> - <div class="table"> - <table> - % for row in table - <tr> - % for cell in row - <td>${cell}</td> - % endfor - </tr> - % endfor - </table> - </div> - </body> -</html>\ -""") - -def test_jinja(): - jinja_template.render(context) - -try: - from tornado.template import Template -except ImportError: - test_tornado = None -else: - tornado_template = Template("""\ -<!doctype html> -<html> - <head> - <title>{{ page_title }}</title> - </head> - <body> - <div class="header"> - <h1>{{ page_title }}</h1> - </div> - <ul class="navigation"> - {% for href, caption in [ \ - ('index.html', 'Index'), \ - ('downloads.html', 'Downloads'), \ - ('products.html', 'Products') \ - ] %} - <li><a href="{{ href }}">{{ caption }}</a></li> - {% end %} - </ul> - <div class="table"> - <table> - {% for row in table %} - <tr> - {% for cell in row %} - <td>{{ cell }}</td> - {% end %} - </tr> - {% end %} - </table> - </div> - </body> -</html>\ -""") - - def test_tornado(): - tornado_template.generate(**context) - -try: - from django.conf import settings - settings.configure() - from django.template import Template as DjangoTemplate, Context as DjangoContext -except ImportError: - test_django = None -else: - django_template = DjangoTemplate("""\ -<!doctype html> -<html> - <head> - <title>{{ page_title }}</title> - </head> - <body> - <div class="header"> - <h1>{{ page_title }}</h1> - </div> - <ul class="navigation"> - {% for href, caption in navigation %} - <li><a href="{{ href }}">{{ caption }}</a></li> - {% endfor %} - </ul> - <div class="table"> - <table> - {% for row in table %} - <tr> - {% for cell in row %} - <td>{{ cell }}</td> - {% endfor %} - </tr> - {% endfor %} - </table> - </div> - </body> -</html>\ -""") - - def test_django(): - c = DjangoContext(context) - c['navigation'] = [('index.html', 'Index'), ('downloads.html', 'Downloads'), - ('products.html', 'Products')] - django_template.render(c) - -try: - from mako.template import Template as MakoTemplate -except ImportError: - test_mako = None -else: - mako_template = MakoTemplate("""\ -<!doctype html> -<html> - <head> - <title>${page_title|h}</title> - </head> - <body> - <div class="header"> - <h1>${page_title|h}</h1> - </div> - <ul class="navigation"> - % for href, caption in [('index.html', 'Index'), ('downloads.html', 'Downloads'), ('products.html', 'Products')]: - <li><a href="${href|h}">${caption|h}</a></li> - % endfor - </ul> - <div class="table"> - <table> - % for row in table: - <tr> - % for cell in row: - <td>${cell}</td> - % endfor - </tr> - % endfor - </table> - </div> - </body> -</html>\ -""") - - def test_mako(): - mako_template.render(**context) - -try: - from genshi.template import MarkupTemplate as GenshiTemplate -except ImportError: - test_genshi = None -else: - genshi_template = GenshiTemplate("""\ -<html xmlns="http://www.w3.org/1999/xhtml" xmlns:py="http://genshi.edgewall.org/"> - <head> - <title>${page_title}</title> - </head> - <body> - <div class="header"> - <h1>${page_title}</h1> - </div> - <ul class="navigation"> - <li py:for="href, caption in [ - ('index.html', 'Index'), - ('downloads.html', 'Downloads'), - ('products.html', 'Products')]"><a href="${href}">${caption}</a></li> - </ul> - <div class="table"> - <table> - <tr py:for="row in table"> - <td py:for="cell in row">${cell}</td> - </tr> - </table> - </div> - </body> -</html>\ -""") - - def test_genshi(): - genshi_template.generate(**context).render('html', strip_whitespace=False) - -try: - from Cheetah.Template import Template as CheetahTemplate -except ImportError: - test_cheetah = None -else: - cheetah_template = CheetahTemplate("""\ -#import cgi -<!doctype html> -<html> - <head> - <title>$cgi.escape($page_title)</title> - </head> - <body> - <div class="header"> - <h1>$cgi.escape($page_title)</h1> - </div> - <ul class="navigation"> - #for $href, $caption in [('index.html', 'Index'), ('downloads.html', 'Downloads'), ('products.html', 'Products')]: - <li><a href="$cgi.escape($href)">$cgi.escape($caption)</a></li> - #end for - </ul> - <div class="table"> - <table> - #for $row in $table: - <tr> - #for $cell in $row: - <td>$cell</td> - #end for - </tr> - #end for - </table> - </div> - </body> -</html>\ -""", searchList=[dict(context)]) - - def test_cheetah(): - unicode(cheetah_template) - -try: - import tenjin -except ImportError: - test_tenjin = None -else: - tenjin_template = tenjin.Template() - tenjin_template.convert("""\ -<!doctype html> -<html> - <head> - <title>${page_title}</title> - </head> - <body> - <div class="header"> - <h1>${page_title}</h1> - </div> - <ul class="navigation"> -<?py for href, caption in [('index.html', 'Index'), ('downloads.html', 'Downloads'), ('products.html', 'Products')]: ?> - <li><a href="${href}">${caption}</a></li> -<?py #end ?> - </ul> - <div class="table"> - <table> -<?py for row in table: ?> - <tr> -<?py for cell in row: ?> - <td>#{cell}</td> -<?py #end ?> - </tr> -<?py #end ?> - </table> - </div> - </body> -</html>\ -""") - - def test_tenjin(): - from tenjin.helpers import escape, to_str - tenjin_template.render(context, locals()) - -try: - from spitfire.compiler import util as SpitfireTemplate - from spitfire.compiler.analyzer import o2_options as spitfire_optimizer -except ImportError: - test_spitfire = None -else: - spitfire_template = SpitfireTemplate.load_template("""\ -<!doctype html> -<html> - <head> - <title>$cgi.escape($page_title)</title> - </head> - <body> - <div class="header"> - <h1>$cgi.escape($page_title)</h1> - </div> - <ul class="navigation"> - #for $href, $caption in [('index.html', 'Index'), ('downloads.html', 'Downloads'), ('products.html', 'Products')] - <li><a href="$cgi.escape($href)">$cgi.escape($caption)</a></li> - #end for - </ul> - <div class="table"> - <table> - #for $row in $table - <tr> - #for $cell in $row - <td>$cell</td> - #end for - </tr> - #end for - </table> - </div> - </body> -</html>\ -""", 'spitfire_tmpl', spitfire_optimizer, {'enable_filters': False}) - spitfire_context = dict(context, **{'cgi': cgi}) - - def test_spitfire(): - spitfire_template(search_list=[spitfire_context]).main() - - -try: - from chameleon.zpt.template import PageTemplate -except ImportError: - test_chameleon = None -else: - chameleon_template = PageTemplate("""\ -<html xmlns:tal="http://xml.zope.org/namespaces/tal"> - <head> - <title tal:content="page_title">Page Title</title> - </head> - <body> - <div class="header"> - <h1 tal:content="page_title">Page Title</h1> - </div> - <ul class="navigation"> - <li tal:repeat="item sections"><a tal:attributes="href item[0]" tal:content="item[1]">caption</a></li> - </ul> - <div class="table"> - <table> - <tr tal:repeat="row table"> - <td tal:repeat="cell row" tal:content="row[cell]">cell</td> - </tr> - </table> - </div> - </body> -</html>\ -""") - chameleon_context = dict(context) - chameleon_context['sections'] = [ - ('index.html', 'Index'), - ('downloads.html', 'Downloads'), - ('products.html', 'Products') - ] - def test_chameleon(): - chameleon_template.render(**chameleon_context) - -try: - from chameleon.zpt.template import PageTemplate - from chameleon.genshi import language -except ImportError: - test_chameleon_genshi = None -else: - chameleon_genshi_template = PageTemplate("""\ -<html xmlns="http://www.w3.org/1999/xhtml" xmlns:py="http://genshi.edgewall.org/"> - <head> - <title>${page_title}</title> - </head> - <body> - <div class="header"> - <h1>${page_title}</h1> - </div> - <ul class="navigation"> - <li py:for="info in sections"><a href="${info[0]}">${info[1]}</a></li> - </ul> - <div class="table"> - <table> - <tr py:for="row in table"> - <td py:for="cell in row">${row[cell]}</td> - </tr> - </table> - </div> - </body> -</html>\ -""", parser=language.Parser()) - chameleon_genshi_context = dict(context) - chameleon_genshi_context['sections'] = [ - ('index.html', 'Index'), - ('downloads.html', 'Downloads'), - ('products.html', 'Products') - ] - def test_chameleon_genshi(): - chameleon_genshi_template.render(**chameleon_genshi_context) - - -sys.stdout.write('\r' + '\n'.join(( - '=' * 80, - 'Template Engine BigTable Benchmark'.center(80), - '=' * 80, - __doc__, - '-' * 80 -)) + '\n') - - -for test in 'jinja', 'mako', 'tornado', 'tenjin', 'spitfire', 'django', 'genshi', 'cheetah', 'chameleon', 'chameleon_genshi': - if locals()['test_' + test] is None: - sys.stdout.write(' %-20s*not installed*\n' % test) - continue - t = Timer(setup='from __main__ import test_%s as bench' % test, - stmt='bench()') - sys.stdout.write(' >> %-20s<running>' % test) - sys.stdout.flush() - sys.stdout.write('\r %-20s%.4f seconds\n' % (test, t.timeit(number=50) / 50)) -sys.stdout.write('-' * 80 + '\n') -sys.stdout.write('''\ - WARNING: The results of this benchmark are useless to compare the - performance of template engines and should not be taken seriously in any - way. It's testing the performance of simple loops and has no real-world - usefulnes. It only used to check if changes on the Jinja code affect - performance in a good or bad way and how it roughly compares to others. -''' + '=' * 80 + '\n')
http://git-wip-us.apache.org/repos/asf/incubator-slider/blob/4156c1c3/slider-agent/src/main/python/jinja2/examples/profile.py ---------------------------------------------------------------------- diff --git a/slider-agent/src/main/python/jinja2/examples/profile.py b/slider-agent/src/main/python/jinja2/examples/profile.py deleted file mode 100644 index 0c907ae..0000000 --- a/slider-agent/src/main/python/jinja2/examples/profile.py +++ /dev/null @@ -1,52 +0,0 @@ -try: - from cProfile import Profile -except ImportError: - from profile import Profile -from pstats import Stats -from jinja2 import Environment as JinjaEnvironment - -context = { - 'page_title': 'mitsuhiko\'s benchmark', - 'table': [dict(a=1,b=2,c=3,d=4,e=5,f=6,g=7,h=8,i=9,j=10) for x in range(1000)] -} - -source = """\ -% macro testmacro(x) - <span>${x}</span> -% endmacro -<!doctype html> -<html> - <head> - <title>${page_title|e}</title> - </head> - <body> - <div class="header"> - <h1>${page_title|e}</h1> - </div> - <div class="table"> - <table> - % for row in table - <tr> - % for cell in row - <td>${testmacro(cell)}</td> - % endfor - </tr> - % endfor - </table> - </div> - </body> -</html>\ -""" -jinja_template = JinjaEnvironment( - line_statement_prefix='%', - variable_start_string="${", - variable_end_string="}" -).from_string(source) -print jinja_template.environment.compile(source, raw=True) - - -p = Profile() -p.runcall(lambda: jinja_template.render(context)) -stats = Stats(p) -stats.sort_stats('time', 'calls') -stats.print_stats() http://git-wip-us.apache.org/repos/asf/incubator-slider/blob/4156c1c3/slider-agent/src/main/python/jinja2/examples/rwbench/django/_form.html ---------------------------------------------------------------------- diff --git a/slider-agent/src/main/python/jinja2/examples/rwbench/django/_form.html b/slider-agent/src/main/python/jinja2/examples/rwbench/django/_form.html deleted file mode 100644 index 9c4f710..0000000 --- a/slider-agent/src/main/python/jinja2/examples/rwbench/django/_form.html +++ /dev/null @@ -1 +0,0 @@ -<form action="{{ action }}" method="{{ method }}">{{ body }}</form> http://git-wip-us.apache.org/repos/asf/incubator-slider/blob/4156c1c3/slider-agent/src/main/python/jinja2/examples/rwbench/django/_input_field.html ---------------------------------------------------------------------- diff --git a/slider-agent/src/main/python/jinja2/examples/rwbench/django/_input_field.html b/slider-agent/src/main/python/jinja2/examples/rwbench/django/_input_field.html deleted file mode 100644 index 290fdbd..0000000 --- a/slider-agent/src/main/python/jinja2/examples/rwbench/django/_input_field.html +++ /dev/null @@ -1 +0,0 @@ -<input type="{{ type }}" value="{{ value }}" name="{{ name }}"> http://git-wip-us.apache.org/repos/asf/incubator-slider/blob/4156c1c3/slider-agent/src/main/python/jinja2/examples/rwbench/django/_textarea.html ---------------------------------------------------------------------- diff --git a/slider-agent/src/main/python/jinja2/examples/rwbench/django/_textarea.html b/slider-agent/src/main/python/jinja2/examples/rwbench/django/_textarea.html deleted file mode 100644 index 7f10424..0000000 --- a/slider-agent/src/main/python/jinja2/examples/rwbench/django/_textarea.html +++ /dev/null @@ -1 +0,0 @@ -<textarea name="{{ name }}" rows="{{ rows }}" cols="{{ cols }}">{{ value }}</textarea> http://git-wip-us.apache.org/repos/asf/incubator-slider/blob/4156c1c3/slider-agent/src/main/python/jinja2/examples/rwbench/django/index.html ---------------------------------------------------------------------- diff --git a/slider-agent/src/main/python/jinja2/examples/rwbench/django/index.html b/slider-agent/src/main/python/jinja2/examples/rwbench/django/index.html deleted file mode 100644 index 6f620bb..0000000 --- a/slider-agent/src/main/python/jinja2/examples/rwbench/django/index.html +++ /dev/null @@ -1,29 +0,0 @@ -{% extends "layout.html" %} -{% block page_title %}Index Page{% endblock %} -{% block body %} - {% for article in articles %} - {% if article.published %} - <div class="article"> - <h2><a href="{{ article.href }}">{{ article.title }}</a></h2> - <p class="meta">written by <a href="{{ article.user.href }}">{{ article.user.username }}</a> on {{ article.pub_date|dateformat }}</p> - <div class="text">{{ article.body|safe }}</div> - </div> - {% endif %} - {% endfor %} - {% form %} - <dl> - <dt>Name</dt> - <dd>{% input_field 'name' %}</dd> - <dt>E-Mail</dt> - <dd>{% input_field 'email' %}</dd> - <dt>URL</dt> - <dd>{% input_field 'url' %}</dd> - <dt>Comment</dt> - <dd>{% textarea 'comment' %}</dd> - <dt>Captcha</dt> - <dd>{% input_field 'captcha' %}</dd> - </dl> - {% input_field '' 'submit' 'Submit' %} - {% input_field 'cancel' 'submit' 'Cancel' %} - {% endform %} -{% endblock %} http://git-wip-us.apache.org/repos/asf/incubator-slider/blob/4156c1c3/slider-agent/src/main/python/jinja2/examples/rwbench/django/layout.html ---------------------------------------------------------------------- diff --git a/slider-agent/src/main/python/jinja2/examples/rwbench/django/layout.html b/slider-agent/src/main/python/jinja2/examples/rwbench/django/layout.html deleted file mode 100644 index 60039ce..0000000 --- a/slider-agent/src/main/python/jinja2/examples/rwbench/django/layout.html +++ /dev/null @@ -1,29 +0,0 @@ -<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> -<html> -<head> - <title>{% block page_title %}{% endblock %} | RealWorld Benchmark</title> - <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> -</head> -<body> - <div class="contents"> - <div class="header"> - <h1>RealWorld Benchmark</h1> - <blockquote><p> - A less stupid benchmark for Mako and Jinja2 to get an impression how - code changes affect runtime performance. - </p></blockquote> - </div> - <ul class="navigation"> - {% for href, caption in page_navigation %} - <li><a href="{{ href }}">{{ caption }}</a></li> - {% endfor %} - </ul> - <div class="body"> - {% block body %}{% endblock %} - </div> - <div class="footer"> - © Copyright 2008 by I don't know who. - </div> - </div> -</body> -</html> http://git-wip-us.apache.org/repos/asf/incubator-slider/blob/4156c1c3/slider-agent/src/main/python/jinja2/examples/rwbench/djangoext.py ---------------------------------------------------------------------- diff --git a/slider-agent/src/main/python/jinja2/examples/rwbench/djangoext.py b/slider-agent/src/main/python/jinja2/examples/rwbench/djangoext.py deleted file mode 100644 index 9e9fa6c..0000000 --- a/slider-agent/src/main/python/jinja2/examples/rwbench/djangoext.py +++ /dev/null @@ -1,135 +0,0 @@ -# -*- coding: utf-8 -*- -from rwbench import ROOT -from os.path import join -from django.conf import settings -settings.configure( - TEMPLATE_DIRS=(join(ROOT, 'django'),), - TEMPLATE_LOADERS=( - ('django.template.loaders.cached.Loader', ( - 'django.template.loaders.filesystem.Loader', - )), - ) -) -from django.template import loader as django_loader, Context as DjangoContext, \ - Node, NodeList, Variable, TokenParser -from django import template as django_template_module -from django.template import Library - - -# for django extensions. We monkey patch our extensions in so that -# we don't have to initialize a more complex django setup. -django_extensions = django_template_module.Library() -django_template_module.builtins.append(django_extensions) - - -from rwbench import dateformat -django_extensions.filter(dateformat) - - -def var_or_none(x): - if x is not None: - return Variable(x) - - -# and more django extensions -@django_extensions.tag -def input_field(parser, token): - p = TokenParser(token.contents) - args = [p.value()] - while p.more(): - args.append(p.value()) - return InputFieldNode(*args) - - -@django_extensions.tag -def textarea(parser, token): - p = TokenParser(token.contents) - args = [p.value()] - while p.more(): - args.append(p.value()) - return TextareaNode(*args) - - -@django_extensions.tag -def form(parser, token): - p = TokenParser(token.contents) - args = [] - while p.more(): - args.append(p.value()) - body = parser.parse(('endform',)) - parser.delete_first_token() - return FormNode(body, *args) - - -class InputFieldNode(Node): - - def __init__(self, name, type=None, value=None): - self.name = var_or_none(name) - self.type = var_or_none(type) - self.value = var_or_none(value) - - def render(self, context): - name = self.name.resolve(context) - type = 'text' - value = '' - if self.type is not None: - type = self.type.resolve(context) - if self.value is not None: - value = self.value.resolve(context) - tmpl = django_loader.get_template('_input_field.html') - return tmpl.render(DjangoContext({ - 'name': name, - 'type': type, - 'value': value - })) - - -class TextareaNode(Node): - - def __init__(self, name, rows=None, cols=None, value=None): - self.name = var_or_none(name) - self.rows = var_or_none(rows) - self.cols = var_or_none(cols) - self.value = var_or_none(value) - - def render(self, context): - name = self.name.resolve(context) - rows = 10 - cols = 40 - value = '' - if self.rows is not None: - rows = int(self.rows.resolve(context)) - if self.cols is not None: - cols = int(self.cols.resolve(context)) - if self.value is not None: - value = self.value.resolve(context) - tmpl = django_loader.get_template('_textarea.html') - return tmpl.render(DjangoContext({ - 'name': name, - 'rows': rows, - 'cols': cols, - 'value': value - })) - - -class FormNode(Node): - - def __init__(self, body, action=None, method=None): - self.body = body - self.action = action - self.method = method - - def render(self, context): - body = self.body.render(context) - action = '' - method = 'post' - if self.action is not None: - action = self.action.resolve(context) - if self.method is not None: - method = self.method.resolve(context) - tmpl = django_loader.get_template('_form.html') - return tmpl.render(DjangoContext({ - 'body': body, - 'action': action, - 'method': method - })) http://git-wip-us.apache.org/repos/asf/incubator-slider/blob/4156c1c3/slider-agent/src/main/python/jinja2/examples/rwbench/genshi/helpers.html ---------------------------------------------------------------------- diff --git a/slider-agent/src/main/python/jinja2/examples/rwbench/genshi/helpers.html b/slider-agent/src/main/python/jinja2/examples/rwbench/genshi/helpers.html deleted file mode 100644 index ecc6dc4..0000000 --- a/slider-agent/src/main/python/jinja2/examples/rwbench/genshi/helpers.html +++ /dev/null @@ -1,12 +0,0 @@ -<div xmlns="http://www.w3.org/1999/xhtml" xmlns:py="http://genshi.edgewall.org/" - py:strip=""> - - <py:def function="input_field(name='', value='', type='text')"> - <input type="$type" value="$value" name="$name" /> - </py:def> - - <py:def function="textarea(name, value='', rows=10, cols=40)"> - <textarea name="$name" rows="$rows" cols="cols">$value</textarea> - </py:def> - -</div> http://git-wip-us.apache.org/repos/asf/incubator-slider/blob/4156c1c3/slider-agent/src/main/python/jinja2/examples/rwbench/genshi/index.html ---------------------------------------------------------------------- diff --git a/slider-agent/src/main/python/jinja2/examples/rwbench/genshi/index.html b/slider-agent/src/main/python/jinja2/examples/rwbench/genshi/index.html deleted file mode 100644 index 70f697d..0000000 --- a/slider-agent/src/main/python/jinja2/examples/rwbench/genshi/index.html +++ /dev/null @@ -1,41 +0,0 @@ -<?python - from rwbench import dateformat -?> -<html xmlns="http://www.w3.org/1999/xhtml" xmlns:xi="http://www.w3.org/2001/XInclude" - xmlns:py="http://genshi.edgewall.org/"> - <xi:include href="layout.html" /> - <xi:include href="helpers.html" /> - <head><title>Index Page</title></head> - <body> - <div class="article" py:for="article in articles"> - <py:if test="article.published"> - <h2><a href="${article.href}">${article.title}</a></h2> - <p class="meta">written by <a href="${article.user.href}" - >${article.user.username}</a> on ${dateformat(article.pub_date)}</p> - <div class="text">${Markup(article.body)}</div> - </py:if> - </div> - <!-- - For a fair and balanced comparison we would have to use a def here - that wraps the form data but I don't know what would be the best - Genshi equivalent for that. Quite frankly I doubt that this makes - sense in Genshi anyways. - --> - <form action="" method="post"> - <dl> - <dt>Name</dt> - <dd>${input_field('name')}</dd> - <dt>E-Mail</dt> - <dd>${input_field('email')}</dd> - <dt>URL</dt> - <dd>${input_field('url')}</dd> - <dt>Comment</dt> - <dd>${textarea('comment')}</dd> - <dt>Captcha</dt> - <dd>${input_field('captcha')}</dd> - </dl> - ${input_field(type='submit', value='Submit')} - ${input_field(name='cancel', type='submit', value='Cancel')} - </form> - </body> -</html> http://git-wip-us.apache.org/repos/asf/incubator-slider/blob/4156c1c3/slider-agent/src/main/python/jinja2/examples/rwbench/genshi/layout.html ---------------------------------------------------------------------- diff --git a/slider-agent/src/main/python/jinja2/examples/rwbench/genshi/layout.html b/slider-agent/src/main/python/jinja2/examples/rwbench/genshi/layout.html deleted file mode 100644 index b12aec4..0000000 --- a/slider-agent/src/main/python/jinja2/examples/rwbench/genshi/layout.html +++ /dev/null @@ -1,30 +0,0 @@ -<html xmlns="http://www.w3.org/1999/xhtml" xmlns:py="http://genshi.edgewall.org/" > - <py:match path="head" once="true"> - <head> - <title>${select('title/text()')} | RealWorld Benchmark</title> - <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> - </head> - </py:match> - <py:match path="body" once="true"> - <body> - <div class="contents"> - <div class="header"> - <h1>RealWorld Benchmark</h1> - <blockquote><p> - A less stupid benchmark for Mako and Jinja2 to get an impression how - code changes affect runtime performance. - </p></blockquote> - </div> - <ul class="navigation"> - <li py:for="href, caption in page_navigation"><a href="$href">$caption</a></li> - </ul> - <div class="body"> - ${select('*|text()')} - </div> - <div class="footer"> - © Copyright 2008 by I don't know who. - </div> - </div> - </body> - </py:match> -</html> http://git-wip-us.apache.org/repos/asf/incubator-slider/blob/4156c1c3/slider-agent/src/main/python/jinja2/examples/rwbench/jinja/helpers.html ---------------------------------------------------------------------- diff --git a/slider-agent/src/main/python/jinja2/examples/rwbench/jinja/helpers.html b/slider-agent/src/main/python/jinja2/examples/rwbench/jinja/helpers.html deleted file mode 100644 index 89976aa..0000000 --- a/slider-agent/src/main/python/jinja2/examples/rwbench/jinja/helpers.html +++ /dev/null @@ -1,12 +0,0 @@ -{% macro input_field(name, value='', type='text') -%} - <input type="{{ type }}" value="{{ value|e }}" name="{{ name }}"> -{%- endmacro %} - -{% macro textarea(name, value='', rows=10, cols=40) -%} - <textarea name="{{ name }}" rows="{{ rows }}" cols="{{ cols }}">{{ - value|e }}</textarea> -{%- endmacro %} - -{% macro form(action='', method='post') -%} - <form action="{{ action|e }}" method="{{ method }}">{{ caller() }}</form> -{%- endmacro %} http://git-wip-us.apache.org/repos/asf/incubator-slider/blob/4156c1c3/slider-agent/src/main/python/jinja2/examples/rwbench/jinja/index.html ---------------------------------------------------------------------- diff --git a/slider-agent/src/main/python/jinja2/examples/rwbench/jinja/index.html b/slider-agent/src/main/python/jinja2/examples/rwbench/jinja/index.html deleted file mode 100644 index b006d05..0000000 --- a/slider-agent/src/main/python/jinja2/examples/rwbench/jinja/index.html +++ /dev/null @@ -1,29 +0,0 @@ -{% extends "layout.html" %} -{% from "helpers.html" import input_field, textarea, form %} -{% block page_title %}Index Page{% endblock %} -{% block body %} - {%- for article in articles if article.published %} - <div class="article"> - <h2><a href="{{ article.href|e }}">{{ article.title|e }}</a></h2> - <p class="meta">written by <a href="{{ article.user.href|e - }}">{{ article.user.username|e }}</a> on {{ article.pub_date|dateformat }}</p> - <div class="text">{{ article.body }}</div> - </div> - {%- endfor %} - {%- call form() %} - <dl> - <dt>Name</dt> - <dd>{{ input_field('name') }}</dd> - <dt>E-Mail</dt> - <dd>{{ input_field('email') }}</dd> - <dt>URL</dt> - <dd>{{ input_field('url') }}</dd> - <dt>Comment</dt> - <dd>{{ textarea('comment') }}</dd> - <dt>Captcha</dt> - <dd>{{ input_field('captcha') }}</dd> - </dl> - {{ input_field(type='submit', value='Submit') }} - {{ input_field('cancel', type='submit', value='Cancel') }} - {%- endcall %} -{% endblock %} http://git-wip-us.apache.org/repos/asf/incubator-slider/blob/4156c1c3/slider-agent/src/main/python/jinja2/examples/rwbench/jinja/layout.html ---------------------------------------------------------------------- diff --git a/slider-agent/src/main/python/jinja2/examples/rwbench/jinja/layout.html b/slider-agent/src/main/python/jinja2/examples/rwbench/jinja/layout.html deleted file mode 100644 index 755789e..0000000 --- a/slider-agent/src/main/python/jinja2/examples/rwbench/jinja/layout.html +++ /dev/null @@ -1,29 +0,0 @@ -<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> -<html> -<head> - <title>{% block page_title %}{% endblock %} | RealWorld Benchmark</title> - <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> -</head> -<body> - <div class="contents"> - <div class="header"> - <h1>RealWorld Benchmark</h1> - <blockquote><p> - A less stupid benchmark for Mako and Jinja2 to get an impression how - code changes affect runtime performance. - </p></blockquote> - </div> - <ul class="navigation"> - {%- for href, caption in page_navigation %} - <li><a href="{{ href|e }}">{{ caption }}</a></li> - {%- endfor %} - </ul> - <div class="body"> - {% block body %}{% endblock %} - </div> - <div class="footer"> - © Copyright 2008 by I don't know who. - </div> - </div> -</body> -</html> http://git-wip-us.apache.org/repos/asf/incubator-slider/blob/4156c1c3/slider-agent/src/main/python/jinja2/examples/rwbench/mako/helpers.html ---------------------------------------------------------------------- diff --git a/slider-agent/src/main/python/jinja2/examples/rwbench/mako/helpers.html b/slider-agent/src/main/python/jinja2/examples/rwbench/mako/helpers.html deleted file mode 100644 index a0290eb..0000000 --- a/slider-agent/src/main/python/jinja2/examples/rwbench/mako/helpers.html +++ /dev/null @@ -1,11 +0,0 @@ -<%def name="input_field(name='', value='', type='text')"> - <input type="${type}" value="${value|h}" name="${name}"> -</%def> - -<%def name="textarea(name, value='', rows=10, cols=40)"> - <textarea name="${name}" rows="${rows}" cols="${cols}">${value|h}</textarea> -</%def> - -<%def name="form(action='', method='post')"> - <form action="${action|h}" method="${method}">${caller.body()}</form> -</%def> http://git-wip-us.apache.org/repos/asf/incubator-slider/blob/4156c1c3/slider-agent/src/main/python/jinja2/examples/rwbench/mako/index.html ---------------------------------------------------------------------- diff --git a/slider-agent/src/main/python/jinja2/examples/rwbench/mako/index.html b/slider-agent/src/main/python/jinja2/examples/rwbench/mako/index.html deleted file mode 100644 index c4c6303..0000000 --- a/slider-agent/src/main/python/jinja2/examples/rwbench/mako/index.html +++ /dev/null @@ -1,31 +0,0 @@ -<%! - from rwbench import dateformat -%> -<%inherit file="layout.html" /> -<%namespace file="helpers.html" import="input_field, textarea, form" /> -<%def name="page_title()">Index Page</%def> -% for article in articles: - <% if not article.published: continue %> -<div class="article"> - <h2><a href="${article.href|h}">${article.title|h}</a></h2> - <p class="meta">written by <a href="${article.user.href|h - }">${article.user.username|h}</a> on ${dateformat(article.pub_date)}</p> - <div class="text">${article.body}</div> -</div> -% endfor -<%call expr="form()"> - <dl> - <dt>Name</dt> - <dd>${input_field('name')}</dd> - <dt>E-Mail</dt> - <dd>${input_field('email')}</dd> - <dt>URL</dt> - <dd>${input_field('url')}</dd> - <dt>Comment</dt> - <dd>${textarea('comment')}</dd> - <dt>Captcha</dt> - <dd>${input_field('captcha')}</dd> - </dl> - ${input_field(type='submit', value='Submit')} - ${input_field(name='cancel', type='submit', value='Cancel')} -</%call> http://git-wip-us.apache.org/repos/asf/incubator-slider/blob/4156c1c3/slider-agent/src/main/python/jinja2/examples/rwbench/mako/layout.html ---------------------------------------------------------------------- diff --git a/slider-agent/src/main/python/jinja2/examples/rwbench/mako/layout.html b/slider-agent/src/main/python/jinja2/examples/rwbench/mako/layout.html deleted file mode 100644 index a9c353e..0000000 --- a/slider-agent/src/main/python/jinja2/examples/rwbench/mako/layout.html +++ /dev/null @@ -1,30 +0,0 @@ -<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> -<html> -<head> - <title>${self.page_title()} | RealWorld Benchmark</title> - <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> -</head> -<body> - <div class="contents"> - <div class="header"> - <h1>RealWorld Benchmark</h1> - <blockquote><p> - A less stupid benchmark for Mako and Jinja2 to get an impression how - code changes affect runtime performance. - </p></blockquote> - </div> - <ul class="navigation"> - % for href, caption in page_navigation: - <li><a href="${href|h}">${caption}</a></li> - % endfor - </ul> - <div class="body"> - ${self.body()} - </div> - <div class="footer"> - © Copyright 2008 by I don't know who. - </div> - </div> -</body> -</html> -<%def name="page_title()"></%def> http://git-wip-us.apache.org/repos/asf/incubator-slider/blob/4156c1c3/slider-agent/src/main/python/jinja2/examples/rwbench/rwbench.py ---------------------------------------------------------------------- diff --git a/slider-agent/src/main/python/jinja2/examples/rwbench/rwbench.py b/slider-agent/src/main/python/jinja2/examples/rwbench/rwbench.py deleted file mode 100644 index 813dd56..0000000 --- a/slider-agent/src/main/python/jinja2/examples/rwbench/rwbench.py +++ /dev/null @@ -1,112 +0,0 @@ -# -*- coding: utf-8 -*- -""" - RealWorldish Benchmark - ~~~~~~~~~~~~~~~~~~~~~~ - - A more real-world benchmark of Jinja2. Like the other benchmark in the - Jinja2 repository this has no real-world usefulnes (despite the name). - Just go away and ignore it. NOW! - - :copyright: (c) 2009 by the Jinja Team. - :license: BSD. -""" -import sys -from os.path import join, dirname, abspath -try: - from cProfile import Profile -except ImportError: - from profile import Profile -from pstats import Stats -ROOT = abspath(dirname(__file__)) - -from random import choice, randrange -from datetime import datetime -from timeit import Timer -from jinja2 import Environment, FileSystemLoader -from jinja2.utils import generate_lorem_ipsum -from mako.lookup import TemplateLookup -from genshi.template import TemplateLoader as GenshiTemplateLoader - - -def dateformat(x): - return x.strftime('%Y-%m-%d') - - -jinja_env = Environment(loader=FileSystemLoader(join(ROOT, 'jinja'))) -jinja_env.filters['dateformat'] = dateformat -mako_lookup = TemplateLookup(directories=[join(ROOT, 'mako')]) -genshi_loader = GenshiTemplateLoader([join(ROOT, 'genshi')]) - -class Article(object): - - def __init__(self, id): - self.id = id - self.href = '/article/%d' % self.id - self.title = generate_lorem_ipsum(1, False, 5, 10) - self.user = choice(users) - self.body = generate_lorem_ipsum() - self.pub_date = datetime.utcfromtimestamp(randrange(10 ** 9, 2 * 10 ** 9)) - self.published = True - - -class User(object): - - def __init__(self, username): - self.href = '/user/%s' % username - self.username = username - - -users = map(User, [u'John Doe', u'Jane Doe', u'Peter Somewhat']) -articles = map(Article, range(20)) -navigation = [ - ('index', 'Index'), - ('about', 'About'), - ('foo?bar=1', 'Foo with Bar'), - ('foo?bar=2&s=x', 'Foo with X'), - ('blah', 'Blub Blah'), - ('hehe', 'Haha'), -] * 5 - -context = dict(users=users, articles=articles, page_navigation=navigation) - - -jinja_template = jinja_env.get_template('index.html') -mako_template = mako_lookup.get_template('index.html') -genshi_template = genshi_loader.load('index.html') - - -def test_jinja(): - jinja_template.render(context) - -def test_mako(): - mako_template.render_unicode(**context) - - -from djangoext import django_loader, DjangoContext -def test_django(): - # not cached because django is not thread safe and does - # not cache by itself so it would be unfair to cache it here. - django_template = django_loader.get_template('index.html') - django_template.render(DjangoContext(context)) - - -def test_genshi(): - genshi_template.generate(**context).render('html', doctype='html') - - -if __name__ == '__main__': - sys.stdout.write('Realworldish Benchmark:\n') - for test in 'jinja', 'mako', 'django', 'genshi': - t = Timer(setup='from __main__ import test_%s as bench' % test, - stmt='bench()') - sys.stdout.write(' >> %-20s<running>' % test) - sys.stdout.flush() - sys.stdout.write('\r %-20s%.4f seconds\n' % (test, t.timeit(number=200) / 200)) - - if '-p' in sys.argv: - print 'Jinja profile' - p = Profile() - p.runcall(test_jinja) - stats = Stats(p) - stats.sort_stats('time', 'calls') - stats.print_stats() http://git-wip-us.apache.org/repos/asf/incubator-slider/blob/4156c1c3/slider-agent/src/main/python/kazoo/tests/__init__.py ---------------------------------------------------------------------- diff --git a/slider-agent/src/main/python/kazoo/tests/__init__.py b/slider-agent/src/main/python/kazoo/tests/__init__.py deleted file mode 100644 index 901253b..0000000 --- a/slider-agent/src/main/python/kazoo/tests/__init__.py +++ /dev/null @@ -1 +0,0 @@ -"""license: Apache License 2.0, see LICENSE for more details.""" http://git-wip-us.apache.org/repos/asf/incubator-slider/blob/4156c1c3/slider-agent/src/main/python/kazoo/tests/test_barrier.py ---------------------------------------------------------------------- diff --git a/slider-agent/src/main/python/kazoo/tests/test_barrier.py b/slider-agent/src/main/python/kazoo/tests/test_barrier.py deleted file mode 100644 index 461664f..0000000 --- a/slider-agent/src/main/python/kazoo/tests/test_barrier.py +++ /dev/null @@ -1,158 +0,0 @@ -"""license: Apache License 2.0, see LICENSE for more details.""" -import threading - -from nose.tools import eq_ - -from kazoo.testing import KazooTestCase - - -class KazooBarrierTests(KazooTestCase): - def test_barrier_not_exist(self): - b = self.client.Barrier("/some/path") - eq_(b.wait(), True) - - def test_barrier_exists(self): - b = self.client.Barrier("/some/path") - b.create() - eq_(b.wait(0), False) - b.remove() - eq_(b.wait(), True) - - def test_remove_nonexistent_barrier(self): - b = self.client.Barrier("/some/path") - eq_(b.remove(), False) - - -class KazooDoubleBarrierTests(KazooTestCase): - - def test_basic_barrier(self): - b = self.client.DoubleBarrier("/some/path", 1) - eq_(b.participating, False) - b.enter() - eq_(b.participating, True) - b.leave() - eq_(b.participating, False) - - def test_two_barrier(self): - av = threading.Event() - ev = threading.Event() - bv = threading.Event() - release_all = threading.Event() - b1 = self.client.DoubleBarrier("/some/path", 2) - b2 = self.client.DoubleBarrier("/some/path", 2) - - def make_barrier_one(): - b1.enter() - ev.set() - release_all.wait() - b1.leave() - ev.set() - - def make_barrier_two(): - bv.wait() - b2.enter() - av.set() - release_all.wait() - b2.leave() - av.set() - - # Spin up both of them - t1 = threading.Thread(target=make_barrier_one) - t1.start() - t2 = threading.Thread(target=make_barrier_two) - t2.start() - - eq_(b1.participating, False) - eq_(b2.participating, False) - - bv.set() - av.wait() - ev.wait() - eq_(b1.participating, True) - eq_(b2.participating, True) - - av.clear() - ev.clear() - - release_all.set() - av.wait() - ev.wait() - eq_(b1.participating, False) - eq_(b2.participating, False) - t1.join() - t2.join() - - def test_three_barrier(self): - av = threading.Event() - ev = threading.Event() - bv = threading.Event() - release_all = threading.Event() - b1 = self.client.DoubleBarrier("/some/path", 3) - b2 = self.client.DoubleBarrier("/some/path", 3) - b3 = self.client.DoubleBarrier("/some/path", 3) - - def make_barrier_one(): - b1.enter() - ev.set() - release_all.wait() - b1.leave() - ev.set() - - def make_barrier_two(): - bv.wait() - b2.enter() - av.set() - release_all.wait() - b2.leave() - av.set() - - # Spin up both of them - t1 = threading.Thread(target=make_barrier_one) - t1.start() - t2 = threading.Thread(target=make_barrier_two) - t2.start() - - eq_(b1.participating, False) - eq_(b2.participating, False) - - bv.set() - eq_(b1.participating, False) - eq_(b2.participating, False) - b3.enter() - ev.wait() - av.wait() - - eq_(b1.participating, True) - eq_(b2.participating, True) - eq_(b3.participating, True) - - av.clear() - ev.clear() - - release_all.set() - b3.leave() - av.wait() - ev.wait() - eq_(b1.participating, False) - eq_(b2.participating, False) - eq_(b3.participating, False) - t1.join() - t2.join() - - def test_barrier_existing_parent_node(self): - b = self.client.DoubleBarrier('/some/path', 1) - self.assertFalse(b.participating) - self.client.create('/some', ephemeral=True) - # the barrier cannot create children under an ephemeral node - b.enter() - self.assertFalse(b.participating) - - def test_barrier_existing_node(self): - b = self.client.DoubleBarrier('/some', 1) - self.assertFalse(b.participating) - self.client.ensure_path(b.path) - self.client.create(b.create_path, ephemeral=True) - # the barrier will re-use an existing node - b.enter() - self.assertTrue(b.participating) - b.leave() http://git-wip-us.apache.org/repos/asf/incubator-slider/blob/4156c1c3/slider-agent/src/main/python/kazoo/tests/test_build.py ---------------------------------------------------------------------- diff --git a/slider-agent/src/main/python/kazoo/tests/test_build.py b/slider-agent/src/main/python/kazoo/tests/test_build.py deleted file mode 100644 index 0f75d7c..0000000 --- a/slider-agent/src/main/python/kazoo/tests/test_build.py +++ /dev/null @@ -1,30 +0,0 @@ -"""license: Apache License 2.0, see LICENSE for more details.""" -import os - -from nose import SkipTest - -from kazoo.testing import KazooTestCase - - -class TestBuildEnvironment(KazooTestCase): - - def setUp(self): - KazooTestCase.setUp(self) - if not os.environ.get('TRAVIS'): - raise SkipTest('Only run build config tests on Travis.') - - def test_gevent_version(self): - try: - import gevent - except ImportError: - raise SkipTest('gevent not available.') - env_version = os.environ.get('GEVENT_VERSION') - if env_version: - self.assertEqual(env_version, gevent.__version__) - - def test_zookeeper_version(self): - server_version = self.client.server_version() - server_version = '.'.join([str(i) for i in server_version]) - env_version = os.environ.get('ZOOKEEPER_VERSION') - if env_version: - self.assertEqual(env_version, server_version) http://git-wip-us.apache.org/repos/asf/incubator-slider/blob/4156c1c3/slider-agent/src/main/python/kazoo/tests/test_client.py ---------------------------------------------------------------------- diff --git a/slider-agent/src/main/python/kazoo/tests/test_client.py b/slider-agent/src/main/python/kazoo/tests/test_client.py deleted file mode 100644 index f851b63..0000000 --- a/slider-agent/src/main/python/kazoo/tests/test_client.py +++ /dev/null @@ -1,1102 +0,0 @@ -"""license: Apache License 2.0, see LICENSE for more details.""" -import socket -import sys -import threading -import time -import uuid -import unittest - -from mock import patch -from nose import SkipTest -from nose.tools import eq_ -from nose.tools import raises - -from kazoo.testing import KazooTestCase -from kazoo.exceptions import ( - AuthFailedError, - BadArgumentsError, - ConfigurationError, - ConnectionClosedError, - ConnectionLoss, - InvalidACLError, - NoAuthError, - NoNodeError, - NodeExistsError, - SessionExpiredError, -) -from kazoo.protocol.connection import _CONNECTION_DROP -from kazoo.protocol.states import KeeperState, KazooState -from kazoo.tests.util import TRAVIS_ZK_VERSION - - -if sys.version_info > (3, ): # pragma: nocover - def u(s): - return s -else: # pragma: nocover - def u(s): - return unicode(s, "unicode_escape") - - -class TestClientTransitions(KazooTestCase): - def test_connection_and_disconnection(self): - states = [] - rc = threading.Event() - - @self.client.add_listener - def listener(state): - states.append(state) - if state == KazooState.CONNECTED: - rc.set() - - self.client.stop() - eq_(states, [KazooState.LOST]) - states.pop() - - self.client.start() - rc.wait(2) - eq_(states, [KazooState.CONNECTED]) - rc.clear() - states.pop() - self.expire_session() - rc.wait(2) - - req_states = [KazooState.LOST, KazooState.CONNECTED] - eq_(states, req_states) - - -class TestClientConstructor(unittest.TestCase): - - def _makeOne(self, *args, **kw): - from kazoo.client import KazooClient - return KazooClient(*args, **kw) - - def test_invalid_handler(self): - from kazoo.handlers.threading import SequentialThreadingHandler - self.assertRaises( - ConfigurationError, - self._makeOne, handler=SequentialThreadingHandler) - - def test_chroot(self): - self.assertEqual(self._makeOne(hosts='127.0.0.1:2181/').chroot, '') - self.assertEqual(self._makeOne(hosts='127.0.0.1:2181/a').chroot, '/a') - self.assertEqual(self._makeOne(hosts='127.0.0.1/a').chroot, '/a') - self.assertEqual(self._makeOne(hosts='127.0.0.1/a/b').chroot, '/a/b') - self.assertEqual(self._makeOne( - hosts='127.0.0.1:2181,127.0.0.1:2182/a/b').chroot, '/a/b') - - def test_connection_timeout(self): - from kazoo.handlers.threading import KazooTimeoutError - client = self._makeOne(hosts='127.0.0.1:9') - self.assertTrue(client.handler.timeout_exception is KazooTimeoutError) - self.assertRaises(KazooTimeoutError, client.start, 0.1) - - def test_ordered_host_selection(self): - client = self._makeOne(hosts='127.0.0.1:9,127.0.0.2:9/a', - randomize_hosts=False) - hosts = [h for h in client.hosts] - eq_(hosts, [('127.0.0.1', 9), ('127.0.0.2', 9)]) - - def test_invalid_hostname(self): - client = self._makeOne(hosts='nosuchhost/a') - timeout = client.handler.timeout_exception - self.assertRaises(timeout, client.start, 0.1) - - def test_retry_options_dict(self): - from kazoo.retry import KazooRetry - client = self._makeOne(command_retry=dict(max_tries=99), - connection_retry=dict(delay=99)) - self.assertTrue(type(client._conn_retry) is KazooRetry) - self.assertTrue(type(client._retry) is KazooRetry) - eq_(client._retry.max_tries, 99) - eq_(client._conn_retry.delay, 99) - - -class TestAuthentication(KazooTestCase): - - def _makeAuth(self, *args, **kwargs): - from kazoo.security import make_digest_acl - return make_digest_acl(*args, **kwargs) - - def test_auth(self): - username = uuid.uuid4().hex - password = uuid.uuid4().hex - - digest_auth = "%s:%s" % (username, password) - acl = self._makeAuth(username, password, all=True) - - client = self._get_client() - client.start() - client.add_auth("digest", digest_auth) - client.default_acl = (acl,) - - try: - client.create("/1") - client.create("/1/2") - client.ensure_path("/1/2/3") - - eve = self._get_client() - eve.start() - - self.assertRaises(NoAuthError, eve.get, "/1/2") - - # try again with the wrong auth token - eve.add_auth("digest", "badbad:bad") - - self.assertRaises(NoAuthError, eve.get, "/1/2") - finally: - # Ensure we remove the ACL protected nodes - client.delete("/1", recursive=True) - eve.stop() - eve.close() - - def test_connect_auth(self): - username = uuid.uuid4().hex - password = uuid.uuid4().hex - - digest_auth = "%s:%s" % (username, password) - acl = self._makeAuth(username, password, all=True) - - client = self._get_client(auth_data=[('digest', digest_auth)]) - client.start() - try: - client.create('/1', acl=(acl,)) - # give ZK a chance to copy data to other node - time.sleep(0.1) - self.assertRaises(NoAuthError, self.client.get, "/1") - finally: - client.delete('/1') - client.stop() - client.close() - - def test_unicode_auth(self): - username = u("xe4/\hm") - password = u("/\xe4hm") - digest_auth = "%s:%s" % (username, password) - acl = self._makeAuth(username, password, all=True) - - client = self._get_client() - client.start() - client.add_auth("digest", digest_auth) - client.default_acl = (acl,) - - try: - client.create("/1") - client.ensure_path("/1/2/3") - - eve = self._get_client() - eve.start() - - self.assertRaises(NoAuthError, eve.get, "/1/2") - - # try again with the wrong auth token - eve.add_auth("digest", "badbad:bad") - - self.assertRaises(NoAuthError, eve.get, "/1/2") - finally: - # Ensure we remove the ACL protected nodes - client.delete("/1", recursive=True) - eve.stop() - eve.close() - - def test_invalid_auth(self): - client = self._get_client() - client.start() - self.assertRaises(TypeError, client.add_auth, - 'digest', ('user', 'pass')) - self.assertRaises(TypeError, client.add_auth, - None, ('user', 'pass')) - - def test_async_auth(self): - client = self._get_client() - client.start() - username = uuid.uuid4().hex - password = uuid.uuid4().hex - digest_auth = "%s:%s" % (username, password) - result = client.add_auth_async("digest", digest_auth) - self.assertTrue(result.get()) - - def test_async_auth_failure(self): - client = self._get_client() - client.start() - username = uuid.uuid4().hex - password = uuid.uuid4().hex - digest_auth = "%s:%s" % (username, password) - - self.assertRaises(AuthFailedError, client.add_auth, - "unknown-scheme", digest_auth) - - def test_add_auth_on_reconnect(self): - client = self._get_client() - client.start() - client.add_auth("digest", "jsmith:jsmith") - client._connection._socket.shutdown(socket.SHUT_RDWR) - while not client.connected: - time.sleep(0.1) - self.assertTrue(("digest", "jsmith:jsmith") in client.auth_data) - - -class TestConnection(KazooTestCase): - - def test_chroot_warning(self): - k = self._get_nonchroot_client() - k.chroot = 'abba' - try: - with patch('warnings.warn') as mock_func: - k.start() - assert mock_func.called - finally: - k.stop() - - def test_session_expire(self): - from kazoo.protocol.states import KazooState - - cv = threading.Event() - - def watch_events(event): - if event == KazooState.LOST: - cv.set() - - self.client.add_listener(watch_events) - self.expire_session() - cv.wait(3) - assert cv.is_set() - - def test_bad_session_expire(self): - from kazoo.protocol.states import KazooState - - cv = threading.Event() - ab = threading.Event() - - def watch_events(event): - if event == KazooState.LOST: - ab.set() - raise Exception("oops") - cv.set() - - self.client.add_listener(watch_events) - self.expire_session() - ab.wait(0.5) - assert ab.is_set() - cv.wait(0.5) - assert not cv.is_set() - - def test_state_listener(self): - from kazoo.protocol.states import KazooState - states = [] - condition = threading.Condition() - - def listener(state): - with condition: - states.append(state) - condition.notify_all() - - self.client.stop() - eq_(self.client.state, KazooState.LOST) - self.client.add_listener(listener) - self.client.start(5) - - with condition: - if not states: - condition.wait(5) - - eq_(len(states), 1) - eq_(states[0], KazooState.CONNECTED) - - def test_invalid_listener(self): - self.assertRaises(ConfigurationError, self.client.add_listener, 15) - - def test_listener_only_called_on_real_state_change(self): - from kazoo.protocol.states import KazooState - self.assertTrue(self.client.state, KazooState.CONNECTED) - called = [False] - condition = threading.Event() - - def listener(state): - called[0] = True - condition.set() - - self.client.add_listener(listener) - self.client._make_state_change(KazooState.CONNECTED) - condition.wait(3) - self.assertFalse(called[0]) - - def test_no_connection(self): - client = self.client - client.stop() - self.assertFalse(client.connected) - self.assertTrue(client.client_id is None) - self.assertRaises(ConnectionClosedError, client.exists, '/') - - def test_close_connecting_connection(self): - client = self.client - client.stop() - ev = threading.Event() - - def close_on_connecting(state): - if state in (KazooState.CONNECTED, KazooState.LOST): - ev.set() - - client.add_listener(close_on_connecting) - client.start() - - # Wait until we connect - ev.wait(5) - ev.clear() - self.client._call(_CONNECTION_DROP, client.handler.async_result()) - - client.stop() - - # ...and then wait until the connection is lost - ev.wait(5) - - self.assertRaises(ConnectionClosedError, - self.client.create, '/foobar') - - def test_double_start(self): - self.assertTrue(self.client.connected) - self.client.start() - self.assertTrue(self.client.connected) - - def test_double_stop(self): - self.client.stop() - self.assertFalse(self.client.connected) - self.client.stop() - self.assertFalse(self.client.connected) - - def test_restart(self): - self.assertTrue(self.client.connected) - self.client.restart() - self.assertTrue(self.client.connected) - - def test_closed(self): - client = self.client - client.stop() - - write_sock = client._connection._write_sock - - # close the connection to free the socket - client.close() - eq_(client._connection._write_sock, None) - - # sneak in and patch client to simulate race between a thread - # calling stop(); close() and one running a command - oldstate = client._state - client._state = KeeperState.CONNECTED - client._connection._write_sock = write_sock - try: - # simulate call made after write socket is closed - self.assertRaises(ConnectionClosedError, client.exists, '/') - - # simulate call made after write socket is set to None - client._connection._write_sock = None - self.assertRaises(ConnectionClosedError, client.exists, '/') - - finally: - # reset for teardown - client._state = oldstate - client._connection._write_sock = None - - -class TestClient(KazooTestCase): - def _getKazooState(self): - from kazoo.protocol.states import KazooState - return KazooState - - def test_client_id(self): - client_id = self.client.client_id - self.assertEqual(type(client_id), tuple) - # make sure password is of correct length - self.assertEqual(len(client_id[1]), 16) - - def test_connected(self): - client = self.client - self.assertTrue(client.connected) - - def test_create(self): - client = self.client - path = client.create("/1") - eq_(path, "/1") - self.assertTrue(client.exists("/1")) - - def test_create_on_broken_connection(self): - client = self.client - client.start() - - client._state = KeeperState.EXPIRED_SESSION - self.assertRaises(SessionExpiredError, client.create, - '/closedpath', b'bar') - - client._state = KeeperState.AUTH_FAILED - self.assertRaises(AuthFailedError, client.create, - '/closedpath', b'bar') - - client._state = KeeperState.CONNECTING - self.assertRaises(SessionExpiredError, client.create, - '/closedpath', b'bar') - client.stop() - client.close() - - self.assertRaises(ConnectionClosedError, client.create, - '/closedpath', b'bar') - - def test_create_null_data(self): - client = self.client - client.create("/nulldata", None) - value, _ = client.get("/nulldata") - self.assertEqual(value, None) - - def test_create_empty_string(self): - client = self.client - client.create("/empty", b"") - value, _ = client.get("/empty") - eq_(value, b"") - - def test_create_unicode_path(self): - client = self.client - path = client.create(u("/ascii")) - eq_(path, u("/ascii")) - path = client.create(u("/\xe4hm")) - eq_(path, u("/\xe4hm")) - - def test_create_async_returns_unchrooted_path(self): - client = self.client - path = client.create_async('/1').get() - eq_(path, "/1") - - def test_create_invalid_path(self): - client = self.client - self.assertRaises(TypeError, client.create, ('a', )) - self.assertRaises(ValueError, client.create, ".") - self.assertRaises(ValueError, client.create, "/a/../b") - self.assertRaises(BadArgumentsError, client.create, "/b\x00") - self.assertRaises(BadArgumentsError, client.create, "/b\x1e") - - def test_create_invalid_arguments(self): - from kazoo.security import OPEN_ACL_UNSAFE - single_acl = OPEN_ACL_UNSAFE[0] - client = self.client - self.assertRaises(TypeError, client.create, 'a', acl='all') - self.assertRaises(TypeError, client.create, 'a', acl=single_acl) - self.assertRaises(TypeError, client.create, 'a', value=['a']) - self.assertRaises(TypeError, client.create, 'a', ephemeral='yes') - self.assertRaises(TypeError, client.create, 'a', sequence='yes') - self.assertRaises(TypeError, client.create, 'a', makepath='yes') - - def test_create_value(self): - client = self.client - client.create("/1", b"bytes") - data, stat = client.get("/1") - eq_(data, b"bytes") - - def test_create_unicode_value(self): - client = self.client - self.assertRaises(TypeError, client.create, "/1", u("\xe4hm")) - - def test_create_large_value(self): - client = self.client - kb_512 = b"a" * (512 * 1024) - client.create("/1", kb_512) - self.assertTrue(client.exists("/1")) - mb_2 = b"a" * (2 * 1024 * 1024) - self.assertRaises(ConnectionLoss, client.create, "/2", mb_2) - - def test_create_acl_duplicate(self): - from kazoo.security import OPEN_ACL_UNSAFE - single_acl = OPEN_ACL_UNSAFE[0] - client = self.client - client.create("/1", acl=[single_acl, single_acl]) - acls, stat = client.get_acls("/1") - # ZK >3.4 removes duplicate ACL entries - if TRAVIS_ZK_VERSION: - version = TRAVIS_ZK_VERSION - else: - version = client.server_version() - self.assertEqual(len(acls), 1 if version > (3, 4) else 2) - - def test_create_acl_empty_list(self): - from kazoo.security import OPEN_ACL_UNSAFE - client = self.client - client.create("/1", acl=[]) - acls, stat = client.get_acls("/1") - self.assertEqual(acls, OPEN_ACL_UNSAFE) - - def test_version_no_connection(self): - @raises(ConnectionLoss) - def testit(): - self.client.server_version() - self.client.stop() - testit() - - def test_create_ephemeral(self): - client = self.client - client.create("/1", b"ephemeral", ephemeral=True) - data, stat = client.get("/1") - eq_(data, b"ephemeral") - eq_(stat.ephemeralOwner, client.client_id[0]) - - def test_create_no_ephemeral(self): - client = self.client - client.create("/1", b"val1") - data, stat = client.get("/1") - self.assertFalse(stat.ephemeralOwner) - - def test_create_ephemeral_no_children(self): - from kazoo.exceptions import NoChildrenForEphemeralsError - client = self.client - client.create("/1", b"ephemeral", ephemeral=True) - self.assertRaises(NoChildrenForEphemeralsError, - client.create, "/1/2", b"val1") - self.assertRaises(NoChildrenForEphemeralsError, - client.create, "/1/2", b"val1", ephemeral=True) - - def test_create_sequence(self): - client = self.client - client.create("/folder") - path = client.create("/folder/a", b"sequence", sequence=True) - eq_(path, "/folder/a0000000000") - path2 = client.create("/folder/a", b"sequence", sequence=True) - eq_(path2, "/folder/a0000000001") - path3 = client.create("/folder/", b"sequence", sequence=True) - eq_(path3, "/folder/0000000002") - - def test_create_ephemeral_sequence(self): - basepath = "/" + uuid.uuid4().hex - realpath = self.client.create(basepath, b"sandwich", - sequence=True, ephemeral=True) - self.assertTrue(basepath != realpath and realpath.startswith(basepath)) - data, stat = self.client.get(realpath) - eq_(data, b"sandwich") - - def test_create_makepath(self): - self.client.create("/1/2", b"val1", makepath=True) - data, stat = self.client.get("/1/2") - eq_(data, b"val1") - - self.client.create("/1/2/3/4/5", b"val2", makepath=True) - data, stat = self.client.get("/1/2/3/4/5") - eq_(data, b"val2") - - self.assertRaises(NodeExistsError, self.client.create, - "/1/2/3/4/5", b"val2", makepath=True) - - def test_create_makepath_incompatible_acls(self): - from kazoo.client import KazooClient - from kazoo.security import make_digest_acl_credential, CREATOR_ALL_ACL - credential = make_digest_acl_credential("username", "password") - alt_client = KazooClient( - self.cluster[0].address + self.client.chroot, - max_retries=5, auth_data=[("digest", credential)]) - alt_client.start() - alt_client.create("/1/2", b"val2", makepath=True, acl=CREATOR_ALL_ACL) - - try: - self.assertRaises(NoAuthError, self.client.create, - "/1/2/3/4/5", b"val2", makepath=True) - finally: - alt_client.delete('/', recursive=True) - alt_client.stop() - - def test_create_no_makepath(self): - self.assertRaises(NoNodeError, self.client.create, - "/1/2", b"val1") - self.assertRaises(NoNodeError, self.client.create, - "/1/2", b"val1", makepath=False) - - self.client.create("/1/2", b"val1", makepath=True) - self.assertRaises(NoNodeError, self.client.create, - "/1/2/3/4", b"val1", makepath=False) - - def test_create_exists(self): - from kazoo.exceptions import NodeExistsError - client = self.client - path = client.create("/1") - self.assertRaises(NodeExistsError, client.create, path) - - def test_create_get_set(self): - nodepath = "/" + uuid.uuid4().hex - - self.client.create(nodepath, b"sandwich", ephemeral=True) - - data, stat = self.client.get(nodepath) - eq_(data, b"sandwich") - - newstat = self.client.set(nodepath, b"hats", stat.version) - self.assertTrue(newstat) - assert newstat.version > stat.version - - # Some other checks of the ZnodeStat object we got - eq_(newstat.acl_version, stat.acl_version) - eq_(newstat.created, stat.ctime / 1000.0) - eq_(newstat.last_modified, newstat.mtime / 1000.0) - eq_(newstat.owner_session_id, stat.ephemeralOwner) - eq_(newstat.creation_transaction_id, stat.czxid) - eq_(newstat.last_modified_transaction_id, newstat.mzxid) - eq_(newstat.data_length, newstat.dataLength) - eq_(newstat.children_count, stat.numChildren) - eq_(newstat.children_version, stat.cversion) - - def test_get_invalid_arguments(self): - client = self.client - self.assertRaises(TypeError, client.get, ('a', 'b')) - self.assertRaises(TypeError, client.get, 'a', watch=True) - - def test_bad_argument(self): - client = self.client - client.ensure_path("/1") - self.assertRaises(TypeError, self.client.set, "/1", 1) - - def test_ensure_path(self): - client = self.client - client.ensure_path("/1/2") - self.assertTrue(client.exists("/1/2")) - - client.ensure_path("/1/2/3/4") - self.assertTrue(client.exists("/1/2/3/4")) - - def test_sync(self): - client = self.client - self.assertTrue(client.sync('/'), '/') - - def test_exists(self): - nodepath = "/" + uuid.uuid4().hex - - exists = self.client.exists(nodepath) - eq_(exists, None) - - self.client.create(nodepath, b"sandwich", ephemeral=True) - exists = self.client.exists(nodepath) - self.assertTrue(exists) - assert isinstance(exists.version, int) - - multi_node_nonexistent = "/" + uuid.uuid4().hex + "/hats" - exists = self.client.exists(multi_node_nonexistent) - eq_(exists, None) - - def test_exists_invalid_arguments(self): - client = self.client - self.assertRaises(TypeError, client.exists, ('a', 'b')) - self.assertRaises(TypeError, client.exists, 'a', watch=True) - - def test_exists_watch(self): - nodepath = "/" + uuid.uuid4().hex - event = self.client.handler.event_object() - - def w(watch_event): - eq_(watch_event.path, nodepath) - event.set() - - exists = self.client.exists(nodepath, watch=w) - eq_(exists, None) - - self.client.create(nodepath, ephemeral=True) - - event.wait(1) - self.assertTrue(event.is_set()) - - def test_exists_watcher_exception(self): - nodepath = "/" + uuid.uuid4().hex - event = self.client.handler.event_object() - - # if the watcher throws an exception, all we can really do is log it - def w(watch_event): - eq_(watch_event.path, nodepath) - event.set() - - raise Exception("test exception in callback") - - exists = self.client.exists(nodepath, watch=w) - eq_(exists, None) - - self.client.create(nodepath, ephemeral=True) - - event.wait(1) - self.assertTrue(event.is_set()) - - def test_create_delete(self): - nodepath = "/" + uuid.uuid4().hex - - self.client.create(nodepath, b"zzz") - - self.client.delete(nodepath) - - exists = self.client.exists(nodepath) - eq_(exists, None) - - def test_get_acls(self): - from kazoo.security import make_digest_acl - acl = make_digest_acl('user', 'pass', all=True) - client = self.client - try: - client.create('/a', acl=[acl]) - self.assertTrue(acl in client.get_acls('/a')[0]) - finally: - client.delete('/a') - - def test_get_acls_invalid_arguments(self): - client = self.client - self.assertRaises(TypeError, client.get_acls, ('a', 'b')) - - def test_set_acls(self): - from kazoo.security import make_digest_acl - acl = make_digest_acl('user', 'pass', all=True) - client = self.client - client.create('/a') - try: - client.set_acls('/a', [acl]) - self.assertTrue(acl in client.get_acls('/a')[0]) - finally: - client.delete('/a') - - def test_set_acls_empty(self): - client = self.client - client.create('/a') - self.assertRaises(InvalidACLError, client.set_acls, '/a', []) - - def test_set_acls_no_node(self): - from kazoo.security import OPEN_ACL_UNSAFE - client = self.client - self.assertRaises(NoNodeError, client.set_acls, '/a', OPEN_ACL_UNSAFE) - - def test_set_acls_invalid_arguments(self): - from kazoo.security import OPEN_ACL_UNSAFE - single_acl = OPEN_ACL_UNSAFE[0] - client = self.client - self.assertRaises(TypeError, client.set_acls, ('a', 'b'), ()) - self.assertRaises(TypeError, client.set_acls, 'a', single_acl) - self.assertRaises(TypeError, client.set_acls, 'a', 'all') - self.assertRaises(TypeError, client.set_acls, 'a', [single_acl], 'V1') - - def test_set(self): - client = self.client - client.create('a', b'first') - stat = client.set('a', b'second') - data, stat2 = client.get('a') - self.assertEqual(data, b'second') - self.assertEqual(stat, stat2) - - def test_set_null_data(self): - client = self.client - client.create("/nulldata", b"not none") - client.set("/nulldata", None) - value, _ = client.get("/nulldata") - self.assertEqual(value, None) - - def test_set_empty_string(self): - client = self.client - client.create("/empty", b"not empty") - client.set("/empty", b"") - value, _ = client.get("/empty") - eq_(value, b"") - - def test_set_invalid_arguments(self): - client = self.client - client.create('a', b'first') - self.assertRaises(TypeError, client.set, ('a', 'b'), b'value') - self.assertRaises(TypeError, client.set, 'a', ['v', 'w']) - self.assertRaises(TypeError, client.set, 'a', b'value', 'V1') - - def test_delete(self): - client = self.client - client.ensure_path('/a/b') - self.assertTrue('b' in client.get_children('a')) - client.delete('/a/b') - self.assertFalse('b' in client.get_children('a')) - - def test_delete_recursive(self): - client = self.client - client.ensure_path('/a/b/c') - client.ensure_path('/a/b/d') - client.delete('/a/b', recursive=True) - client.delete('/a/b/c', recursive=True) - self.assertFalse('b' in client.get_children('a')) - - def test_delete_invalid_arguments(self): - client = self.client - client.ensure_path('/a/b') - self.assertRaises(TypeError, client.delete, '/a/b', recursive='all') - self.assertRaises(TypeError, client.delete, ('a', 'b')) - self.assertRaises(TypeError, client.delete, '/a/b', version='V1') - - def test_get_children(self): - client = self.client - client.ensure_path('/a/b/c') - client.ensure_path('/a/b/d') - self.assertEqual(client.get_children('/a'), ['b']) - self.assertEqual(set(client.get_children('/a/b')), set(['c', 'd'])) - self.assertEqual(client.get_children('/a/b/c'), []) - - def test_get_children2(self): - client = self.client - client.ensure_path('/a/b') - children, stat = client.get_children('/a', include_data=True) - value, stat2 = client.get('/a') - self.assertEqual(children, ['b']) - self.assertEqual(stat2.version, stat.version) - - def test_get_children2_many_nodes(self): - client = self.client - client.ensure_path('/a/b') - client.ensure_path('/a/c') - client.ensure_path('/a/d') - children, stat = client.get_children('/a', include_data=True) - value, stat2 = client.get('/a') - self.assertEqual(set(children), set(['b', 'c', 'd'])) - self.assertEqual(stat2.version, stat.version) - - def test_get_children_no_node(self): - client = self.client - self.assertRaises(NoNodeError, client.get_children, '/none') - self.assertRaises(NoNodeError, client.get_children, - '/none', include_data=True) - - def test_get_children_invalid_path(self): - client = self.client - self.assertRaises(ValueError, client.get_children, '../a') - - def test_get_children_invalid_arguments(self): - client = self.client - self.assertRaises(TypeError, client.get_children, ('a', 'b')) - self.assertRaises(TypeError, client.get_children, 'a', watch=True) - self.assertRaises(TypeError, client.get_children, - 'a', include_data='yes') - - def test_invalid_auth(self): - from kazoo.exceptions import AuthFailedError - from kazoo.protocol.states import KeeperState - - client = self.client - client.stop() - client._state = KeeperState.AUTH_FAILED - - @raises(AuthFailedError) - def testit(): - client.get('/') - testit() - - def test_client_state(self): - from kazoo.protocol.states import KeeperState - eq_(self.client.client_state, KeeperState.CONNECTED) - - def test_update_host_list(self): - from kazoo.client import KazooClient - from kazoo.protocol.states import KeeperState - hosts = self.cluster[0].address - # create a client with only one server in its list - client = KazooClient(hosts=hosts) - client.start() - - # try to change the chroot, not currently allowed - self.assertRaises(ConfigurationError, - client.set_hosts, hosts + '/new_chroot') - - # grow the cluster to 3 - client.set_hosts(self.servers) - - # shut down the first host - try: - self.cluster[0].stop() - time.sleep(5) - eq_(client.client_state, KeeperState.CONNECTED) - finally: - self.cluster[0].run() - - -dummy_dict = { - 'aversion': 1, 'ctime': 0, 'cversion': 1, - 'czxid': 110, 'dataLength': 1, 'ephemeralOwner': 'ben', - 'mtime': 1, 'mzxid': 1, 'numChildren': 0, 'pzxid': 1, 'version': 1 -} - - -class TestClientTransactions(KazooTestCase): - - def setUp(self): - KazooTestCase.setUp(self) - skip = False - if TRAVIS_ZK_VERSION and TRAVIS_ZK_VERSION < (3, 4): - skip = True - elif TRAVIS_ZK_VERSION and TRAVIS_ZK_VERSION >= (3, 4): - skip = False - else: - ver = self.client.server_version() - if ver[1] < 4: - skip = True - if skip: - raise SkipTest("Must use Zookeeper 3.4 or above") - - def test_basic_create(self): - t = self.client.transaction() - t.create('/freddy') - t.create('/fred', ephemeral=True) - t.create('/smith', sequence=True) - results = t.commit() - eq_(results[0], '/freddy') - eq_(len(results), 3) - self.assertTrue(results[2].startswith('/smith0')) - - def test_bad_creates(self): - args_list = [(True,), ('/smith', 0), ('/smith', b'', 'bleh'), - ('/smith', b'', None, 'fred'), - ('/smith', b'', None, True, 'fred')] - - @raises(TypeError) - def testit(args): - t = self.client.transaction() - t.create(*args) - - for args in args_list: - testit(args) - - def test_default_acl(self): - from kazoo.security import make_digest_acl - username = uuid.uuid4().hex - password = uuid.uuid4().hex - - digest_auth = "%s:%s" % (username, password) - acl = make_digest_acl(username, password, all=True) - - self.client.add_auth("digest", digest_auth) - self.client.default_acl = (acl,) - - t = self.client.transaction() - t.create('/freddy') - results = t.commit() - eq_(results[0], '/freddy') - - def test_basic_delete(self): - self.client.create('/fred') - t = self.client.transaction() - t.delete('/fred') - results = t.commit() - eq_(results[0], True) - - def test_bad_deletes(self): - args_list = [(True,), ('/smith', 'woops'), ] - - @raises(TypeError) - def testit(args): - t = self.client.transaction() - t.delete(*args) - - for args in args_list: - testit(args) - - def test_set(self): - self.client.create('/fred', b'01') - t = self.client.transaction() - t.set_data('/fred', b'oops') - t.commit() - res = self.client.get('/fred') - eq_(res[0], b'oops') - - def test_bad_sets(self): - args_list = [(42, 52), ('/smith', False), ('/smith', b'', 'oops')] - - @raises(TypeError) - def testit(args): - t = self.client.transaction() - t.set_data(*args) - - for args in args_list: - testit(args) - - def test_check(self): - self.client.create('/fred') - version = self.client.get('/fred')[1].version - t = self.client.transaction() - t.check('/fred', version) - t.create('/blah') - results = t.commit() - eq_(results[0], True) - eq_(results[1], '/blah') - - def test_bad_checks(self): - args_list = [(42, 52), ('/smith', 'oops')] - - @raises(TypeError) - def testit(args): - t = self.client.transaction() - t.check(*args) - - for args in args_list: - testit(args) - - def test_bad_transaction(self): - from kazoo.exceptions import RolledBackError, NoNodeError - t = self.client.transaction() - t.create('/fred') - t.delete('/smith') - results = t.commit() - eq_(results[0].__class__, RolledBackError) - eq_(results[1].__class__, NoNodeError) - - def test_bad_commit(self): - t = self.client.transaction() - - @raises(ValueError) - def testit(): - t.commit() - - t.committed = True - testit() - - def test_bad_context(self): - @raises(TypeError) - def testit(): - with self.client.transaction() as t: - t.check(4232) - testit() - - def test_context(self): - with self.client.transaction() as t: - t.create('/smith', b'32') - eq_(self.client.get('/smith')[0], b'32') - - -class TestCallbacks(unittest.TestCase): - def test_session_callback_states(self): - from kazoo.protocol.states import KazooState, KeeperState - from kazoo.client import KazooClient - - client = KazooClient() - client._handle = 1 - client._live.set() - - result = client._session_callback(KeeperState.CONNECTED) - eq_(result, None) - - # Now with stopped - client._stopped.set() - result = client._session_callback(KeeperState.CONNECTED) - eq_(result, None) - - # Test several state transitions - client._stopped.clear() - client.start_async = lambda: True - client._session_callback(KeeperState.CONNECTED) - eq_(client.state, KazooState.CONNECTED) - - client._session_callback(KeeperState.AUTH_FAILED) - eq_(client.state, KazooState.LOST) - - client._handle = 1 - client._session_callback(-250) - eq_(client.state, KazooState.SUSPENDED) - - -class TestNonChrootClient(KazooTestCase): - - def test_create(self): - client = self._get_nonchroot_client() - self.assertEqual(client.chroot, '') - client.start() - node = uuid.uuid4().hex - path = client.create(node, ephemeral=True) - client.delete(path) - client.stop() - - def test_unchroot(self): - client = self._get_nonchroot_client() - client.chroot = '/a' - self.assertEquals(client.unchroot('/a/b'), '/b') - self.assertEquals(client.unchroot('/b/c'), '/b/c')
