SLIDER-781 cut tests/ module from included kazoo source tree; examples and docs from jinja

diff --git a/slider-agent/src/main/python/jinja2/docs/Makefile b/slider-agent/src/main/python/jinja2/docs/Makefile
deleted file mode 100644
index 5e24ec1..0000000
--- a/slider-agent/src/main/python/jinja2/docs/Makefile
+++ /dev/null
@@ -1,75 +0,0 @@
-# Makefile for Sphinx documentation
-#
-
-# You can set these variables from the command line.
-SPHINXOPTS =
-SPHINXBUILD = sphinx-build
-PAPER =
-
-# Internal variables.
-PAPEROPT_a4 = -D latex_paper_size=a4
-PAPEROPT_letter = -D latex_paper_size=letter
-ALLSPHINXOPTS = -d _build/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
-
-.PHONY: help clean html web pickle htmlhelp latex changes linkcheck
-
-help:
- @echo "Please use \`make <target>' where <target> is one of"
- @echo " html to make standalone HTML files"
- @echo " pickle to make pickle files"
- @echo " json to make JSON files"
- @echo " htmlhelp to make HTML files and a HTML help project"
- @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
- @echo " changes to make an overview over all changed/added/deprecated items"
- @echo " linkcheck to check all external links for integrity"
-
-clean:
- -rm -rf _build/*
-
-html:
- mkdir -p _build/html _build/doctrees
- $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) _build/html
- @echo
- @echo "Build finished. The HTML pages are in _build/html."
-
-pickle:
- mkdir -p _build/pickle _build/doctrees
- $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) _build/pickle
- @echo
- @echo "Build finished; now you can process the pickle files"
-
-json:
- mkdir -p _build/json _build/doctrees
- $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) _build/json
- @echo
- @echo "Build finished; now you can process the json files"
-
-web: pickle
-
-htmlhelp:
- mkdir -p _build/htmlhelp _build/doctrees
- $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) _build/htmlhelp
- @echo
- @echo "Build finished; now you can run HTML Help Workshop with the" \
- ".hhp project file in _build/htmlhelp."
-
-latex:
- mkdir -p _build/latex _build/doctrees
- $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) _build/latex
- @echo
- @echo "Build finished; the LaTeX files are in _build/latex."
- @echo "Run \`make all-pdf' or \`make all-ps' in that directory to" \
- "run these through (pdf)latex."
-
-changes:
- mkdir -p _build/changes _build/doctrees
- $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) _build/changes
- @echo
- @echo "The overview file is in _build/changes."
-
-linkcheck:
- mkdir -p _build/linkcheck _build/doctrees
- $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) _build/linkcheck
- @echo
- @echo "Link check complete; look for any errors in the above output " \
- "or in _build/linkcheck/output.txt."
diff --git a/slider-agent/src/main/python/jinja2/docs/_build/.ignore b/slider-agent/src/main/python/jinja2/docs/_build/.ignore
deleted file mode 100644
index e69de29..0000000
--- a/slider-agent/src/main/python/jinja2/docs/_build/.ignore
+++ /dev/null
diff --git a/slider-agent/src/main/python/jinja2/docs/_static/.ignore b/slider-agent/src/main/python/jinja2/docs/_static/.ignore
deleted file mode 100644
index e69de29..0000000
--- a/slider-agent/src/main/python/jinja2/docs/_static/.ignore
+++ /dev/null
diff --git a/slider-agent/src/main/python/jinja2/docs/_static/jinja.js b/slider-agent/src/main/python/jinja2/docs/_static/jinja.js
deleted file mode 100644
index 1c04218..0000000
--- a/slider-agent/src/main/python/jinja2/docs/_static/jinja.js
+++ /dev/null
@@ -1,26 +0,0 @@
-$(function() {
-
- var
- toc = $('#toc').show(),
- items = $('#toc > ul').hide();
-
- $('#toc h3')
- .click(function() {
- if (items.is(':visible')) {
- items.animate({
- height: 'hide',
- opacity: 'hide'
- }, 300, function() {
- toc.removeClass('expandedtoc');
- });
- }
- else {
- items.animate({
- height: 'show',
- opacity: 'show'
- }, 400);
- toc.addClass('expandedtoc');
- }
- });
-
-});
diff --git a/slider-agent/src/main/python/jinja2/docs/_static/print.css b/slider-agent/src/main/python/jinja2/docs/_static/print.css
deleted file mode 100644
index fb633d8..0000000
--- a/slider-agent/src/main/python/jinja2/docs/_static/print.css
+++ /dev/null
@@ -1,5 +0,0 @@
-div.header, div.relnav, #toc { display: none; }
-#contentwrapper { padding: 0; margin: 0; border: none; }
-body { color: black; background-color: white; }
-div.footer { border-top: 1px solid #888; color: #888; margin-top: 1cm; }
-div.footer a { text-decoration: none; }
diff --git a/slider-agent/src/main/python/jinja2/docs/_static/style.css b/slider-agent/src/main/python/jinja2/docs/_static/style.css
deleted file mode 100644
index a1c4d59..0000000
--- a/slider-agent/src/main/python/jinja2/docs/_static/style.css
+++ /dev/null
@@ -1,390 +0,0 @@
-body {
- background-color: #222;
- margin: 0;
- padding: 0;
- font-family: 'Georgia', serif;
- font-size: 15px;
- color: #eee;
-}
-
-div.footer {
- border-top: 1px solid #111;
- padding: 8px;
- font-size: 11px;
- text-align: center;
- letter-spacing: 0.5px;
-}
-
-div.footer a {
- color: #eee;
-}
-
-div.header {
- margin: 0 -15px 0 -15px;
- background: url(headerbg.png) repeat-x;
- border-top: 6px solid #D20000;
-}
-
-div.relnav {
- border-bottom: 1px solid #111;
- background: url(navigation.png);
- margin: 0 -15px 0 -15px;
- padding: 2px 20px 0 28px;
- line-height: 25px;
- color: #aaa;
- font-size: 12px;
- text-align: center;
-}
-
-div.relnav a {
- color: #eee;
- font-weight: bold;
- text-decoration: none;
-}
-
-div.relnav a:hover {
- text-decoration: underline;
-}
-
-#content {
- background-color: white;
- color: #111;
- border-bottom: 1px solid black;
- background: url(watermark.png) center 0;
- padding: 0 15px 0 15px;
- margin: 0;
-}
-
-h1 {
- margin: 0;
- padding: 15px 0 0 0;
-}
-
-h1.heading {
- margin: 0;
- padding: 0;
- height: 80px;
-}
-
-h1.heading:hover {
- background: #222;
-}
-
-h1.heading a {
- background: url(jinjabanner.png) no-repeat center 0;
- display: block;
- width: 100%;
- height: 80px;
-}
-
-h1.heading a:focus {
- -moz-outline: none;
- outline: none;
-}
-
-h1.heading span {
- display: none;
-}
-
-#jinjalogo {
- background-image: url(jinjalogo.png);
- background-repeat: no-repeat;
- width: 400px;
- height: 160px;
-}
-
-#contentwrapper {
- max-width: 680px;
- padding: 0 18px 20px 18px;
- margin: 0 auto 0 auto;
- border-right: 1px solid #eee;
- border-left: 1px solid #eee;
- background: url(watermark_blur.png) center -114px;
-}
-
-#contentwrapper h2,
-#contentwrapper h2 a {
- color: #222;
- font-size: 24px;
- margin: 20px 0 0 0;
-}
-
-#contentwrapper h3,
-#contentwrapper h3 a {
- color: #b41717;
- font-size: 20px;
- margin: 20px 0 0 0;
-}
-
-table.docutils {
- border-collapse: collapse;
- border: 2px solid #aaa;
- margin: 0.5em 1.5em 0.5em 1.5em;
-}
-
-table.docutils td {
- padding: 2px;
- border: 1px solid #ddd;
-}
-
-p, li, dd, dt, blockquote {
- color: #333;
-}
-
-blockquote {
- margin: 10px 0 10px 20px;
-}
-
-p {
- line-height: 20px;
- margin-bottom: 0;
- margin-top: 10px;
-}
-
-hr {
- border-top: 1px solid #ccc;
- border-bottom: 0;
- border-right: 0;
- border-left: 0;
- margin-bottom: 10px;
- margin-top: 20px;
-}
-
-dl {
- margin-left: 10px;
-}
-
-li, dt {
- margin-top: 5px;
-}
-
-dt {
- font-weight: bold;
- color: #000;
-}
-
-dd {
- margin-top: 10px;
- line-height: 20px;
-}
-
-th {
- text-align: left;
- padding: 3px;
- background-color: #f2f2f2;
-}
-
-a {
- color: #b41717;
-}
-
-a:hover {
- color: #444;
-}
-
-pre {
- background: #ededed url(metal.png);
- border-top: 1px solid #ccc;
- border-bottom: 1px solid #ccc;
- padding: 5px;
- font-size: 13px;
- font-family: 'Bitstream Vera Sans Mono', 'Monaco', monospace;
-}
-
-tt {
- font-size: 13px;
- font-family: 'Bitstream Vera Sans Mono', 'Monaco', monospace;
- color: black;
- padding: 1px 2px 1px 2px;
- background-color: #fafafa;
- border-bottom: 1px solid #eee;
-}
-
-a.reference:hover tt {
- border-bottom-color: #aaa;
-}
-
-cite {
- /* abusing <cite>, it's generated by ReST for `x` */
- font-size: 13px;
- font-family: 'Bitstream Vera Sans Mono', 'Monaco', monospace;
- font-weight: bold;
- font-style: normal;
-}
-
-div.admonition {
- margin: 10px 0 10px 0;
- padding: 10px 10px 10px 60px;
- border: 1px solid #ccc;
-}
-
-div.admonition p.admonition-title {
- background-color: #b41717;
- color: white;
- margin: -10px -10px 10px -60px;
- padding: 4px 10px 4px 10px;
- font-weight: bold;
- font-size: 15px;
-}
-
-div.admonition p.admonition-title a {
- color: white!important;
-}
-
-div.admonition-note {
- background: url(note.png) no-repeat 10px 40px;
-}
-
-div.admonition-implementation {
- background: url(implementation.png) no-repeat 10px 40px;
-}
-
-a.headerlink {
- color: #B4B4B4!important;
- font-size: 0.8em;
- padding: 0 4px 0 4px;
- text-decoration: none!important;
- visibility: hidden;
-}
-
-h1:hover > a.headerlink,
-h2:hover > a.headerlink,
-h3:hover > a.headerlink,
-h4:hover > a.headerlink,
-h5:hover > a.headerlink,
-h6:hover > a.headerlink,
-dt:hover > a.headerlink,
-dt:hover > a.headerlink {
- visibility: visible;
-}
-
-a.headerlink:hover {
- background-color: #B4B4B4;
- color: #F0F0F0!important;
-}
-
-table.indextable {
- width: 100%;
-}
-
-table.indextable td {
- vertical-align: top;
- width: 50%;
-}
-
-table.indextable dl dd {
- font-size: 11px;
-}
-
-table.indextable dl dd a {
- color: #000;
-}
-
-dl.function dt,
-dl.class dt,
-dl.exception dt,
-dl.method dt,
-dl.attribute dt {
- font-weight: normal;
-}
-
-dt .descname {
- font-weight: bold;
- margin-right: 4px;
-}
-
-dt .descname, dt .descclassname {
- padding: 0;
- background: transparent;
- border-bottom: 1px solid #111;
-}
-
-dt .descclassname {
- margin-left: 2px;
-}
-
-dl dt big {
- font-size: 100%;
-}
-
-ul.search {
- margin: 10px 0 0 30px;
- padding: 0;
-}
-
-ul.search li {
- margin: 10px 0 0 0;
- padding: 0;
-}
-
-ul.search div.context {
- font-size: 12px;
- padding: 4px 0 0 20px;
- color: #888;
-}
-
-span.highlight {
- background-color: #eee;
- border: 1px solid #ccc;
-}
-
-#toc {
- margin: 0 -17px 0 -17px;
- display: none;
-}
-
-#toc h3 {
- float: right;
- margin: 5px 5px 0 0;
- padding: 0;
- font-size: 12px;
- color: #777;
-}
-
-#toc h3:hover {
- color: #333;
- cursor: pointer;
-}
-
-.expandedtoc {
- background: #222 url(darkmetal.png);
- border-bottom: 1px solid #111;
- outline-bottom: 1px solid #000;
- padding: 5px;
-}
-
-.expandedtoc h3 {
- color: #aaa;
- margin: 0!important;
-}
-
-.expandedtoc h3:hover {
- color: white!important;
-}
-
-#tod h3:hover {
- color: white;
-}
-
-#toc a {
- color: #ddd;
- text-decoration: none;
-}
-
-#toc a:hover {
- color: white;
- text-decoration: underline;
-}
-
-#toc ul {
- margin: 5px 0 12px 17px;
- padding: 0 7px 0 7px;
-}
-
-#toc ul ul {
- margin-bottom: 0;
-}
-
-#toc ul li {
- margin: 2px 0 0 0;
-}
diff --git a/slider-agent/src/main/python/jinja2/docs/_templates/.ignore b/slider-agent/src/main/python/jinja2/docs/_templates/.ignore
deleted file mode 100644
index e69de29..0000000
--- a/slider-agent/src/main/python/jinja2/docs/_templates/.ignore
+++ /dev/null
diff --git a/slider-agent/src/main/python/jinja2/docs/_templates/genindex.html b/slider-agent/src/main/python/jinja2/docs/_templates/genindex.html
deleted file mode 100644
index 9add6e9..0000000
--- a/slider-agent/src/main/python/jinja2/docs/_templates/genindex.html
+++ /dev/null
@@ -1,36 +0,0 @@
-{% extends "layout.html" %}
-{% set title = 'Index' %}
-{% block body %}
-
- <h1 id="index">Index</h1>
-
- {% for key, dummy in genindexentries -%}
- <a href="#{{ key }}"><strong>{{ key }}</strong></a> {% if not loop.last %}| {% endif %}
- {%- endfor %}
- <hr>
-
- {% for key, entries in genindexentries %}
- <h2 id="{{ key }}">{{ key }}</h2>
- <table class="indextable"><tr>
- {%- for column in entries|slice(2) if column %}
- <td><dl>
- {%- for entryname, (links, subitems) in column %}
- <dt>{% if links %}<a href="{{ links[0] }}">{{ entryname|e }}</a>
- {% for link in links[1:] %}, <a href="{{ link }}">[Link]</a>{% endfor %}
- {%- else %}{{ entryname|e }}{% endif %}</dt>
- {%- if subitems %}
- <dd><dl>
- {%- for subentryname, subentrylinks in subitems %}
- <dt><a href="{{ subentrylinks[0] }}">{{ subentryname|e }}</a>
- {%- for link in subentrylinks[1:] %}, <a href="{{ link }}">[Link]</a>{% endfor -%}
- </dt>
- {%- endfor %}
- </dl></dd>
- {%- endif -%}
- {%- endfor %}
- </dl></td>
- {%- endfor %}
- </tr></table>
- {% endfor %}
-
-{% endblock %}
diff --git a/slider-agent/src/main/python/jinja2/docs/_templates/layout.html b/slider-agent/src/main/python/jinja2/docs/_templates/layout.html
deleted file mode 100644
index f682f90..0000000
--- a/slider-agent/src/main/python/jinja2/docs/_templates/layout.html
+++ /dev/null
@@ -1,77 +0,0 @@
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
-<html>
- <head>
- <title>Jinja2 Documentation</title>
- <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
- <link rel="stylesheet" href="{{ pathto('_static/style.css', 1) }}" type="text/css">
- <link rel="stylesheet" href="{{ pathto('_static/print.css', 1) }}" type="text/css" media="print">
- <link rel="stylesheet" href="{{ pathto('_static/pygments.css', 1) }}" type="text/css">
- {%- if builder != 'htmlhelp' %}
- <script type="text/javascript">
- var DOCUMENTATION_OPTIONS = {
- URL_ROOT: '{{ pathto("", 1) }}',
- VERSION: '{{ release }}'
- };
- </script>
- <script type="text/javascript" src="{{ pathto('_static/jquery.js', 1) }}"></script>
- <script type="text/javascript" src="{{ pathto('_static/interface.js', 1) }}"></script>
- <script type="text/javascript" src="{{ pathto('_static/doctools.js', 1) }}"></script>
- <script type="text/javascript" src="{{ pathto('_static/jinja.js', 1) }}"></script>
- {%- endif %}
- {%- if use_opensearch and builder != 'htmlhelp' %}
- <link rel="search" type="application/opensearchdescription+xml"
- title="Search within {{ docstitle }}"
- href="{{ pathto('_static/opensearch.xml', 1) }}">
- {%- endif %}
- {%- if hasdoc('about') %}
- <link rel="author" title="About these documents" href="{{ pathto('about') }}">
- {%- endif %}
- <link rel="contents" title="Global table of contents" href="{{ pathto('contents') }}">
- <link rel="index" title="Global index" href="{{ pathto('genindex') }}">
- <link rel="search" title="Search" href="{{ pathto('search') }}">
- {%- if hasdoc('copyright') %}
- <link rel="copyright" title="Copyright" href="{{ pathto('copyright') }}">
- {%- endif %}
- <link rel="top" title="{{ docstitle }}" href="{{ pathto('index') }}">
- {%- if parents %}
- <link rel="up" title="{{ parents[-1].title|striptags }}" href="{{ parents[-1].link|e }}">
- {%- endif %}
- {%- if next %}
- <link rel="next" title="{{ next.title|striptags }}" href="{{ next.link|e }}">
- {%- endif %}
- {%- if prev %}
- <link rel="prev" title="{{ prev.title|striptags }}" href="{{ prev.link|e }}">
- {%- endif %}
- {% block extrahead %}{% endblock %}
- </head>
- <body>
- <div id="content">
- <div class="header">
- <h1 class="heading"><a href="{{ pathto('index') }}"
- title="back to the documentation overview"><span>Jinja</span></a></h1>
- </div>
- <div class="relnav">
- {%- if prev %}
- <a href="{{ prev.link|e }}">« {{ prev.title }}</a> |
- {%- endif %}
- <a href="{{ pathto(current_page_name) if current_page_name else '#' }}">{{ title }}</a>
- {%- if next %}
- | <a href="{{ next.link|e }}">{{ next.title }} »</a>
- {%- endif %}
- </div>
- <div id="contentwrapper">
- {%- if display_toc %}
- <div id="toc">
- <h3>Table Of Contents</h3>
- {{ toc }}
- </div>
- {%- endif %}
- {% block body %}{% endblock %}
- </div>
- </div>
- <div class="footer">
- © Copyright 2010 by the <a href="http://pocoo.org/">Pocoo Team</a>,
- documentation generated by <a href="http://sphinx.pocoo.org/">Sphinx</a>
- </div>
- </body>
-</html>
diff --git a/slider-agent/src/main/python/jinja2/docs/_templates/opensearch.xml b/slider-agent/src/main/python/jinja2/docs/_templates/opensearch.xml
deleted file mode 100644
index 9f2fa42..0000000
--- a/slider-agent/src/main/python/jinja2/docs/_templates/opensearch.xml
+++ /dev/null
@@ -1,9 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/">
- <ShortName>{{ project }}</ShortName>
- <Description>Search {{ docstitle }}</Description>
- <InputEncoding>utf-8</InputEncoding>
- <Url type="text/html" method="get"
- template="{{ use_opensearch }}/{{ pathto('search') }}?q={searchTerms}&check_keywords=yes&area=default"/>
- <LongName>{{ docstitle }}</LongName>
-</OpenSearchDescription>
diff --git a/slider-agent/src/main/python/jinja2/docs/_templates/page.html b/slider-agent/src/main/python/jinja2/docs/_templates/page.html
deleted file mode 100644
index ee6cad3..0000000
--- a/slider-agent/src/main/python/jinja2/docs/_templates/page.html
+++ /dev/null
@@ -1,4 +0,0 @@
-{% extends 'layout.html' %}
-{% block body %}
- {{ body }}
-{% endblock %}
diff --git a/slider-agent/src/main/python/jinja2/docs/_templates/search.html b/slider-agent/src/main/python/jinja2/docs/_templates/search.html
deleted file mode 100644
index 0c942b7..0000000
--- a/slider-agent/src/main/python/jinja2/docs/_templates/search.html
+++ /dev/null
@@ -1,35 +0,0 @@
-{% extends "layout.html" %}
-{% set title = 'Search' %}
-{% block extrahead %}
- <script type="text/javascript" src="{{ pathto('_static/searchtools.js', 1) }}"></script>
-{% endblock %}
-{% block body %}
- <h1 id="search-documentation">Search</h1>
- <p>
- From here you can search these documents. Enter your search
- words into the box below and click "search". Note that the search
- function will automatically search for all of the words. Pages
- containing less words won't appear in the result list.
- </p>
- <form action="" method="get"><p>
- <input type="text" name="q" value="">
- <input type="submit" value="search">
- </p></form>
- {% if search_performed %}
- <h2>Search Results</h2>
- {% if not search_results %}
- <p>Your search did not match any results.</p>
- {% endif %}
- {% endif %}
- <div id="search-results">
- {% if search_results %}
- <ul>
- {% for href, caption, context in search_results %}
- <li><a href="{{ pathto(item.href) }}">{{ caption }}</a>
- <div class="context">{{ context|e }}</div>
- </li>
- {% endfor %}
- </ul>
- {% endif %}
- </div>
-{% endblock %}
diff --git a/slider-agent/src/main/python/jinja2/docs/api.rst b/slider-agent/src/main/python/jinja2/docs/api.rst
deleted file mode 100644
index 3bf8a94..0000000
--- a/slider-agent/src/main/python/jinja2/docs/api.rst
+++ /dev/null
@@ -1,787 +0,0 @@
-API
-===
-
-.. module:: jinja2
- :synopsis: public Jinja2 API
-
-This document describes the API to Jinja2 and not the template language. It
-will be most useful as reference to those implementing the template interface
-to the application and not those who are creating Jinja2 templates.
-
-Basics
-------
-
-Jinja2 uses a central object called the template :class:`Environment`.
-Instances of this class are used to store the configuration, global objects
-and are used to load templates from the file system or other locations.
-Even if you are creating templates from strings by using the constructor of
-:class:`Template` class, an environment is created automatically for you,
-albeit a shared one.
-
-Most applications will create one :class:`Environment` object on application
-initialization and use that to load templates. In some cases it's however
-useful to have multiple environments side by side, if different configurations
-are in use.
-
-The simplest way to configure Jinja2 to load templates for your application
-looks roughly like this::
-
- from jinja2 import Environment, PackageLoader
- env = Environment(loader=PackageLoader('yourapplication', 'templates'))
-
-This will create a template environment with the default settings and a
-loader that looks up the templates in the `templates` folder inside the
-`yourapplication` python package. Different loaders are available
-and you can also write your own if you want to load templates from a
-database or other resources.
-
-To load a template from this environment you just have to call the
-:meth:`get_template` method which then returns the loaded :class:`Template`::
-
- template = env.get_template('mytemplate.html')
-
-To render it with some variables, just call the :meth:`render` method::
-
- print template.render(the='variables', go='here')
-
-Using a template loader rather then passing strings to :class:`Template`
-or :meth:`Environment.from_string` has multiple advantages. Besides being
-a lot easier to use it also enables template inheritance.
-
-
-Unicode
--------
-
-Jinja2 is using Unicode internally which means that you have to pass Unicode
-objects to the render function or bytestrings that only consist of ASCII
-characters. Additionally newlines are normalized to one end of line
-sequence which is per default UNIX style (``\n``).
-
-Python 2.x supports two ways of representing string objects. One is the
-`str` type and the other is the `unicode` type, both of which extend a type
-called `basestring`. Unfortunately the default is `str` which should not
-be used to store text based information unless only ASCII characters are
-used. With Python 2.6 it is possible to make `unicode` the default on a per
-module level and with Python 3 it will be the default.
-
-To explicitly use a Unicode string you have to prefix the string literal
-with a `u`: ``u'Hänsel und Gretel sagen Hallo'``. That way Python will
-store the string as Unicode by decoding the string with the character
-encoding from the current Python module. If no encoding is specified this
-defaults to 'ASCII' which means that you can't use any non ASCII identifier.
-
-To set a better module encoding add the following comment to the first or
-second line of the Python module using the Unicode literal::
-
- # -*- coding: utf-8 -*-
-
-We recommend utf-8 as Encoding for Python modules and templates as it's
-possible to represent every Unicode character in utf-8 and because it's
-backwards compatible to ASCII. For Jinja2 the default encoding of templates
-is assumed to be utf-8.
-
-It is not possible to use Jinja2 to process non-Unicode data. The reason
-for this is that Jinja2 uses Unicode already on the language level. For
-example Jinja2 treats the non-breaking space as valid whitespace inside
-expressions which requires knowledge of the encoding or operating on an
-Unicode string.
-
-For more details about Unicode in Python have a look at the excellent
-`Unicode documentation`_.
-
-Another important thing is how Jinja2 is handling string literals in
-templates. A naive implementation would be using Unicode strings for
-all string literals but it turned out in the past that this is problematic
-as some libraries are typechecking against `str` explicitly. For example
-`datetime.strftime` does not accept Unicode arguments. To not break it
-completely Jinja2 is returning `str` for strings that fit into ASCII and
-for everything else `unicode`:
-
->>> m = Template(u"{% set a, b = 'foo', 'föö' %}").module
->>> m.a
-'foo'
->>> m.b
-u'f\xf6\xf6'
-
-
-.. _Unicode documentation: http://docs.python.org/dev/howto/unicode.html
-
-High Level API
---------------
-
-The high-level API is the API you will use in the application to load and
-render Jinja2 templates. The :ref:`low-level-api` on the other side is only
-useful if you want to dig deeper into Jinja2 or :ref:`develop extensions
-<jinja-extensions>`.
-
-.. autoclass:: Environment([options])
- :members: from_string, get_template, select_template,
- get_or_select_template, join_path, extend, compile_expression
-
- .. attribute:: shared
-
- If a template was created by using the :class:`Template` constructor
- an environment is created automatically. These environments are
- created as shared environments which means that multiple templates
- may have the same anonymous environment. For all shared environments
- this attribute is `True`, else `False`.
-
- .. attribute:: sandboxed
-
- If the environment is sandboxed this attribute is `True`. For the
- sandbox mode have a look at the documentation for the
- :class:`~jinja2.sandbox.SandboxedEnvironment`.
-
- .. attribute:: filters
-
- A dict of filters for this environment. As long as no template was
- loaded it's safe to add new filters or remove old. For custom filters
- see :ref:`writing-filters`. For valid filter names have a look at
- :ref:`identifier-naming`.
-
- .. attribute:: tests
-
- A dict of test functions for this environment. As long as no
- template was loaded it's safe to modify this dict. For custom tests
- see :ref:`writing-tests`. For valid test names have a look at
- :ref:`identifier-naming`.
-
- .. attribute:: globals
-
- A dict of global variables. These variables are always available
- in a template. As long as no template was loaded it's safe
- to modify this dict. For more details see :ref:`global-namespace`.
- For valid object names have a look at :ref:`identifier-naming`.
-
- .. automethod:: overlay([options])
-
- .. method:: undefined([hint, obj, name, exc])
-
- Creates a new :class:`Undefined` object for `name`. This is useful
- for filters or functions that may return undefined objects for
- some operations. All parameters except of `hint` should be provided
- as keyword parameters for better readability. The `hint` is used as
- error message for the exception if provided, otherwise the error
- message will be generated from `obj` and `name` automatically. The exception
- provided as `exc` is raised if something with the generated undefined
- object is done that the undefined object does not allow. The default
- exception is :exc:`UndefinedError`. If a `hint` is provided the
- `name` may be ommited.
-
- The most common way to create an undefined object is by providing
- a name only::
-
- return environment.undefined(name='some_name')
-
- This means that the name `some_name` is not defined. If the name
- was from an attribute of an object it makes sense to tell the
- undefined object the holder object to improve the error message::
-
- if not hasattr(obj, 'attr'):
- return environment.undefined(obj=obj, name='attr')
-
- For a more complex example you can provide a hint. For example
- the :func:`first` filter creates an undefined object that way::
-
- return environment.undefined('no first item, sequence was empty')
-
- If it the `name` or `obj` is known (for example because an attribute
- was accessed) it shold be passed to the undefined object, even if
- a custom `hint` is provided. This gives undefined objects the
- possibility to enhance the error message.
-
-.. autoclass:: Template
- :members: module, make_module
-
- .. attribute:: globals
-
- The dict with the globals of that template. It's unsafe to modify
- this dict as it may be shared with other templates or the environment
- that loaded the template.
-
- .. attribute:: name
-
- The loading name of the template. If the template was loaded from a
- string this is `None`.
-
- .. attribute:: filename
-
- The filename of the template on the file system if it was loaded from
- there. Otherwise this is `None`.
-
- .. automethod:: render([context])
-
- .. automethod:: generate([context])
-
- .. automethod:: stream([context])
-
-
-.. autoclass:: jinja2.environment.TemplateStream()
- :members: disable_buffering, enable_buffering, dump
-
-
-Autoescaping
-------------
-
-.. versionadded:: 2.4
-
-As of Jinja 2.4 the preferred way to do autoescaping is to enable the
-:ref:`autoescape-extension` and to configure a sensible default for
-autoescaping. This makes it possible to enable and disable autoescaping
-on a per-template basis (HTML versus text for instance).
-
-Here a recommended setup that enables autoescaping for templates ending
-in ``'.html'``, ``'.htm'`` and ``'.xml'`` and disabling it by default
-for all other extensions::
-
- def guess_autoescape(template_name):
- if template_name is None or '.' not in template_name:
- return False
- ext = template_name.rsplit('.', 1)[1]
- return ext in ('html', 'htm', 'xml')
-
- env = Environment(autoescape=guess_autoescape,
- loader=PackageLoader('mypackage'),
- extensions=['jinja2.ext.autoescape'])
-
-When implementing a guessing autoescape function, make sure you also
-accept `None` as valid template name. This will be passed when generating
-templates from strings.
-
-Inside the templates the behaviour can be temporarily changed by using
-the `autoescape` block (see :ref:`autoescape-overrides`).
-
-
-.. _identifier-naming:
-
-Notes on Identifiers
---------------------
-
-Jinja2 uses the regular Python 2.x naming rules. Valid identifiers have to
-match ``[a-zA-Z_][a-zA-Z0-9_]*``. As a matter of fact non ASCII characters
-are currently not allowed. This limitation will probably go away as soon as
-unicode identifiers are fully specified for Python 3.
-
-Filters and tests are looked up in separate namespaces and have slightly
-modified identifier syntax. Filters and tests may contain dots to group
-filters and tests by topic. For example it's perfectly valid to add a
-function into the filter dict and call it `to.unicode`. The regular
-expression for filter and test identifiers is
-``[a-zA-Z_][a-zA-Z0-9_]*(\.[a-zA-Z_][a-zA-Z0-9_]*)*```.
-
-
-Undefined Types
----------------
-
-These classes can be used as undefined types. The :class:`Environment`
-constructor takes an `undefined` parameter that can be one of those classes
-or a custom subclass of :class:`Undefined`. Whenever the template engine is
-unable to look up a name or access an attribute one of those objects is
-created and returned. Some operations on undefined values are then allowed,
-others fail.
-
-The closest to regular Python behavior is the `StrictUndefined` which
-disallows all operations beside testing if it's an undefined object.
-
-.. autoclass:: jinja2.Undefined()
-
- .. attribute:: _undefined_hint
-
- Either `None` or an unicode string with the error message for
- the undefined object.
-
- .. attribute:: _undefined_obj
-
- Either `None` or the owner object that caused the undefined object
- to be created (for example because an attribute does not exist).
-
- .. attribute:: _undefined_name
-
- The name for the undefined variable / attribute or just `None`
- if no such information exists.
-
- .. attribute:: _undefined_exception
-
- The exception that the undefined object wants to raise. This
- is usually one of :exc:`UndefinedError` or :exc:`SecurityError`.
-
- .. method:: _fail_with_undefined_error(\*args, \**kwargs)
-
- When called with any arguments this method raises
- :attr:`_undefined_exception` with an error message generated
- from the undefined hints stored on the undefined object.
-
-.. autoclass:: jinja2.DebugUndefined()
-
-.. autoclass:: jinja2.StrictUndefined()
-
-Undefined objects are created by calling :attr:`undefined`.
-
-.. admonition:: Implementation
-
- :class:`Undefined` objects are implemented by overriding the special
- `__underscore__` methods. For example the default :class:`Undefined`
- class implements `__unicode__` in a way that it returns an empty
- string, however `__int__` and others still fail with an exception. To
- allow conversion to int by returning ``0`` you can implement your own::
-
- class NullUndefined(Undefined):
- def __int__(self):
- return 0
- def __float__(self):
- return 0.0
-
- To disallow a method, just override it and raise
- :attr:`~Undefined._undefined_exception`. Because this is a very common
- idom in undefined objects there is the helper method
- :meth:`~Undefined._fail_with_undefined_error` that does the error raising
- automatically. Here a class that works like the regular :class:`Undefined`
- but chokes on iteration::
-
- class NonIterableUndefined(Undefined):
- __iter__ = Undefined._fail_with_undefined_error
-
-
-The Context
------------
-
-.. autoclass:: jinja2.runtime.Context()
- :members: resolve, get_exported, get_all
-
- .. attribute:: parent
-
- A dict of read only, global variables the template looks up. These
- can either come from another :class:`Context`, from the
- :attr:`Environment.globals` or :attr:`Template.globals` or points
- to a dict created by combining the globals with the variables
- passed to the render function. It must not be altered.
-
- .. attribute:: vars
-
- The template local variables. This list contains environment and
- context functions from the :attr:`parent` scope as well as local
- modifications and exported variables from the template. The template
- will modify this dict during template evaluation but filters and
- context functions are not allowed to modify it.
-
- .. attribute:: environment
-
- The environment that loaded the template.
-
- .. attribute:: exported_vars
-
- This set contains all the names the template exports. The values for
- the names are in the :attr:`vars` dict. In order to get a copy of the
- exported variables as dict, :meth:`get_exported` can be used.
-
- .. attribute:: name
-
- The load name of the template owning this context.
-
- .. attribute:: blocks
-
- A dict with the current mapping of blocks in the template. The keys
- in this dict are the names of the blocks, and the values a list of
- blocks registered. The last item in each list is the current active
- block (latest in the inheritance chain).
-
- .. attribute:: eval_ctx
-
- The current :ref:`eval-context`.
-
- .. automethod:: jinja2.runtime.Context.call(callable, \*args, \**kwargs)
-
-
-.. admonition:: Implementation
-
- Context is immutable for the same reason Python's frame locals are
- immutable inside functions. Both Jinja2 and Python are not using the
- context / frame locals as data storage for variables but only as primary
- data source.
-
- When a template accesses a variable the template does not define, Jinja2
- looks up the variable in the context, after that the variable is treated
- as if it was defined in the template.
-
-
-.. _loaders:
-
-Loaders
--------
-
-Loaders are responsible for loading templates from a resource such as the
-file system. The environment will keep the compiled modules in memory like
-Python's `sys.modules`. Unlike `sys.modules` however this cache is limited in
-size by default and templates are automatically reloaded.
-All loaders are subclasses of :class:`BaseLoader`. If you want to create your
-own loader, subclass :class:`BaseLoader` and override `get_source`.
-
-.. autoclass:: jinja2.BaseLoader
- :members: get_source, load
-
-Here a list of the builtin loaders Jinja2 provides:
-
-.. autoclass:: jinja2.FileSystemLoader
-
-.. autoclass:: jinja2.PackageLoader
-
-.. autoclass:: jinja2.DictLoader
-
-.. autoclass:: jinja2.FunctionLoader
-
-.. autoclass:: jinja2.PrefixLoader
-
-.. autoclass:: jinja2.ChoiceLoader
-
-
-.. _bytecode-cache:
-
-Bytecode Cache
---------------
-
-Jinja 2.1 and higher support external bytecode caching. Bytecode caches make
-it possible to store the generated bytecode on the file system or a different
-location to avoid parsing the templates on first use.
-
-This is especially useful if you have a web application that is initialized on
-the first request and Jinja compiles many templates at once which slows down
-the application.
-
-To use a bytecode cache, instanciate it and pass it to the :class:`Environment`.
-
-.. autoclass:: jinja2.BytecodeCache
- :members: load_bytecode, dump_bytecode, clear
-
-.. autoclass:: jinja2.bccache.Bucket
- :members: write_bytecode, load_bytecode, bytecode_from_string,
- bytecode_to_string, reset
-
- .. attribute:: environment
-
- The :class:`Environment` that created the bucket.
-
- .. attribute:: key
-
- The unique cache key for this bucket
-
- .. attribute:: code
-
- The bytecode if it's loaded, otherwise `None`.
-
-
-Builtin bytecode caches:
-
-.. autoclass:: jinja2.FileSystemBytecodeCache
-
-.. autoclass:: jinja2.MemcachedBytecodeCache
-
-
-Utilities
----------
-
-These helper functions and classes are useful if you add custom filters or
-functions to a Jinja2 environment.
-
-.. autofunction:: jinja2.environmentfilter
-
-.. autofunction:: jinja2.contextfilter
-
-.. autofunction:: jinja2.evalcontextfilter
-
-.. autofunction:: jinja2.environmentfunction
-
-.. autofunction:: jinja2.contextfunction
-
-.. autofunction:: jinja2.evalcontextfunction
-
-.. function:: escape(s)
-
- Convert the characters ``&``, ``<``, ``>``, ``'``, and ``"`` in string `s`
- to HTML-safe sequences. Use this if you need to display text that might
- contain such characters in HTML. This function will not escaped objects
- that do have an HTML representation such as already escaped data.
-
- The return value is a :class:`Markup` string.
-
-.. autofunction:: jinja2.clear_caches
-
-.. autofunction:: jinja2.is_undefined
-
-.. autoclass:: jinja2.Markup([string])
- :members: escape, unescape, striptags
-
-.. admonition:: Note
-
- The Jinja2 :class:`Markup` class is compatible with at least Pylons and
- Genshi. It's expected that more template engines and framework will pick
- up the `__html__` concept soon.
-
-
-Exceptions
-----------
-
-.. autoexception:: jinja2.TemplateError
-
-.. autoexception:: jinja2.UndefinedError
-
-.. autoexception:: jinja2.TemplateNotFound
-
-.. autoexception:: jinja2.TemplatesNotFound
-
-.. autoexception:: jinja2.TemplateSyntaxError
-
- .. attribute:: message
-
- The error message as utf-8 bytestring.
-
- .. attribute:: lineno
-
- The line number where the error occurred
-
- .. attribute:: name
-
- The load name for the template as unicode string.
-
- .. attribute:: filename
-
- The filename that loaded the template as bytestring in the encoding
- of the file system (most likely utf-8 or mbcs on Windows systems).
-
- The reason why the filename and error message are bytestrings and not
- unicode strings is that Python 2.x is not using unicode for exceptions
- and tracebacks as well as the compiler. This will change with Python 3.
-
-.. autoexception:: jinja2.TemplateAssertionError
-
-
-.. _writing-filters:
-
-Custom Filters
---------------
-
-Custom filters are just regular Python functions that take the left side of
-the filter as first argument and the the arguments passed to the filter as
-extra arguments or keyword arguments.
-
-For example in the filter ``{{ 42|myfilter(23) }}`` the function would be
-called with ``myfilter(42, 23)``. Here for example a simple filter that can
-be applied to datetime objects to format them::
-
- def datetimeformat(value, format='%H:%M / %d-%m-%Y'):
- return value.strftime(format)
-
-You can register it on the template environment by updating the
-:attr:`~Environment.filters` dict on the environment::
-
- environment.filters['datetimeformat'] = datetimeformat
-
-Inside the template it can then be used as follows:
-
-.. sourcecode:: jinja
-
- written on: {{ article.pub_date|datetimeformat }}
- publication date: {{ article.pub_date|datetimeformat('%d-%m-%Y') }}
-
-Filters can also be passed the current template context or environment. This
-is useful if a filter wants to return an undefined value or check the current
-:attr:`~Environment.autoescape` setting. For this purpose three decorators
-exist: :func:`environmentfilter`, :func:`contextfilter` and
-:func:`evalcontextfilter`.
-
-Here a small example filter that breaks a text into HTML line breaks and
-paragraphs and marks the return value as safe HTML string if autoescaping is
-enabled::
-
- import re
- from jinja2 import environmentfilter, Markup, escape
-
- _paragraph_re = re.compile(r'(?:\r\n|\r|\n){2,}')
-
- @evalcontextfilter
- def nl2br(eval_ctx, value):
- result = u'\n\n'.join(u'<p>%s</p>' % p.replace('\n', '<br>\n')
- for p in _paragraph_re.split(escape(value)))
- if eval_ctx.autoescape:
- result = Markup(result)
- return result
-
-Context filters work the same just that the first argument is the current
-active :class:`Context` rather then the environment.
-
-
-.. _eval-context:
-
-Evaluation Context
-------------------
-
-The evaluation context (short eval context or eval ctx) is a new object
-introducted in Jinja 2.4 that makes it possible to activate and deactivate
-compiled features at runtime.
-
-Currently it is only used to enable and disable the automatic escaping but
-can be used for extensions as well.
-
-In previous Jinja versions filters and functions were marked as
-environment callables in order to check for the autoescape status from the
-environment. In new versions it's encouraged to check the setting from the
-evaluation context instead.
-
-Previous versions::
-
- @environmentfilter
- def filter(env, value):
- result = do_something(value)
- if env.autoescape:
- result = Markup(result)
- return result
-
-In new versions you can either use a :func:`contextfilter` and access the
-evaluation context from the actual context, or use a
-:func:`evalcontextfilter` which directly passes the evaluation context to
-the function::
-
- @contextfilter
- def filter(context, value):
- result = do_something(value)
- if context.eval_ctx.autoescape:
- result = Markup(result)
- return result
-
- @evalcontextfilter
- def filter(eval_ctx, value):
- result = do_something(value)
- if eval_ctx.autoescape:
- result = Markup(result)
- return result
-
-The evaluation context must not be modified at runtime. Modifications
-must only happen with a :class:`nodes.EvalContextModifier` and
-:class:`nodes.ScopedEvalContextModifier` from an extension, not on the
-eval context object itself.
-
-.. autoclass:: jinja2.nodes.EvalContext
-
- .. attribute:: autoescape
-
- `True` or `False` depending on if autoescaping is active or not.
-
- .. attribute:: volatile
-
- `True` if the compiler cannot evaluate some expressions at compile
- time. At runtime this should always be `False`.
-
-
-.. _writing-tests:
-
-Custom Tests
-------------
-
-Tests work like filters just that there is no way for a test to get access
-to the environment or context and that they can't be chained. The return
-value of a test should be `True` or `False`. The purpose of a test is to
-give the template designers the possibility to perform type and conformability
-checks.
-
-Here a simple test that checks if a variable is a prime number::
-
- import math
-
- def is_prime(n):
- if n == 2:
- return True
- for i in xrange(2, int(math.ceil(math.sqrt(n))) + 1):
- if n % i == 0:
- return False
- return True
-
-
-You can register it on the template environment by updating the
-:attr:`~Environment.tests` dict on the environment::
-
- environment.tests['prime'] = is_prime
-
-A template designer can then use the test like this:
-
-.. sourcecode:: jinja
-
- {% if 42 is prime %}
- 42 is a prime number
- {% else %}
- 42 is not a prime number
- {% endif %}
-
-
-.. _global-namespace:
-
-The Global Namespace
---------------------
-
-Variables stored in the :attr:`Environment.globals` dict are special as they
-are available for imported templates too, even if they are imported without
-context. This is the place where you can put variables and functions
-that should be available all the time. Additionally :attr:`Template.globals`
-exist that are variables available to a specific template that are available
-to all :meth:`~Template.render` calls.
-
-
-.. _low-level-api:
-
-Low Level API
--------------
-
-The low level API exposes functionality that can be useful to understand some
-implementation details, debugging purposes or advanced :ref:`extension
-<jinja-extensions>` techniques. Unless you know exactly what you are doing we
-don't recommend using any of those.
-
-.. automethod:: Environment.lex
-
-.. automethod:: Environment.parse
-
-.. automethod:: Environment.preprocess
-
-.. automethod:: Template.new_context
-
-.. method:: Template.root_render_func(context)
-
- This is the low level render function. It's passed a :class:`Context`
- that has to be created by :meth:`new_context` of the same template or
- a compatible template. This render function is generated by the
- compiler from the template code and returns a generator that yields
- unicode strings.
-
- If an exception in the template code happens the template engine will
- not rewrite the exception but pass through the original one. As a
- matter of fact this function should only be called from within a
- :meth:`render` / :meth:`generate` / :meth:`stream` call.
-
-.. attribute:: Template.blocks
-
- A dict of block render functions. Each of these functions works exactly
- like the :meth:`root_render_func` with the same limitations.
-
-.. attribute:: Template.is_up_to_date
-
- This attribute is `False` if there is a newer version of the template
- available, otherwise `True`.
-
-.. admonition:: Note
-
- The low-level API is fragile. Future Jinja2 versions will try not to
- change it in a backwards incompatible way but modifications in the Jinja2
- core may shine through. For example if Jinja2 introduces a new AST node
- in later versions that may be returned by :meth:`~Environment.parse`.
-
-The Meta API
-------------
-
-.. versionadded:: 2.2
-
-The meta API returns some information about abstract syntax trees that
-could help applications to implement more advanced template concepts. All
-the functions of the meta API operate on an abstract syntax tree as
-returned by the :meth:`Environment.parse` method.
-
-.. autofunction:: jinja2.meta.find_undeclared_variables
-
-.. autofunction:: jinja2.meta.find_referenced_templates
diff --git a/slider-agent/src/main/python/jinja2/docs/cache_extension.py b/slider-agent/src/main/python/jinja2/docs/cache_extension.py
deleted file mode 100644
index 8fdefb5..0000000
--- a/slider-agent/src/main/python/jinja2/docs/cache_extension.py
+++ /dev/null
@@ -1,56 +0,0 @@
-from jinja2 import nodes
-from jinja2.ext import Extension
-
-
-class FragmentCacheExtension(Extension):
- # a set of names that trigger the extension.
- tags = set(['cache'])
-
- def __init__(self, environment):
- super(FragmentCacheExtension, self).__init__(environment)
-
- # add the defaults to the environment
- environment.extend(
- fragment_cache_prefix='',
- fragment_cache=None
- )
-
- def parse(self, parser):
- # the first token is the token that started the tag. In our case
- # we only listen to ``'cache'`` so this will be a name token with
- # `cache` as value. We get the line number so that we can give
- # that line number to the nodes we create by hand.
- lineno = parser.stream.next().lineno
-
- # now we parse a single expression that is used as cache key.
- args = [parser.parse_expression()]
-
- # if there is a comma, the user provided a timeout. If not use
- # None as second parameter.
- if parser.stream.skip_if('comma'):
- args.append(parser.parse_expression())
- else:
- args.append(nodes.Const(None))
-
- # now we parse the body of the cache block up to `endcache` and
- # drop the needle (which would always be `endcache` in that case)
- body = parser.parse_statements(['name:endcache'], drop_needle=True)
-
- # now return a `CallBlock` node that calls our _cache_support
- # helper method on this extension.
- return nodes.CallBlock(self.call_method('_cache_support', args),
- [], [], body).set_lineno(lineno)
-
- def _cache_support(self, name, timeout, caller):
- """Helper callback."""
- key = self.environment.fragment_cache_prefix + name
-
- # try to load the block from the cache
- # if there is no fragment in the cache, render it and store
- # it in the cache.
- rv = self.environment.fragment_cache.get(key)
- if rv is not None:
- return rv
- rv = caller()
- self.environment.fragment_cache.add(key, rv, timeout)
- return rv
diff --git a/slider-agent/src/main/python/jinja2/docs/changelog.rst b/slider-agent/src/main/python/jinja2/docs/changelog.rst
deleted file mode 100644
index 9f11484..0000000
--- a/slider-agent/src/main/python/jinja2/docs/changelog.rst
+++ /dev/null
@@ -1,3 +0,0 @@
-.. module:: jinja2
-
-.. include:: ../CHANGES
diff --git a/slider-agent/src/main/python/jinja2/docs/conf.py b/slider-agent/src/main/python/jinja2/docs/conf.py
deleted file mode 100644
index ba90c49..0000000
--- a/slider-agent/src/main/python/jinja2/docs/conf.py
+++ /dev/null
@@ -1,141 +0,0 @@
-# -*- coding: utf-8 -*-
-#
-# Jinja2 documentation build configuration file, created by
-# sphinx-quickstart on Sun Apr 27 21:42:41 2008.
-#
-# This file is execfile()d with the current directory set to its containing dir.
-#
-# The contents of this file are pickled, so don't put values in the namespace
-# that aren't pickleable (module imports are okay, they're removed automatically).
-#
-# All configuration values have a default value; values that are commented out
-# serve to show the default value.
-
-import sys, os
-
-# If your extensions are in another directory, add it here. If the directory
-# is relative to the documentation root, use os.path.abspath to make it
-# absolute, like shown here.
-sys.path.append(os.path.dirname(os.path.abspath(__file__)))
-
-# General configuration
-# ---------------------
-
-# Add any Sphinx extension module names here, as strings. They can be extensions
-# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
-extensions = ['sphinx.ext.autodoc', 'jinjaext']
-
-# Add any paths that contain templates here, relative to this directory.
-templates_path = ['_templates']
-
-# The suffix of source filenames.
-source_suffix = '.rst'
-
-# The master toctree document.
-master_doc = 'index'
-
-# General substitutions.
-project = 'Jinja2'
-copyright = '2008, Armin Ronacher'
-
-# The default replacements for |version| and |release|, also used in various
-# other places throughout the built documents.
-#
-# The short X.Y version.
-version = '2.0'
-# The full version, including alpha/beta/rc tags.
-release = '2.0'
-
-# There are two options for replacing |today|: either, you set today to some
-# non-false value, then it is used:
-#today = ''
-# Else, today_fmt is used as the format for a strftime call.
-today_fmt = '%B %d, %Y'
-
-# List of documents that shouldn't be included in the build.
-#unused_docs = []
-
-# If true, '()' will be appended to :func: etc. cross-reference text.
-#add_function_parentheses = True
-
-# If true, the current module name will be prepended to all description
-# unit titles (such as .. function::).
-#add_module_names = True
-
-# If true, sectionauthor and moduleauthor directives will be shown in the
-# output. They are ignored by default.
-#show_authors = False
-
-# The name of the Pygments (syntax highlighting) style to use.
-pygments_style = 'jinjaext.JinjaStyle'
-
-
-# Options for HTML output
-# -----------------------
-
-# The style sheet to use for HTML and HTML Help pages. A file of that name
-# must exist either in Sphinx' static/ path, or in one of the custom paths
-# given in html_static_path.
-html_style = 'style.css'
-
-# The name for this set of Sphinx documents. If None, it defaults to
-# "<project> v<release> documentation".
-#html_title = None
-
-# Add any paths that contain custom static files (such as style sheets) here,
-# relative to this directory. They are copied after the builtin static files,
-# so a file named "default.css" will overwrite the builtin "default.css".
-html_static_path = ['_static']
-
-# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
-# using the given strftime format.
-html_last_updated_fmt = '%b %d, %Y'
-
-# If true, SmartyPants will be used to convert quotes and dashes to
-# typographically correct entities.
-#html_use_smartypants = True
-
-# no modindex
-html_use_modindex = False
-
-# If true, the reST sources are included in the HTML build as _sources/<name>.
-#html_copy_source = True
-
-# If true, an OpenSearch description file will be output, and all pages will
-# contain a <link> tag referring to it.
-#html_use_opensearch = False
-
-# Output file base name for HTML help builder.
-htmlhelp_basename = 'Jinja2doc'
-
-
-# Options for LaTeX output
-# ------------------------
-
-# The paper size ('letter' or 'a4').
-latex_paper_size = 'a4'
-
-# The font size ('10pt', '11pt' or '12pt').
-#latex_font_size = '10pt'
-
-# Grouping the document tree into LaTeX files. List of tuples
-# (source start file, target name, title, author, document class [howto/manual]).
-latex_documents = [
- ('index', 'Jinja2.tex', 'Jinja2 Documentation', 'Armin Ronacher', 'manual', 'toctree_only'),
-]
-
-# Additional stuff for the LaTeX preamble.
-latex_preamble = '''
-\usepackage{palatino}
-\definecolor{TitleColor}{rgb}{0.7,0,0}
-\definecolor{InnerLinkColor}{rgb}{0.7,0,0}
-\definecolor{OuterLinkColor}{rgb}{0.8,0,0}
-\definecolor{VerbatimColor}{rgb}{0.985,0.985,0.985}
-\definecolor{VerbatimBorderColor}{rgb}{0.8,0.8,0.8}
-'''
-
-# Documents to append as an appendix to all manuals.
-#latex_appendices = []
-
-# If false, no module index is generated.
-latex_use_modindex = False
diff --git a/slider-agent/src/main/python/jinja2/docs/extensions.rst b/slider-agent/src/main/python/jinja2/docs/extensions.rst
deleted file mode 100644
index c6b6ec9..0000000
--- a/slider-agent/src/main/python/jinja2/docs/extensions.rst
+++ /dev/null
@@ -1,347 +0,0 @@
-.. _jinja-extensions:
-
-Extensions
-==========
-
-Jinja2 supports extensions that can add extra filters, tests, globals or even
-extend the parser. The main motivation of extensions is it to move often used
-code into a reusable class like adding support for internationalization.
-
-
-Adding Extensions
------------------
-
-Extensions are added to the Jinja2 environment at creation time. Once the
-environment is created additional extensions cannot be added. To add an
-extension pass a list of extension classes or import paths to the
-`environment` parameter of the :class:`Environment` constructor. The following
-example creates a Jinja2 environment with the i18n extension loaded::
-
- jinja_env = Environment(extensions=['jinja2.ext.i18n'])
-
-
-.. _i18n-extension:
-
-i18n Extension
---------------
-
-**Import name:** `jinja2.ext.i18n`
-
-Jinja2 currently comes with one extension, the i18n extension. It can be
-used in combination with `gettext`_ or `babel`_. If the i18n extension is
-enabled Jinja2 provides a `trans` statement that marks the wrapped string as
-translatable and calls `gettext`.
-
-After enabling dummy `_` function that forwards calls to `gettext` is added
-to the environment globals. An internationalized application then has to
-provide at least an `gettext` and optoinally a `ngettext` function into the
-namespace. Either globally or for each rendering.
-
-Environment Methods
-~~~~~~~~~~~~~~~~~~~
-
-After enabling of the extension the environment provides the following
-additional methods:
-
-.. method:: jinja2.Environment.install_gettext_translations(translations, newstyle=False)
-
- Installs a translation globally for that environment. The tranlations
- object provided must implement at least `ugettext` and `ungettext`.
- The `gettext.NullTranslations` and `gettext.GNUTranslations` classes
- as well as `Babel`_\s `Translations` class are supported.
-
- .. versionchanged:: 2.5 newstyle gettext added
-
-.. method:: jinja2.Environment.install_null_translations(newstyle=False)
-
- Install dummy gettext functions. This is useful if you want to prepare
- the application for internationalization but don't want to implement the
- full internationalization system yet.
-
- .. versionchanged:: 2.5 newstyle gettext added
-
-.. method:: jinja2.Environment.install_gettext_callables(gettext, ngettext, newstyle=False)
-
- Installs the given `gettext` and `ngettext` callables into the
- environment as globals. They are supposed to behave exactly like the
- standard library's :func:`gettext.ugettext` and
- :func:`gettext.ungettext` functions.
-
- If `newstyle` is activated, the callables are wrapped to work like
- newstyle callables. See :ref:`newstyle-gettext` for more information.
-
- .. versionadded:: 2.5
-
-.. method:: jinja2.Environment.uninstall_gettext_translations()
-
- Uninstall the translations again.
-
-.. method:: jinja2.Environment.extract_translations(source)
-
- Extract localizable strings from the given template node or source.
-
- For every string found this function yields a ``(lineno, function,
- message)`` tuple, where:
-
- * `lineno` is the number of the line on which the string was found,
- * `function` is the name of the `gettext` function used (if the
- string was extracted from embedded Python code), and
- * `message` is the string itself (a `unicode` object, or a tuple
- of `unicode` objects for functions with multiple string arguments).
-
- If `Babel`_ is installed :ref:`the babel integration <babel-integration>`
- can be used to extract strings for babel.
-
-For a web application that is available in multiple languages but gives all
-the users the same language (for example a multilingual forum software
-installed for a French community) may load the translations once and add the
-translation methods to the environment at environment generation time::
-
- translations = get_gettext_translations()
- env = Environment(extensions=['jinja2.ext.i18n'])
- env.install_gettext_translations(translations)
-
-The `get_gettext_translations` function would return the translator for the
-current configuration. (For example by using `gettext.find`)
-
-The usage of the `i18n` extension for template designers is covered as part
-:ref:`of the template documentation <i18n-in-templates>`.
-
-.. _gettext: http://docs.python.org/dev/library/gettext
-.. _Babel: http://babel.edgewall.org/
-
-.. _newstyle-gettext:
-
-Newstyle Gettext
-~~~~~~~~~~~~~~~~
-
-.. versionadded:: 2.5
-
-Starting with version 2.5 you can use newstyle gettext calls. These are
-inspired by trac's internal gettext functions and are fully supported by
-the babel extraction tool. They might not work as expected by other
-extraction tools in case you are not using Babel's.
-
-What's the big difference between standard and newstyle gettext calls? In
-general they are less to type and less error prone. Also if they are used
-in an autoescaping environment they better support automatic escaping.
-Here some common differences between old and new calls:
-
-standard gettext:
-
-.. sourcecode:: html+jinja
-
- {{ gettext('Hello World!') }}
- {{ gettext('Hello %(name)s!')|format(name='World') }}
- {{ ngettext('%(num)d apple', '%(num)d apples', apples|count)|format(
- num=apples|count
- )}}
-
-newstyle gettext looks like this instead:
-
-.. sourcecode:: html+jinja
-
- {{ gettext('Hello World!') }}
- {{ gettext('Hello %(name)s!', name='World') }}
- {{ ngettext('%(num)d apple', '%(num)d apples', apples|count) }}
-
-The advantages of newstyle gettext is that you have less to type and that
-named placeholders become mandatory. The latter sounds like a
-disadvantage but solves a lot of troubles translators are often facing
-when they are unable to switch the positions of two placeholder. With
-newstyle gettext, all format strings look the same.
-
-Furthermore with newstyle gettext, string formatting is also used if no
-placeholders are used which makes all strings behave exactly the same.
-Last but not least are newstyle gettext calls able to properly mark
-strings for autoescaping which solves lots of escaping related issues many
-templates are experiencing over time when using autoescaping.
-
-Expression Statement
---------------------
-
-**Import name:** `jinja2.ext.do`
-
-The "do" aka expression-statement extension adds a simple `do` tag to the
-template engine that works like a variable expression but ignores the
-return value.
-
-.. _loopcontrols-extension:
-
-Loop Controls
--------------
-
-**Import name:** `jinja2.ext.loopcontrols`
-
-This extension adds support for `break` and `continue` in loops. After
-enabling Jinja2 provides those two keywords which work exactly like in
-Python.
-
-.. _with-extension:
-
-With Statement
---------------
-
-**Import name:** `jinja2.ext.with_`
-
-.. versionadded:: 2.3
-
-This extension adds support for the with keyword. Using this keyword it
-is possible to enforce a nested scope in a template. Variables can be
-declared directly in the opening block of the with statement or using a
-standard `set` statement directly within.
-
-.. _autoescape-extension:
-
-Autoescape Extension
---------------------
-
-**Import name:** `jinja2.ext.autoescape`
-
-.. versionadded:: 2.4
-
-The autoescape extension allows you to toggle the autoescape feature from
-within the template. If the environment's :attr:`~Environment.autoescape`
-setting is set to `False` it can be activated, if it's `True` it can be
-deactivated. The setting overriding is scoped.
-
-
-.. _writing-extensions:
-
-Writing Extensions
-------------------
-
-.. module:: jinja2.ext
-
-By writing extensions you can add custom tags to Jinja2. This is a non trival
-task and usually not needed as the default tags and expressions cover all
-common use cases. The i18n extension is a good example of why extensions are
-useful, another one would be fragment caching.
-
-When writing extensions you have to keep in mind that you are working with the
-Jinja2 template compiler which does not validate the node tree you are possing
-to it. If the AST is malformed you will get all kinds of compiler or runtime
-errors that are horrible to debug. Always make sure you are using the nodes
-you create correctly. The API documentation below shows which nodes exist and
-how to use them.
-
-Example Extension
-~~~~~~~~~~~~~~~~~
-
-The following example implements a `cache` tag for Jinja2 by using the
-`Werkzeug`_ caching contrib module:
-
-.. literalinclude:: cache_extension.py
- :language: python
-
-And here is how you use it in an environment::
-
- from jinja2 import Environment
- from werkzeug.contrib.cache import SimpleCache
-
- env = Environment(extensions=[FragmentCacheExtension])
- env.fragment_cache = SimpleCache()
-
-Inside the template it's then possible to mark blocks as cacheable. The
-following example caches a sidebar for 300 seconds:
-
-.. sourcecode:: html+jinja
-
- {% cache 'sidebar', 300 %}
- <div class="sidebar">
- ...
- </div>
- {% endcache %}
-
-.. _Werkzeug: http://werkzeug.pocoo.org/
-
-Extension API
-~~~~~~~~~~~~~
-
-Extensions always have to extend the :class:`jinja2.ext.Extension` class:
-
-.. autoclass:: Extension
- :members: preprocess, filter_stream, parse, attr, call_method
-
- .. attribute:: identifier
-
- The identifier of the extension. This is always the true import name
- of the extension class and must not be changed.
-
- .. attribute:: tags
-
- If the extension implements custom tags this is a set of tag names
- the extension is listening for.
-
-Parser API
-~~~~~~~~~~
-
-The parser passed to :meth:`Extension.parse` provides ways to parse
-expressions of different types. The following methods may be used by
-extensions:
-
-.. autoclass:: jinja2.parser.Parser
- :members: parse_expression, parse_tuple, parse_assign_target,
- parse_statements, free_identifier, fail
-
- .. attribute:: filename
-
- The filename of the template the parser processes. This is **not**
- the load name of the template. For the load name see :attr:`name`.
- For templates that were not loaded form the file system this is
- `None`.
-
- .. attribute:: name
-
- The load name of the template.
-
- .. attribute:: stream
-
- The current :class:`~jinja2.lexer.TokenStream`
-
-.. autoclass:: jinja2.lexer.TokenStream
- :members: push, look, eos, skip, next, next_if, skip_if, expect
-
- .. attribute:: current
-
- The current :class:`~jinja2.lexer.Token`.
-
-.. autoclass:: jinja2.lexer.Token
- :members: test, test_any
-
- .. attribute:: lineno
-
- The line number of the token
-
- .. attribute:: type
-
- The type of the token. This string is interned so you may compare
- it with arbitrary strings using the `is` operator.
-
- .. attribute:: value
-
- The value of the token.
-
-There is also a utility function in the lexer module that can count newline
-characters in strings:
-
-.. autofunction:: jinja2.lexer.count_newlines
-
-AST
-~~~
-
-The AST (Abstract Syntax Tree) is used to represent a template after parsing.
-It's build of nodes that the compiler then converts into executable Python
-code objects. Extensions that provide custom statements can return nodes to
-execute custom Python code.
-
-The list below describes all nodes that are currently available. The AST may
-change between Jinja2 versions but will stay backwards compatible.
-
-For more information have a look at the repr of :meth:`jinja2.Environment.parse`.
-
-.. module:: jinja2.nodes
-
-.. jinjanodes::
-
-.. autoexception:: Impossible
diff --git a/slider-agent/src/main/python/jinja2/docs/faq.rst b/slider-agent/src/main/python/jinja2/docs/faq.rst
deleted file mode 100644
index 89186b1..0000000
--- a/slider-agent/src/main/python/jinja2/docs/faq.rst
+++ /dev/null
@@ -1,191 +0,0 @@
-Frequently Asked Questions
-==========================
-
-This page answers some of the often asked questions about Jinja.
-
-.. highlight:: html+jinja
-
-Why is it called Jinja?
------------------------
-
-The name Jinja was chosen because it's the name of a Japanese temple and
-temple and template share a similar pronunciation. It is not named after
-the capital city of Uganda.
-
-How fast is it?
----------------
-
-We really hate benchmarks especially since they don't reflect much. The
-performance of a template depends on many factors and you would have to
-benchmark different engines in different situations. The benchmarks from the
-testsuite show that Jinja2 has a similar performance to `Mako`_ and is between
-10 and 20 times faster than Django's template engine or Genshi. These numbers
-should be taken with tons of salt as the benchmarks that took these numbers
-only test a few performance related situations such as looping. Generally
-speaking the performance of a template engine doesn't matter much as the
-usual bottleneck in a web application is either the database or the application
-code.
-
-.. _Mako: http://www.makotemplates.org/
-
-How Compatible is Jinja2 with Django?
--------------------------------------
-
-The default syntax of Jinja2 matches Django syntax in many ways. However
-this similarity doesn't mean that you can use a Django template unmodified
-in Jinja2. For example filter arguments use a function call syntax rather
-than a colon to separate filter name and arguments. Additionally the
-extension interface in Jinja is fundamentally different from the Django one
-which means that your custom tags won't work any longer.
-
-Generally speaking you will use much less custom extensions as the Jinja
-template system allows you to use a certain subset of Python expressions
-which can replace most Django extensions. For example instead of using
-something like this::
-
- {% load comments %}
- {% get_latest_comments 10 as latest_comments %}
- {% for comment in latest_comments %}
- ...
- {% endfor %}
-
-You will most likely provide an object with attributes to retrieve
-comments from the database::
-
- {% for comment in models.comments.latest(10) %}
- ...
- {% endfor %}
-
-Or directly provide the model for quick testing::
-
- {% for comment in Comment.objects.order_by('-pub_date')[:10] %}
- ...
- {% endfor %}
-
-Please keep in mind that even though you may put such things into templates
-it still isn't a good idea. Queries should go into the view code and not
-the template!
-
-Isn't it a terrible idea to put Logic into Templates?
------------------------------------------------------
-
-Without a doubt you should try to remove as much logic from templates as
-possible. But templates without any logic mean that you have to do all
-the processing in the code which is boring and stupid. A template engine
-that does that is shipped with Python and called `string.Template`. Comes
-without loops and if conditions and is by far the fastest template engine
-you can get for Python.
-
-So some amount of logic is required in templates to keep everyone happy.
-And Jinja leaves it pretty much to you how much logic you want to put into
-templates. There are some restrictions in what you can do and what not.
-
-Jinja2 neither allows you to put arbitrary Python code into templates nor
-does it allow all Python expressions. The operators are limited to the
-most common ones and more advanced expressions such as list comprehensions
-and generator expressions are not supported. This keeps the template engine
-easier to maintain and templates more readable.
-
-Why is Autoescaping not the Default?
-------------------------------------
-
-There are multiple reasons why automatic escaping is not the default mode
-and also not the recommended one. While automatic escaping of variables
-means that you will less likely have an XSS problem it also causes a huge
-amount of extra processing in the template engine which can cause serious
-performance problems. As Python doesn't provide a way to mark strings as
-unsafe Jinja has to hack around that limitation by providing a custom
-string class (the :class:`Markup` string) that safely interacts with safe
-and unsafe strings.
-
-With explicit escaping however the template engine doesn't have to perform
-any safety checks on variables. Also a human knows not to escape integers
-or strings that may never contain characters one has to escape or already
-HTML markup. For example when iterating over a list over a table of
-integers and floats for a table of statistics the template designer can
-omit the escaping because he knows that integers or floats don't contain
-any unsafe parameters.
-
-Additionally Jinja2 is a general purpose template engine and not only used
-for HTML/XML generation. For example you may generate LaTeX, emails,
-CSS, JavaScript, or configuration files.
-
-Why is the Context immutable?
------------------------------
-
-When writing a :func:`contextfunction` or something similar you may have
-noticed that the context tries to stop you from modifying it. If you have
-managed to modify the context by using an internal context API you may
-have noticed that changes in the context don't seem to be visible in the
-template. The reason for this is that Jinja uses the context only as
-primary data source for template variables for performance reasons.
-
-If you want to modify the context write a function that returns a variable
-instead that one can assign to a variable by using set::
-
- {% set comments = get_latest_comments() %}
-
-What is the speedups module and why is it missing?
---------------------------------------------------
-
-To achieve a good performance with automatic escaping enabled, the escaping
-function was also implemented in pure C in older Jinja2 releases and used if
-Jinja2 was installed with the speedups module.
-
-Because this feature itself is very useful for non-template engines as
-well it was moved into a separate project on PyPI called `MarkupSafe`_.
-
-Jinja2 no longer ships with a C implementation of it but only the pure
-Python implementation. It will however check if MarkupSafe is available
-and installed, and if it is, use the Markup class from MarkupSafe.
-
-So if you want the speedups, just import MarkupSafe.
-
-.. _MarkupSafe: http://pypi.python.org/pypi/MarkupSafe
-
-My tracebacks look weird. What's happening?
---------------------------------------------
-
-If the debugsupport module is not compiled and you are using a Python
-installation without ctypes (Python 2.4 without ctypes, Jython or Google's
-AppEngine) Jinja2 is unable to provide correct debugging information and
-the traceback may be incomplete. There is currently no good workaround
-for Jython or the AppEngine as ctypes is unavailable there and it's not
-possible to use the debugsupport extension.
-
-Why is there no Python 2.3 support?
------------------------------------
-
-Python 2.3 is missing a lot of features that are used heavily in Jinja2. This
-decision was made as with the upcoming Python 2.6 and 3.0 versions it becomes
-harder to maintain the code for older Python versions. If you really need
-Python 2.3 support you either have to use `Jinja 1`_ or other templating
-engines that still support 2.3.
-
-My Macros are overriden by something
-------------------------------------
-
-In some situations the Jinja scoping appears arbitrary:
-
-layout.tmpl:
-
-.. sourcecode:: jinja
-
- {% macro foo() %}LAYOUT{% endmacro %}
- {% block body %}{% endblock %}
-
-child.tmpl:
-
-.. sourcecode:: jinja
-
- {% extends 'layout.tmpl' %}
- {% macro foo() %}CHILD{% endmacro %}
- {% block body %}{{ foo() }}{% endblock %}
-
-This will print ``LAYOUT`` in Jinja2. This is a side effect of having
-the parent template evaluated after the child one. This allows child
-templates passing information to the parent template. To avoid this
-issue rename the macro or variable in the parent template to have an
-uncommon prefix.
-
-.. _Jinja 1: http://jinja.pocoo.org/1/
diff --git a/slider-agent/src/main/python/jinja2/docs/index.rst b/slider-agent/src/main/python/jinja2/docs/index.rst
deleted file mode 100644
index 27bee23..0000000
--- a/slider-agent/src/main/python/jinja2/docs/index.rst
+++ /dev/null
@@ -1,27 +0,0 @@
-Jinja2 Documentation
-====================
-
-This is the documentation for the Jinja2 general purpose templating language.
-Jinja2 is a library for Python 2.4 and onwards that is designed to be flexible,
-fast and secure.
-
-.. toctree::
- :maxdepth: 2
-
- intro
- api
- sandbox
- templates
- extensions
- integration
- switching
- tricks
-
- faq
- changelog
-
-If you can't find the information you're looking for, have a look at the
-index of try to find it using the search function:
-
-* :ref:`genindex`
-* :ref:`search`
diff --git a/slider-agent/src/main/python/jinja2/docs/integration.rst b/slider-agent/src/main/python/jinja2/docs/integration.rst
deleted file mode 100644
index 1875711..0000000
--- a/slider-agent/src/main/python/jinja2/docs/integration.rst
+++ /dev/null
@@ -1,88 +0,0 @@
-Integration
-===========
-
-Jinja2 provides some code for integration into other tools such as frameworks,
-the `Babel`_ library or your favourite editor for fancy code highlighting.
-This is a brief description of whats included.
-
-.. _babel-integration:
-
-Babel Integration
------------------
-
-Jinja provides support for extracting gettext messages from templates via a
-`Babel`_ extractor entry point called `jinja2.ext.babel_extract`. The Babel
-support is implemented as part of the :ref:`i18n-extension` extension.
-
-Gettext messages extracted from both `trans` tags and code expressions.
-
-To extract gettext messages from templates, the project needs a Jinja2 section
-in its Babel extraction method `mapping file`_:
-
-.. sourcecode:: ini
-
- [jinja2: **/templates/**.html]
- encoding = utf-8
-
-The syntax related options of the :class:`Environment` are also available as
-configuration values in the mapping file. For example to tell the extraction
-that templates use ``%`` as `line_statement_prefix` you can use this code:
-
-.. sourcecode:: ini
-
- [jinja2: **/templates/**.html]
- encoding = utf-8
- line_statement_prefix = %
-
-:ref:`jinja-extensions` may also be defined by passing a comma separated list
-of import paths as `extensions` value. The i18n extension is added
-automatically.
-
-.. _mapping file: http://babel.edgewall.org/wiki/Documentation/messages.html#extraction-method-mapping-and-configuration
-
-Pylons
-------
-
-With `Pylons`_ 0.9.7 onwards it's incredible easy to integrate Jinja into a
-Pylons powered application.
-
-The template engine is configured in `config/environment.py`. The configuration
-for Jinja2 looks something like that::
-
- from jinja2 import Environment, PackageLoader
- config['pylons.app_globals'].jinja_env = Environment(
- loader=PackageLoader('yourapplication', 'templates')
- )
-
-After that you can render Jinja templates by using the `render_jinja` function
-from the `pylons.templating` module.
-
-Additionally it's a good idea to set the Pylons' `c` object into strict mode.
-Per default any attribute to not existing attributes on the `c` object return
-an empty string and not an undefined object. To change this just use this
-snippet and add it into your `config/environment.py`::
-
- config['pylons.strict_c'] = True
-
-.. _Pylons: http://www.pylonshq.com/
-
-TextMate
---------
-
-Inside the `ext` folder of Jinja2 there is a bundle for TextMate that supports
-syntax highlighting for Jinja1 and Jinja2 for text based templates as well as
-HTML. It also contains a few often used snippets.
-
-Vim
----
-
-A syntax plugin for `Vim`_ exists in the Vim-scripts directory as well as the
-ext folder of Jinja2. `The script <http://www.vim.org/scripts/script.php?script_id=1856>`_
-supports Jinja1 and Jinja2. Once installed two file types are available `jinja`
-and `htmljinja`. The first one for text based templates, the latter for HTML
-templates.
-
-Copy the files into your `syntax` folder.
-
-.. _Babel: http://babel.edgewall.org/
-.. _Vim: http://www.vim.org/
diff --git a/slider-agent/src/main/python/jinja2/docs/intro.rst b/slider-agent/src/main/python/jinja2/docs/intro.rst
deleted file mode 100644
index 0800615..0000000
--- a/slider-agent/src/main/python/jinja2/docs/intro.rst
+++ /dev/null
@@ -1,168 +0,0 @@
-Introduction
-============
-
-This is the documentation for the Jinja2 general purpose templating language.
-Jinja2 is a library for Python 2.4 and onwards that is designed to be flexible,
-fast and secure.
-
-If you have any exposure to other text-based template languages, such as Smarty or
-Django, you should feel right at home with Jinja2. It's both designer and
-developer friendly by sticking to Python's principles and adding functionality
-useful for templating environments.
-
-The key-features are...
-
-- ... **configurable syntax**. If you are generating LaTeX or other formats
- with Jinja2 you can change the delimiters to something that integrates better
- into the LaTeX markup.
-
-- ... **fast**. While performance is not the primarily target of Jinja2 it's
- surprisingly fast. The overhead compared to regular Python code was reduced
- to the very minimum.
-
-- ... **easy to debug**. Jinja2 integrates directly into the python traceback
- system which allows you to debug Jinja2 templates with regular python
- debugging helpers.
-
-- ... **secure**. It's possible to evaluate untrusted template code if the
- optional sandbox is enabled. This allows Jinja2 to be used as templating
- language for applications where users may modify the template design.
-
-
-Prerequisites
--------------
-
-Jinja2 needs at least **Python 2.4** to run. Additionally a working C-compiler
-that can create python extensions should be installed for the debugger if you
-are using Python 2.4.
-
-If you don't have a working C-compiler and you are trying to install the source
-release with the debugsupport you will get a compiler error.
-
-.. _ctypes: http://python.net/crew/theller/ctypes/
-
-
-Installation
-------------
-
-You have multiple ways to install Jinja2. If you are unsure what to do, go
-with the Python egg or tarball.
-
-As a Python egg (via easy_install)
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-You can install the most recent Jinja2 version using `easy_install`_ or `pip`_::
-
- easy_install Jinja2
- pip install Jinja2
-
-This will install a Jinja2 egg in your Python installation's site-packages
-directory.
-
-(If you are installing from the windows command line omit the `sudo` and make
-sure to run the command as user with administrator rights)
-
-From the tarball release
-~~~~~~~~~~~~~~~~~~~~~~~~~
-
-1. Download the most recent tarball from the `download page`_
-2. Unpack the tarball
-3. ``sudo python setup.py install``
-
-Note that you either have to have setuptools or `distribute`_ installed,
-the latter is preferred.
-
-This will install Jinja2 into your Python installation's site-packages directory.
-
-.. _distribute: http://pypi.python.org/pypi/distribute
-
-Installing the development version
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-1. Install `git`_
-2. ``git clone git://github.com/mitsuhiko/jinja2.git``
-3. ``cd jinja2``
-4. ``ln -s jinja2 /usr/lib/python2.X/site-packages``
-
-As an alternative to steps 4 you can also do ``python setup.py develop``
-which will install the package via distribute in development mode. This also
-has the advantage that the C extensions are compiled.
-
-.. _download page: http://pypi.python.org/pypi/Jinja2
-.. _setuptools: http://peak.telecommunity.com/DevCenter/setuptools
-.. _easy_install: http://peak.telecommunity.com/DevCenter/EasyInstall
-.. _pip: http://pypi.python.org/pypi/pip
-.. _git: http://git-scm.org/
-
-
-More Speed with MarkupSafe
-~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-As of version 2.5.1 Jinja2 will check for an installed `MarkupSafe`_
-module. If it can find it, it will use the Markup class of that module
-instead of the one that comes with Jinja2. `MarkupSafe` replaces the
-older speedups module that came with Jinja2 and has the advantage that is
-has a better setup script and will automatically attempt to install the C
-version and nicely fall back to a pure Python implementation if that is
-not possible.
-
-The C implementation of MarkupSafe is much faster and recommended when
-using Jinja2 with autoescaping.
-
-.. _MarkupSafe: http://pypi.python.org/pypi/MarkupSafe
-
-
-Enable the debug support Module
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-By default Jinja2 will not compile the debug support module. Enabling this
-will fail if you don't have the Python headers or a working compiler. This
-is often the case if you are installing Jinja2 from a windows machine.
-
-Because the debug support is only necessary for Python 2.4 you will not
-have to do this unless you run 2.4::
-
- sudo python setup.py --with-debugsupport install
-
-
-Basic API Usage
----------------
-
-This section gives you a brief introduction to the Python API for Jinja2
-templates.
-
-The most basic way to create a template and render it is through
-:class:`~jinja2.Template`. This however is not the recommended way to
-work with it if your templates are not loaded from strings but the file
-system or another data source:
-
->>> from jinja2 import Template
->>> template = Template('Hello {{ name }}!')
->>> template.render(name='John Doe')
-u'Hello John Doe!'
-
-By creating an instance of :class:`~jinja2.Template` you get back a new template
-object that provides a method called :meth:`~jinja2.Template.render` which when
-called with a dict or keyword arguments expands the template. The dict
-or keywords arguments passed to the template are the so-called "context"
-of the template.
-
-What you can see here is that Jinja2 is using unicode internally and the
-return value is an unicode string. So make sure that your application is
-indeed using unicode internally.
-
-
-Experimental Python 3 Support
------------------------------
-
-Jinja 2.3 brings experimental support for Python 3. It means that all
-unittests pass on the new version, but there might still be small bugs in
-there and behavior might be inconsistent. If you notice any bugs, please
-provide feedback in the `Jinja bug tracker`_.
-
-Also please keep in mind that the documentation is written with Python 2
-in mind, you will have to adapt the shown code examples to Python 3 syntax
-for yourself.
-
-
-.. _Jinja bug tracker: http://github.com/mitsuhiko/jinja2/issues
diff --git a/slider-agent/src/main/python/jinja2/docs/jinjaext.py b/slider-agent/src/main/python/jinja2/docs/jinjaext.py
deleted file mode 100644
index 66f4ba1..0000000
--- a/slider-agent/src/main/python/jinja2/docs/jinjaext.py
+++ /dev/null
@@ -1,192 +0,0 @@
-# -*- coding: utf-8 -*-
-"""
- Jinja Documentation Extensions
- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
- Support for automatically documenting filters and tests.
-
- :copyright: Copyright 2008 by Armin Ronacher.
- :license: BSD.
-"""
-import os
-import re
-import inspect
-import jinja2
-from itertools import islice
-from types import BuiltinFunctionType
-from docutils import nodes
-from docutils.statemachine import ViewList
-from sphinx.ext.autodoc import prepare_docstring
-from sphinx.application import TemplateBridge
-from pygments.style import Style
-from pygments.token import Keyword, Name, Comment, String, Error, \
- Number, Operator, Generic
-from jinja2 import Environment, FileSystemLoader
-
-
-def parse_rst(state, content_offset, doc):
- node = nodes.section()
- # hack around title style bookkeeping
- surrounding_title_styles = state.memo.title_styles
- surrounding_section_level = state.memo.section_level
- state.memo.title_styles = []
- state.memo.section_level = 0
- state.nested_parse(doc, content_offset, node, match_titles=1)
- state.memo.title_styles = surrounding_title_styles
- state.memo.section_level = surrounding_section_level
- return node.children
-
-
-class JinjaStyle(Style):
- title = 'Jinja Style'
- default_style = ""
- styles = {
- Comment: 'italic #aaaaaa',
- Comment.Preproc: 'noitalic #B11414',
- Comment.Special: 'italic #505050',
-
- Keyword: 'bold #B80000',
- Keyword.Type: '#808080',
-
- Operator.Word: 'bold #B80000',
-
- Name.Builtin: '#333333',
- Name.Function: '#333333',
- Name.Class: 'bold #333333',
- Name.Namespace: 'bold #333333',
- Name.Entity: 'bold #363636',
- Name.Attribute: '#686868',
- Name.Tag: 'bold #686868',
- Name.Decorator: '#686868',
-
- String: '#AA891C',
- Number: '#444444',
-
- Generic.Heading: 'bold #000080',
- Generic.Subheading: 'bold #800080',
- Generic.Deleted: '#aa0000',
- Generic.Inserted: '#00aa00',
- Generic.Error: '#aa0000',
- Generic.Emph: 'italic',
- Generic.Strong: 'bold',
- Generic.Prompt: '#555555',
- Generic.Output: '#888888',
- Generic.Traceback: '#aa0000',
-
- Error: '#F00 bg:#FAA'
- }
-
-
-_sig_re = re.compile(r'^[a-zA-Z_][a-zA-Z0-9_]*(\(.*?\))')
-
-
-def format_function(name, aliases, func):
- lines = inspect.getdoc(func).splitlines()
- signature = '()'
- if isinstance(func, BuiltinFunctionType):
- match = _sig_re.match(lines[0])
- if match is not None:
- del lines[:1 + bool(lines and not lines[0])]
- signature = match.group(1)
- else:
- try:
- argspec = inspect.getargspec(func)
- if getattr(func, 'environmentfilter', False) or \
- getattr(func, 'contextfilter', False):
- del argspec[0][0]
- signature = inspect.formatargspec(*argspec)
- except:
- pass
- result = ['.. function:: %s%s' % (name, signature), '']
- result.extend(' ' + line for line in lines)
- if aliases:
- result.extend(('', ' :aliases: %s' % ', '.join(
- '``%s``' % x for x in sorted(aliases))))
- return result
-
-
-def dump_functions(mapping):
- def directive(dirname, arguments, options, content, lineno,
- content_offset, block_text, state, state_machine):
- reverse_mapping = {}
- for name, func in mapping.iteritems():
- reverse_mapping.setdefault(func, []).append(name)
- filters = []
- for func, names in reverse_mapping.iteritems():
- aliases = sorted(names, key=lambda x: len(x))
- name = aliases.pop()
- filters.append((name, aliases, func))
- filters.sort()
-
- result = ViewList()
- for name, aliases, func in filters:
- for item in format_function(name, aliases, func):
- result.append(item, '<jinjaext>')
-
- node = nodes.paragraph()
- state.nested_parse(result, content_offset, node)
- return node.children
- return directive
-
-
-from jinja2.defaults import DEFAULT_FILTERS, DEFAULT_TESTS
-jinja_filters = dump_functions(DEFAULT_FILTERS)
-jinja_tests = dump_functions(DEFAULT_TESTS)
-
-
-def jinja_nodes(dirname, arguments, options, content, lineno,
- content_offset, block_text, state, state_machine):
- from jinja2.nodes import Node
- doc = ViewList()
- def walk(node, indent):
- p = ' ' * indent
- sig = ', '.join(node.fields)
- doc.append(p + '.. autoclass:: %s(%s)' % (node.__name__, sig), '')
- if node.abstract:
- members = []
- for key, name in node.__dict__.iteritems():
- if not key.startswith('_') and \
- not hasattr(node.__base__, key) and callable(name):
- members.append(key)
- if members:
- members.sort()
- doc.append('%s :members: %s' % (p, ', '.join(members)), '')
- if node.__base__ != object:
- doc.append('', '')
- doc.append('%s :Node type: :class:`%s`' %
- (p, node.__base__.__name__), '')
- doc.append('', '')
- children = node.__subclasses__()
- children.sort(key=lambda x: x.__name__.lower())
- for child in children:
- walk(child, indent)
- walk(Node, 0)
- return parse_rst(state, content_offset, doc)
-
-
-def inject_toc(app, doctree, docname):
- titleiter = iter(doctree.traverse(nodes.title))
- try:
- # skip first title, we are not interested in that one
- titleiter.next()
- title = titleiter.next()
- # and check if there is at least another title
- titleiter.next()
- except StopIteration:
- return
- tocnode = nodes.section('')
- tocnode['classes'].append('toc')
- toctitle = nodes.section('')
- toctitle['classes'].append('toctitle')
- toctitle.append(nodes.title(text='Table Of Contents'))
- tocnode.append(toctitle)
- tocnode += doctree.document.settings.env.get_toc_for(docname)[0][1]
- title.parent.insert(title.parent.children.index(title), tocnode)
-
-
-def setup(app):
- app.add_directive('jinjafilters', jinja_filters, 0, (0, 0, 0))
- app.add_directive('jinjatests', jinja_tests, 0, (0, 0, 0))
- app.add_directive('jinjanodes', jinja_nodes, 0, (0, 0, 0))
- # uncomment for inline toc. links are broken unfortunately
- ##app.connect('doctree-resolved', inject_toc)
diff --git a/slider-agent/src/main/python/jinja2/docs/sandbox.rst b/slider-agent/src/main/python/jinja2/docs/sandbox.rst
deleted file mode 100644
index bb0ca9f..0000000
--- a/slider-agent/src/main/python/jinja2/docs/sandbox.rst
+++ /dev/null
@@ -1,46 +0,0 @@
-Sandbox
-=======
-
-The Jinja2 sandbox can be used to evaluate untrusted code. Access to unsafe
-attributes and methods is prohibited.
-
-Assuming `env` is a :class:`SandboxedEnvironment` in the default configuration
-the following piece of code shows how it works:
-
->>> env.from_string("{{ func.func_code }}").render(func=lambda:None)
-u''
->>> env.from_string("{{ func.func_code.do_something }}").render(func=lambda:None)
-Traceback (most recent call last):
- ...
-SecurityError: access to attribute 'func_code' of 'function' object is unsafe.
-
-
-.. module:: jinja2.sandbox
-
-.. autoclass:: SandboxedEnvironment([options])
- :members: is_safe_attribute, is_safe_callable
-
-.. autoclass:: ImmutableSandboxedEnvironment([options])
-
-.. autoexception:: SecurityError
-
-.. autofunction:: unsafe
-
-.. autofunction:: is_internal_attribute
-
-.. autofunction:: modifies_known_mutable
-
-.. admonition:: Note
-
- The Jinja2 sandbox alone is no solution for perfect security. Especially
- for web applications you have to keep in mind that users may create
- templates with arbitrary HTML in so it's crucial to ensure that (if you
- are running multiple users on the same server) they can't harm each other
- via JavaScript insertions and much more.
-
- Also the sandbox is only as good as the configuration. We stronly
- recommend only passing non-shared resources to the template and use
- some sort of whitelisting for attributes.
-
- Also keep in mind that templates may raise runtime or compile time errors,
- so make sure to catch them.
diff --git a/slider-agent/src/main/python/jinja2/docs/switching.rst b/slider-agent/src/main/python/jinja2/docs/switching.rst
deleted file mode 100644
index ba3cfb1..0000000
--- a/slider-agent/src/main/python/jinja2/docs/switching.rst
+++ /dev/null
@@ -1,242 +0,0 @@
-Switching from other Template Engines
-=====================================
-
-.. highlight:: html+jinja
-
-If you have used a different template engine in the past and want to swtich
-to Jinja2 here is a small guide that shows the basic syntatic and semantic
-changes between some common, similar text template engines for Python.
-
-Jinja1
-------
-
-Jinja2 is mostly compatible with Jinja1 in terms of API usage and template
-syntax. The differences between Jinja1 and 2 are explained in the following
-list.
-
-API
-~~~
-
-Loaders
- Jinja2 uses a different loader API. Because the internal representation
- of templates changed there is no longer support for external caching
- systems such as memcached. The memory consumed by templates is comparable
- with regular Python modules now and external caching doesn't give any
- advantage. If you have used a custom loader in the past have a look at
- the new :ref:`loader API <loaders>`.
-
-Loading templates from strings
- In the past it was possible to generate templates from a string with the
- default environment configuration by using `jinja.from_string`. Jinja2
- provides a :class:`Template` class that can be used to do the same, but
- with optional additional configuration.
-
-Automatic unicode conversion
- Jinja1 performed automatic conversion of bytestrings in a given encoding
- into unicode objects. This conversion is no longer implemented as it
- was inconsistent as most libraries are using the regular Python ASCII
- bytestring to Unicode conversion. An application powered by Jinja2
- *has to* use unicode internally everywhere or make sure that Jinja2 only
- gets unicode strings passed.
-
-i18n
- Jinja1 used custom translators for internationalization. i18n is now
- available as Jinja2 extension and uses a simpler, more gettext friendly
- interface and has support for babel. For more details see
- :ref:`i18n-extension`.
-
-Internal methods
- Jinja1 exposed a few internal methods on the environment object such
- as `call_function`, `get_attribute` and others. While they were marked
- as being an internal method it was possible to override them. Jinja2
- doesn't have equivalent methods.
-
-Sandbox
- Jinja1 was running sandbox mode by default. Few applications actually
- used that feature so it became optional in Jinja2. For more details
- about the sandboxed execution see :class:`SandboxedEnvironment`.
-
-Context
- Jinja1 had a stacked context as storage for variables passed to the
- environment. In Jinja2 a similar object exists but it doesn't allow
- modifications nor is it a singleton. As inheritance is dynamic now
- multiple context objects may exist during template evaluation.
-
-Filters and Tests
- Filters and tests are regular functions now. It's no longer necessary
- and allowed to use factory functions.
-
-
-Templates
-~~~~~~~~~
-
-Jinja2 has mostly the same syntax as Jinja1. What's different is that
-macros require parentheses around the argument list now.
-
-Additionally Jinja2 allows dynamic inheritance now and dynamic includes.
-The old helper function `rendertemplate` is gone now, `include` can be used
-instead. Includes no longer import macros and variable assignments, for
-that the new `import` tag is used. This concept is explained in the
-:ref:`import` documentation.
-
-Another small change happened in the `for`-tag. The special loop variable
-doesn't have a `parent` attribute, instead you have to alias the loop
-yourself. See :ref:`accessing-the-parent-loop` for more details.
-
-
-Django
-------
-
-If you have previously worked with Django templates, you should find
-Jinja2 very familiar. In fact, most of the syntax elements look and
-work the same.
-
-However, Jinja2 provides some more syntax elements covered in the
-documentation and some work a bit different.
-
-This section covers the template changes. As the API is fundamentally
-different we won't cover it here.
-
-Method Calls
-~~~~~~~~~~~~
-
-In Django method calls work implicitly. With Jinja2 you have to specify that
-you want to call an object. Thus this Django code::
-
- {% for page in user.get_created_pages %}
- ...
- {% endfor %}
-
-will look like this in Jinja::
-
- {% for page in user.get_created_pages() %}
- ...
- {% endfor %}
-
-This allows you to pass variables to the function which is also used for macros
-which is not possible in Django.
-
-Conditions
-~~~~~~~~~~
-
-In Django you can use the following constructs to check for equality::
-
- {% ifequal foo "bar" %}
- ...
- {% else %}
- ...
- {% endifequal %}
-
-In Jinja2 you can use the normal if statement in combination with operators::
-
- {% if foo == 'bar' %}
- ...
- {% else %}
- ...
- {% endif %}
-
-You can also have multiple elif branches in your template::
-
- {% if something %}
- ...
- {% elif otherthing %}
- ...
- {% elif foothing %}
- ...
- {% else %}
- ...
- {% endif %}
-
-Filter Arguments
-~~~~~~~~~~~~~~~~
-
-Jinja2 provides more than one argument for filters. Also the syntax for
-argument passing is different. A template that looks like this in Django::
-
- {{ items|join:", " }}
-
-looks like this in Jinja2::
-
- {{ items|join(', ') }}
-
-In fact it's a bit more verbose but it allows different types of arguments -
-including variables - and more than one of them.
-
-Tests
-~~~~~
-
-In addition to filters there also are tests you can perform using the is
-operator. Here are some examples::
-
- {% if user.user_id is odd %}
- {{ user.username|e }} is odd
- {% else %}
- hmm. {{ user.username|e }} looks pretty normal
- {% endif %}
-
-Loops
-~~~~~
-
-For loops work very similar to Django, the only incompatibility is that in
-Jinja2 the special variable for the loop context is called `loop` and not
-`forloop` like in Django.
-
-Cycle
-~~~~~
-
-The ``{% cycle %}`` tag does not exist in Jinja because of it's implicit
-nature. However you can achieve mostly the same by using the `cycle`
-method on a loop object.
-
-The following Django template::
-
- {% for user in users %}
- <li class="{% cycle 'odd' 'even' %}">{{ user }}</li>
- {% endfor %}
-
-Would look like this in Jinja::
-
- {% for user in users %}
- <li class="{{ loop.cycle('odd', 'even') }}">{{ user }}</li>
- {% endfor %}
-
-There is no equivalent of ``{% cycle ... as variable %}``.
-
-
-Mako
-----
-
-.. highlight:: html+mako
-
-If you have used Mako so far and want to switch to Jinja2 you can configure
-Jinja2 to look more like Mako:
-
-.. sourcecode:: python
-
- env = Environment('<%', '%>', '${', '}', '%')
-
-Once the environment is configure like that Jinja2 should be able to interpret
-a small subset of Mako templates. Jinja2 does not support embedded Python code
-so you would have to move that out of the template. The syntax for defs (in
-Jinja2 defs are called macros) and template inheritance is different too. The
-following Mako template::
-
- <%inherit file="layout.html" />
- <%def name="title()">Page Title</%def>
- <ul>
- % for item in list:
- <li>${item}</li>
- % endfor
- </ul>
-
-Looks like this in Jinja2 with the above configuration::
-
- <% extends "layout.html" %>
- <% block title %>Page Title<% endblock %>
- <% block body %>
- <ul>
- % for item in list:
- <li>${item}</li>
- % endfor
- </ul>
- <% endblock %>
diff --git a/slider-agent/src/main/python/jinja2/docs/templates.rst b/slider-agent/src/main/python/jinja2/docs/templates.rst
deleted file mode 100644
index 4a1f6ff..0000000
--- a/slider-agent/src/main/python/jinja2/docs/templates.rst
+++ /dev/null
@@ -1,1365 +0,0 @@
-Template Designer Documentation
-===============================
-
-.. highlight:: html+jinja
-
-This document describes the syntax and semantics of the template engine and
-will be most useful as reference to those creating Jinja templates. As the
-template engine is very flexible the configuration from the application might
-be slightly different from here in terms of delimiters and behavior of
-undefined values.
-
-
-Synopsis
---------
-
-A template is simply a text file. It can generate any text-based format
-(HTML, XML, CSV, LaTeX, etc.). It doesn't have a specific extension,
-``.html`` or ``.xml`` are just fine.
-
-A template contains **variables** or **expressions**, which get replaced with
-values when the template is evaluated, and tags, which control the logic of
-the template. The template syntax is heavily inspired by Django and Python.
-
-Below is a minimal template that illustrates a few basics. We will cover
-the details later in that document::
-
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
- <html lang="en">
- <head>
- <title>My Webpage</title>
- </head>
- <body>
- <ul id="navigation">
- {% for item in navigation %}
- <li><a href="{{ item.href }}">{{ item.caption }}</a></li>
- {% endfor %}
- </ul>
-
- <h1>My Webpage</h1>
- {{ a_variable }}
- </body>
- </html>
-
-This covers the default settings. The application developer might have
-changed the syntax from ``{% foo %}`` to ``<% foo %>`` or something similar.
-
-There are two kinds of delimiers. ``{% ... %}`` and ``{{ ... }}``. The first
-one is used to execute statements such as for-loops or assign values, the
-latter prints the result of the expression to the template.
-
-.. _variables:
-
-Variables
----------
-
-The application passes variables to the templates you can mess around in the
-template. Variables may have attributes or elements on them you can access
-too. How a variable looks like, heavily depends on the application providing
-those.
-
-You can use a dot (``.``) to access attributes of a variable, alternative the
-so-called "subscript" syntax (``[]``) can be used. The following lines do
-the same::
-
- {{ foo.bar }}
- {{ foo['bar'] }}
-
-It's important to know that the curly braces are *not* part of the variable
-but the print statement. If you access variables inside tags don't put the
-braces around.
-
-If a variable or attribute does not exist you will get back an undefined
-value. What you can do with that kind of value depends on the application
-configuration, the default behavior is that it evaluates to an empty string
-if printed and that you can iterate over it, but every other operation fails.
-
-.. _notes-on-subscriptions:
-
-.. admonition:: Implementation
-
- For convenience sake ``foo.bar`` in Jinja2 does the following things on
- the Python layer:
-
- - check if there is an attribute called `bar` on `foo`.
- - if there is not, check if there is an item ``'bar'`` in `foo`.
- - if there is not, return an undefined object.
-
- ``foo['bar']`` on the other hand works mostly the same with the a small
- difference in the order:
-
- - check if there is an item ``'bar'`` in `foo`.
- - if there is not, check if there is an attribute called `bar` on `foo`.
- - if there is not, return an undefined object.
-
- This is important if an object has an item or attribute with the same
- name. Additionally there is the :func:`attr` filter that just looks up
- attributes.
-
-.. _filters:
-
-Filters
--------
-
-Variables can by modified by **filters**. Filters are separated from the
-variable by a pipe symbol (``|``) and may have optional arguments in
-parentheses. Multiple filters can be chained. The output of one filter is
-applied to the next.
-
-``{{ name|striptags|title }}`` for example will remove all HTML Tags from the
-`name` and title-cases it. Filters that accept arguments have parentheses
-around the arguments, like a function call. This example will join a list
-by commas: ``{{ list|join(', ') }}``.
-
-The :ref:`builtin-filters` below describes all the builtin filters.
-
-.. _tests:
-
-Tests
------
-
-Beside filters there are also so called "tests" available. Tests can be used
-to test a variable against a common expression. To test a variable or
-expression you add `is` plus the name of the test after the variable. For
-example to find out if a variable is defined you can do ``name is defined``
-which will then return true or false depending on if `name` is defined.
-
-Tests can accept arguments too. If the test only takes one argument you can
-leave out the parentheses to group them. For example the following two
-expressions do the same::
-
- {% if loop.index is divisibleby 3 %}
- {% if loop.index is divisibleby(3) %}
-
-The :ref:`builtin-tests` below describes all the builtin tests.
-
-
-Comments
---------
-
-To comment-out part of a line in a template, use the comment syntax which is
-by default set to ``{# ... #}``. This is useful to comment out parts of the
-template for debugging or to add information for other template designers or
-yourself::
-
- {# note: disabled template because we no longer use this
- {% for user in users %}
- ...
- {% endfor %}
- #}
-
-
-Whitespace Control
-------------------
-
-In the default configuration whitespace is not further modified by the
-template engine, so each whitespace (spaces, tabs, newlines etc.) is returned
-unchanged. If the application configures Jinja to `trim_blocks` the first
-newline after a a template tag is removed automatically (like in PHP).
-
-But you can also strip whitespace in templates by hand. If you put an minus
-sign (``-``) to the start or end of an block (for example a for tag), a
-comment or variable expression you can remove the whitespaces after or before
-that block::
-
- {% for item in seq -%}
- {{ item }}
- {%- endfor %}
-
-This will yield all elements without whitespace between them. If `seq` was
-a list of numbers from ``1`` to ``9`` the output would be ``123456789``.
-
-If :ref:`line-statements` are enabled they strip leading whitespace
-automatically up to the beginning of the line.
-
-.. admonition:: Note
-
- You must not use a whitespace between the tag and the minus sign.
-
- **valid**::
-
- {%- if foo -%}...{% endif %}
-
- **invalid**::
-
- {% - if foo - %}...{% endif %}
-
-
-Escaping
---------
-
-It is sometimes desirable or even necessary to have Jinja ignore parts it
-would otherwise handle as variables or blocks. For example if the default
-syntax is used and you want to use ``{{`` as raw string in the template and
-not start a variable you have to use a trick.
-
-The easiest way is to output the variable delimiter (``{{``) by using a
-variable expression::
-
- {{ '{{' }}
-
-For bigger sections it makes sense to mark a block `raw`. For example to
-put Jinja syntax as example into a template you can use this snippet::
-
- {% raw %}
- <ul>
- {% for item in seq %}
- <li>{{ item }}</li>
- {% endfor %}
- </ul>
- {% endraw %}
-
-
-.. _line-statements:
-
-Line Statements
----------------
-
-If line statements are enabled by the application it's possible to mark a
-line as a statement. For example if the line statement prefix is configured
-to ``#`` the following two examples are equivalent::
-
- <ul>
- # for item in seq
- <li>{{ item }}</li>
- # endfor
- </ul>
-
- <ul>
- {% for item in seq %}
- <li>{{ item }}</li>
- {% endfor %}
- </ul>
-
-The line statement prefix can appear anywhere on the line as long as no text
-precedes it. For better readability statements that start a block (such as
-`for`, `if`, `elif` etc.) may end with a colon::
-
- # for item in seq:
- ...
- # endfor
-
-
-.. admonition:: Note
-
- Line statements can span multiple lines if there are open parentheses,
- braces or brackets::
-
- <ul>
- # for href, caption in [('index.html', 'Index'),
- ('about.html', 'About')]:
- <li><a href="{{ href }}">{{ caption }}</a></li>
- # endfor
- </ul>
-
-Since Jinja 2.2 line-based comments are available as well. For example if
-the line-comment prefix is configured to be ``##`` everything from ``##`` to
-the end of the line is ignored (excluding the newline sign)::
-
- # for item in seq:
- <li>{{ item }}</li> ## this comment is ignored
- # endfor
-
-
-.. _template-inheritance:
-
-Template Inheritance
---------------------
-
-The most powerful part of Jinja is template inheritance. Template inheritance
-allows you to build a base "skeleton" template that contains all the common
-elements of your site and defines **blocks** that child templates can override.
-
-Sounds complicated but is very basic. It's easiest to understand it by starting
-with an example.
-
-
-Base Template
-~~~~~~~~~~~~~
-
-This template, which we'll call ``base.html``, defines a simple HTML skeleton
-document that you might use for a simple two-column page. It's the job of
-"child" templates to fill the empty blocks with content::
-
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
- <html lang="en">
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head>
- {% block head %}
- <link rel="stylesheet" href="style.css" />
- <title>{% block title %}{% endblock %} - My Webpage</title>
- {% endblock %}
- </head>
- <body>
- <div id="content">{% block content %}{% endblock %}</div>
- <div id="footer">
- {% block footer %}
- © Copyright 2008 by <a href="http://domain.invalid/">you</a>.
- {% endblock %}
- </div>
- </body>
-
-In this example, the ``{% block %}`` tags define four blocks that child templates
-can fill in. All the `block` tag does is to tell the template engine that a
-child template may override those portions of the template.
-
-Child Template
-~~~~~~~~~~~~~~
-
-A child template might look like this::
-
- {% extends "base.html" %}
- {% block title %}Index{% endblock %}
- {% block head %}
- {{ super() }}
- <style type="text/css">
- .important { color: #336699; }
- </style>
- {% endblock %}
- {% block content %}
- <h1>Index</h1>
- <p class="important">
- Welcome on my awesome homepage.
- </p>
- {% endblock %}
-
-The ``{% extends %}`` tag is the key here. It tells the template engine that
-this template "extends" another template. When the template system evaluates
-this template, first it locates the parent. The extends tag should be the
-first tag in the template. Everything before it is printed out normally and
-may cause confusion. For details about this behavior and how to take
-advantage of it, see :ref:`null-master-fallback`.
-
-The filename of the template depends on the template loader. For example the
-:class:`FileSystemLoader` allows you to access other templates by giving the
-filename. You can access templates in subdirectories with an slash::
-
- {% extends "layout/default.html" %}
-
-But this behavior can depend on the application embedding Jinja. Note that
-since the child template doesn't define the ``footer`` block, the value from
-the parent template is used instead.
-
-You can't define multiple ``{% block %}`` tags with the same name in the
-same template. This limitation exists because a block tag works in "both"
-directions. That is, a block tag doesn't just provide a hole to fill - it
-also defines the content that fills the hole in the *parent*. If there
-were two similarly-named ``{% block %}`` tags in a template, that template's
-parent wouldn't know which one of the blocks' content to use.
-
-If you want to print a block multiple times you can however use the special
-`self` variable and call the block with that name::
-
- <title>{% block title %}{% endblock %}</title>
- <h1>{{ self.title() }}</h1>
- {% block body %}{% endblock %}
-
-
-Super Blocks
-~~~~~~~~~~~~
-
-It's possible to render the contents of the parent block by calling `super`.
-This gives back the results of the parent block::
-
- {% block sidebar %}
- <h3>Table Of Contents</h3>
- ...
- {{ super() }}
- {% endblock %}
-
-
-Named Block End-Tags
-~~~~~~~~~~~~~~~~~~~~
-
-Jinja2 allows you to put the name of the block after the end tag for better
-readability::
-
- {% block sidebar %}
- {% block inner_sidebar %}
- ...
- {% endblock inner_sidebar %}
- {% endblock sidebar %}
-
-However the name after the `endblock` word must match the block name.
-
-
-Block Nesting and Scope
-~~~~~~~~~~~~~~~~~~~~~~~
-
-Blocks can be nested for more complex layouts. However per default blocks
-may not access variables from outer scopes::
-
- {% for item in seq %}
- <li>{% block loop_item %}{{ item }}{% endblock %}</li>
- {% endfor %}
-
-This example would output empty ``<li>`` items because `item` is unavailable
-inside the block. The reason for this is that if the block is replaced by
-a child template a variable would appear that was not defined in the block or
-passed to the context.
-
-Starting with Jinja 2.2 you can explicitly specify that variables are
-available in a block by setting the block to "scoped" by adding the `scoped`
-modifier to a block declaration::
-
- {% for item in seq %}
- <li>{% block loop_item scoped %}{{ item }}{% endblock %}</li>
- {% endfor %}
-
-When overriding a block the `scoped` modifier does not have to be provided.
-
-
-Template Objects
-~~~~~~~~~~~~~~~~
-
-.. versionchanged:: 2.4
-
-If a template object was passed to the template context you can
-extend from that object as well. Assuming the calling code passes
-a layout template as `layout_template` to the environment, this
-code works::
-
- {% extends layout_template %}
-
-Previously the `layout_template` variable had to be a string with
-the layout template's filename for this to work.
-
-
-HTML Escaping
--------------
-
-When generating HTML from templates, there's always a risk that a variable will
-include characters that affect the resulting HTML. There are two approaches:
-manually escaping each variable or automatically escaping everything by default.
-
-Jinja supports both, but what is used depends on the application configuration.
-The default configuaration is no automatic escaping for various reasons:
-
-- escaping everything except of safe values will also mean that Jinja is
- escaping variables known to not include HTML such as numbers which is
- a huge performance hit.
-
-- The information about the safety of a variable is very fragile. It could
- happen that by coercing safe and unsafe values the return value is double
- escaped HTML.
-
-Working with Manual Escaping
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-If manual escaping is enabled it's **your** responsibility to escape
-variables if needed. What to escape? If you have a variable that *may*
-include any of the following chars (``>``, ``<``, ``&``, or ``"``) you
-**have to** escape it unless the variable contains well-formed and trusted
-HTML. Escaping works by piping the variable through the ``|e`` filter:
-``{{ user.username|e }}``.
-
-Working with Automatic Escaping
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-When automatic escaping is enabled everything is escaped by default except
-for values explicitly marked as safe. Those can either be marked by the
-application or in the template by using the `|safe` filter. The main
-problem with this approach is that Python itself doesn't have the concept
-of tainted values so the information if a value is safe or unsafe can get
-lost. If the information is lost escaping will take place which means that
-you could end up with double escaped contents.
-
-Double escaping is easy to avoid however, just rely on the tools Jinja2
-provides and don't use builtin Python constructs such as the string modulo
-operator.
-
-Functions returning template data (macros, `super`, `self.BLOCKNAME`) return
-safe markup always.
-
-String literals in templates with automatic escaping are considered unsafe
-too. The reason for this is that the safe string is an extension to Python
-and not every library will work properly with it.
-
-
-List of Control Structures
---------------------------
-
-A control structure refers to all those things that control the flow of a
-program - conditionals (i.e. if/elif/else), for-loops, as well as things like
-macros and blocks. Control structures appear inside ``{% ... %}`` blocks
-in the default syntax.
-
-For
-~~~
-
-Loop over each item in a sequence. For example, to display a list of users
-provided in a variable called `users`::
-
- <h1>Members</h1>
- <ul>
- {% for user in users %}
- <li>{{ user.username|e }}</li>
- {% endfor %}
- </ul>
-
-Inside of a for loop block you can access some special variables:
-
-+-----------------------+---------------------------------------------------+
-| Variable | Description |
-+=======================+===================================================+
-| `loop.index` | The current iteration of the loop. (1 indexed) |
-+-----------------------+---------------------------------------------------+
-| `loop.index0` | The current iteration of the loop. (0 indexed) |
-+-----------------------+---------------------------------------------------+
-| `loop.revindex` | The number of iterations from the end of the loop |
-| | (1 indexed) |
-+-----------------------+---------------------------------------------------+
-| `loop.revindex0` | The number of iterations from the end of the loop |
-| | (0 indexed) |
-+-----------------------+---------------------------------------------------+
-| `loop.first` | True if first iteration. |
-+-----------------------+---------------------------------------------------+
-| `loop.last` | True if last iteration. |
-+-----------------------+---------------------------------------------------+
-| `loop.length` | The number of items in the sequence. |
-+-----------------------+---------------------------------------------------+
-| `loop.cycle` | A helper function to cycle between a list of |
-| | sequences. See the explanation below. |
-+-----------------------+---------------------------------------------------+
-
-Within a for-loop, it's possible to cycle among a list of strings/variables
-each time through the loop by using the special `loop.cycle` helper::
-
- {% for row in rows %}
- <li class="{{ loop.cycle('odd', 'even') }}">{{ row }}</li>
- {% endfor %}
-
-With Jinja 2.1 an extra `cycle` helper exists that allows loop-unbound
-cycling. For more information have a look at the :ref:`builtin-globals`.
-
-.. _loop-filtering:
-
-Unlike in Python it's not possible to `break` or `continue` in a loop. You
-can however filter the sequence during iteration which allows you to skip
-items. The following example skips all the users which are hidden::
-
- {% for user in users if not user.hidden %}
- <li>{{ user.username|e }}</li>
- {% endfor %}
-
-The advantage is that the special `loop` variable will count correctly thus
-not counting the users not iterated over.
-
-If no iteration took place because the sequence was empty or the filtering
-removed all the items from the sequence you can render a replacement block
-by using `else`::
-
- <ul>
- {% for user in users %}
- <li>{{ user.username|e }}</li>
- {% else %}
- <li><em>no users found</em></li>
- {% endfor %}
- </ul>
-
-It is also possible to use loops recursively. This is useful if you are
-dealing with recursive data such as sitemaps. To use loops recursively you
-basically have to add the `recursive` modifier to the loop definition and
-call the `loop` variable with the new iterable where you want to recurse.
-
-The following example implements a sitemap with recursive loops::
-
- <ul class="sitemap">
- {%- for item in sitemap recursive %}
- <li><a href="{{ item.href|e }}">{{ item.title }}</a>
- {%- if item.children -%}
- <ul class="submenu">{{ loop(item.children) }}</ul>
- {%- endif %}</li>
- {%- endfor %}
- </ul>
-
-
-If
-~~
-
-The `if` statement in Jinja is comparable with the if statements of Python.
-In the simplest form you can use it to test if a variable is defined, not
-empty or not false::
-
- {% if users %}
- <ul>
- {% for user in users %}
- <li>{{ user.username|e }}</li>
- {% endfor %}
- </ul>
- {% endif %}
-
-For multiple branches `elif` and `else` can be used like in Python. You can
-use more complex :ref:`expressions` there too::
-
- {% if kenny.sick %}
- Kenny is sick.
- {% elif kenny.dead %}
- You killed Kenny! You bastard!!!
- {% else %}
- Kenny looks okay --- so far
- {% endif %}
-
-If can also be used as :ref:`inline expression <if-expression>` and for
-:ref:`loop filtering <loop-filtering>`.
-
-
-Macros
-~~~~~~
-
-Macros are comparable with functions in regular programming languages. They
-are useful to put often used idioms into reusable functions to not repeat
-yourself.
-
-Here a small example of a macro that renders a form element::
-
- {% macro input(name, value='', type='text', size=20) -%}
- <input type="{{ type }}" name="{{ name }}" value="{{
- value|e }}" size="{{ size }}">
- {%- endmacro %}
-
-The macro can then be called like a function in the namespace::
-
- <p>{{ input('username') }}</p>
- <p>{{ input('password', type='password') }}</p>
-
-If the macro was defined in a different template you have to
-:ref:`import <import>` it first.
-
-Inside macros you have access to three special variables:
-
-`varargs`
- If more positional arguments are passed to the macro than accepted by the
- macro they end up in the special `varargs` variable as list of values.
-
-`kwargs`
- Like `varargs` but for keyword arguments. All unconsumed keyword
- arguments are stored in this special variable.
-
-`caller`
- If the macro was called from a :ref:`call<call>` tag the caller is stored
- in this variable as macro which can be called.
-
-Macros also expose some of their internal details. The following attributes
-are available on a macro object:
-
-`name`
- The name of the macro. ``{{ input.name }}`` will print ``input``.
-
-`arguments`
- A tuple of the names of arguments the macro accepts.
-
-`defaults`
- A tuple of default values.
-
-`catch_kwargs`
- This is `true` if the macro accepts extra keyword arguments (ie: accesses
- the special `kwargs` variable).
-
-`catch_varargs`
- This is `true` if the macro accepts extra positional arguments (ie:
- accesses the special `varargs` variable).
-
-`caller`
- This is `true` if the macro accesses the special `caller` variable and may
- be called from a :ref:`call<call>` tag.
-
-If a macro name starts with an underscore it's not exported and can't
-be imported.
-
-
-.. _call:
-
-Call
-~~~~
-
-In some cases it can be useful to pass a macro to another macro. For this
-purpose you can use the special `call` block. The following example shows
-a macro that takes advantage of the call functionality and how it can be
-used::
-
- {% macro render_dialog(title, class='dialog') -%}
- <div class="{{ class }}">
- <h2>{{ title }}</h2>
- <div class="contents">
- {{ caller() }}
- </div>
- </div>
- {%- endmacro %}
-
- {% call render_dialog('Hello World') %}
- This is a simple dialog rendered by using a macro and
- a call block.
- {% endcall %}
-
-It's also possible to pass arguments back to the call block. This makes it
-useful as replacement for loops. Generally speaking a call block works
-exactly like an macro, just that it doesn't have a name.
-
-Here an example of how a call block can be used with arguments::
-
- {% macro dump_users(users) -%}
- <ul>
- {%- for user in users %}
- <li><p>{{ user.username|e }}</p>{{ caller(user) }}</li>
- {%- endfor %}
- </ul>
- {%- endmacro %}
-
- {% call(user) dump_users(list_of_user) %}
- <dl>
- <dl>Realname</dl>
- <dd>{{ user.realname|e }}</dd>
- <dl>Description</dl>
- <dd>{{ user.description }}</dd>
- </dl>
- {% endcall %}
-
-
-Filters
-~~~~~~~
-
-Filter sections allow you to apply regular Jinja2 filters on a block of
-template data. Just wrap the code in the special `filter` section::
-
- {% filter upper %}
- This text becomes uppercase
- {% endfilter %}
-
-
-Assignments
-~~~~~~~~~~~
-
-Inside code blocks you can also assign values to variables. Assignments at
-top level (outside of blocks, macros or loops) are exported from the template
-like top level macros and can be imported by other templates.
-
-Assignments use the `set` tag and can have multiple targets::
-
- {% set navigation = [('index.html', 'Index'), ('about.html', 'About')] %}
- {% set key, value = call_something() %}
-
-
-Extends
-~~~~~~~
-
-The `extends` tag can be used to extend a template from another one. You
-can have multiple of them in a file but only one of them may be executed
-at the time. See the section about :ref:`template-inheritance` above.
-
-
-Block
-~~~~~
-
-Blocks are used for inheritance and act as placeholders and replacements
-at the same time. They are documented in detail as part of the section
-about :ref:`template-inheritance`.
-
-
-Include
-~~~~~~~
-
-The `include` statement is useful to include a template and return the
-rendered contents of that file into the current namespace::
-
- {% include 'header.html' %}
- Body
- {% include 'footer.html' %}
-
-Included templates have access to the variables of the active context by
-default. For more details about context behavior of imports and includes
-see :ref:`import-visibility`.
-
-From Jinja 2.2 onwards you can mark an include with ``ignore missing`` in
-which case Jinja will ignore the statement if the template to be ignored
-does not exist. When combined with ``with`` or ``without context`` it has
-to be placed *before* the context visibility statement. Here some valid
-examples::
-
- {% include "sidebar.html" ignore missing %}
- {% include "sidebar.html" ignore missing with context %}
- {% include "sidebar.html" ignore missing without context %}
-
-.. versionadded:: 2.2
-
-You can also provide a list of templates that are checked for existence
-before inclusion. The first template that exists will be included. If
-`ignore missing` is given, it will fall back to rendering nothing if
-none of the templates exist, otherwise it will raise an exception.
-
-Example::
-
- {% include ['page_detailed.html', 'page.html'] %}
- {% include ['special_sidebar.html', 'sidebar.html'] ignore missing %}
-
-.. versionchanged:: 2.4
- If a template object was passed to the template context you can
- include that object using `include`.
-
-.. _import:
-
-Import
-~~~~~~
-
-Jinja2 supports putting often used code into macros. These macros can go into
-different templates and get imported from there. This works similar to the
-import statements in Python. It's important to know that imports are cached
-and imported templates don't have access to the current template variables,
-just the globals by defualt. For more details about context behavior of
-imports and includes see :ref:`import-visibility`.
-
-There are two ways to import templates. You can import the complete template
-into a variable or request specific macros / exported variables from it.
-
-Imagine we have a helper module that renders forms (called `forms.html`)::
-
- {% macro input(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 %}
-
-The easiest and most flexible is importing the whole module into a variable.
-That way you can access the attributes::
-
- {% import 'forms.html' as forms %}
- <dl>
- <dt>Username</dt>
- <dd>{{ forms.input('username') }}</dd>
- <dt>Password</dt>
- <dd>{{ forms.input('password', type='password') }}</dd>
- </dl>
- <p>{{ forms.textarea('comment') }}</p>
-
-
-Alternatively you can import names from the template into the current
-namespace::
-
- {% from 'forms.html' import input as input_field, textarea %}
- <dl>
- <dt>Username</dt>
- <dd>{{ input_field('username') }}</dd>
- <dt>Password</dt>
- <dd>{{ input_field('password', type='password') }}</dd>
- </dl>
- <p>{{ textarea('comment') }}</p>
-
-Macros and variables starting with one ore more underscores are private and
-cannot be imported.
-
-.. versionchanged:: 2.4
- If a template object was passed to the template context you can
- import from that object.
-
-
-.. _import-visibility:
-
-Import Context Behavior
------------------------
-
-Per default included templates are passed the current context and imported
-templates not. The reason for this is that imports unlike includes are
-cached as imports are often used just as a module that holds macros.
-
-This however can be changed of course explicitly. By adding `with context`
-or `without context` to the import/include directive the current context
-can be passed to the template and caching is disabled automatically.
-
-Here two examples::
-
- {% from 'forms.html' import input with context %}
- {% include 'header.html' without context %}
-
-.. admonition:: Note
-
- In Jinja 2.0 the context that was passed to the included template
- did not include variables defined in the template. As a matter of
- fact this did not work::
-
- {% for box in boxes %}
- {% include "render_box.html" %}
- {% endfor %}
-
- The included template ``render_box.html`` is not able to access
- `box` in Jinja 2.0, but in Jinja 2.1.
-
-
-.. _expressions:
-
-Expressions
------------
-
-Jinja allows basic expressions everywhere. These work very similar to regular
-Python and even if you're not working with Python you should feel comfortable
-with it.
-
-Literals
-~~~~~~~~
-
-The simplest form of expressions are literals. Literals are representations
-for Python objects such as strings and numbers. The following literals exist:
-
-"Hello World":
- Everything between two double or single quotes is a string. They are
- useful whenever you need a string in the template (for example as
- arguments to function calls, filters or just to extend or include a
- template).
-
-42 / 42.23:
- Integers and floating point numbers are created by just writing the
- number down. If a dot is present the number is a float, otherwise an
- integer. Keep in mind that for Python ``42`` and ``42.0`` is something
- different.
-
-['list', 'of', 'objects']:
- Everything between two brackets is a list. Lists are useful to store
- sequential data in or to iterate over them. For example you can easily
- create a list of links using lists and tuples with a for loop::
-
- <ul>
- {% for href, caption in [('index.html', 'Index'), ('about.html', 'About'),
- ('downloads.html', 'Downloads')] %}
- <li><a href="{{ href }}">{{ caption }}</a></li>
- {% endfor %}
- </ul>
-
-('tuple', 'of', 'values'):
- Tuples are like lists, just that you can't modify them. If the tuple
- only has one item you have to end it with a comma. Tuples are usually
- used to represent items of two or more elements. See the example above
- for more details.
-
-{'dict': 'of', 'key': 'and', 'value': 'pairs'}:
- A dict in Python is a structure that combines keys and values. Keys must
- be unique and always have exactly one value. Dicts are rarely used in
- templates, they are useful in some rare cases such as the :func:`xmlattr`
- filter.
-
-true / false:
- true is always true and false is always false.
-
-.. admonition:: Note
-
- The special constants `true`, `false` and `none` are indeed lowercase.
- Because that caused confusion in the past, when writing `True` expands
- to an undefined variable that is considered false, all three of them can
- be written in title case too (`True`, `False`, and `None`). However for
- consistency (all Jinja identifiers are lowercase) you should use the
- lowercase versions.
-
-Math
-~~~~
-
-Jinja allows you to calculate with values. This is rarely useful in templates
-but exists for completeness' sake. The following operators are supported:
-
-\+
- Adds two objects together. Usually the objects are numbers but if both are
- strings or lists you can concatenate them this way. This however is not
- the preferred way to concatenate strings! For string concatenation have
- a look at the ``~`` operator. ``{{ 1 + 1 }}`` is ``2``.
-
-\-
- Substract the second number from the first one. ``{{ 3 - 2 }}`` is ``1``.
-
-/
- Divide two numbers. The return value will be a floating point number.
- ``{{ 1 / 2 }}`` is ``{{ 0.5 }}``.
-
-//
- Divide two numbers and return the truncated integer result.
- ``{{ 20 / 7 }}`` is ``2``.
-
-%
- Calculate the remainder of an integer division. ``{{ 11 % 7 }}`` is ``4``.
-
-\*
- Multiply the left operand with the right one. ``{{ 2 * 2 }}`` would
- return ``4``. This can also be used to repeat a string multiple times.
- ``{{ '=' * 80 }}`` would print a bar of 80 equal signs.
-
-\**
- Raise the left operand to the power of the right operand. ``{{ 2**3 }}``
- would return ``8``.
-
-Comparisons
-~~~~~~~~~~~
-
-==
- Compares two objects for equality.
-
-!=
- Compares two objects for inequality.
-
->
- `true` if the left hand side is greater than the right hand side.
-
->=
- `true` if the left hand side is greater or equal to the right hand side.
-
-<
- `true` if the left hand side is lower than the right hand side.
-
-<=
- `true` if the left hand side is lower or equal to the right hand side.
-
-Logic
-~~~~~
-
-For `if` statements, `for` filtering or `if` expressions it can be useful to
-combine multiple expressions:
-
-and
- Return true if the left and the right operand is true.
-
-or
- Return true if the left or the right operand is true.
-
-not
- negate a statement (see below).
-
-(expr)
- group an expression.
-
-.. admonition:: Note
-
- The ``is`` and ``in`` operators support negation using an infix notation
- too: ``foo is not bar`` and ``foo not in bar`` instead of ``not foo is bar``
- and ``not foo in bar``. All other expressions require a prefix notation:
- ``not (foo and bar).``
-
-
-Other Operators
-~~~~~~~~~~~~~~~
-
-The following operators are very useful but don't fit into any of the other
-two categories:
-
-in
- Perform sequence / mapping containment test. Returns true if the left
- operand is contained in the right. ``{{ 1 in [1, 2, 3] }}`` would for
- example return true.
-
-is
- Performs a :ref:`test <tests>`.
-
-\|
- Applies a :ref:`filter <filters>`.
-
-~
- Converts all operands into strings and concatenates them.
- ``{{ "Hello " ~ name ~ "!" }}`` would return (assuming `name` is
- ``'John'``) ``Hello John!``.
-
-()
- Call a callable: ``{{ post.render() }}``. Inside of the parentheses you
- can use positional arguments and keyword arguments like in python:
- ``{{ post.render(user, full=true) }}``.
-
-. / []
- Get an attribute of an object. (See :ref:`variables`)
-
-
-.. _if-expression:
-
-If Expression
-~~~~~~~~~~~~~
-
-It is also possible to use inline `if` expressions. These are useful in some
-situations. For example you can use this to extend from one template if a
-variable is defined, otherwise from the default layout template::
-
- {% extends layout_template if layout_template is defined else 'master.html' %}
-
-The general syntax is ``<do something> if <something is true> else <do
-something else>``.
-
-The `else` part is optional. If not provided the else block implicitly
-evaluates into an undefined object::
-
- {{ '[%s]' % page.title if page.title }}
-
-
-.. _builtin-filters:
-
-List of Builtin Filters
------------------------
-
-.. jinjafilters::
-
-
-.. _builtin-tests:
-
-List of Builtin Tests
----------------------
-
-.. jinjatests::
-
-.. _builtin-globals:
-
-List of Global Functions
-------------------------
-
-The following functions are available in the global scope by default:
-
-.. function:: range([start,] stop[, step])
-
- Return a list containing an arithmetic progression of integers.
- range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.
- When step is given, it specifies the increment (or decrement).
- For example, range(4) returns [0, 1, 2, 3]. The end point is omitted!
- These are exactly the valid indices for a list of 4 elements.
-
- This is useful to repeat a template block multiple times for example
- to fill a list. Imagine you have 7 users in the list but you want to
- render three empty items to enforce a height with CSS::
-
- <ul>
- {% for user in users %}
- <li>{{ user.username }}</li>
- {% endfor %}
- {% for number in range(10 - users|count) %}
- <li class="empty"><span>...</span></li>
- {% endfor %}
- </ul>
-
-.. function:: lipsum(n=5, html=True, min=20, max=100)
-
- Generates some lorem ipsum for the template. Per default five paragraphs
- with HTML are generated each paragraph between 20 and 100 words. If html
- is disabled regular text is returned. This is useful to generate simple
- contents for layout testing.
-
-.. function:: dict(\**items)
-
- A convenient alternative to dict literals. ``{'foo': 'bar'}`` is the same
- as ``dict(foo='bar')``.
-
-.. class:: cycler(\*items)
-
- The cycler allows you to cycle among values similar to how `loop.cycle`
- works. Unlike `loop.cycle` however you can use this cycler outside of
- loops or over multiple loops.
-
- This is for example very useful if you want to show a list of folders and
- files, with the folders on top, but both in the same list with alternating
- row colors.
-
- The following example shows how `cycler` can be used::
-
- {% set row_class = cycler('odd', 'even') %}
- <ul class="browser">
- {% for folder in folders %}
- <li class="folder {{ row_class.next() }}">{{ folder|e }}</li>
- {% endfor %}
- {% for filename in files %}
- <li class="file {{ row_class.next() }}">{{ filename|e }}</li>
- {% endfor %}
- </ul>
-
- A cycler has the following attributes and methods:
-
- .. method:: reset()
-
- Resets the cycle to the first item.
-
- .. method:: next()
-
- Goes one item a head and returns the then current item.
-
- .. attribute:: current
-
- Returns the current item.
-
- **new in Jinja 2.1**
-
-.. class:: joiner(sep=', ')
-
- A tiny helper that can be use to "join" multiple sections. A joiner is
- passed a string and will return that string every time it's calld, except
- the first time in which situation it returns an empty string. You can
- use this to join things::
-
- {% set pipe = joiner("|") %}
- {% if categories %} {{ pipe() }}
- Categories: {{ categories|join(", ") }}
- {% endif %}
- {% if author %} {{ pipe() }}
- Author: {{ author() }}
- {% endif %}
- {% if can_edit %} {{ pipe() }}
- <a href="?action=edit">Edit</a>
- {% endif %}
-
- **new in Jinja 2.1**
-
-
-Extensions
-----------
-
-The following sections cover the built-in Jinja2 extensions that may be
-enabled by the application. The application could also provide further
-extensions not covered by this documentation. In that case there should
-be a separate document explaining the extensions.
-
-.. _i18n-in-templates:
-
-i18n
-~~~~
-
-If the i18n extension is enabled it's possible to mark parts in the template
-as translatable. To mark a section as translatable you can use `trans`::
-
- <p>{% trans %}Hello {{ user }}!{% endtrans %}</p>
-
-To translate a template expression --- say, using template filters or just
-accessing an attribute of an object --- you need to bind the expression to a
-name for use within the translation block::
-
- <p>{% trans user=user.username %}Hello {{ user }}!{% endtrans %}</p>
-
-If you need to bind more than one expression inside a `trans` tag, separate
-the pieces with a comma (``,``)::
-
- {% trans book_title=book.title, author=author.name %}
- This is {{ book_title }} by {{ author }}
- {% endtrans %}
-
-Inside trans tags no statements are allowed, only variable tags are.
-
-To pluralize, specify both the singular and plural forms with the `pluralize`
-tag, which appears between `trans` and `endtrans`::
-
- {% trans count=list|length %}
- There is {{ count }} {{ name }} object.
- {% pluralize %}
- There are {{ count }} {{ name }} objects.
- {% endtrans %}
-
-Per default the first variable in a block is used to determine the correct
-singular or plural form. If that doesn't work out you can specify the name
-which should be used for pluralizing by adding it as parameter to `pluralize`::
-
- {% trans ..., user_count=users|length %}...
- {% pluralize user_count %}...{% endtrans %}
-
-It's also possible to translate strings in expressions. For that purpose
-three functions exist:
-
-_ `gettext`: translate a single string
-- `ngettext`: translate a pluralizable string
-- `_`: alias for `gettext`
-
-For example you can print a translated string easily this way::
-
- {{ _('Hello World!') }}
-
-To use placeholders you can use the `format` filter::
-
- {{ _('Hello %(user)s!')|format(user=user.username) }}
-
-For multiple placeholders always use keyword arguments to `format` as other
-languages may not use the words in the same order.
-
-.. versionchanged:: 2.5
-
-If newstyle gettext calls are activated (:ref:`newstyle-gettext`), using
-placeholders is a lot easier:
-
-.. sourcecode:: html+jinja
-
- {{ gettext('Hello World!') }}
- {{ gettext('Hello %(name)s!', name='World') }}
- {{ ngettext('%(num)d apple', '%(num)d apples', apples|count) }}
-
-Note that the `ngettext` function's format string automatically recieves
-the count as `num` parameter additionally to the regular parameters.
-
-
-Expression Statement
-~~~~~~~~~~~~~~~~~~~~
-
-If the expression-statement extension is loaded a tag called `do` is available
-that works exactly like the regular variable expression (``{{ ... }}``) just
-that it doesn't print anything. This can be used to modify lists::
-
- {% do navigation.append('a string') %}
-
-
-Loop Controls
-~~~~~~~~~~~~~
-
-If the application enables the :ref:`loopcontrols-extension` it's possible to
-use `break` and `continue` in loops. When `break` is reached, the loop is
-terminated, if `continue` is eached the processing is stopped and continues
-with the next iteration.
-
-Here a loop that skips every second item::
-
- {% for user in users %}
- {%- if loop.index is even %}{% continue %}{% endif %}
- ...
- {% endfor %}
-
-Likewise a look that stops processing after the 10th iteration::
-
- {% for user in users %}
- {%- if loop.index >= 10 %}{% break %}{% endif %}
- {%- endfor %}
-
-
-With Statement
-~~~~~~~~~~~~~~
-
-.. versionadded:: 2.3
-
-If the application enables the :ref:`with-extension` it is possible to
-use the `with` keyword in templates. This makes it possible to create
-a new inner scope. Variables set within this scope are not visible
-outside of the scope.
-
-With in a nutshell::
-
- {% with %}
- {% set foo = 42 %}
- {{ foo }} foo is 42 here
- {% endwith %}
- foo is not visible here any longer
-
-Because it is common to set variables at the beginning of the scope
-you can do that within the with statement. The following two examples
-are equivalent::
-
- {% with foo = 42 %}
- {{ foo }}
- {% endwith %}
-
- {% with %}
- {% set foo = 42 %}
- {{ foo }}
- {% endwith %}
-
-.. _autoescape-overrides:
-
-Autoescape Extension
---------------------
-
-.. versionadded:: 2.4
-
-If the application enables the :ref:`autoescape-extension` one can
-activate and deactivate the autoescaping from within the templates.
-
-Example::
-
- {% autoescape true %}
- Autoescaping is active within this block
- {% endautoescape %}
-
- {% autoescape false %}
- Autoescaping is inactive within this block
- {% endautoescape %}
-
-After the `endautoescape` the behavior is reverted to what it was before.
diff --git a/slider-agent/src/main/python/jinja2/docs/tricks.rst b/slider-agent/src/main/python/jinja2/docs/tricks.rst
deleted file mode 100644
index 566575e..0000000
--- a/slider-agent/src/main/python/jinja2/docs/tricks.rst
+++ /dev/null
@@ -1,100 +0,0 @@
-Tips and Tricks
-===============
-
-.. highlight:: html+jinja
-
-This part of the documentation shows some tips and tricks for Jinja2
-templates.
-
-
-.. _null-master-fallback:
-
-Null-Master Fallback
---------------------
-
-Jinja2 supports dynamic inheritance and does not distinguish between parent
-and child template as long as no `extends` tag is visited. While this leads
-to the surprising behavior that everything before the first `extends` tag
-including whitespace is printed out instead of being igored, it can be used
-for a neat trick.
-
-Usually child templates extend from one template that adds a basic HTML
-skeleton. However it's possible put the `extends` tag into an `if` tag to
-only extend from the layout template if the `standalone` variable evaluates
-to false which it does per default if it's not defined. Additionally a very
-basic skeleton is added to the file so that if it's indeed rendered with
-`standalone` set to `True` a very basic HTML skeleton is added::
-
- {% if not standalone %}{% extends 'master.html' %}{% endif -%}
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <title>{% block title %}The Page Title{% endblock %}</title>
- <link rel="stylesheet" href="style.css" type="text/css">
- {% block body %}
- <p>This is the page body.</p>
- {% endblock %}
-
-
-Alternating Rows
-----------------
-
-If you want to have different styles for each row of a table or
-list you can use the `cycle` method on the `loop` object::
-
- <ul>
- {% for row in rows %}
- <li class="{{ loop.cycle('odd', 'even') }}">{{ row }}</li>
- {% endfor %}
- </ul>
-
-`cycle` can take an unlimited amount of strings. Each time this
-tag is encountered the next item from the list is rendered.
-
-
-Highlighting Active Menu Items
-------------------------------
-
-Often you want to have a navigation bar with an active navigation
-item. This is really simple to achieve. Because assignments outside
-of `block`\s in child templates are global and executed before the layout
-template is evaluated it's possible to define the active menu item in the
-child template::
-
- {% extends "layout.html" %}
- {% set active_page = "index" %}
-
-The layout template can then access `active_page`. Additionally it makes
-sense to defined a default for that variable::
-
- {% set navigation_bar = [
- ('/', 'index', 'Index'),
- ('/downloads/', 'downloads', 'Downloads'),
- ('/about/', 'about', 'About')
- ] -%}
- {% set active_page = active_page|default('index') -%}
- ...
- <ul id="navigation">
- {% for href, id, caption in navigation_bar %}
- <li{% if id == active_page %} class="active"{% endif
- %}><a href="{{ href|e }}">{{ caption|e }}</a>/li>
- {% endfor %}
- </ul>
- ...
-
-.. _accessing-the-parent-loop:
-
-Accessing the parent Loop
--------------------------
-
-The special `loop` variable always points to the innermost loop. If it's
-desired to have access to an outer loop it's possible to alias it::
-
- <table>
- {% for row in table %}
- <tr>
- {% set rowloop = loop %}
- {% for cell in row %}
- <td id="cell-{{ rowloop.index }}-{{ loop.index }}>{{ cell }}</td>
- {% endfor %}
- </tr>
- {% endfor %}
- </table>
diff --git a/slider-agent/src/main/python/jinja2/examples/basic/cycle.py b/slider-agent/src/main/python/jinja2/examples/basic/cycle.py
deleted file mode 100644
index 73dd632..0000000
--- a/slider-agent/src/main/python/jinja2/examples/basic/cycle.py
+++ /dev/null
@@ -1,13 +0,0 @@
-from jinja2 import Environment
-
-
-env = Environment(line_statement_prefix="#", variable_start_string="${", variable_end_string="}")
-
-
-print env.from_string("""\
-<ul>
-# for item in range(10)
- <li class="${loop.cycle('odd', 'even')}">${item}</li>
-# endfor
-</ul>\
-""").render()
diff --git a/slider-agent/src/main/python/jinja2/examples/basic/debugger.py b/slider-agent/src/main/python/jinja2/examples/basic/debugger.py
deleted file mode 100644
index 4291ff7..0000000
--- a/slider-agent/src/main/python/jinja2/examples/basic/debugger.py
+++ /dev/null
@@ -1,7 +0,0 @@
-from jinja2 import Environment
-from jinja2.loaders import FileSystemLoader
-
-env = Environment(loader=FileSystemLoader('templates'))
-
-tmpl = env.get_template('broken.html')
-print tmpl.render(seq=[3, 2, 4, 5, 3, 2, 0, 2, 1])
diff --git a/slider-agent/src/main/python/jinja2/examples/basic/inheritance.py b/slider-agent/src/main/python/jinja2/examples/basic/inheritance.py
deleted file mode 100644
index aa687c8..0000000
--- a/slider-agent/src/main/python/jinja2/examples/basic/inheritance.py
+++ /dev/null
@@ -1,12 +0,0 @@
-from jinja2 import Environment
-from jinja2.loaders import DictLoader
-
-
-env = Environment(loader=DictLoader({
-'a': '''[A[{% block body %}{% endblock %}]]''',
-'b': '''{% extends 'a' %}{% block body %}[B]{% endblock %}''',
-'c': '''{% extends 'b' %}{% block body %}###{{ super() }}###{% endblock %}'''
-}))
-
-
-print env.get_template('c').render()
diff --git a/slider-agent/src/main/python/jinja2/examples/basic/templates/broken.html b/slider-agent/src/main/python/jinja2/examples/basic/templates/broken.html
deleted file mode 100644
index 294d5c9..0000000
--- a/slider-agent/src/main/python/jinja2/examples/basic/templates/broken.html
+++ /dev/null
@@ -1,6 +0,0 @@
-{% from 'subbroken.html' import may_break %}
-<ul>
-{% for item in seq %}
- <li>{{ may_break(item) }}</li>
-{% endfor %}
-</ul>
diff --git a/slider-agent/src/main/python/jinja2/examples/basic/templates/subbroken.html b/slider-agent/src/main/python/jinja2/examples/basic/templates/subbroken.html
deleted file mode 100644
index 245eb7e..0000000
--- a/slider-agent/src/main/python/jinja2/examples/basic/templates/subbroken.html
+++ /dev/null
@@ -1,3 +0,0 @@
-{% macro may_break(item) -%}
- [{{ item / 0 }}]
-{%- endmacro %}
diff --git a/slider-agent/src/main/python/jinja2/examples/basic/test.py b/slider-agent/src/main/python/jinja2/examples/basic/test.py
deleted file mode 100644
index b62c84f..0000000
--- a/slider-agent/src/main/python/jinja2/examples/basic/test.py
+++ /dev/null
@@ -1,27 +0,0 @@
-from jinja2 import Environment
-from jinja2.loaders import DictLoader
-
-env = Environment(loader=DictLoader({
-'child.html': u'''\
-{% extends master_layout or 'master.html' %}
-{% include helpers = 'helpers.html' %}
-{% macro get_the_answer() %}42{% endmacro %}
-{% title = 'Hello World' %}
-{% block body %}
- {{ get_the_answer() }}
- {{ helpers.conspirate() }}
-{% endblock %}
-''',
-'master.html': u'''\
-<!doctype html>
-<title>{{ title }}</title>
-{% block body %}{% endblock %}
-''',
-'helpers.html': u'''\
-{% macro conspirate() %}23{% endmacro %}
-'''
-}))
-
-
-tmpl = env.get_template("child.html")
-print tmpl.render()
diff --git a/slider-agent/src/main/python/jinja2/examples/basic/test_filter_and_linestatements.py b/slider-agent/src/main/python/jinja2/examples/basic/test_filter_and_linestatements.py
deleted file mode 100644
index c9e8f95..0000000
--- a/slider-agent/src/main/python/jinja2/examples/basic/test_filter_and_linestatements.py
+++ /dev/null
@@ -1,25 +0,0 @@
-from jinja2 import Environment
-
-
-env = Environment(line_statement_prefix='%', variable_start_string="${", variable_end_string="}")
-tmpl = env.from_string("""\
-% macro foo()
- ${caller(42)}
-% endmacro
-<ul>
-% for item in seq
- <li>${item}</li>
-% endfor
-</ul>
-% call(var) foo()
- [${var}]
-% endcall
-% filter escape
- <hello world>
- % for item in [1, 2, 3]
- - ${item}
- % endfor
-% endfilter
-""")
-
-print tmpl.render(seq=range(10))
diff --git a/slider-agent/src/main/python/jinja2/examples/basic/test_loop_filter.py b/slider-agent/src/main/python/jinja2/examples/basic/test_loop_filter.py
deleted file mode 100644
index 49c2efc..0000000
--- a/slider-agent/src/main/python/jinja2/examples/basic/test_loop_filter.py
+++ /dev/null
@@ -1,12 +0,0 @@
-from jinja2 import Environment
-
-tmpl = Environment().from_string("""\
-<ul>
-{%- for item in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] if item % 2 == 0 %}
- <li>{{ loop.index }} / {{ loop.length }}: {{ item }}</li>
-{%- endfor %}
-</ul>
-if condition: {{ 1 if foo else 0 }}
-""")
-
-print tmpl.render(foo=True)
diff --git a/slider-agent/src/main/python/jinja2/examples/basic/translate.py b/slider-agent/src/main/python/jinja2/examples/basic/translate.py
deleted file mode 100644
index 3358765..0000000
--- a/slider-agent/src/main/python/jinja2/examples/basic/translate.py
+++ /dev/null
@@ -1,6 +0,0 @@
-from jinja2 import Environment
-
-print Environment(extensions=['jinja2.i18n.TransExtension']).from_string("""\
-{% trans %}Hello {{ user }}!{% endtrans %}
-{% trans count=users|count %}{{ count }} user{% pluralize %}{{ count }} users{% endtrans %}
-""").render(user="someone")
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')
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()
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>
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 }}">
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>
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 %}
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>
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
- }))
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>
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>
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>
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 %}
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 %}
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>
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>
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>
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>
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()
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."""
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()
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)
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')
diff --git a/slider-agent/src/main/python/kazoo/tests/test_connection.py b/slider-agent/src/main/python/kazoo/tests/test_connection.py
deleted file mode 100644
index c8c4581..0000000
--- a/slider-agent/src/main/python/kazoo/tests/test_connection.py
+++ /dev/null
@@ -1,310 +0,0 @@
-"""license: Apache License 2.0, see LICENSE for more details."""
-from collections import namedtuple
-import sys
-import os
-import errno
-import threading
-import time
-import uuid
-import struct
-
-from nose import SkipTest
-from nose.tools import eq_
-from nose.tools import raises
-import mock
-
-from kazoo.exceptions import ConnectionLoss
-from kazoo.protocol.serialization import (
- Connect,
- int_struct,
- write_string,
-)
-from kazoo.protocol.states import KazooState
-from kazoo.protocol.connection import _CONNECTION_DROP
-from kazoo.testing import KazooTestCase
-from kazoo.tests.util import wait
-from kazoo.tests.util import TRAVIS_ZK_VERSION
-
-
-class Delete(namedtuple('Delete', 'path version')):
- type = 2
-
- def serialize(self):
- b = bytearray()
- b.extend(write_string(self.path))
- b.extend(int_struct.pack(self.version))
- return b
-
- @classmethod
- def deserialize(self, bytes, offset):
- raise ValueError("oh my")
-
-
-class TestConnectionHandler(KazooTestCase):
- def test_bad_deserialization(self):
- async_object = self.client.handler.async_result()
- self.client._queue.append(
- (Delete(self.client.chroot, -1), async_object))
- self.client._connection._write_sock.send(b'\0')
-
- @raises(ValueError)
- def testit():
- async_object.get()
- testit()
-
- def test_with_bad_sessionid(self):
- ev = threading.Event()
-
- def expired(state):
- if state == KazooState.CONNECTED:
- ev.set()
-
- password = os.urandom(16)
- client = self._get_client(client_id=(82838284824, password))
- client.add_listener(expired)
- client.start()
- try:
- ev.wait(15)
- eq_(ev.is_set(), True)
- finally:
- client.stop()
-
- def test_connection_read_timeout(self):
- client = self.client
- ev = threading.Event()
- path = "/" + uuid.uuid4().hex
- handler = client.handler
- _select = handler.select
- _socket = client._connection._socket
-
- def delayed_select(*args, **kwargs):
- result = _select(*args, **kwargs)
- if len(args[0]) == 1 and _socket in args[0]:
- # for any socket read, simulate a timeout
- return [], [], []
- return result
-
- def back(state):
- if state == KazooState.CONNECTED:
- ev.set()
-
- client.add_listener(back)
- client.create(path, b"1")
- try:
- handler.select = delayed_select
- self.assertRaises(ConnectionLoss, client.get, path)
- finally:
- handler.select = _select
- # the client reconnects automatically
- ev.wait(5)
- eq_(ev.is_set(), True)
- eq_(client.get(path)[0], b"1")
-
- def test_connection_write_timeout(self):
- client = self.client
- ev = threading.Event()
- path = "/" + uuid.uuid4().hex
- handler = client.handler
- _select = handler.select
- _socket = client._connection._socket
-
- def delayed_select(*args, **kwargs):
- result = _select(*args, **kwargs)
- if _socket in args[1]:
- # for any socket write, simulate a timeout
- return [], [], []
- return result
-
- def back(state):
- if state == KazooState.CONNECTED:
- ev.set()
- client.add_listener(back)
-
- try:
- handler.select = delayed_select
- self.assertRaises(ConnectionLoss, client.create, path)
- finally:
- handler.select = _select
- # the client reconnects automatically
- ev.wait(5)
- eq_(ev.is_set(), True)
- eq_(client.exists(path), None)
-
- def test_connection_deserialize_fail(self):
- client = self.client
- ev = threading.Event()
- path = "/" + uuid.uuid4().hex
- handler = client.handler
- _select = handler.select
- _socket = client._connection._socket
-
- def delayed_select(*args, **kwargs):
- result = _select(*args, **kwargs)
- if _socket in args[1]:
- # for any socket write, simulate a timeout
- return [], [], []
- return result
-
- def back(state):
- if state == KazooState.CONNECTED:
- ev.set()
- client.add_listener(back)
-
- deserialize_ev = threading.Event()
-
- def bad_deserialize(_bytes, offset):
- deserialize_ev.set()
- raise struct.error()
-
- # force the connection to die but, on reconnect, cause the
- # server response to be non-deserializable. ensure that the client
- # continues to retry. This partially reproduces a rare bug seen
- # in production.
-
- with mock.patch.object(Connect, 'deserialize') as mock_deserialize:
- mock_deserialize.side_effect = bad_deserialize
- try:
- handler.select = delayed_select
- self.assertRaises(ConnectionLoss, client.create, path)
- finally:
- handler.select = _select
- # the client reconnects automatically but the first attempt will
- # hit a deserialize failure. wait for that.
- deserialize_ev.wait(5)
- eq_(deserialize_ev.is_set(), True)
-
- # this time should succeed
- ev.wait(5)
- eq_(ev.is_set(), True)
- eq_(client.exists(path), None)
-
- def test_connection_close(self):
- self.assertRaises(Exception, self.client.close)
- self.client.stop()
- self.client.close()
-
- # should be able to restart
- self.client.start()
-
- def test_connection_sock(self):
- client = self.client
- read_sock = client._connection._read_sock
- write_sock = client._connection._write_sock
-
- assert read_sock is not None
- assert write_sock is not None
-
- # stop client and socket should not yet be closed
- client.stop()
- assert read_sock is not None
- assert write_sock is not None
-
- read_sock.getsockname()
- write_sock.getsockname()
-
- # close client, and sockets should be closed
- client.close()
-
- # Todo check socket closing
-
- # start client back up. should get a new, valid socket
- client.start()
- read_sock = client._connection._read_sock
- write_sock = client._connection._write_sock
-
- assert read_sock is not None
- assert write_sock is not None
- read_sock.getsockname()
- write_sock.getsockname()
-
-
- def test_dirty_sock(self):
- client = self.client
- read_sock = client._connection._read_sock
- write_sock = client._connection._write_sock
-
- # add a stray byte to the socket and ensure that doesn't
- # blow up client. simulates case where some error leaves
- # a byte in the socket which doesn't correspond to the
- # request queue.
- write_sock.send(b'\0')
-
- # eventually this byte should disappear from socket
- wait(lambda: client.handler.select([read_sock], [], [], 0)[0] == [])
-
-
-class TestConnectionDrop(KazooTestCase):
- def test_connection_dropped(self):
- ev = threading.Event()
-
- def back(state):
- if state == KazooState.CONNECTED:
- ev.set()
-
- # create a node with a large value and stop the ZK node
- path = "/" + uuid.uuid4().hex
- self.client.create(path)
- self.client.add_listener(back)
- result = self.client.set_async(path, b'a' * 1000 * 1024)
- self.client._call(_CONNECTION_DROP, None)
-
- self.assertRaises(ConnectionLoss, result.get)
- # we have a working connection to a new node
- ev.wait(30)
- eq_(ev.is_set(), True)
-
-
-class TestReadOnlyMode(KazooTestCase):
-
- def setUp(self):
- self.setup_zookeeper(read_only=True)
- 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 tearDown(self):
- self.client.stop()
-
- def test_read_only(self):
- from kazoo.exceptions import NotReadOnlyCallError
- from kazoo.protocol.states import KeeperState
-
- client = self.client
- states = []
- ev = threading.Event()
-
- @client.add_listener
- def listen(state):
- states.append(state)
- if client.client_state == KeeperState.CONNECTED_RO:
- ev.set()
- try:
- self.cluster[1].stop()
- self.cluster[2].stop()
- ev.wait(6)
- eq_(ev.is_set(), True)
- eq_(client.client_state, KeeperState.CONNECTED_RO)
-
- # Test read only command
- eq_(client.get_children('/'), [])
-
- # Test error with write command
- @raises(NotReadOnlyCallError)
- def testit():
- client.create('/fred')
- testit()
-
- # Wait for a ping
- time.sleep(15)
- finally:
- client.remove_listener(listen)
- self.cluster[1].run()
- self.cluster[2].run()
diff --git a/slider-agent/src/main/python/kazoo/tests/test_counter.py b/slider-agent/src/main/python/kazoo/tests/test_counter.py
deleted file mode 100644
index b0361d0..0000000
--- a/slider-agent/src/main/python/kazoo/tests/test_counter.py
+++ /dev/null
@@ -1,36 +0,0 @@
-"""license: Apache License 2.0, see LICENSE for more details."""
-import uuid
-
-from nose.tools import eq_
-
-from kazoo.testing import KazooTestCase
-
-
-class KazooCounterTests(KazooTestCase):
-
- def _makeOne(self, **kw):
- path = "/" + uuid.uuid4().hex
- return self.client.Counter(path, **kw)
-
- def test_int_counter(self):
- counter = self._makeOne()
- eq_(counter.value, 0)
- counter += 2
- counter + 1
- eq_(counter.value, 3)
- counter -= 3
- counter - 1
- eq_(counter.value, -1)
-
- def test_float_counter(self):
- counter = self._makeOne(default=0.0)
- eq_(counter.value, 0.0)
- counter += 2.1
- eq_(counter.value, 2.1)
- counter -= 3.1
- eq_(counter.value, -1.0)
-
- def test_errors(self):
- counter = self._makeOne()
- self.assertRaises(TypeError, counter.__add__, 2.1)
- self.assertRaises(TypeError, counter.__add__, b"a")
diff --git a/slider-agent/src/main/python/kazoo/tests/test_election.py b/slider-agent/src/main/python/kazoo/tests/test_election.py
deleted file mode 100644
index a9610bf..0000000
--- a/slider-agent/src/main/python/kazoo/tests/test_election.py
+++ /dev/null
@@ -1,140 +0,0 @@
-"""license: Apache License 2.0, see LICENSE for more details."""
-import uuid
-import sys
-import threading
-
-from nose.tools import eq_
-
-from kazoo.testing import KazooTestCase
-from kazoo.tests.util import wait
-
-
-class UniqueError(Exception):
- """Error raised only by test leader function
- """
-
-
-class KazooElectionTests(KazooTestCase):
- def setUp(self):
- super(KazooElectionTests, self).setUp()
- self.path = "/" + uuid.uuid4().hex
-
- self.condition = threading.Condition()
-
- # election contenders set these when elected. The exit event is set by
- # the test to make the leader exit.
- self.leader_id = None
- self.exit_event = None
-
- # tests set this before the event to make the leader raise an error
- self.raise_exception = False
-
- # set by a worker thread when an unexpected error is hit.
- # better way to do this?
- self.thread_exc_info = None
-
- def _spawn_contender(self, contender_id, election):
- thread = threading.Thread(target=self._election_thread,
- args=(contender_id, election))
- thread.daemon = True
- thread.start()
- return thread
-
- def _election_thread(self, contender_id, election):
- try:
- election.run(self._leader_func, contender_id)
- except UniqueError:
- if not self.raise_exception:
- self.thread_exc_info = sys.exc_info()
- except Exception:
- self.thread_exc_info = sys.exc_info()
- else:
- if self.raise_exception:
- e = Exception("expected leader func to raise exception")
- self.thread_exc_info = (Exception, e, None)
-
- def _leader_func(self, name):
- exit_event = threading.Event()
- with self.condition:
- self.exit_event = exit_event
- self.leader_id = name
- self.condition.notify_all()
-
- exit_event.wait(45)
- if self.raise_exception:
- raise UniqueError("expected error in the leader function")
-
- def _check_thread_error(self):
- if self.thread_exc_info:
- t, o, tb = self.thread_exc_info
- raise t(o)
-
- def test_election(self):
- elections = {}
- threads = {}
- for _ in range(3):
- contender = "c" + uuid.uuid4().hex
- elections[contender] = self.client.Election(self.path, contender)
- threads[contender] = self._spawn_contender(contender,
- elections[contender])
-
- # wait for a leader to be elected
- times = 0
- with self.condition:
- while not self.leader_id:
- self.condition.wait(5)
- times += 1
- if times > 5:
- raise Exception("Still not a leader: lid: %s",
- self.leader_id)
-
- election = self.client.Election(self.path)
-
- # make sure all contenders are in the pool
- wait(lambda: len(election.contenders()) == len(elections))
- contenders = election.contenders()
-
- eq_(set(contenders), set(elections.keys()))
-
- # first one in list should be leader
- first_leader = contenders[0]
- eq_(first_leader, self.leader_id)
-
- # tell second one to cancel election. should never get elected.
- elections[contenders[1]].cancel()
-
- # make leader exit. third contender should be elected.
- self.exit_event.set()
- with self.condition:
- while self.leader_id == first_leader:
- self.condition.wait(45)
- eq_(self.leader_id, contenders[2])
- self._check_thread_error()
-
- # make first contender re-enter the race
- threads[first_leader].join()
- threads[first_leader] = self._spawn_contender(first_leader,
- elections[first_leader])
-
- # contender set should now be the current leader plus the first leader
- wait(lambda: len(election.contenders()) == 2)
- contenders = election.contenders()
- eq_(set(contenders), set([self.leader_id, first_leader]))
-
- # make current leader raise an exception. first should be reelected
- self.raise_exception = True
- self.exit_event.set()
- with self.condition:
- while self.leader_id != first_leader:
- self.condition.wait(45)
- eq_(self.leader_id, first_leader)
- self._check_thread_error()
-
- self.exit_event.set()
- for thread in threads.values():
- thread.join()
- self._check_thread_error()
-
- def test_bad_func(self):
- election = self.client.Election(self.path)
- self.assertRaises(ValueError, election.run, "not a callable")
diff --git a/slider-agent/src/main/python/kazoo/tests/test_exceptions.py b/slider-agent/src/main/python/kazoo/tests/test_exceptions.py
deleted file mode 100644
index e469089..0000000
--- a/slider-agent/src/main/python/kazoo/tests/test_exceptions.py
+++ /dev/null
@@ -1,23 +0,0 @@
-"""license: Apache License 2.0, see LICENSE for more details."""
-from unittest import TestCase
-
-
-class ExceptionsTestCase(TestCase):
-
- def _get(self):
- from kazoo import exceptions
- return exceptions
-
- def test_backwards_alias(self):
- module = self._get()
- self.assertTrue(getattr(module, 'NoNodeException'))
- self.assertTrue(module.NoNodeException, module.NoNodeError)
-
- def test_exceptions_code(self):
- module = self._get()
- exc_8 = module.EXCEPTIONS[-8]
- self.assertTrue(isinstance(exc_8(), module.BadArgumentsError))
-
- def test_invalid_code(self):
- module = self._get()
- self.assertRaises(RuntimeError, module.EXCEPTIONS.__getitem__, 666)
diff --git a/slider-agent/src/main/python/kazoo/tests/test_gevent_handler.py b/slider-agent/src/main/python/kazoo/tests/test_gevent_handler.py
deleted file mode 100644
index 71d9727..0000000
--- a/slider-agent/src/main/python/kazoo/tests/test_gevent_handler.py
+++ /dev/null
@@ -1,161 +0,0 @@
-"""license: Apache License 2.0, see LICENSE for more details."""
-import unittest
-
-from nose import SkipTest
-from nose.tools import eq_
-from nose.tools import raises
-
-from kazoo.client import KazooClient
-from kazoo.exceptions import NoNodeError
-from kazoo.protocol.states import Callback
-from kazoo.testing import KazooTestCase
-from kazoo.tests import test_client
-
-
-class TestGeventHandler(unittest.TestCase):
-
- def setUp(self):
- try:
- import gevent
- except ImportError:
- raise SkipTest('gevent not available.')
-
- def _makeOne(self, *args):
- from kazoo.handlers.gevent import SequentialGeventHandler
- return SequentialGeventHandler(*args)
-
- def _getAsync(self, *args):
- from kazoo.handlers.gevent import AsyncResult
- return AsyncResult
-
- def _getEvent(self):
- from gevent.event import Event
- return Event
-
- def test_proper_threading(self):
- h = self._makeOne()
- h.start()
- assert isinstance(h.event_object(), self._getEvent())
-
- def test_matching_async(self):
- h = self._makeOne()
- h.start()
- async = self._getAsync()
- assert isinstance(h.async_result(), async)
-
- def test_exception_raising(self):
- h = self._makeOne()
-
- @raises(h.timeout_exception)
- def testit():
- raise h.timeout_exception("This is a timeout")
- testit()
-
- def test_exception_in_queue(self):
- h = self._makeOne()
- h.start()
- ev = self._getEvent()()
-
- def func():
- ev.set()
- raise ValueError('bang')
-
- call1 = Callback('completion', func, ())
- h.dispatch_callback(call1)
- ev.wait()
-
- def test_queue_empty_exception(self):
- from gevent.queue import Empty
- h = self._makeOne()
- h.start()
- ev = self._getEvent()()
-
- def func():
- ev.set()
- raise Empty()
-
- call1 = Callback('completion', func, ())
- h.dispatch_callback(call1)
- ev.wait()
-
-
-class TestBasicGeventClient(KazooTestCase):
-
- def setUp(self):
- try:
- import gevent
- except ImportError:
- raise SkipTest('gevent not available.')
- KazooTestCase.setUp(self)
-
- def _makeOne(self, *args):
- from kazoo.handlers.gevent import SequentialGeventHandler
- return SequentialGeventHandler(*args)
-
- def _getEvent(self):
- from gevent.event import Event
- return Event
-
- def test_start(self):
- client = self._get_client(handler=self._makeOne())
- client.start()
- self.assertEqual(client.state, 'CONNECTED')
- client.stop()
-
- def test_start_stop_double(self):
- client = self._get_client(handler=self._makeOne())
- client.start()
- self.assertEqual(client.state, 'CONNECTED')
- client.handler.start()
- client.handler.stop()
- client.stop()
-
- def test_basic_commands(self):
- client = self._get_client(handler=self._makeOne())
- client.start()
- self.assertEqual(client.state, 'CONNECTED')
- client.create('/anode', 'fred')
- eq_(client.get('/anode')[0], 'fred')
- eq_(client.delete('/anode'), True)
- eq_(client.exists('/anode'), None)
- client.stop()
-
- def test_failures(self):
- client = self._get_client(handler=self._makeOne())
- client.start()
- self.assertRaises(NoNodeError, client.get, '/none')
- client.stop()
-
- def test_data_watcher(self):
- client = self._get_client(handler=self._makeOne())
- client.start()
- client.ensure_path('/some/node')
- ev = self._getEvent()()
-
- @client.DataWatch('/some/node')
- def changed(d, stat):
- ev.set()
-
- ev.wait()
- ev.clear()
- client.set('/some/node', 'newvalue')
- ev.wait()
- client.stop()
-
-
-class TestGeventClient(test_client.TestClient):
-
- def setUp(self):
- try:
- import gevent
- except ImportError:
- raise SkipTest('gevent not available.')
- KazooTestCase.setUp(self)
-
- def _makeOne(self, *args):
- from kazoo.handlers.gevent import SequentialGeventHandler
- return SequentialGeventHandler(*args)
-
- def _get_client(self, **kwargs):
- kwargs["handler"] = self._makeOne()
- return KazooClient(self.hosts, **kwargs)
diff --git a/slider-agent/src/main/python/kazoo/tests/test_lock.py b/slider-agent/src/main/python/kazoo/tests/test_lock.py
deleted file mode 100644
index 6dd15b0..0000000
--- a/slider-agent/src/main/python/kazoo/tests/test_lock.py
+++ /dev/null
@@ -1,518 +0,0 @@
-"""license: Apache License 2.0, see LICENSE for more details."""
-import uuid
-import threading
-
-from nose.tools import eq_, ok_
-
-from kazoo.exceptions import CancelledError
-from kazoo.exceptions import LockTimeout
-from kazoo.testing import KazooTestCase
-from kazoo.tests.util import wait
-
-
-class KazooLockTests(KazooTestCase):
- def setUp(self):
- super(KazooLockTests, self).setUp()
- self.lockpath = "/" + uuid.uuid4().hex
-
- self.condition = threading.Condition()
- self.released = threading.Event()
- self.active_thread = None
- self.cancelled_threads = []
-
- def _thread_lock_acquire_til_event(self, name, lock, event):
- try:
- with lock:
- with self.condition:
- eq_(self.active_thread, None)
- self.active_thread = name
- self.condition.notify_all()
-
- event.wait()
-
- with self.condition:
- eq_(self.active_thread, name)
- self.active_thread = None
- self.condition.notify_all()
- self.released.set()
- except CancelledError:
- with self.condition:
- self.cancelled_threads.append(name)
- self.condition.notify_all()
-
- def test_lock_one(self):
- lock_name = uuid.uuid4().hex
- lock = self.client.Lock(self.lockpath, lock_name)
- event = threading.Event()
-
- thread = threading.Thread(target=self._thread_lock_acquire_til_event,
- args=(lock_name, lock, event))
- thread.start()
-
- lock2_name = uuid.uuid4().hex
- anotherlock = self.client.Lock(self.lockpath, lock2_name)
-
- # wait for any contender to show up on the lock
- wait(anotherlock.contenders)
- eq_(anotherlock.contenders(), [lock_name])
-
- with self.condition:
- while self.active_thread != lock_name:
- self.condition.wait()
-
- # release the lock
- event.set()
-
- with self.condition:
- while self.active_thread:
- self.condition.wait()
- self.released.wait()
- thread.join()
-
- def test_lock(self):
- threads = []
- names = ["contender" + str(i) for i in range(5)]
-
- contender_bits = {}
-
- for name in names:
- e = threading.Event()
-
- l = self.client.Lock(self.lockpath, name)
- t = threading.Thread(target=self._thread_lock_acquire_til_event,
- args=(name, l, e))
- contender_bits[name] = (t, e)
- threads.append(t)
-
- # acquire the lock ourselves first to make the others line up
- lock = self.client.Lock(self.lockpath, "test")
- lock.acquire()
-
- for t in threads:
- t.start()
-
- # wait for everyone to line up on the lock
- wait(lambda: len(lock.contenders()) == 6)
- contenders = lock.contenders()
-
- eq_(contenders[0], "test")
- contenders = contenders[1:]
- remaining = list(contenders)
-
- # release the lock and contenders should claim it in order
- lock.release()
-
- for contender in contenders:
- thread, event = contender_bits[contender]
-
- with self.condition:
- while not self.active_thread:
- self.condition.wait()
- eq_(self.active_thread, contender)
-
- eq_(lock.contenders(), remaining)
- remaining = remaining[1:]
-
- event.set()
-
- with self.condition:
- while self.active_thread:
- self.condition.wait()
- for thread in threads:
- thread.join()
-
- def test_lock_reconnect(self):
- event = threading.Event()
- other_lock = self.client.Lock(self.lockpath, 'contender')
- thread = threading.Thread(target=self._thread_lock_acquire_til_event,
- args=('contender', other_lock, event))
-
- # acquire the lock ourselves first to make the contender line up
- lock = self.client.Lock(self.lockpath, "test")
- lock.acquire()
-
- thread.start()
- # wait for the contender to line up on the lock
- wait(lambda: len(lock.contenders()) == 2)
- eq_(lock.contenders(), ['test', 'contender'])
-
- self.expire_session()
-
- lock.release()
-
- with self.condition:
- while not self.active_thread:
- self.condition.wait()
- eq_(self.active_thread, 'contender')
-
- event.set()
- thread.join()
-
- def test_lock_non_blocking(self):
- lock_name = uuid.uuid4().hex
- lock = self.client.Lock(self.lockpath, lock_name)
- event = threading.Event()
-
- thread = threading.Thread(target=self._thread_lock_acquire_til_event,
- args=(lock_name, lock, event))
- thread.start()
-
- lock1 = self.client.Lock(self.lockpath, lock_name)
-
- # wait for the thread to acquire the lock
- with self.condition:
- if not self.active_thread:
- self.condition.wait(5)
-
- ok_(not lock1.acquire(blocking=False))
- eq_(lock.contenders(), [lock_name]) # just one - itself
-
- event.set()
- thread.join()
-
- def test_lock_fail_first_call(self):
- event1 = threading.Event()
- lock1 = self.client.Lock(self.lockpath, "one")
- thread1 = threading.Thread(target=self._thread_lock_acquire_til_event,
- args=("one", lock1, event1))
- thread1.start()
-
- # wait for this thread to acquire the lock
- with self.condition:
- if not self.active_thread:
- self.condition.wait(5)
- eq_(self.active_thread, "one")
- eq_(lock1.contenders(), ["one"])
- event1.set()
- thread1.join()
-
- def test_lock_cancel(self):
- event1 = threading.Event()
- lock1 = self.client.Lock(self.lockpath, "one")
- thread1 = threading.Thread(target=self._thread_lock_acquire_til_event,
- args=("one", lock1, event1))
- thread1.start()
-
- # wait for this thread to acquire the lock
- with self.condition:
- if not self.active_thread:
- self.condition.wait(5)
- eq_(self.active_thread, "one")
-
- client2 = self._get_client()
- client2.start()
- event2 = threading.Event()
- lock2 = client2.Lock(self.lockpath, "two")
- thread2 = threading.Thread(target=self._thread_lock_acquire_til_event,
- args=("two", lock2, event2))
- thread2.start()
-
- # this one should block in acquire. check that it is a contender
- wait(lambda: len(lock2.contenders()) > 1)
- eq_(lock2.contenders(), ["one", "two"])
-
- lock2.cancel()
- with self.condition:
- if not "two" in self.cancelled_threads:
- self.condition.wait()
- assert "two" in self.cancelled_threads
-
- eq_(lock2.contenders(), ["one"])
-
- thread2.join()
- event1.set()
- thread1.join()
- client2.stop()
-
- def test_lock_double_calls(self):
- lock1 = self.client.Lock(self.lockpath, "one")
- lock1.acquire()
- lock1.acquire()
- lock1.release()
- lock1.release()
-
- def test_lock_reacquire(self):
- lock = self.client.Lock(self.lockpath, "one")
- lock.acquire()
- lock.release()
- lock.acquire()
- lock.release()
-
- def test_lock_timeout(self):
- timeout = 3
- e = threading.Event()
- started = threading.Event()
-
- # In the background thread, acquire the lock and wait thrice the time
- # that the main thread is going to wait to acquire the lock.
- lock1 = self.client.Lock(self.lockpath, "one")
-
- def _thread(lock, event, timeout):
- with lock:
- started.set()
- event.wait(timeout)
- if not event.isSet():
- # Eventually fail to avoid hanging the tests
- self.fail("lock2 never timed out")
-
- t = threading.Thread(target=_thread, args=(lock1, e, timeout * 3))
- t.start()
-
- # Start the main thread's kazoo client and try to acquire the lock
- # but give up after `timeout` seconds
- client2 = self._get_client()
- client2.start()
- started.wait(5)
- self.assertTrue(started.isSet())
- lock2 = client2.Lock(self.lockpath, "two")
- try:
- lock2.acquire(timeout=timeout)
- except LockTimeout:
- # A timeout is the behavior we're expecting, since the background
- # thread should still be holding onto the lock
- pass
- else:
- self.fail("Main thread unexpectedly acquired the lock")
- finally:
- # Cleanup
- e.set()
- t.join()
- client2.stop()
-
-
-class TestSemaphore(KazooTestCase):
- def setUp(self):
- super(TestSemaphore, self).setUp()
- self.lockpath = "/" + uuid.uuid4().hex
-
- self.condition = threading.Condition()
- self.released = threading.Event()
- self.active_thread = None
- self.cancelled_threads = []
-
- def test_basic(self):
- sem1 = self.client.Semaphore(self.lockpath)
- sem1.acquire()
- sem1.release()
-
- def test_lock_one(self):
- sem1 = self.client.Semaphore(self.lockpath, max_leases=1)
- sem2 = self.client.Semaphore(self.lockpath, max_leases=1)
- started = threading.Event()
- event = threading.Event()
-
- sem1.acquire()
-
- def sema_one():
- started.set()
- with sem2:
- event.set()
-
- thread = threading.Thread(target=sema_one, args=())
- thread.start()
- started.wait(10)
-
- self.assertFalse(event.is_set())
-
- sem1.release()
- event.wait(10)
- self.assert_(event.is_set())
- thread.join()
-
- def test_non_blocking(self):
- sem1 = self.client.Semaphore(
- self.lockpath, identifier='sem1', max_leases=2)
- sem2 = self.client.Semaphore(
- self.lockpath, identifier='sem2', max_leases=2)
- sem3 = self.client.Semaphore(
- self.lockpath, identifier='sem3', max_leases=2)
-
- sem1.acquire()
- sem2.acquire()
- ok_(not sem3.acquire(blocking=False))
- eq_(set(sem1.lease_holders()), set(['sem1', 'sem2']))
- sem2.release()
- # the next line isn't required, but avoids timing issues in tests
- sem3.acquire()
- eq_(set(sem1.lease_holders()), set(['sem1', 'sem3']))
- sem1.release()
- sem3.release()
-
- def test_non_blocking_release(self):
- sem1 = self.client.Semaphore(
- self.lockpath, identifier='sem1', max_leases=1)
- sem2 = self.client.Semaphore(
- self.lockpath, identifier='sem2', max_leases=1)
- sem1.acquire()
- sem2.acquire(blocking=False)
-
- # make sure there's no shutdown / cleanup error
- sem1.release()
- sem2.release()
-
- def test_holders(self):
- started = threading.Event()
- event = threading.Event()
-
- def sema_one():
- with self.client.Semaphore(self.lockpath, 'fred', max_leases=1):
- started.set()
- event.wait()
-
- thread = threading.Thread(target=sema_one, args=())
- thread.start()
- started.wait()
- sem1 = self.client.Semaphore(self.lockpath)
- holders = sem1.lease_holders()
- eq_(holders, ['fred'])
- event.set()
- thread.join()
-
- def test_semaphore_cancel(self):
- sem1 = self.client.Semaphore(self.lockpath, 'fred', max_leases=1)
- sem2 = self.client.Semaphore(self.lockpath, 'george', max_leases=1)
- sem1.acquire()
- started = threading.Event()
- event = threading.Event()
-
- def sema_one():
- started.set()
- try:
- with sem2:
- started.set()
- except CancelledError:
- event.set()
-
- thread = threading.Thread(target=sema_one, args=())
- thread.start()
- started.wait()
- eq_(sem1.lease_holders(), ['fred'])
- eq_(event.is_set(), False)
- sem2.cancel()
- event.wait()
- eq_(event.is_set(), True)
- thread.join()
-
- def test_multiple_acquire_and_release(self):
- sem1 = self.client.Semaphore(self.lockpath, 'fred', max_leases=1)
- sem1.acquire()
- sem1.acquire()
-
- eq_(True, sem1.release())
- eq_(False, sem1.release())
-
- def test_handle_session_loss(self):
- expire_semaphore = self.client.Semaphore(self.lockpath, 'fred',
- max_leases=1)
-
- client = self._get_client()
- client.start()
- lh_semaphore = client.Semaphore(self.lockpath, 'george', max_leases=1)
- lh_semaphore.acquire()
-
- started = threading.Event()
- event = threading.Event()
- event2 = threading.Event()
-
- def sema_one():
- started.set()
- with expire_semaphore:
- event.set()
- event2.wait()
-
- thread = threading.Thread(target=sema_one, args=())
- thread.start()
-
- started.wait()
- eq_(lh_semaphore.lease_holders(), ['george'])
-
- # Fired in a separate thread to make sure we can see the effect
- expired = threading.Event()
-
- def expire():
- self.expire_session()
- expired.set()
-
- thread = threading.Thread(target=expire, args=())
- thread.start()
- expire_semaphore.wake_event.wait()
- expired.wait()
-
- lh_semaphore.release()
- client.stop()
-
- event.wait(5)
- eq_(expire_semaphore.lease_holders(), ['fred'])
- event2.set()
- thread.join()
-
- def test_inconsistent_max_leases(self):
- sem1 = self.client.Semaphore(self.lockpath, max_leases=1)
- sem2 = self.client.Semaphore(self.lockpath, max_leases=2)
-
- sem1.acquire()
- self.assertRaises(ValueError, sem2.acquire)
-
- def test_inconsistent_max_leases_other_data(self):
- sem1 = self.client.Semaphore(self.lockpath, max_leases=1)
- sem2 = self.client.Semaphore(self.lockpath, max_leases=2)
-
- self.client.ensure_path(self.lockpath)
- self.client.set(self.lockpath, b'a$')
-
- sem1.acquire()
- # sem2 thinks it's ok to have two lease holders
- ok_(sem2.acquire(blocking=False))
-
- def test_reacquire(self):
- lock = self.client.Semaphore(self.lockpath)
- lock.acquire()
- lock.release()
- lock.acquire()
- lock.release()
-
- def test_acquire_after_cancelled(self):
- lock = self.client.Semaphore(self.lockpath)
- self.assertTrue(lock.acquire())
- self.assertTrue(lock.release())
- lock.cancel()
- self.assertTrue(lock.cancelled)
- self.assertTrue(lock.acquire())
-
- def test_timeout(self):
- timeout = 3
- e = threading.Event()
- started = threading.Event()
-
- # In the background thread, acquire the lock and wait thrice the time
- # that the main thread is going to wait to acquire the lock.
- sem1 = self.client.Semaphore(self.lockpath, "one")
-
- def _thread(sem, event, timeout):
- with sem:
- started.set()
- event.wait(timeout)
- if not event.isSet():
- # Eventually fail to avoid hanging the tests
- self.fail("sem2 never timed out")
-
- t = threading.Thread(target=_thread, args=(sem1, e, timeout * 3))
- t.start()
-
- # Start the main thread's kazoo client and try to acquire the lock
- # but give up after `timeout` seconds
- client2 = self._get_client()
- client2.start()
- started.wait(5)
- self.assertTrue(started.isSet())
- sem2 = client2.Semaphore(self.lockpath, "two")
- try:
- sem2.acquire(timeout=timeout)
- except LockTimeout:
- # A timeout is the behavior we're expecting, since the background
- # thread will still be holding onto the lock
- e.set()
- finally:
- # Cleanup
- t.join()
- client2.stop()
diff --git a/slider-agent/src/main/python/kazoo/tests/test_partitioner.py b/slider-agent/src/main/python/kazoo/tests/test_partitioner.py
deleted file mode 100644
index 1a4f205..0000000
--- a/slider-agent/src/main/python/kazoo/tests/test_partitioner.py
+++ /dev/null
@@ -1,93 +0,0 @@
-"""license: Apache License 2.0, see LICENSE for more details."""
-import uuid
-import time
-
-from nose.tools import eq_
-
-from kazoo.testing import KazooTestCase
-from kazoo.recipe.partitioner import PartitionState
-
-
-class KazooPartitionerTests(KazooTestCase):
- def setUp(self):
- super(KazooPartitionerTests, self).setUp()
- self.path = "/" + uuid.uuid4().hex
-
- def test_party_of_one(self):
- partitioner = self.client.SetPartitioner(
- self.path, set=(1, 2, 3), time_boundary=0.2)
- partitioner.wait_for_acquire(14)
- eq_(partitioner.state, PartitionState.ACQUIRED)
- eq_(list(partitioner), [1, 2, 3])
- partitioner.finish()
-
- def test_party_of_two(self):
- partitioners = [self.client.SetPartitioner(self.path, (1, 2),
- identifier="p%s" % i, time_boundary=0.2)
- for i in range(2)]
-
- partitioners[0].wait_for_acquire(14)
- partitioners[1].wait_for_acquire(14)
- eq_(list(partitioners[0]), [1])
- eq_(list(partitioners[1]), [2])
- partitioners[0].finish()
- time.sleep(0.1)
- eq_(partitioners[1].release, True)
- partitioners[1].finish()
-
- def test_party_expansion(self):
- partitioners = [self.client.SetPartitioner(self.path, (1, 2, 3),
- identifier="p%s" % i, time_boundary=0.2)
- for i in range(2)]
-
- partitioners[0].wait_for_acquire(14)
- partitioners[1].wait_for_acquire(14)
- eq_(partitioners[0].state, PartitionState.ACQUIRED)
- eq_(partitioners[1].state, PartitionState.ACQUIRED)
-
- eq_(list(partitioners[0]), [1, 3])
- eq_(list(partitioners[1]), [2])
-
- # Add another partition, wait till they settle
- partitioners.append(self.client.SetPartitioner(self.path, (1, 2, 3),
- identifier="p2", time_boundary=0.2))
- time.sleep(0.1)
- eq_(partitioners[0].release, True)
- for p in partitioners[:-1]:
- p.release_set()
-
- for p in partitioners:
- p.wait_for_acquire(14)
-
- eq_(list(partitioners[0]), [1])
- eq_(list(partitioners[1]), [2])
- eq_(list(partitioners[2]), [3])
-
- for p in partitioners:
- p.finish()
-
- def test_more_members_than_set_items(self):
- partitioners = [self.client.SetPartitioner(self.path, (1,),
- identifier="p%s" % i, time_boundary=0.2)
- for i in range(2)]
-
- partitioners[0].wait_for_acquire(14)
- partitioners[1].wait_for_acquire(14)
- eq_(partitioners[0].state, PartitionState.ACQUIRED)
- eq_(partitioners[1].state, PartitionState.ACQUIRED)
-
- eq_(list(partitioners[0]), [1])
- eq_(list(partitioners[1]), [])
-
- for p in partitioners:
- p.finish()
-
- def test_party_session_failure(self):
- partitioner = self.client.SetPartitioner(
- self.path, set=(1, 2, 3), time_boundary=0.2)
- partitioner.wait_for_acquire(14)
- eq_(partitioner.state, PartitionState.ACQUIRED)
- # simulate session failure
- partitioner._fail_out()
- partitioner.release_set()
- self.assertTrue(partitioner.failed)
diff --git a/slider-agent/src/main/python/kazoo/tests/test_party.py b/slider-agent/src/main/python/kazoo/tests/test_party.py
deleted file mode 100644
index 61400ae..0000000
--- a/slider-agent/src/main/python/kazoo/tests/test_party.py
+++ /dev/null
@@ -1,85 +0,0 @@
-"""license: Apache License 2.0, see LICENSE for more details."""
-import uuid
-
-from nose.tools import eq_
-
-from kazoo.testing import KazooTestCase
-
-
-class KazooPartyTests(KazooTestCase):
- def setUp(self):
- super(KazooPartyTests, self).setUp()
- self.path = "/" + uuid.uuid4().hex
-
- def test_party(self):
- parties = [self.client.Party(self.path, "p%s" % i)
- for i in range(5)]
-
- one_party = parties[0]
-
- eq_(list(one_party), [])
- eq_(len(one_party), 0)
-
- participants = set()
- for party in parties:
- party.join()
- participants.add(party.data.decode('utf-8'))
-
- eq_(set(party), participants)
- eq_(len(party), len(participants))
-
- for party in parties:
- party.leave()
- participants.remove(party.data.decode('utf-8'))
-
- eq_(set(party), participants)
- eq_(len(party), len(participants))
-
- def test_party_reuse_node(self):
- party = self.client.Party(self.path, "p1")
- self.client.ensure_path(self.path)
- self.client.create(party.create_path)
- party.join()
- self.assertTrue(party.participating)
- party.leave()
- self.assertFalse(party.participating)
- self.assertEqual(len(party), 0)
-
- def test_party_vanishing_node(self):
- party = self.client.Party(self.path, "p1")
- party.join()
- self.assertTrue(party.participating)
- self.client.delete(party.create_path)
- party.leave()
- self.assertFalse(party.participating)
- self.assertEqual(len(party), 0)
-
-
-class KazooShallowPartyTests(KazooTestCase):
- def setUp(self):
- super(KazooShallowPartyTests, self).setUp()
- self.path = "/" + uuid.uuid4().hex
-
- def test_party(self):
- parties = [self.client.ShallowParty(self.path, "p%s" % i)
- for i in range(5)]
-
- one_party = parties[0]
-
- eq_(list(one_party), [])
- eq_(len(one_party), 0)
-
- participants = set()
- for party in parties:
- party.join()
- participants.add(party.data.decode('utf-8'))
-
- eq_(set(party), participants)
- eq_(len(party), len(participants))
-
- for party in parties:
- party.leave()
- participants.remove(party.data.decode('utf-8'))
-
- eq_(set(party), participants)
- eq_(len(party), len(participants))
diff --git a/slider-agent/src/main/python/kazoo/tests/test_paths.py b/slider-agent/src/main/python/kazoo/tests/test_paths.py
deleted file mode 100644
index c9064bb..0000000
--- a/slider-agent/src/main/python/kazoo/tests/test_paths.py
+++ /dev/null
@@ -1,99 +0,0 @@
-"""license: Apache License 2.0, see LICENSE for more details."""
-import sys
-from unittest import TestCase
-
-from kazoo.protocol import paths
-
-
-if sys.version_info > (3, ): # pragma: nocover
- def u(s):
- return s
-else: # pragma: nocover
- def u(s):
- return unicode(s, "unicode_escape")
-
-
-class NormPathTestCase(TestCase):
-
- def test_normpath(self):
- self.assertEqual(paths.normpath('/a/b'), '/a/b')
-
- def test_normpath_empty(self):
- self.assertEqual(paths.normpath(''), '')
-
- def test_normpath_unicode(self):
- self.assertEqual(paths.normpath(u('/\xe4/b')), u('/\xe4/b'))
-
- def test_normpath_dots(self):
- self.assertEqual(paths.normpath('/a./b../c'), '/a./b../c')
-
- def test_normpath_slash(self):
- self.assertEqual(paths.normpath('/'), '/')
-
- def test_normpath_multiple_slashes(self):
- self.assertEqual(paths.normpath('//'), '/')
- self.assertEqual(paths.normpath('//a/b'), '/a/b')
- self.assertEqual(paths.normpath('/a//b//'), '/a/b')
- self.assertEqual(paths.normpath('//a////b///c/'), '/a/b/c')
-
- def test_normpath_relative(self):
- self.assertRaises(ValueError, paths.normpath, './a/b')
- self.assertRaises(ValueError, paths.normpath, '/a/../b')
-
-
-class JoinTestCase(TestCase):
-
- def test_join(self):
- self.assertEqual(paths.join('/a'), '/a')
- self.assertEqual(paths.join('/a', 'b/'), '/a/b/')
- self.assertEqual(paths.join('/a', 'b', 'c'), '/a/b/c')
-
- def test_join_empty(self):
- self.assertEqual(paths.join(''), '')
- self.assertEqual(paths.join('', 'a', 'b'), 'a/b')
- self.assertEqual(paths.join('/a', '', 'b/', 'c'), '/a/b/c')
-
- def test_join_absolute(self):
- self.assertEqual(paths.join('/a/b', '/c'), '/c')
-
-
-class IsAbsTestCase(TestCase):
-
- def test_isabs(self):
- self.assertTrue(paths.isabs('/'))
- self.assertTrue(paths.isabs('/a'))
- self.assertTrue(paths.isabs('/a//b/c'))
- self.assertTrue(paths.isabs('//a/b'))
-
- def test_isabs_false(self):
- self.assertFalse(paths.isabs(''))
- self.assertFalse(paths.isabs('a/'))
- self.assertFalse(paths.isabs('a/../'))
-
-
-class BaseNameTestCase(TestCase):
-
- def test_basename(self):
- self.assertEquals(paths.basename(''), '')
- self.assertEquals(paths.basename('/'), '')
- self.assertEquals(paths.basename('//a'), 'a')
- self.assertEquals(paths.basename('//a/'), '')
- self.assertEquals(paths.basename('/a/b.//c..'), 'c..')
-
-
-class PrefixRootTestCase(TestCase):
-
- def test_prefix_root(self):
- self.assertEquals(paths._prefix_root('/a/', 'b/c'), '/a/b/c')
- self.assertEquals(paths._prefix_root('/a/b', 'c/d'), '/a/b/c/d')
- self.assertEquals(paths._prefix_root('/a', '/b/c'), '/a/b/c')
- self.assertEquals(paths._prefix_root('/a', '//b/c.'), '/a/b/c.')
-
-
-class NormRootTestCase(TestCase):
-
- def test_norm_root(self):
- self.assertEquals(paths._norm_root(''), '/')
- self.assertEquals(paths._norm_root('/'), '/')
- self.assertEquals(paths._norm_root('//a'), '/a')
- self.assertEquals(paths._norm_root('//a./b'), '/a./b')
diff --git a/slider-agent/src/main/python/kazoo/tests/test_queue.py b/slider-agent/src/main/python/kazoo/tests/test_queue.py
deleted file mode 100644
index 4c13ca9..0000000
--- a/slider-agent/src/main/python/kazoo/tests/test_queue.py
+++ /dev/null
@@ -1,180 +0,0 @@
-"""license: Apache License 2.0, see LICENSE for more details."""
-import uuid
-
-from nose import SkipTest
-from nose.tools import eq_, ok_
-
-from kazoo.testing import KazooTestCase
-from kazoo.tests.util import TRAVIS_ZK_VERSION
-
-
-class KazooQueueTests(KazooTestCase):
-
- def _makeOne(self):
- path = "/" + uuid.uuid4().hex
- return self.client.Queue(path)
-
- def test_queue_validation(self):
- queue = self._makeOne()
- self.assertRaises(TypeError, queue.put, {})
- self.assertRaises(TypeError, queue.put, b"one", b"100")
- self.assertRaises(TypeError, queue.put, b"one", 10.0)
- self.assertRaises(ValueError, queue.put, b"one", -100)
- self.assertRaises(ValueError, queue.put, b"one", 100000)
-
- def test_empty_queue(self):
- queue = self._makeOne()
- eq_(len(queue), 0)
- self.assertTrue(queue.get() is None)
- eq_(len(queue), 0)
-
- def test_queue(self):
- queue = self._makeOne()
- queue.put(b"one")
- queue.put(b"two")
- queue.put(b"three")
- eq_(len(queue), 3)
-
- eq_(queue.get(), b"one")
- eq_(queue.get(), b"two")
- eq_(queue.get(), b"three")
- eq_(len(queue), 0)
-
- def test_priority(self):
- queue = self._makeOne()
- queue.put(b"four", priority=101)
- queue.put(b"one", priority=0)
- queue.put(b"two", priority=0)
- queue.put(b"three", priority=10)
-
- eq_(queue.get(), b"one")
- eq_(queue.get(), b"two")
- eq_(queue.get(), b"three")
- eq_(queue.get(), b"four")
-
-
-class KazooLockingQueueTests(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 _makeOne(self):
- path = "/" + uuid.uuid4().hex
- return self.client.LockingQueue(path)
-
- def test_queue_validation(self):
- queue = self._makeOne()
- self.assertRaises(TypeError, queue.put, {})
- self.assertRaises(TypeError, queue.put, b"one", b"100")
- self.assertRaises(TypeError, queue.put, b"one", 10.0)
- self.assertRaises(ValueError, queue.put, b"one", -100)
- self.assertRaises(ValueError, queue.put, b"one", 100000)
- self.assertRaises(TypeError, queue.put_all, {})
- self.assertRaises(TypeError, queue.put_all, [{}])
- self.assertRaises(TypeError, queue.put_all, [b"one"], b"100")
- self.assertRaises(TypeError, queue.put_all, [b"one"], 10.0)
- self.assertRaises(ValueError, queue.put_all, [b"one"], -100)
- self.assertRaises(ValueError, queue.put_all, [b"one"], 100000)
-
- def test_empty_queue(self):
- queue = self._makeOne()
- eq_(len(queue), 0)
- self.assertTrue(queue.get(0) is None)
- eq_(len(queue), 0)
-
- def test_queue(self):
- queue = self._makeOne()
- queue.put(b"one")
- queue.put_all([b"two", b"three"])
- eq_(len(queue), 3)
-
- ok_(not queue.consume())
- ok_(not queue.holds_lock())
- eq_(queue.get(1), b"one")
- ok_(queue.holds_lock())
- # Without consuming, should return the same element
- eq_(queue.get(1), b"one")
- ok_(queue.consume())
- ok_(not queue.holds_lock())
- eq_(queue.get(1), b"two")
- ok_(queue.holds_lock())
- ok_(queue.consume())
- ok_(not queue.holds_lock())
- eq_(queue.get(1), b"three")
- ok_(queue.holds_lock())
- ok_(queue.consume())
- ok_(not queue.holds_lock())
- ok_(not queue.consume())
- eq_(len(queue), 0)
-
- def test_consume(self):
- queue = self._makeOne()
-
- queue.put(b"one")
- ok_(not queue.consume())
- queue.get(.1)
- ok_(queue.consume())
- ok_(not queue.consume())
-
- def test_holds_lock(self):
- queue = self._makeOne()
-
- ok_(not queue.holds_lock())
- queue.put(b"one")
- queue.get(.1)
- ok_(queue.holds_lock())
- queue.consume()
- ok_(not queue.holds_lock())
-
- def test_priority(self):
- queue = self._makeOne()
- queue.put(b"four", priority=101)
- queue.put(b"one", priority=0)
- queue.put(b"two", priority=0)
- queue.put(b"three", priority=10)
-
- eq_(queue.get(1), b"one")
- ok_(queue.consume())
- eq_(queue.get(1), b"two")
- ok_(queue.consume())
- eq_(queue.get(1), b"three")
- ok_(queue.consume())
- eq_(queue.get(1), b"four")
- ok_(queue.consume())
-
- def test_concurrent_execution(self):
- queue = self._makeOne()
- value1 = []
- value2 = []
- value3 = []
- event1 = self.client.handler.event_object()
- event2 = self.client.handler.event_object()
- event3 = self.client.handler.event_object()
-
- def get_concurrently(value, event):
- q = self.client.LockingQueue(queue.path)
- value.append(q.get(.1))
- event.set()
-
- self.client.handler.spawn(get_concurrently, value1, event1)
- self.client.handler.spawn(get_concurrently, value2, event2)
- self.client.handler.spawn(get_concurrently, value3, event3)
- queue.put(b"one")
- event1.wait(.2)
- event2.wait(.2)
- event3.wait(.2)
-
- result = value1 + value2 + value3
- eq_(result.count(b"one"), 1)
- eq_(result.count(None), 2)
diff --git a/slider-agent/src/main/python/kazoo/tests/test_retry.py b/slider-agent/src/main/python/kazoo/tests/test_retry.py
deleted file mode 100644
index 84c8d41..0000000
--- a/slider-agent/src/main/python/kazoo/tests/test_retry.py
+++ /dev/null
@@ -1,78 +0,0 @@
-"""license: Apache License 2.0, see LICENSE for more details."""
-import unittest
-
-from nose.tools import eq_
-
-
-class TestRetrySleeper(unittest.TestCase):
-
- def _pass(self):
- pass
-
- def _fail(self, times=1):
- from kazoo.retry import ForceRetryError
- scope = dict(times=0)
-
- def inner():
- if scope['times'] >= times:
- pass
- else:
- scope['times'] += 1
- raise ForceRetryError('Failed!')
- return inner
-
- def _makeOne(self, *args, **kwargs):
- from kazoo.retry import KazooRetry
- return KazooRetry(*args, **kwargs)
-
- def test_reset(self):
- retry = self._makeOne(delay=0, max_tries=2)
- retry(self._fail())
- eq_(retry._attempts, 1)
- retry.reset()
- eq_(retry._attempts, 0)
-
- def test_too_many_tries(self):
- from kazoo.retry import RetryFailedError
- retry = self._makeOne(delay=0)
- self.assertRaises(RetryFailedError, retry, self._fail(times=999))
- eq_(retry._attempts, 1)
-
- def test_maximum_delay(self):
- def sleep_func(_time):
- pass
-
- retry = self._makeOne(delay=10, max_tries=100, sleep_func=sleep_func)
- retry(self._fail(times=10))
- self.assertTrue(retry._cur_delay < 4000, retry._cur_delay)
- # gevent's sleep function is picky about the type
- eq_(type(retry._cur_delay), float)
-
- def test_copy(self):
- _sleep = lambda t: None
- retry = self._makeOne(sleep_func=_sleep)
- rcopy = retry.copy()
- self.assertTrue(rcopy.sleep_func is _sleep)
-
-
-class TestKazooRetry(unittest.TestCase):
-
- def _makeOne(self, **kw):
- from kazoo.retry import KazooRetry
- return KazooRetry(**kw)
-
- def test_connection_closed(self):
- from kazoo.exceptions import ConnectionClosedError
- retry = self._makeOne()
-
- def testit():
- raise ConnectionClosedError()
- self.assertRaises(ConnectionClosedError, retry, testit)
-
- def test_session_expired(self):
- from kazoo.exceptions import SessionExpiredError
- retry = self._makeOne(max_tries=1)
-
- def testit():
- raise SessionExpiredError()
- self.assertRaises(Exception, retry, testit)
diff --git a/slider-agent/src/main/python/kazoo/tests/test_security.py b/slider-agent/src/main/python/kazoo/tests/test_security.py
deleted file mode 100644
index 587c265..0000000
--- a/slider-agent/src/main/python/kazoo/tests/test_security.py
+++ /dev/null
@@ -1,41 +0,0 @@
-"""license: Apache License 2.0, see LICENSE for more details."""
-import unittest
-
-from nose.tools import eq_
-from kazoo.security import Permissions
-
-
-class TestACL(unittest.TestCase):
- def _makeOne(self, *args, **kwargs):
- from kazoo.security import make_acl
- return make_acl(*args, **kwargs)
-
- def test_read_acl(self):
- acl = self._makeOne("digest", ":", read=True)
- eq_(acl.perms & Permissions.READ, Permissions.READ)
-
- def test_all_perms(self):
- acl = self._makeOne("digest", ":", read=True, write=True,
- create=True, delete=True, admin=True)
- for perm in [Permissions.READ, Permissions.CREATE, Permissions.WRITE,
- Permissions.DELETE, Permissions.ADMIN]:
- eq_(acl.perms & perm, perm)
-
- def test_perm_listing(self):
- from kazoo.security import ACL
- f = ACL(15, 'fred')
- self.assert_('READ' in f.acl_list)
- self.assert_('WRITE' in f.acl_list)
- self.assert_('CREATE' in f.acl_list)
- self.assert_('DELETE' in f.acl_list)
-
- f = ACL(16, 'fred')
- self.assert_('ADMIN' in f.acl_list)
-
- f = ACL(31, 'george')
- self.assert_('ALL' in f.acl_list)
-
- def test_perm_repr(self):
- from kazoo.security import ACL
- f = ACL(16, 'fred')
- self.assert_("ACL(perms=16, acl_list=['ADMIN']" in repr(f))
diff --git a/slider-agent/src/main/python/kazoo/tests/test_threading_handler.py b/slider-agent/src/main/python/kazoo/tests/test_threading_handler.py
deleted file mode 100644
index 4de5781..0000000
--- a/slider-agent/src/main/python/kazoo/tests/test_threading_handler.py
+++ /dev/null
@@ -1,327 +0,0 @@
-"""license: Apache License 2.0, see LICENSE for more details."""
-import threading
-import unittest
-
-import mock
-from nose.tools import assert_raises
-from nose.tools import eq_
-from nose.tools import raises
-
-
-class TestThreadingHandler(unittest.TestCase):
- def _makeOne(self, *args):
- from kazoo.handlers.threading import SequentialThreadingHandler
- return SequentialThreadingHandler(*args)
-
- def _getAsync(self, *args):
- from kazoo.handlers.threading import AsyncResult
- return AsyncResult
-
- def test_proper_threading(self):
- h = self._makeOne()
- h.start()
- # In Python 3.3 _Event is gone, before Event is function
- event_class = getattr(threading, '_Event', threading.Event)
- assert isinstance(h.event_object(), event_class)
-
- def test_matching_async(self):
- h = self._makeOne()
- h.start()
- async = self._getAsync()
- assert isinstance(h.async_result(), async)
-
- def test_exception_raising(self):
- h = self._makeOne()
-
- @raises(h.timeout_exception)
- def testit():
- raise h.timeout_exception("This is a timeout")
- testit()
-
- def test_double_start_stop(self):
- h = self._makeOne()
- h.start()
- self.assertTrue(h._running)
- h.start()
- h.stop()
- h.stop()
- self.assertFalse(h._running)
-
-
-class TestThreadingAsync(unittest.TestCase):
- def _makeOne(self, *args):
- from kazoo.handlers.threading import AsyncResult
- return AsyncResult(*args)
-
- def _makeHandler(self):
- from kazoo.handlers.threading import SequentialThreadingHandler
- return SequentialThreadingHandler()
-
- def test_ready(self):
- mock_handler = mock.Mock()
- async = self._makeOne(mock_handler)
-
- eq_(async.ready(), False)
- async.set('val')
- eq_(async.ready(), True)
- eq_(async.successful(), True)
- eq_(async.exception, None)
-
- def test_callback_queued(self):
- mock_handler = mock.Mock()
- mock_handler.completion_queue = mock.Mock()
- async = self._makeOne(mock_handler)
-
- async.rawlink(lambda a: a)
- async.set('val')
-
- assert mock_handler.completion_queue.put.called
-
- def test_set_exception(self):
- mock_handler = mock.Mock()
- mock_handler.completion_queue = mock.Mock()
- async = self._makeOne(mock_handler)
- async.rawlink(lambda a: a)
- async.set_exception(ImportError('Error occured'))
-
- assert isinstance(async.exception, ImportError)
- assert mock_handler.completion_queue.put.called
-
- def test_get_wait_while_setting(self):
- mock_handler = mock.Mock()
- async = self._makeOne(mock_handler)
-
- lst = []
- bv = threading.Event()
- cv = threading.Event()
-
- def wait_for_val():
- bv.set()
- val = async.get()
- lst.append(val)
- cv.set()
- th = threading.Thread(target=wait_for_val)
- th.start()
- bv.wait()
-
- async.set('fred')
- cv.wait()
- eq_(lst, ['fred'])
- th.join()
-
- def test_get_with_nowait(self):
- mock_handler = mock.Mock()
- async = self._makeOne(mock_handler)
- timeout = self._makeHandler().timeout_exception
-
- @raises(timeout)
- def test_it():
- async.get(block=False)
- test_it()
-
- @raises(timeout)
- def test_nowait():
- async.get_nowait()
- test_nowait()
-
- def test_get_with_exception(self):
- mock_handler = mock.Mock()
- async = self._makeOne(mock_handler)
-
- lst = []
- bv = threading.Event()
- cv = threading.Event()
-
- def wait_for_val():
- bv.set()
- try:
- val = async.get()
- except ImportError:
- lst.append('oops')
- else:
- lst.append(val)
- cv.set()
- th = threading.Thread(target=wait_for_val)
- th.start()
- bv.wait()
-
- async.set_exception(ImportError)
- cv.wait()
- eq_(lst, ['oops'])
- th.join()
-
- def test_wait(self):
- mock_handler = mock.Mock()
- async = self._makeOne(mock_handler)
-
- lst = []
- bv = threading.Event()
- cv = threading.Event()
-
- def wait_for_val():
- bv.set()
- try:
- val = async.wait(10)
- except ImportError:
- lst.append('oops')
- else:
- lst.append(val)
- cv.set()
- th = threading.Thread(target=wait_for_val)
- th.start()
- bv.wait(10)
-
- async.set("fred")
- cv.wait(15)
- eq_(lst, [True])
- th.join()
-
- def test_set_before_wait(self):
- mock_handler = mock.Mock()
- async = self._makeOne(mock_handler)
-
- lst = []
- cv = threading.Event()
- async.set('fred')
-
- def wait_for_val():
- val = async.get()
- lst.append(val)
- cv.set()
- th = threading.Thread(target=wait_for_val)
- th.start()
- cv.wait()
- eq_(lst, ['fred'])
- th.join()
-
- def test_set_exc_before_wait(self):
- mock_handler = mock.Mock()
- async = self._makeOne(mock_handler)
-
- lst = []
- cv = threading.Event()
- async.set_exception(ImportError)
-
- def wait_for_val():
- try:
- val = async.get()
- except ImportError:
- lst.append('ooops')
- else:
- lst.append(val)
- cv.set()
- th = threading.Thread(target=wait_for_val)
- th.start()
- cv.wait()
- eq_(lst, ['ooops'])
- th.join()
-
- def test_linkage(self):
- mock_handler = mock.Mock()
- async = self._makeOne(mock_handler)
- cv = threading.Event()
-
- lst = []
-
- def add_on():
- lst.append(True)
-
- def wait_for_val():
- async.get()
- cv.set()
-
- th = threading.Thread(target=wait_for_val)
- th.start()
-
- async.rawlink(add_on)
- async.set('fred')
- assert mock_handler.completion_queue.put.called
- async.unlink(add_on)
- cv.wait()
- eq_(async.value, 'fred')
- th.join()
-
- def test_linkage_not_ready(self):
- mock_handler = mock.Mock()
- async = self._makeOne(mock_handler)
-
- lst = []
-
- def add_on():
- lst.append(True)
-
- async.set('fred')
- assert not mock_handler.completion_queue.called
- async.rawlink(add_on)
- assert mock_handler.completion_queue.put.called
-
- def test_link_and_unlink(self):
- mock_handler = mock.Mock()
- async = self._makeOne(mock_handler)
-
- lst = []
-
- def add_on():
- lst.append(True)
-
- async.rawlink(add_on)
- assert not mock_handler.completion_queue.put.called
- async.unlink(add_on)
- async.set('fred')
- assert not mock_handler.completion_queue.put.called
-
- def test_captured_exception(self):
- from kazoo.handlers.utils import capture_exceptions
-
- mock_handler = mock.Mock()
- async = self._makeOne(mock_handler)
-
- @capture_exceptions(async)
- def exceptional_function():
- return 1/0
-
- exceptional_function()
-
- assert_raises(ZeroDivisionError, async.get)
-
- def test_no_capture_exceptions(self):
- from kazoo.handlers.utils import capture_exceptions
-
- mock_handler = mock.Mock()
- async = self._makeOne(mock_handler)
-
- lst = []
-
- def add_on():
- lst.append(True)
-
- async.rawlink(add_on)
-
- @capture_exceptions(async)
- def regular_function():
- return True
-
- regular_function()
-
- assert not mock_handler.completion_queue.put.called
-
- def test_wraps(self):
- from kazoo.handlers.utils import wrap
-
- mock_handler = mock.Mock()
- async = self._makeOne(mock_handler)
-
- lst = []
-
- def add_on(result):
- lst.append(result.get())
-
- async.rawlink(add_on)
-
- @wrap(async)
- def regular_function():
- return 'hello'
-
- assert regular_function() == 'hello'
- assert mock_handler.completion_queue.put.called
- assert async.get() == 'hello'
diff --git a/slider-agent/src/main/python/kazoo/tests/test_watchers.py b/slider-agent/src/main/python/kazoo/tests/test_watchers.py
deleted file mode 100644
index 44795c4..0000000
--- a/slider-agent/src/main/python/kazoo/tests/test_watchers.py
+++ /dev/null
@@ -1,490 +0,0 @@
-"""license: Apache License 2.0, see LICENSE for more details."""
-import time
-import threading
-import uuid
-
-from nose.tools import eq_
-from nose.tools import raises
-
-from kazoo.exceptions import KazooException
-from kazoo.protocol.states import EventType
-from kazoo.testing import KazooTestCase
-
-
-class KazooDataWatcherTests(KazooTestCase):
- def setUp(self):
- super(KazooDataWatcherTests, self).setUp()
- self.path = "/" + uuid.uuid4().hex
- self.client.ensure_path(self.path)
-
- def test_data_watcher(self):
- update = threading.Event()
- data = [True]
-
- # Make it a non-existent path
- self.path += 'f'
-
- @self.client.DataWatch(self.path)
- def changed(d, stat):
- data.pop()
- data.append(d)
- update.set()
-
- update.wait(10)
- eq_(data, [None])
- update.clear()
-
- self.client.create(self.path, b'fred')
- update.wait(10)
- eq_(data[0], b'fred')
- update.clear()
-
- def test_data_watcher_once(self):
- update = threading.Event()
- data = [True]
-
- # Make it a non-existent path
- self.path += 'f'
-
- dwatcher = self.client.DataWatch(self.path)
-
- @dwatcher
- def changed(d, stat):
- data.pop()
- data.append(d)
- update.set()
-
- update.wait(10)
- eq_(data, [None])
- update.clear()
-
- @raises(KazooException)
- def test_it():
- @dwatcher
- def func(d, stat):
- data.pop()
- test_it()
-
- def test_data_watcher_with_event(self):
- # Test that the data watcher gets passed the event, if it
- # accepts three arguments
- update = threading.Event()
- data = [True]
-
- # Make it a non-existent path
- self.path += 'f'
-
- @self.client.DataWatch(self.path)
- def changed(d, stat, event):
- data.pop()
- data.append(event)
- update.set()
-
- update.wait(10)
- eq_(data, [None])
- update.clear()
-
- self.client.create(self.path, b'fred')
- update.wait(10)
- eq_(data[0].type, EventType.CREATED)
- update.clear()
-
- def test_func_style_data_watch(self):
- update = threading.Event()
- data = [True]
-
- # Make it a non-existent path
- path = self.path + 'f'
-
- def changed(d, stat):
- data.pop()
- data.append(d)
- update.set()
- self.client.DataWatch(path, changed)
-
- update.wait(10)
- eq_(data, [None])
- update.clear()
-
- self.client.create(path, b'fred')
- update.wait(10)
- eq_(data[0], b'fred')
- update.clear()
-
- def test_datawatch_across_session_expire(self):
- update = threading.Event()
- data = [True]
-
- @self.client.DataWatch(self.path)
- def changed(d, stat):
- data.pop()
- data.append(d)
- update.set()
-
- update.wait(10)
- eq_(data, [b""])
- update.clear()
-
- self.expire_session()
- self.client.retry(self.client.set, self.path, b'fred')
- update.wait(25)
- eq_(data[0], b'fred')
-
- def test_func_stops(self):
- update = threading.Event()
- data = [True]
-
- self.path += "f"
-
- fail_through = []
-
- @self.client.DataWatch(self.path)
- def changed(d, stat):
- data.pop()
- data.append(d)
- update.set()
- if fail_through:
- return False
-
- update.wait(10)
- eq_(data, [None])
- update.clear()
-
- fail_through.append(True)
- self.client.create(self.path, b'fred')
- update.wait(10)
- eq_(data[0], b'fred')
- update.clear()
-
- self.client.set(self.path, b'asdfasdf')
- update.wait(0.2)
- eq_(data[0], b'fred')
-
- d, stat = self.client.get(self.path)
- eq_(d, b'asdfasdf')
-
- def test_no_such_node(self):
- args = []
-
- @self.client.DataWatch("/some/path")
- def changed(d, stat):
- args.extend([d, stat])
-
- eq_(args, [None, None])
-
- def test_bad_watch_func2(self):
- counter = 0
-
- @self.client.DataWatch(self.path)
- def changed(d, stat):
- if counter > 0:
- raise Exception("oops")
-
- raises(Exception)(changed)
-
- counter += 1
- self.client.set(self.path, b'asdfasdf')
-
- def test_watcher_evaluating_to_false(self):
- class WeirdWatcher(list):
- def __call__(self, *args):
- self.called = True
- watcher = WeirdWatcher()
- self.client.DataWatch(self.path, watcher)
- self.client.set(self.path, b'mwahaha')
- self.assertTrue(watcher.called)
-
- def test_watcher_repeat_delete(self):
- a = []
- ev = threading.Event()
-
- self.client.delete(self.path)
-
- @self.client.DataWatch(self.path)
- def changed(val, stat):
- a.append(val)
- ev.set()
-
- eq_(a, [None])
- ev.wait(10)
- ev.clear()
- self.client.create(self.path, b'blah')
- ev.wait(10)
- eq_(ev.is_set(), True)
- ev.clear()
- eq_(a, [None, b'blah'])
- self.client.delete(self.path)
- ev.wait(10)
- eq_(ev.is_set(), True)
- ev.clear()
- eq_(a, [None, b'blah', None])
- self.client.create(self.path, b'blah')
- ev.wait(10)
- eq_(ev.is_set(), True)
- ev.clear()
- eq_(a, [None, b'blah', None, b'blah'])
-
- def test_watcher_with_closing(self):
- a = []
- ev = threading.Event()
-
- self.client.delete(self.path)
-
- @self.client.DataWatch(self.path)
- def changed(val, stat):
- a.append(val)
- ev.set()
- eq_(a, [None])
-
- b = False
- try:
- self.client.stop()
- except:
- b = True
- eq_(b, False)
-
-
-class KazooChildrenWatcherTests(KazooTestCase):
- def setUp(self):
- super(KazooChildrenWatcherTests, self).setUp()
- self.path = "/" + uuid.uuid4().hex
- self.client.ensure_path(self.path)
-
- def test_child_watcher(self):
- update = threading.Event()
- all_children = ['fred']
-
- @self.client.ChildrenWatch(self.path)
- def changed(children):
- while all_children:
- all_children.pop()
- all_children.extend(children)
- update.set()
-
- update.wait(10)
- eq_(all_children, [])
- update.clear()
-
- self.client.create(self.path + '/' + 'smith')
- update.wait(10)
- eq_(all_children, ['smith'])
- update.clear()
-
- self.client.create(self.path + '/' + 'george')
- update.wait(10)
- eq_(sorted(all_children), ['george', 'smith'])
-
- def test_child_watcher_once(self):
- update = threading.Event()
- all_children = ['fred']
-
- cwatch = self.client.ChildrenWatch(self.path)
-
- @cwatch
- def changed(children):
- while all_children:
- all_children.pop()
- all_children.extend(children)
- update.set()
-
- update.wait(10)
- eq_(all_children, [])
- update.clear()
-
- @raises(KazooException)
- def test_it():
- @cwatch
- def changed_again(children):
- update.set()
- test_it()
-
- def test_child_watcher_with_event(self):
- update = threading.Event()
- events = [True]
-
- @self.client.ChildrenWatch(self.path, send_event=True)
- def changed(children, event):
- events.pop()
- events.append(event)
- update.set()
-
- update.wait(10)
- eq_(events, [None])
- update.clear()
-
- self.client.create(self.path + '/' + 'smith')
- update.wait(10)
- eq_(events[0].type, EventType.CHILD)
- update.clear()
-
- def test_func_style_child_watcher(self):
- update = threading.Event()
- all_children = ['fred']
-
- def changed(children):
- while all_children:
- all_children.pop()
- all_children.extend(children)
- update.set()
-
- self.client.ChildrenWatch(self.path, changed)
-
- update.wait(10)
- eq_(all_children, [])
- update.clear()
-
- self.client.create(self.path + '/' + 'smith')
- update.wait(10)
- eq_(all_children, ['smith'])
- update.clear()
-
- self.client.create(self.path + '/' + 'george')
- update.wait(10)
- eq_(sorted(all_children), ['george', 'smith'])
-
- def test_func_stops(self):
- update = threading.Event()
- all_children = ['fred']
-
- fail_through = []
-
- @self.client.ChildrenWatch(self.path)
- def changed(children):
- while all_children:
- all_children.pop()
- all_children.extend(children)
- update.set()
- if fail_through:
- return False
-
- update.wait(10)
- eq_(all_children, [])
- update.clear()
-
- fail_through.append(True)
- self.client.create(self.path + '/' + 'smith')
- update.wait(10)
- eq_(all_children, ['smith'])
- update.clear()
-
- self.client.create(self.path + '/' + 'george')
- update.wait(0.5)
- eq_(all_children, ['smith'])
-
- def test_child_watch_session_loss(self):
- update = threading.Event()
- all_children = ['fred']
-
- @self.client.ChildrenWatch(self.path)
- def changed(children):
- while all_children:
- all_children.pop()
- all_children.extend(children)
- update.set()
-
- update.wait(10)
- eq_(all_children, [])
- update.clear()
-
- self.client.create(self.path + '/' + 'smith')
- update.wait(10)
- eq_(all_children, ['smith'])
- update.clear()
- self.expire_session()
-
- self.client.retry(self.client.create,
- self.path + '/' + 'george')
- update.wait(20)
- eq_(sorted(all_children), ['george', 'smith'])
-
- def test_child_stop_on_session_loss(self):
- update = threading.Event()
- all_children = ['fred']
-
- @self.client.ChildrenWatch(self.path, allow_session_lost=False)
- def changed(children):
- while all_children:
- all_children.pop()
- all_children.extend(children)
- update.set()
-
- update.wait(10)
- eq_(all_children, [])
- update.clear()
-
- self.client.create(self.path + '/' + 'smith')
- update.wait(10)
- eq_(all_children, ['smith'])
- update.clear()
- self.expire_session()
-
- self.client.retry(self.client.create,
- self.path + '/' + 'george')
- update.wait(4)
- eq_(update.is_set(), False)
- eq_(all_children, ['smith'])
-
- children = self.client.get_children(self.path)
- eq_(sorted(children), ['george', 'smith'])
-
- def test_bad_children_watch_func(self):
- counter = 0
-
- @self.client.ChildrenWatch(self.path)
- def changed(children):
- if counter > 0:
- raise Exception("oops")
-
- raises(Exception)(changed)
- counter += 1
- self.client.create(self.path + '/' + 'smith')
-
-
-class KazooPatientChildrenWatcherTests(KazooTestCase):
- def setUp(self):
- super(KazooPatientChildrenWatcherTests, self).setUp()
- self.path = "/" + uuid.uuid4().hex
-
- def _makeOne(self, *args, **kwargs):
- from kazoo.recipe.watchers import PatientChildrenWatch
- return PatientChildrenWatch(*args, **kwargs)
-
- def test_watch(self):
- self.client.ensure_path(self.path)
- watcher = self._makeOne(self.client, self.path, 0.1)
- result = watcher.start()
- children, asy = result.get()
- eq_(len(children), 0)
- eq_(asy.ready(), False)
-
- self.client.create(self.path + '/' + 'fred')
- asy.get(timeout=1)
- eq_(asy.ready(), True)
-
- def test_exception(self):
- from kazoo.exceptions import NoNodeError
- watcher = self._makeOne(self.client, self.path, 0.1)
- result = watcher.start()
-
- @raises(NoNodeError)
- def testit():
- result.get()
- testit()
-
- def test_watch_iterations(self):
- self.client.ensure_path(self.path)
- watcher = self._makeOne(self.client, self.path, 0.5)
- result = watcher.start()
- eq_(result.ready(), False)
-
- time.sleep(0.08)
- self.client.create(self.path + '/' + uuid.uuid4().hex)
- eq_(result.ready(), False)
- time.sleep(0.08)
- eq_(result.ready(), False)
- self.client.create(self.path + '/' + uuid.uuid4().hex)
- time.sleep(0.08)
- eq_(result.ready(), False)
-
- children, asy = result.get()
- eq_(len(children), 2)
diff --git a/slider-agent/src/main/python/kazoo/tests/util.py b/slider-agent/src/main/python/kazoo/tests/util.py
deleted file mode 100644
index 906cbc0..0000000
--- a/slider-agent/src/main/python/kazoo/tests/util.py
+++ /dev/null
@@ -1,127 +0,0 @@
-"""license: Apache License 2.0, see LICENSE for more details."""
-##############################################################################
-#
-# Copyright Zope Foundation and Contributors.
-# All Rights Reserved.
-#
-# This software is subject to the provisions of the Zope Public License,
-# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
-# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
-# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
-# FOR A PARTICULAR PURPOSE.
-#
-##############################################################################
-
-import logging
-import os
-import time
-
-TRAVIS = os.environ.get('TRAVIS', False)
-TRAVIS_ZK_VERSION = TRAVIS and os.environ.get('ZOOKEEPER_VERSION', None)
-if TRAVIS_ZK_VERSION:
- TRAVIS_ZK_VERSION = tuple([int(n) for n in TRAVIS_ZK_VERSION.split('.')])
-
-
-class Handler(logging.Handler):
-
- def __init__(self, *names, **kw):
- logging.Handler.__init__(self)
- self.names = names
- self.records = []
- self.setLoggerLevel(**kw)
-
- def setLoggerLevel(self, level=1):
- self.level = level
- self.oldlevels = {}
-
- def emit(self, record):
- self.records.append(record)
-
- def clear(self):
- del self.records[:]
-
- def install(self):
- for name in self.names:
- logger = logging.getLogger(name)
- self.oldlevels[name] = logger.level
- logger.setLevel(self.level)
- logger.addHandler(self)
-
- def uninstall(self):
- for name in self.names:
- logger = logging.getLogger(name)
- logger.setLevel(self.oldlevels[name])
- logger.removeHandler(self)
-
- def __str__(self):
- return '\n'.join(
- [("%s %s\n %s" %
- (record.name, record.levelname,
- '\n'.join([line
- for line in record.getMessage().split('\n')
- if line.strip()])
- )
- )
- for record in self.records]
- )
-
-
-class InstalledHandler(Handler):
-
- def __init__(self, *names, **kw):
- Handler.__init__(self, *names, **kw)
- self.install()
-
-
-class Wait(object):
-
- class TimeOutWaitingFor(Exception):
- "A test condition timed out"
-
- timeout = 9
- wait = .01
-
- def __init__(self, timeout=None, wait=None, exception=None,
- getnow=(lambda: time.time), getsleep=(lambda: time.sleep)):
-
- if timeout is not None:
- self.timeout = timeout
-
- if wait is not None:
- self.wait = wait
-
- if exception is not None:
- self.TimeOutWaitingFor = exception
-
- self.getnow = getnow
- self.getsleep = getsleep
-
- def __call__(self, func=None, timeout=None, wait=None, message=None):
- if func is None:
- return lambda func: self(func, timeout, wait, message)
-
- if func():
- return
-
- now = self.getnow()
- sleep = self.getsleep()
- if timeout is None:
- timeout = self.timeout
- if wait is None:
- wait = self.wait
- wait = float(wait)
-
- deadline = now() + timeout
- while 1:
- sleep(wait)
- if func():
- return
- if now() > deadline:
- raise self.TimeOutWaitingFor(
- message or
- getattr(func, '__doc__') or
- getattr(func, '__name__')
- )
-
-wait = Wait()