# Copyright 2009-2011 Ram Rachum.
# This program is distributed under the LGPL2.1 license.

'''Testing package for `garlicsim_wx`.'''

def __bootstrap():
    '''
    Add needed packages in repo to path if we can't find them.

    This adds `garlicsim`'s, `garlicsim_lib`'s and `garlicsim_wx`'s root
    folders to `sys.path` if they can't currently be imported.
    '''
    import os
    import sys
    from garlicsim.general_misc import import_tools
    if not import_tools.exists('garlicsim'):
        garlicsim_candidate_path = os.path.realpath(
            os.path.join(
                os.path.split(__file__)[0],
                '..',
                '..',
                'garlicsim'
            )
        )
        sys.path.append(garlicsim_candidate_path)
    if not import_tools.exists('garlicsim_lib'):

garlicsim_lib_candidate_path = os.path.realpath(
            os.path.join(
                os.path.split(__file__)[0],
                '..',
                '..',
                'garlicsim_lib'
            )
        )
        sys.path.append(garlicsim_lib_candidate_path)

    if not import_tools.exists('garlicsim_wx'):
        garlicsim_wx_candidate_path = os.path.realpath(
            os.path.join(
                os.path.split(__file__)[0],
                '..',
                '..',
                'garlicsim_wx'
            )
        )
        sys.path.append(garlicsim_wx_candidate_path)

__bootstrap()


import wx
import wx.lib.agw.aui as aui
from wx.lib.agw.aui import *

class MyFrame(wx.Frame):

    def __init__(self, parent, id=-1, title="AUI Test", pos=wx.DefaultPosition,
                 size=(800, 600), style=wx.DEFAULT_FRAME_STYLE):

        wx.Frame.__init__(self, parent, id, title, pos, size, style)

        self._mgr = aui.AuiManager()

        # notify AUI which frame to use
        self._mgr.SetManagedWindow(self)

        # create several text controls
        text1 = wx.TextCtrl(self, -1, "Pane 1 - sample text",
                            wx.DefaultPosition, wx.Size(200,150),
                            wx.NO_BORDER | wx.TE_MULTILINE)

        text2 = wx.TextCtrl(self, -1, "Pane 2 - sample text",
                            wx.DefaultPosition, wx.Size(200,150),
                            wx.NO_BORDER | wx.TE_MULTILINE)

        text3 = wx.TextCtrl(self, -1, "Main content window",
                            wx.DefaultPosition, wx.Size(200,150),
                            wx.NO_BORDER | wx.TE_MULTILINE)

        # add the panes to the manager
        self._mgr.AddPane(text1, AuiPaneInfo().Left().Caption("Pane Number One"))
        self._mgr.AddPane(text2, AuiPaneInfo().Bottom().Caption("Pane Number Two"))
        self._mgr.AddPane(text3, AuiPaneInfo().CenterPane())

        # tell the manager to "commit" all the changes just made
        self._mgr.Update()

        sel

f.Bind(wx.EVT_CLOSE, self.OnClose)

    def OnClose(self, event):

        # deinitialize the frame manager
        self._mgr.UnInit()

        self.Destroy()
        event.Skip()

# our normal wxApp-derived class, as usual

app = wx.PySimpleApp()

frame = MyFrame(None)
app.SetTopWindow(frame)
frame.Show()

app.MainLoop()


# Copyright 2009-2010 Ram Rachum.
# This program is distributed under the LGPL2.1 license.

'''This module defines miscellaneous tools.'''

import math

def frange(start, finish=None, step=1.):
    '''
    Make a list containing an arithmetic progression of numbers.

    This is an extension of the builtin `range`; It allows using floating point
    numbers.
    '''
    if finish is None:
        finish, start = start, 0.
    else:
        start = float(start)

    count = int(math.ceil(finish - start)/step)
    return (start + n*step for n in range(count))

def shorten_class_address(module_name, class_name):
    '''
    Shorten the address of a class.

    This is mostly used in `__repr__` methods of various classes to shorten the
    text and make the final output more conscise. For example, if you have a
    class `garlicsim.asynchronous_crunching.project.Project`, but which is also
    available as `garlicsim.Project`, this function will return
    'garlicsim.Project'.
    '''
    get_module = lambda module_name: __import__(module_name, fromlist=[''])
    original_module = get_module(module_name)
    original_class = getattr(original_module, class_name)

    current_module_name = module_name

    last_successful_module_name = current_module_name

    while True:
        # Removing the last submodule from the module name:
        current_module_name = '.'.join(current_module_name.split('.')[:-1])

        if not current_module_name:
            # We've reached the top module and it's successful, can break now.
            break

        current_module = get_module(current_module_name)

        candidate_class = getattr(current_module, class_name, None)

        if candidate_class is original_class:
            last_successful_module_name = current_module_name
        else:
            break

    return '.'.join((last_successful_module_name, class_name))

def get_object_from_address(address, parent_object=None):
    if not parent_object:
        if '.' not in address:
            try:

return eval(address)
            except NameError:
                return __import__(address, fromlist=[''])

        else: # '.' in address
            first_object_address, second_object_address = \
                address.rsplit('.', 1)
            first_object = get_object_from_address(first_object_address)
            second_object = get_object_from_address(second_object_address,
                                                    parent_object=first_object)
            return second_object

    else: # parent_object is not none
        if '.' not in address:
            if isinstance(parent_object, types.ModuleType):
                import_tools.import_if_exists(
                    '.'.join(parent_object.__name__, address)
                )
                # Not keeping reference, just importing so we could get later
            return getattr(parent_object, address)
        else: # '.' in address
            first_object_address, second_object_address = \
                address.rsplit('.', 1)
            first_object = get_object_from_address(first_object_address, parent_object)
            second_object = get_object_from_address(second_object_address,
                                                    parent_object=first_object)
            return second_object

class LazilyEvaluatedConstantProperty(object):
    '''
    A property that is calculated (a) lazily and (b) only once for an object.

    Usage:

        class MyObject(object):

            # ... Regular definitions here

            def _get_personality(self):
                print('Calculating personality...')
                time.sleep(5) # Time consuming process that creates personality
                return 'Nice person'

            personality = LazilyEvaluatedConstantProperty(_get_personality)

    '''
    def __init__(self, getter, name=None):
        '''
        Construct the LEC-property.

        You may optionally pass in the name the this property has in the class;
        This will save a bit of processing later.
        '''
        self.getter = getter
        self.our_name = name

    def __get__(self, obj, our_type=None):

        value = self.getter(obj)

        if not self.our_name:
            if not our_type:
                our_type = type(obj)
            (self.our_name,) = (key for (key, value) in
                                vars(our_type).iteritems()
                                if value is self)

        setattr(obj, self.our_name, value)

        return value

def getted_vars(thing):
    # todo: can make "fallback" option, to use value from original `vars` if get
    # is unsuccessful.
    my_vars = vars(thing)
    return dict((name, getattr(thing, name)) for name in my_vars.iterkeys())

if __name__ == '__main__': # todo: move to test suite
    import random
    class A(object):
        def _get_personality(self):
            print(
                "Calculating personality for %s. (Should happen only once.)" % self
            )
            return random.choice(['Angry', 'Happy', 'Sad', 'Excited'])
        personality = LazilyEvaluatedConstantProperty(_get_personality)
    a = A()
    print(a.personality)
    print(a.personality)
    print(a.personality)

    a2 = A()
    print(a2.personality)
    print(a2.personality)
    print(a2.personality)


# Copyright 2009 Ram Rachum.
# This program is distributed under the LGPL2.1 license.

"""
This module defines the Project class. See its documentation for more
information.
"""

import garlicsim.data_structures
import garlicsim.simpack_grokker
import crunching_manager

import garlicsim.misc.read_write_lock as read_write_lock
from garlicsim.misc.infinity import Infinity
import garlicsim.misc.module_wrapper
import garlicsim.misc.cool_dict

__all__ = ["Project"]

class Project(object):
    """
    You create a project when you want to do a simulation which will crunch
    in the background with worker threads or worker processes.

    A project contains within it a tree.

    The crunching is taken care of by the CrunchingManager which is a part of
    every project. The CrunchingManager employs CruncherThreads and/or
    CruncherProcesses to get the work done. To make the CrunchingManager take
    work from the crunchers and coordinate them, call the sync_crunchers method
    of the project.

    What the crunching manager's sync_crunchers method will do is check the
    attribute .nodes_to_crunch of the project. This attribute is a dict-like
    object which maps nodes that should be crunched to a number specifying how
    many states should be crunched from this node. The crunching manager will
    then coordinate the crunchers in order to do this work. It will update the
    .nodes_to_crunch attribute when the crunchers have completed some of the
    work.
    """

    def __init__(self, simpack):

        wrapped_simpack = \
            garlicsim.misc.module_wrapper.module_wrapper_factory(simpack)

        self.simpack_grokker = \
            garlicsim.simpack_grokker.SimpackGrokker(wrapped_simpack)

        self.simpack = wrapped_simpack

        self.tree = garlicsim.data_structures.Tree()

        self.crunching_manager = crunching_manager.CrunchingManager(self)

        self.tree_lock = read_write_lock.ReadWriteLock()
        """
        The tree_lock is a read-write lock that guards access to the tree.
        We need such a thing because some simulations are history-dependent
        and require reading from the tree in the same time that sync_crunchers
        could potentially be writing to it.
        """

        self.nodes_to_crunch = garlicsim.misc.cool_dict.CoolDict()
        """
        A dict that maps leaves that should be worked on to a number specifying
        how many nodes should be created after them.
        """

    def make_plain_root(self, *args, **kwargs):
        """
        Creates a parentless node, whose state is a simple plain state.
        The simulation package should define the function `make_plain_state`
        for this to work.
        Returns the node.
        """
        state = self.simpack.make_plain_state(*args, **kwargs)
        return self.root_this_state(state)

    def make_random_root(self, *args, **kwargs):
        """
        Creates a parentless node, whose state is a random and messy state.
        The simulation package should define the function `make_random_state`
        for this to work.
        Returns the node.
        """
        state = self.simpack.make_random_state(*args, **kwargs)
        return self.root_this_state(state)

    def root_this_state(self, state):
        """
        Takes a state, wraps it in a node and adds to the tree without a
        parent.
        Returns the node.
        """
        return self.tree.add_state(state)

    def crunch_all_leaves(self, node, wanted_distance):
        """
        Orders to start crunching from all the leaves of `node`, so that there
        will be a buffer whose length is at least `wanted_distance`.
        """
        leaves = node.get_all_leaves(wanted_distance)
        for (leaf, distance) in leaves.items():
            new_distance = wanted_distance - distance
            self.nodes_to_crunch.raise_to(leaf, new_distance)

    def sync_crunchers(self, temp_infinity_node=None):
        """
        Talks with all the crunchers, takes work from them for
        implementing into the tree, terminates crunchers or creates
        new crunchers if necessary.
        You can pass a node as `temp_infinity_node`. That will cause this
        function to temporarily treat this node as if it should be crunched
        indefinitely.

        Returns the total amount of nodes that were added to the tree.
        """

        return self.crunching_manager.sync_crunchers \
               (temp_infinity_node=temp_infinity_node)

    @with_tree_lock
    def simulate(self, node, iterations=1, *args, **kwargs):
        """
        Simulates from the given node for the given number of iterations,
        implementing the results into the tree. Note this is done
        synchronously, i.e. in the currrent thread.

        Any extraneous parameters will be passed to the step function.

        Returns the final node.
        """

        if self.simpack_grokker.history_dependent:
            return self.__history_dependent_simulate(node, iterations,
                                                     *args, **kwargs)
        else:
            return self.__non_history_dependent_simulate(node, iterations,
                                                         *args, **kwargs)

    def __history_dependent_simulate(self, node, iterations=1,
                                     *args, **kwargs):
        """
        For history-dependent simulations only:

        Simulates from the given node for the given number of iterations,
        implementing the results into the tree. Note this is done
        synchronously, i.e. in the currrent thread.

        Any extraneous parameters will be passed to the step function.

        Returns the final node.
        """

        path = node.make_containing_path()
        history_browser = garlicsim.synchronous_crunching.\
                        history_browser.HistoryBrowser(path)
        current_node = node
        state = node.state
        for i in range(iterations):

state = self.simpack_grokker.step(history_browser,
                                              *args, **kwargs)
            current_node = self.tree.add_state(state, parent=current_node)

        return current_node

    def __non_history_dependent_simulate(self, node, iterations=1,
                                         *args, **kwargs):
        """
        For non-history-dependent simulations only:

        Simulates from the given node for the given number of iterations,
        implementing the results into the tree. Note this is done
        synchronously, i.e. in the currrent thread.

        Any extraneous parameters will be passed to the step function.

        Returns the final node.
        """

        current_node = node
        state = node.state
        for i in range(iterations):
            state = self.simpack_grokker.step(state, *args, **kwargs)
            current_node = self.tree.add_state(state, parent=current_node)

        return current_node

    def __getstate__(self):
        my_dict = dict(self.__dict__)

        del my_dict["tree_lock"]
        del my_dict["crunching_manager"]

        return my_dict

    def __setstate__(self, pickled_project):
        self.__init__(pickled_project["simpack"])
        self.__dict__.update(pickled_project)


# Copyright 2009 Ram Rachum.
# This program is distributed under the LGPL2.1 license.

"""
This module defines a variable Infinity which simply stands for float("inf").
The only reason for this alias is to make code more readable.
"""
Infinity = float("inf")

class FunnyInfinityClass(object):
    def __init__(self):
        self.added = 0
        self.sign = 1
    def __add__(self, other):
        if is_a_number(other):
            result = cop

y.deepcopy(self)
            result.added += other
            return result
        elif isinstance(other, FunnyInfinityClass):
            if self.sign == other.sign:
                raise NotImplementedError
            else:
                return self.added + other.added
        else:

            raise NotImplementedError
    def __cmp__(self, other):
        if is_a_number(other):
            return 1
        elif isinstance(other, FunnyInfinityClass):
            sign_comparison = cmp(self.sign, other.sign)
            if sign_comparison != 0:
                return sign_comparison
            else:
                return cmp(self.added, other.added)
        else:
            raise NotImplementedError
    def __neg__(self):
        result = copy.deepcopy(self)
        result.sign *= -1
    def __repr__(self):
        if self.added == 0:
            return "FunnyInfinity"
        else:
            return "(FunnyInfinity + %s)" % self.added

FunnyInfinity = FunnyInfinityClass()


# -*- coding: utf-8 -*-
"""
    tests.securecookie
    ~~~~~~~~~~~~~~~~~~

    Tests the secure cookie.

    :copyright: (c) 2014 by Armin Ronacher.
    :license: BSD, see LICENSE for more details.
"""

from werkzeug.utils import parse_cookie
from werkzeug.wrappers import Request, Response
from werkzeug.contrib.securecookie import SecureCookie

def test_basic_support():
    c = SecureCookie(secret_key=b'foo')
    assert c.new
    assert not c.modified
    assert not c.should_save
    c['x'] = 42
    assert c.modified
    assert c.should_save
    s = c.serialize()

    c2 = SecureCookie.unserialize(s, b'foo')
    assert c is not c2
    assert not c2.new
    assert not c2.modified
    assert not c2.should_save
    assert c2 == c

    c3 = SecureCookie.unserialize(s, b'wrong foo')
    assert not c3.modified
    assert not c3.new
    assert c3 == {}

    c4 = SecureCookie({'x': 42}, 'foo')
    c4_serialized = c4.serialize()
    assert SecureCookie.unserialize(c4_serialized, 'foo') == c4

def test_wrapper_support():
    req = Request.from_values()
    resp = Response()
    c = SecureCookie.load_cookie(req, secret_key=b'foo')
    assert c.new
    c['foo'] = 42
    assert c.secret_key == b'foo'
    c.save_cookie(resp)

    req = Request.from_values(headers={
        'Cookie':  'session="%s"' % parse_cookie(resp.headers['set-cookie'])['session']
    })
    c2 = SecureCookie.load_cookie(req, secret_key=b'foo')
    assert not c2.new
    assert c2 == c

def test_pickle_deprecated():
    with pytest.warns(UserWarning):
        SecureCookie({"foo": "bar"}, "secret").serialize()

def test_json():
    class JSONCompat(object):
        dumps = staticmethod(json.dumps)

@staticmethod
        def loads(s):
            # json on Python < 3.6 fails on bytes
            return json.loads(to_native(s, "utf8"))

    class JSONSecureCookie(SecureCookie):
        serialization_method = JSONCompat

    secure = JSONSecureCookie({"foo": "bar"}, "secret").serialize()
    data = JSONSecureCookie.unserialize(secure, "secret")
    assert data == {"foo": "bar"}


# -*- coding: utf-8 -*-
from os.path import join, dirname, abspath
from werkzeug import Client, Request, Response

@Request.application
def form_data_consumer(request):
    result_object = request.args['object']
    if result_object == 'text':
        return Response(repr(request.form['text']))
    f = request.files[result_object]
    return Response('\n'.join((
        repr(f.filename),
        repr(f.name),
        repr(f.content_type),
        f.stream.read()
    )))

def get_contents(filename):
    f = file(filename, 'rb')
    try:
        return f.read()
    finally:
        f.close()

def test_multipart():
    """Tests multipart parsing against data collected from webbrowsers"""
    resources = join(dirname(__file__), 'multipart')
    client = Client(form_data_consumer, Response)

    repository = [
        ('firefox3-2png1txt', '---------------------------186454651713519341951581030105', [
            (u'anchor.png', 'file1', 'image/png', 'file1.png'),
            (u'application_edit.png', 'file2', 'image/png', 'file2.png')
        ], u'example text'),
        ('firefox3-2pnglongtext', '---------------------------14904044739787191031754711748', [
            (u'accept.png', 'file1', 'image/png', 'file1.png'),
            (u'add.png', 'file2', 'image/png', 'file2.png')
        ], u'--long text\r\n--with boundary\r\n--lookalikes--'),
        ('opera8-2png1txt', '----------zEO9jQKmLc2Cq88c23Dx19', [
            (u'arrow_branch.png', 'file1', 'image/png', 'file1.png'),
            (u'award_star_bronze_1.png', 'file2', 'image/png', 'file2.png')
        ], u'blafasel öäü'),
        ('webkit3-2png1txt', '----WebKitFormBoundaryjdSFhcARk8fyGNy6', [
            (u'gtk-apply.png', 'file1', 'image/png', 'file1.png'),
            (u'gtk-no.png', 'file2', 'image/png', 'file2.png')
        ], u'this is another text with ümläüts'),
        ('ie6-2png1txt', '---------------------------7d91b03a20128', [
            (u'file1.png', 'file1', 'image/x-png', 'file1.png'),
            (u'file2.png', 'file2', 'image/x-png', 'file2.png')
        ], u'ie6 sucks :-/')
    ]

    for name, boundary, files, text in repository:
        folder = join(resources, name)
        data = get_contents(join(folder, 'request.txt'))
        for filename, field, content_type, fsname in files:
            response = client.post('/?object=' + field, data=data, content_type=
                                   'multipart/form-data; boundary="%s"' % boundary,
                                   content_length=len(data))
            lines = response.data.split('\n', 3)
            assert lines[0] == repr(filename)
            assert lines[1] == repr(field)
            assert lines[2] == repr(content_type)
            assert lines[3] == get_contents(join(folder, fsname))
        response = client.post('/?object=text', data=data, content_type=
                               'multipart/form-data; boundary="%s"' % boundary,
                               content_length=len(data))
        assert response.data == repr(text)

def test_limiting():
    """Test the limiting features."""
    data = 'foo=Hello+World&bar=baz'
    req = Request.from_values(input_stream=StringIO(data),
                              content_length=len(data),
                              content_type='application/x-www-form-urlencoded',
                              method='POST')
    req.max_content_length = 4

    req = Request.from_values(input_stream=StringIO(data),
                              content_length=len(data),
                              content_type='application/x-www-form-urlencoded',
                              method='POST')
    req.max_content_length = 400
    assert req.form['foo'] == 'Hello World'

    req = Request.from_values(input_stream=StringIO(data),
                              content_length=len(data),
                              content_type='application/x-www-form-urlencoded',
                              method='POST')
    req.max_form_memory_size = 7
    assert_raises(RequestEntityTooLarge, lambda: req.form['foo'])

    req = Request.from_values(input_stream=StringIO(data),
                              content_length=len(data),
                              content_type='application/x-www-form-urlencoded',
                              method='POST')
    req.max_form_memory_size = 400
    assert req.form['foo'] == 'Hello World'

    data = ('--foo\r\nContent-Disposition: form-field; name=foo\r\n\r\n'
            'Hello World\r\n'
            '--foo\r\nContent-Disposition: form-field; name=bar\r\n\r\n'
            'bar=baz\r\n--foo--')
    req = Request.from_values(input_stream=StringIO(data),
                              content_length=len(data),
                              content_type='multipart/form-data; boundary=foo',
                              method='POST')
    req.max_content_length = 4
    assert_raises(RequestEntityTooLarge, lambda: req.form['foo'])

    req = Request.from_values(input_stream=StringIO(data),
                              content_length=len(data),
                              content_type='multipart/form-data; boundary=foo',
                              method='POST')
    req.max_content_length = 400
    assert req.form['foo'] == 'Hello World'

    req = Request.from_values(input_stream=StringIO(data),
                              content_length=len(data),
                              content_type='multipart/form-data; boundary=foo',
                              method='POST')
    req.max_form_memory_size = 7
    assert_raises(RequestEntityTooLarge, lambda: req.form['foo'])

    req = Request.from_values(input_stream=StringIO(data),
                              content_length=len(data),


# -*- coding: utf-8 -*-
"""
    werkzeug.debug.util
    ~~~~~~~~~~~~~~~~~~~

    Debugging utilities.

    :copyright: 2007 by Georg Brandl, Armin Ronacher.
    :license: BSD, see LICENSE for more details.
"""
import os
import sys
import inspect
import threading
from random import random
from cStringIO import StringIO

from werkzeug.debug.highlighter import PythonParser

def get_current_thread():
    return threading.currentThread()

class Namespace(object):
    def __init__(self, **kwds):
        self.__dict__.update(kwds)

class ThreadedStream(object):
    _orig = None

    def __init__(self):
        self._buffer = {}

    def install(cls, environ):
        if cls._orig or not environ['wsgi.multithread']:
            return
        cls._orig = sys.stdout
        sys.stdout = cls()
    install = classmethod(install)

    def can_interact(cls):
        return not cls._orig is None
    can_interact = classmethod(can_interact)

    def push(self):
        tid = get_current_thread()
        self._buffer[tid] = StringIO()

    def release(self):
        tid = get_current_thread()
        if tid in self._buffer:
            result = self._buffer[tid].getvalue()
            del self._buffer[tid]
        else:
            result = ''
        return result

    def write(self, d):
        tid = get_current_thread()
        if tid in self._buffer:
            self._buffer[tid].write(d)
        else:
            self._orig.write(d)

def get_uid():
    """
    Return a random unique ID.
    """
    return str(random()).encode('base64')[3:11]

class PythonParser(object):
    """
    Simple python sourcecode highlighter.

    Usage::

        p = PythonParser(source)
        p.parse()
        for line in p.get_html_output():
            print line
    """

    _KEYWORD = token.NT_OFFSET + 1
    _TEXT    = token.NT_OFFSET + 2
    _classes = {
        token.NUMBER:       'num',
        token.OP:           'op',
        token.STRING:       'str',
        tokenize.COMMENT:   'cmt',
        token.NAME:         'id',
        token.ERRORTOKEN:   'error',
        _KEYWORD:           'kw',
        _TEXT:              'txt',
    }

    def __init__(self, raw):
        self.raw = raw.expandtabs(8)
        if isinstance(self.raw, unicode):
            self.raw = self.raw.encode('utf-8', 'ignore')
        self.out = StringIO()

    def parse(self):
        self.lines = [0, 0]
        pos = 0
        while 1:

pos = self.raw.find('\n', pos) + 1
            if not pos:
                break
            self.lines.append(pos)

self.lines.append(len(self.raw))

        self.pos = 0
        text = StringIO(self.raw)
        try:
            tokenize.tokenize(text.readline, self)
        except tokenize.TokenError:
            pass

    def get_html_output(self):
        """ Return line generator. """
        def html_splitlines(lines):
            # this cool function was taken from trac.
            # http://projects.edgewall.com/trac/
            open_tag_re = re.compile(r'<(\w+)(\s.*)?[^/]?>')
            close_tag_re = re.compile(r'</(\w+)>')
            open_tags = []
            for line in lines:
                for tag in open_tags:
                    line = tag.group(0) + line
                open_tags = []
                for tag in open_tag_re.finditer(line):
                    open_tags.append(tag)
                open_tags.reverse()
                for ctag in close_tag_re.finditer(line):
                    for otag in open_tags:
                        if otag.group(1) == ctag.group(1):
                            open_tags.remove(otag)
                            break
                for tag in open_tags:
                    line += '</%s>' % tag.group(1)
                yield line

        return list(html_splitlines(self.out.getvalue().splitlines()))

    def __call__(self, toktype, toktext, (srow,scol), (erow,ecol), line):
        oldpos = self.pos
        newpos = self.lines[srow] + scol
        self.pos = newpos + len(toktext)

        if toktype in [token.NEWLINE, tokenize.NL]:
            self.out.write('\n')
            return

        if newpos > oldpos:
            self.out.write(self.raw[oldpos:newpos])

        if toktype in [token.INDENT, token.DEDENT]:
            self.pos = newpos
            return

        if token.LPAR <= toktype and toktype <= token.OP:
            toktype = token.OP
        elif toktype == token.NAME and keyword.iskeyword(toktext):
            toktype = self._KEYWORD
        clsname = self._classes.get(toktype, 'txt')

        self.out.write('' % clsname)
        self.out.write(escape(toktext))
        self.out.write('')

def get_frame_info(tb, context_lines=7):
    """
    Return a dict of information about a given traceback.
    """
    # line numbers / function / variables
    lineno = tb.tb_lineno
    function = tb.tb_frame.f_code.co_name
    variables = tb.tb_frame.f_locals

    # get filename
    fn = tb.tb_frame.f_globals.get('__file__')
    if not fn:
        fn = os.path.realpath(inspect.getsourcefile(tb) or
                              inspect.getfile(tb))
    if fn[-4:] in ('.pyc', '.pyo'):
        fn = fn[:-1]

    # module name
    modname = tb.tb_frame.f_globals.get('__name__')

    # get loader
    loader = tb.tb_frame.f_globals.get('__loader__')

    # sourcecode
    try:
        if not loader is None:
            source = loader.get_source(modname)
        else:
            source = file(fn).read()
    except:
        source = ''
        pre_context, post_context = [], []
        context_line, context_lineno = None, None
    else:
        parser = PythonParser(source)
        parser.parse()
        parsed_source = parser.get_html_output()
        lbound = max(0, lineno - context_lines - 1)
        ubound = lineno + context_lines
        try:
            context_line = parsed_source[lineno - 1]
            pre_context = parsed_source[lbound:lineno - 1]
            post_context = parsed_source[lineno:ubound]
        except IndexError, e:
            context_line = None
            pre_context = post_context = [], []
        context_lineno = lbound

    return {
        'tb':               tb,
        'filename':         isinstance(fn, unicode) and fn.encode('utf-8') or fn,
        'loader':           loader,
        'function':         function,
        'lineno':           lineno,
        'vars':             variables,
        'pre_context':      pre_context,
        'context_line':     context_line,
        'post_context':     post_context,
        'context_lineno':   context_lineno,
        'source':           source
    }


# -*- coding: utf-8 -*-
"""
    werkzeug.contrib.fixers
    ~~~~~~~~~~~~~~~~~~~~~~~

    .. versionadded:: 0.5

    This module includes various helpers that fix bugs in web servers.  They may
    be necessary for some versions of a buggy web server but not others.  We try
    to stay updated with the status of the bugs as good as possible but you have
    to make sure whether they fix the problem you encounter.

    If you notice bugs in webservers not fixed in this module consider
    contributing a patch.

    :copyright: Copyright 2009 by the Werkzeug Team, see AUTHORS for more details.
    :license: BSD, see LICENSE for more details.
"""
from urllib import unquote

class LighttpdCGIRootFix(object):
    """Wrap the application in this middleware if you are using lighttpd
    with FastCGI or CGI and the application is mounted on the URL root.
    """

    def __init__(self, app):
        self.app = app

    def __call__(self, environ, start_response):
        environ['PATH_INFO'] = environ.get('SCRIPT_NAME', '') + \
                               environ.get('PATH_INFO', '')
        environ['SCRIPT_NAME'] = ''
        return self.app(environ, start_response)

class PathInfoFromRequestUriFix(object):
    """On windows environment variables are limited to the system charset
    which makes it impossible to store the `PATH_INFO` variable in the
    environment without loss of information on some systems.

    This is for example a problem for CGI scripts on a Windows Apache.

    This fixer works by recreating the `PATH_INFO` from `REQUEST_URI`,
    `REQUEST_URL`, or `UNENCODED_URL` (whatever is available).  Thus the
    fix can only be applied if the webserver supports either of these
    variables.
    """

    def __init__(self, app):
        self.app = app

    def __call__(self, environ, start_response):
        for key in 'REQUEST_URL', 'REQUEST_URI', 'UNENCODED_URL':
            if key not in environ:
                continue
            request_uri = unquote(environ[key])
            script_name = unquote(environ.get('SCRIPT_NAME', ''))
            if request_uri.startswith(script_name):
                environ['PATH_INFO'] = request_uri[len(script_name):] \
                    .split('?', 1)[0]
                break
        return self.app(environ, start_response)

class ProxyFix(object):
    """This middleware can be applied to add HTTP proxy support to an
    application that was not designed with HTTP proxies in mind.  It
    sets `REMOTE_ADDR`, `HTTP_HOST` from `X-Forwarded` headers.

    Werkzeug wrappers have builtin support for this by setting the
    :attr:`~werkzeug.BaseRequest.is_behind_proxy` attribute to `True`.

    Do not use this middleware in non-proxy setups for security reasons.

    The original values of `REMOTE_ADDR` and `HTTP_HOST` are stored in
    the WSGI environment as `werkzeug.proxy_fix.orig_remote_addr` and
    `werkzeug.proxy_fix.orig_http_host`.
    """

    def __init__(self, app):
        self.app = app

    def __call__(self, environ, start_response):
        getter = environ.get
        forwarded_for = getter('HTTP_X_FORWARDED_FOR', '').split(',')
        forwarded_host = getter('HTTP_X_FORWARDED_HOST', '')
        environ.update({
            'werkzeug.proxy_fix.orig_remote_addr':  getter('REMOTE_ADDR'),
            'werkzeug.proxy_fix.orig_http_host':    getter('HTTP_HOST')
        })
        if forwarded_for:
            environ['REMOTE_ADDR'] = forwarded_for[0].strip()
        if forwarded_host:
            environ['HTTP_HOST'] = forwarded_host
        return self.app(environ, start_response)

class HeaderRewriterFix(object):
    """This middleware can remove response headers and add others.  This
    is for example useful to remove the `Date` header from responses if you
    are using a server that adds that header, no matter if it's present or
    not or to add `X-Powered-By` headers::

        app = HeaderRewriterFix(app, remove_headers=['Date'],
                                add_headers=[('X-Powered-By', 'WSGI')])

    :param app: the WSGI application
    :param remove_headers: a sequence of header keys that should be
                           removed.
    :param add_headers: a sequence of ``(key, value)`` tuples that should
                        be added.
    """

    def __init__(self, app, remove_headers=None, add_headers=None):
        self.app = app
        self.remove_headers = set(x.lower() for x in (remove_headers or ()))
        self.add_headers = list(add_headers or ())

    def __call__(self, environ, start_response):
        def

rewriting_start_response(status, headers, exc_info=None):
            new_headers = []
            for key, value in headers:
                if key.lower() not in self.remove_headers:
                    new_headers.append((key, value))
            new_headers += self.add_headers
            return start_response(status, new_headers, exc_info)


# -*- coding: utf-8 -*-
"""
    werkzeug.debug
    ~~~~~~~~~~~~~~

    WSGI application traceback debugger.

    :copyright: 2007 by Georg Brandl.
    :license: BSD, see LICENSE for more details.
"""
import sys
import inspect
import traceback
import code

from werkzeug.debug.render import debug_page, load_resource
from werkzeug.debug.util import ThreadedStream, Namespace, get_uid, \
     get_frame_info
from werkzeug.utils import url_decode

class DebuggedApplication(object):
    """
    Enables debugging support for a given application::

        from werkzeug.debug import DebuggedApplication
        from myapp import app
        app = DebuggedApplication(app, evalex=True)

    The `evalex` keyword argument allows evaluating expressions in a
    traceback's frame context.

    THIS IS A GAPING SECURITY HOLE IF PUBLICLY ACCESSIBLE!
    """

    def __init__(self, application, evalex=False):
        self.evalex = bool(evalex)
        self.application = application
        self.tracebacks = {}

    def __call__(self, environ, start_response):
        # exec code in open tracebacks or provide shared data
        if environ.get('PATH_INFO', '').strip('/').endswith('__traceback__'):
            parameters = url_decode(environ.get('QUERY_STRING', ''))
            # shared data
            if 'resource' in parameters and 'mimetype' in parameters:
                data = load_resource(parameters['resource'])
                start_response('200 OK', [
                    ('Content-Type', str(parameters['mimetype'])),
                    ('Content-Length', str(len(data)))
                ])
                yield data
                return
            # pastebin
            elif parameters.get('pastetb'):
                from xmlrpclib import ServerProxy
                try:

length = int(environ['CONTENT_LENGTH'])
                except (KeyError, ValueError):
                    length = 0

                data = environ['wsgi.input'].read(length)
                s = ServerProxy('http://paste.pocoo.org/xmlrpc/')
                paste_id = s.pastes.newPaste('pytb', data)
                start_response('200 OK', [('Content-Type', 'text/plain')])
                yield '{"paste_id": %d, "url": "%s"}' % (
                    paste_id,
                    'http://paste.pocoo.org/show/%d' % paste_id
                )
                return
            # execute commands in an existing debug context
            elif self.evalex:
                try:
                    tb = self.tracebacks[parameters['tb']]
                    frame = parameters['frame']
                    context = tb[frame]
                    code = parameters['code']
                except (IndexError, KeyError):
                    pass
                else:
                    result = context.exec_expr(code)
                    start_response('200 OK', [('Content-Type', 'text/plain')])
                    yield result
                    return

        # wrap the application and catch errors.
        appiter = None
        try:
            appiter = self.application(environ, start_response)
            for line in appiter:
                yield line
        except:
            ThreadedStream.install(environ)
            exc_info = sys.exc_info()
            try:
                headers = [('Content-Type', 'text/html; charset=utf-8')]
                start_response('500 INTERNAL SERVER ERROR', headers)
            except:
                pass
            debug_context = self.create_debug_context(environ, exc_info)
            yield debug_page(debug_context).encode('utf-8')

        if hasattr(appiter, 'close'):
            appiter.close()

    def create_debug_context(self, environ, exc_info):
        exception_type, exception_value, tb = exc_info
        # skip first internal frame
        if not tb.tb_next is None:
            tb = tb.tb_next
        plaintb = ''.join(traceback.format_exception(exception_type,
                                                     exception_value, tb))
        environ['wsgi.errors'].write(plaintb)

        # load frames
        frames = []
        frame_map = {}
        tb_uid = None
        if ThreadedStream.can_interact():
            tb_uid = get_uid()
            frame_map = self.tracebacks[tb_uid] = {}

        # walk through frames and collect information
        while tb is not None:
            if not tb.tb_frame.f_locals.get('__traceback_hide__', False):
                if tb_uid:
                    frame_uid = get_uid()
                    frame_map[frame_uid] = InteractiveDebugger(tb.tb_frame)
                else:
                    frame_uid = None
                frame = get_frame_info(tb)
                frame['frame_uid'] = frame_uid
                frames.append(frame)
            tb = tb.tb_next

        # guard for string exceptions
        if isinstance(exception_type, str):
            extypestr = 'string exception'
            exception_value = exception_type
        elif exception_type.__module__ == 'exceptions':
            extypestr = exception_type.__name__
        else:
            extypestr = '%s.%s' % (
                exception_type.__module__,
                exception_type.__name__
            )

        # support for the werkzeug request object or fall back to
        # WSGI environment
        request = environ.get('werkzeug.request')
        if request is not None:
            req_vars = []
            for varname in dir(request):
                if varname[0] == '_':
                    continue
                value = getattr(request, varname)
                if hasattr(value, 'im_func'):
                    continue
                req_vars.append((varname, value))
        else:
            req_vars = [('WSGI Environ', environ)]

        return Namespace(
            evalex =          self.evalex,
            exception_type =  extypestr,
            exception_value = str(exception_value),
            frames =          frames,
            last_frame =      frames[-1],
            plaintb =         plaintb,
            tb_uid =          tb_uid,
            frame_map =       frame_map,
            req_vars =        req_vars,
        )

class InteractiveDebugger(code.InteractiveInterpreter):
    """
    Subclass of the python interactive interpreter that
    automatically captures stdout and buffers older input.
    """

    def __init__(self, frame):
        self.globals = frame.f_globals
        code.InteractiveInterpreter.__init__(self, frame.f_locals)
        self.prompt = '>>> '
        self.buffer = []

    def runsource(self, source):
        prompt = self.prompt
        sys.stdout.push()
        try:
            source_to_eval = ''.join(self.buffer + [source])
            if code.InteractiveInterpreter.runsource(self,
               source_to_eval, '<debugger>', 'single'):
                self.prompt = '... '
                self.buffer.append(source)
            else:
                self.prompt = '>>> '
                del self.buffer[:]
        finally:
            return prompt + source + sys.stdout.release()

    def runcode(self, code):
        try:
            exec code in self.globals, self.locals
        except:
            self.showtraceback()

    def write(self, data):
        sys.stdout.write(data)

    def exec_expr(self, code):
        rv = self.runsource(code)
        if isinstance(rv, unicode):
            return rv.encode('utf-8')
        return rv


import os, tempfile, shutil

from werkzeug.contrib.cache import SimpleCache, FileSystemCache

def test_simplecache_get_dict():
    """SimpleCache.get_dict bug"""
    cache = SimpleCache()
    cache.set('a', 'a')
    cache.set('b', 'b')
    d = cache.get_dict('a', 'b')
    assert 'a' in d
    assert 'a' == d['a']
    assert 'b' in d
    assert 'b' == d['b']

def test_filesystemcache_set_get():
    """
    test if FileSystemCache.set/get works
    """
    tmp_dir = tempfile.mkdtemp()
    try:
        cache = FileSystemCache(cache_dir=tmp_dir)
        for i in range(3):
            cache.set(str(i), i * i)
        for i in range(3):
            result = cache.get(str(i))
            assert result == i * i
    finally:
        shutil.rmtree(tmp_dir)

def test_filesystemcache_prune():
    """
    test if FileSystemCache._prune works and keeps the cache entry count
    below the given threshold.
    """
    THRESHOLD = 13
    tmp_dir = tempfile.mkdtemp()
    cache = FileSystemCache(cache_dir=tmp_dir, threshold=THRESHOLD)
    for i in range(2 * THRESHOLD):
        cache.set(str(i), i)
    cache_files = os.listdir(tmp_dir)
    shutil.rmtree(tmp_dir)
    assert len(cache_files) <= THRESHOLD

def test_filesystemcache_clear():
    """
    test if FileSystemCache.clear works
    """
    tmp_dir = tempfile.mkdtemp()
    cache = FileSystemCache(cache_dir=tmp_dir)
    cache.set('foo', 'bar')
    cache_files = os.listdir(tmp_dir)
    assert len(cache_files) == 1
    cache.clear()
    cache_files = os.listdir(tmp_dir)
    assert len(cache_files) == 0
    shutil.rmtree(tmp_dir)

def test_rediscache_get_set():
    """
    test basic RedisCache capabilities
    """
    cache = RedisCache()
    cache.set('foo', 'bar')
    assert cache.get('foo') == 'bar'

def test_rediscache_expire():
    """
    test RedisCache handling expire time on keys
    """

import time
    cache = RedisCache()
    cache.set('foo', 'bar', 1)
    time.sleep(2)
    assert cache.get('foo') is None

def test_rediscache_add():
    """
    test if RedisCache.add() preserves existing keys
    """
    cache = RedisCache()
    # sanity check that add() works like set()
    cache.add('foo', 'bar')
    assert cache.get('foo') ==  'bar'
    cache.add('foo', 'qux')
    assert cache.get('foo') ==  'bar'

def test_rediscache_delete():
    """
    test if RedisCache correctly deletes single key
    """
    cache = RedisCache()
    cache.add('foo', 'bar')
    assert cache.get('foo') ==  'bar'
    cache.delete('foo')
    assert cache.get('foo') is None

def test_rediscache_delete_many():
    """
    test if RedisCache correctly deletes many keys
    """
    cache = RedisCache()
    cache.add('foo', 'bar')
    cache.add('spam', 'eggs')
    cache.delete_many('foo', 'spam')
    assert cache.get('foo') is None
    assert cache.get('spam') is None


from werkzeug.datastructures import Headers
from werkzeug.sansio.multipart import Data
from werkzeug.sansio.multipart import Epilogue
from werkzeug.sansio.multipart import Field
from werkzeug.sansio.multipart import File
from werkzeug.sansio.multipart import MultipartDecoder
from werkzeug.sansio.multipart import MultipartEncoder
from werkzeug.sansio.multipart import Preamble

def test_decoder_simple() -> None:
    boundary = b"---------------------------9704338192090380615194531385"
    decoder = MultipartDecoder(boundary)
    data = """
-----------------------------9704338192090380615194531385
Content-Disposition: form-data; name="fname"

ß∑œß∂ƒå∂
-----------------------------9704338192090380615194531385
Content-Disposition: form-data; name="lname"; filename="bob"

asdasd
-----------------------------9704338192090380615194531385--
    """.replace(
        "\n", "\r\n"
    ).encode(
        "utf-8"
    )
    decoder.receive_data(data)
    decoder.receive_data(None)
    events = [decoder.next_event()]
    while not isinstance(events[-1], Epilogue) and len(events) < 6:
        events.append(decoder.next_event())
    assert events == [
        Preamble(data=b""),
        Field(
            name="fname",
            headers=Headers([("Content-Disposition", 'form-data; name="fname"')]),
        ),
        Data(data="ß∑œß∂ƒå∂".encode(), more_data=False),
        File(
            name="lname",
            filename="bob",
            headers=Headers(
                [("Content-Disposition", 'form-data; name="lname"; filename="bob"')]
            ),
        ),
        Data(data=b"asdasd", more_data=False),
        Epilogue(data=b"    "),
    ]
    encoder = MultipartEncoder(boundary)
    result = b""
    for event in events:
        result += encoder.send_event(event)
    assert data == result

def test_chunked_boundaries() -> None:
    boundary = b"--boundary"
    decoder = MultipartDecoder(boundary)
    decoder

.receive_data(b"--")
    assert isinstance(decoder.next_event(), NeedData)
    decoder.receive_data(b"--boundary\r\n")
    assert isinstance(decoder.next_event(), Preamble)
    decoder.receive_data(b"Content-Disposition: form-data;")
    assert isinstance(decoder.next_event(), NeedData)

    decoder.receive_data(b'name="fname"\r\n\r\n')
    assert isinstance(decoder.next_event(), Field)
    decoder.receive_data(b"longer than the boundary")
    assert isinstance(decoder.next_event(), Data)
    decoder.receive_data(b"also longer, but includes a linebreak\r\n--")
    assert isinstance(decoder.next_event(), Data)
    assert isinstance(decoder.next_event(), NeedData)
    decoder.receive_data(b"--boundary--\r\n")
    event = decoder.next_event()
    assert isinstance(event, Data)
    assert not event.more_data
    decoder.receive_data(None)
    assert isinstance(decoder.next_event(), Epilogue)


# -*- coding: utf-8 -*-
"""
    werkzeug.testsuite.iterio
    ~~~~~~~~~~~~~~~~~~~~~~~~~

    Tests the iterio object.

    :copyright: (c) 2011 by Armin Ronacher.
    :license: BSD, see LICENSE for more details.
"""
import unittest
from functools import partial

from werkzeug.testsuite import WerkzeugTestCase
from werkzeug.contrib.iterio import IterIO, greenlet

class IterOTestSuite(WerkzeugTestCase):

    def test_basic_native(self):
        io = IterIO(["Hello", "World", "1", "2", "3"])
        self.assert_equal(io.tell(), 0)
        self.assert_equal(io.read(2), "He")
        self.assert_equal(io.tell(), 2)
        self.assert_equal(io.read(3), "llo")
        self.assert_equal(io.tell(), 5)
        io.seek(0)
        self.assert_equal(io.read(5), "Hello")
        self.assert_equal(io.tell(), 5)
        self.assert_equal(io._buf, "Hello")
        self.assert_equal(io.read(), "World123")
        self.assert_equal(io.tell(), 13)
        io.close()
        assert io.closed

        io = IterIO(["Hello\n", "World!"])
        self.assert_equal(io.readline(), 'Hello\n')
        self.assert_equal(io._buf, 'Hello\n')
        self.assert_equal(io.read(), 'World!')
        self.assert_equal(io._buf, 'Hello\nWorld!')
        self.assert_equal(io.tell(), 12)
        io.seek(0)
        self.assert_equal(io.readlines(), ['Hello\n', 'World!'])

        io = IterIO(["foo\n", "bar"])
        io.seek(-4, 2)
        self.assert_equal(io.read(4), '\nbar')

        self.assert_raises(IOError, io.seek, 2, 100)
        io.close()
        self.assert_raises(ValueError, io.read)

    def test_basic_bytes(self):
        io = IterIO([b"Hello", b"World", b"1", b"2", b"3"])
        self.assert_equal(io.tell(), 0)
        self.assert_equal(io.read(2), b"He")
        self.assert_equal(io.tell(), 2)
        self.assert_equal(io.read(3), b"llo")
        self.assert_equal(io.tell(), 5)
        io.seek(0)
        self.assert_equal(io.read(5), b"Hello")
        self.assert_equal(io.tell(), 5)
        self.assert_equal(io._buf, b"Hello")
        self.assert_equal(io.read(), b"World123")
        self.assert_equal(io.tell(), 13)
        io.close()
        assert io.closed

        io = IterIO([b"Hello\n", b"World!"])
        self.assert_equal(io.readline(), b'Hello\n')
        self.assert_equal(io._buf, b'Hello\n')
        self.assert_equal(io.read(), b'World!')
        self.assert_equal(io._buf, b'Hello\nWorld!')
        self.assert_equal(io.tell(), 12)
        io.seek(0)
        self.assert_equal(io.readlines(), [b'Hello\n', b'World!'])

        io = IterIO([b"foo\n", b"bar"])
        io.seek(-4, 2)
        self.assert_equal(io.read(4), b'\nbar')

        self.assert_raises(IOError, io.seek, 2, 100)
        io.close()
        self.assert_raises(ValueError, io.read)

    def test_basic_unicode(self):
        io = IterIO([u"Hello", u"World", u"1", u"2", u"3"])
        self.assert_equal(io.tell(), 0)
        self.assert_equal(io.read(2), u"He")
        self.assert_equal(io.tell(), 2)
        self.assert_equal(io.read(3), u"llo")
        self.assert_equal(io.tell(), 5)
        io.seek(0)
        self.assert_equal(io.read(5), u"Hello")
        self.assert_equal(io.tell(), 5)
        self.assert_equal(io._buf, u"Hello")
        self.assert_equal(io.read(), u"World123")
        self.assert_equal(io.tell(), 13)
        io.close()
        assert io.closed

        io = IterIO([u"Hello\n", u"World!"])
        self.assert_equal(io.readline(), u'Hello\n')
        self.assert_equal(io._buf, u'Hello\n')
        self.assert_equal(io.read(), u'World!')
        self.assert_equal(io._buf, u'Hello\nWorld!')
        self.assert_equal(io.tell(), 12)
        io.seek(0)
        self.assert_equal(io.readlines(), [u'Hello\n', u'World!'])

        io = IterIO([u"foo\n", u"bar"])
        io.seek(-4, 2)
        self.assert_equal(io.read(4), u'\nbar')

        self.assert_raises(IOError, io.seek, 2, 100)
        io.close()
        self.assert_raises(ValueError, io.read)

    def test_sentinel_cases(self):
        io = IterIO([])
        self.assert_strict_equal(io.read(), '')
        io = IterIO([], b'')
        self.assert_strict_equal(io.read(), b'')
        io = IterIO(

[], u'')
        self.assert_strict_equal(io.read(), u'')

        io = IterIO([])
        self.assert_strict_equal(io.read(), '')

        io = IterIO([b''])
        self.assert_strict_equal(io.read(), b'')
        io = IterIO([u''])
        self.assert_strict_equal(io.read(), u'')

        io = IterIO([])
        self.assert_strict_equal(io.readline(), '')
        io = IterIO([], b'')
        self.assert_strict_equal(io.readline(), b'')
        io = IterIO([], u'')
        self.assert_strict_equal(io.readline(), u'')

        io = IterIO([])
        self.assert_strict_equal(io.readline(), '')
        io = IterIO([b''])
        self.assert_strict_equal(io.readline(), b'')
        io = IterIO([u''])
        self.assert_strict_equal(io.readline(), u'')

class IterITestSuite(WerkzeugTestCase):

    def test_basic(self):
        def producer(out):
            out.write('1\n')
            out.write('2\n')
            out.flush()
            out.write('3\n')
        iterable = IterIO(producer)
        self.assert_equal(next(iterable), '1\n2\n')
        self.assert_equal(next(iterable), '3\n')
        self.assert_raises(StopIteration, partial(next, iterable))

def suite():
    suite = unittest.TestSuite()
    suite.addTest(unittest.makeSuite(IterOTestSuite))
    if greenlet is not None:
        suite.addTest(unittest.makeSuite(IterITestSuite))
    return suite


# -*- coding: utf-8 -*-
"""
    werkzeug.serving
    ~~~~~~~~~~~~~~~~

    This module wraps the `wsgiref` module so that it reloads code
    automatically. Works with any WSGI application but it won't help in
    non `wsgiref` environments. Use it only for development.

    Usage::

        from werkzeug.serving import run_simple
        from myproject import make_app
        run_simple('localhost', 8080, make_app())

    :copyright: 2007 by Armin Ronacher.
    :license: BSD, see LICENSE for more details.
"""
import os
import socket
import sys
import time
import thread
from wsgiref.simple_server import ServerHandler, WSGIRequestHandler, \
     WSGIServer
from SocketServer import ThreadingMixIn, ForkingMixIn

class BaseRequestHandler(WSGIRequestHandler):
    """
    Subclass of the normal request handler that thinks it is
    threaded or something like that. The default wsgiref handler
    has wrong information so we need this class.
    """
    multithreaded = False
    multiprocess = False
    _handler_class = None

    def get_handler(self):
        handler = self._handler_class
        if handler is None:
            class handler(ServerHandler):
                wsgi_multithread = self.multithreaded
                wsgi_multiprocess = self.multipro

cess
            self._handler_class = handler

        rv = handler(self.rfile, self.wfile, self.get_stderr(),
                     self.get_environ())
        rv.request_handler = self

        return rv

    def handle(self):
        self.raw_requestline = self.rfile.readline()
        if self.parse_request():
            self.get_handler().run(self.server.get_app())

def make_server(host, port, app=None, threaded=False, processes=1):
    """
    Create a new wsgiref server that is either threaded, or forks
    or just processes one request after another.
    """
    if threaded and processes > 1:
        raise ValueError("cannot have a multithreaded and "
                         "multi process server.")
    elif threaded:
        class handler(BaseRequestHandler):
            multithreaded = True
        class server(ThreadingMixIn, WSGIServer):
            pass
    elif processes > 1:
        class handler(BaseRequestHandler):
            multiprocess = True
            max_children = processes - 1
        class server(ForkingMixIn, WSGIServer):
            pass
    else:
        handler = BaseRequestHandler
        server = WSGIServer
    srv = server((host, port), handler)
    srv.set_app(app)
    return srv

def reloader_loop(extra_files):
    """When this function is run from the main thread, it will force other
    threads to exit when any modules currently loaded change.

    :param extra_files: a list of additional files it should watch.
    """
    mtimes = {}
    while True:
        for filename in filter(None, [getattr(module, '__file__', None)
                                      for module in sys.modules.values()] +
                                     extra_files):
            while not os.path.isfile(filename):
                filename = os.path.dirname(filename)
                if not filename:
                    break
            if not filename:
                continue

            if filename[-4:] in ('.pyc', '.pyo'):
                filename = filename[:-1]

            mtime = os.stat(filename).st_mtime
            if filename not in mtimes:
                mtimes[filename] = mtime
                continue
            if mtime > mtimes[filename]:
                sys.exit(3)
        time.sleep(1)

def restart_with_reloader():
    """Spawn a new Python interpreter with the same arguments as this one,
    but running the reloader thread."""
    while True:
        print '* Restarting with reloader...'
        args = [sys.executable] + sys.argv
        if sys.platform == 'win32':
            args = ['"%s"' % arg for arg in args]
        new_environ = os.environ.copy()
        new_environ['RUN_MAIN'] = 'true'
        exit_code = os.spawnve(os.P_WAIT, sys.executable, args, new_environ)
        if exit_code != 3:
            return exit_code

def run_with_reloader(main_func, extra_watch):
    """
    Run the given function in an independent python interpreter.
    """
    if os.environ.get('RUN_MAIN') == 'true':
        thread.start_new_thread(main_func, ())
        try:
            reloader_loop(extra_watch)
        except KeyboardInterrupt:
            return
    try:
        sys.exit(restart_with_reloader())
    except KeyboardInterrupt:
        pass

def run_simple(hostname, port, application, use_reloader=False,
               extra_files=None):
    """
    Start an application using wsgiref and with an optional reloader.
    """
    from wsgiref.simple_server import make_server
    def inner():
        srv = make_server(hostname, port, application)
        try:
            srv.serve_forever()
        except KeyboardInterrupt:
            pass

    if os.environ.get('RUN_MAIN') != 'true':
        print '* Running on http://%s:%d/' % (hostname, port)
    if use_reloader:
        # Create and destroy a socket so that any exceptions are raised before we
        # spawn a separate Python interpreter and loose this ability.
        test_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        test_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        test_socket.bind((hostname, port))
        test_socket.close()
        run_with_reloader(inner, extra_files or [])
    else:
        inner()


# -*- coding: utf-8 -*-
"""
    werkzeug.testsuite.utils
    ~~~~~~~~~~~~~~~~~~~~~~~~

    General utilities.

    :copyright: (c) 2011 by Armin Ronacher.
    :license: BSD, see LICENSE for more details.
"""
import unittest

from werkzeug.testsuite import WerkzeugTestCase

from werkzeug import utils

class GeneralUtilityTestCase(WerkzeugTestCase):

    def test_redirect(self):
        resp = utils.redirect(u'/füübär')
        assert '/f%C3%BC%C3%BCb%C3%A4r' in resp.data
        assert resp.headers['Location'] == '/f%C3%BC%C3%BCb%C3%A4r'
        assert resp.status_code == 302

        resp = utils.redirect(u'http://☃.net/', 307)
        assert 'http://xn--n3h.net/' in resp.data
        assert resp.headers['Location'] == 'http://xn--n3h.net/'
        assert resp.status_code == 307

        resp = utils.redirect('http://example.com/', 305)
        assert resp.headers['Location'] == 'http://example.com/'
        assert resp.status_code == 305

    def test_cached_property(self):
        foo = []
        class A(object):
            def prop(self):
                foo.append(42)
                return 42
            prop = utils.cached_property(prop)

        a = A()
        p = a.prop
        q = a.prop
        assert p == q == 42
        assert foo == [42]

        foo = []
        class A(object):
            def _prop(self):
                foo.append(42)
                return 42
            prop = utils.cached_property(_prop, name='prop')
            del _prop

        a = A()
        p = a.prop
        q = a.prop
        assert p == q == 42
        assert foo == [42]

    def test_environ_property(self):
        class A(object):
            environ = {'string': 'abc', 'number': '42'}

            string = utils.environ_property('string')
            missing = utils.environ_property('missing', 'spam')
            read_only = utils.environ_property('number')
            number = utils.environ_property('number', load_func=int)
            broken_number = utils.environ_property('broken_number', load_func=int)
            date = utils.environ_property('date', None, parse_date, http_date,
                                    read_only=False)
            foo = utils.environ_property('foo')

        a = A()
        assert a.string == 'abc'
        assert a.missing == 'spam'
        def test_assign():
            a.read_only = 'something'
        self.assert_raises(AttributeError, test_assign)
        assert a.number == 42
        assert a.broken_number == None
        assert a.date is None
        a.date = datetime(2008, 1, 22, 10, 0, 0, 0)
        assert a.environ['date'] == 'Tue, 22 Jan 2008 10:00:00 GMT'

    def test_escape(self):
        class Foo(str):
            def __html__(self):
                return unicode(self)
        assert utils.escape(None) == ''
        assert utils.escape(42) == '42'
        assert utils.escape('<>') == '<>'
        assert utils.escape('"foo"') == '"foo"'
        assert utils.escape('"foo"', True) == '"foo"'
        assert utils.escape(Foo('<foo>')) == '<foo>'

    def test_unescape(self):
        assert utils.unescape('<ä>') == u'<ä>'

    def test_run_wsgi_app(self):
        def foo(environ, start_response):
            start_response('200 OK', [('Content-Type', 'text/plain')])
            yield '1'
            yield '2'
            yield '3'

        app_iter, status, headers = run_wsgi_app(foo, {})
        assert status == '200 OK'
        assert headers == [('Content-Type', 'text/plain')]
        assert app_iter.next() == '1'
        assert app_iter.next() == '2'
        assert app_iter.next() == '3'
        self.assert_raises(StopIteration, app_iter.next)

        got_close = []
        class CloseIter(object):
            def __init__(self):
                self.iterated = False
            def __iter__(self):

return self
            def close(self):
                got_close.append(None)
            def next(self):
                if self.iterated:
                    raise StopIteration()
                self.iterated = True
                return 'bar'

def bar(environ, start_response):
            start_response('200 OK', [('Content-Type', 'text/plain')])
            return CloseIter()

        app_iter, status, headers = run_wsgi_app(bar, {})
        assert status == '200 OK'
        assert headers == [('Content-Type', 'text/plain')]
        assert app_iter.next() == 'bar'
        self.assert_raises(StopIteration, app_iter.next)
        app_iter.close()

        assert run_wsgi_app(bar, {}, True)[0] == ['bar']

        assert len(got_close) == 2

    def test_import_string(self):
        import cgi
        from werkzeug.debug import DebuggedApplication
        assert utils.import_string('cgi.escape') is cgi.escape
        assert utils.import_string(u'cgi.escape') is cgi.escape
        assert utils.import_string('cgi:escape') is cgi.escape
        assert utils.import_string('XXXXXXXXXXXX', True) is None
        assert utils.import_string('cgi.XXXXXXXXXXXX', True) is None
        assert utils.import_string(u'cgi.escape') is cgi.escape
        assert utils.import_string(u'werkzeug.debug.DebuggedApplication') is DebuggedApplication
        self.assert_raises(ImportError, utils.import_string, 'XXXXXXXXXXXXXXXX')
        self.assert_raises(ImportError, utils.import_string, 'cgi.XXXXXXXXXX')

    def test_find_modules(self):
        assert list(utils.find_modules('werkzeug.debug')) == \
            ['werkzeug.debug.console', 'werkzeug.debug.repr',
             'werkzeug.debug.tbtools']

    def test_html_builder(self):
        html = utils.html
        xhtml = utils.xhtml
        assert html.p('Hello World') == '
Hello World
'
        assert html.a('Test', href='#') == 'Test'
        assert html.br() == '
'
        assert xhtml.br() == '
'
        assert html.img(src='foo') == ''
        assert xhtml.img(src='foo') == ''
        assert html.html(
            html.head(
                html.title('foo'),
                html.script(type='text/javascript')
            )
        ) == '<title>foo</title>'
        assert html('<foo>') == '<foo>'
        assert html.input(disabled=True) == '<input disabled>'
        assert xhtml.input(disabled=True) == '<input disabled="disabled" />'
        assert html.input(disabled='') == '<input>'
        assert xhtml.input(disabled='') == '<input />'
        assert html.input(disabled=None) == '<input>'
        assert xhtml.input(disabled=None) == '<input />'
        assert html.script('alert("Hello World");') == ''
        assert xhtml.script('alert("Hello World");') == ''

    def test_validate_arguments(self):
        take_none = lambda: None
        take_two = lambda a, b: None
        take_two_one_default = lambda a, b=0: None

        assert utils.validate_arguments(take_two, (1, 2,), {}) == ((1, 2), {})
        assert utils.validate_arguments(take_two, (1,), {'b': 2}) == ((1, 2), {})
        assert utils.validate_arguments(take_two_one_default, (1,), {}) == ((1, 0), {})
        assert utils.validate_arguments(take_two_one_default, (1, 2), {}) == ((1, 2), {})

        self.assert_raises(utils.ArgumentValidationError,
            utils.validate_arguments, take_two, (), {})

        assert utils.validate_arguments(take_none, (1, 2,), {'c': 3}) == ((), {})
        self.assert_raises(utils.ArgumentValidationError,
               utils.validate_arguments, take_none, (1,), {}, drop_extra=False)
        self.assert_raises(utils.ArgumentValidationError,
               utils.validate_arguments, take_none, (), {'a': 1}, drop_extra=False)

    def test_header_set_duplication_bug(self):
        headers = Headers([
            ('Content-Type', 'text/html'),
            ('Foo', 'bar'),
            ('Blub', 'blah')
        ])
        headers['blub'] = 'hehe'
        headers['blafasel'] = 'humm'
        assert headers == Headers([
            ('Content-Type', 'text/html'),
            ('Foo', 'bar'),
            ('blub', 'hehe'),
            ('blafasel', 'humm')
        ])

    def test_append_slash_redirect(self):
        def app(env, sr):
            return utils.append_slash_redirect(env)(env, sr)
        client = Client(app, BaseResponse)
        response = client.get('foo', base_url='http://example.org/app')
        assert response.status_code == 301
        assert response.headers['Location'] == 'http://example.org/app/foo/'

    def test_cached_property_doc(self):
        @utils.cached_property
        def foo():
            """testing"""
            return 42
        assert foo.__doc__ == 'testing'
        assert foo.__name__ == 'foo'
        assert foo.__module__ == __name__

def suite():
    suite = unittest.TestSuite()
    suite.addTest(unittest.makeSuite(GeneralUtilityTestCase))
    return suite


# -*- coding: utf-8 -*-
"""
    werkzeug.testsuite.local
    ~~~~~~~~~~~~~~~~~~~~~~~~

    Local and local proxy tests.

    :copyright: (c) 2011 by Armin Ronacher.
    :license: BSD, see LICENSE for more details.
"""
import time
import unittest
from threading import Thread

from werkzeug.testsuite import WerkzeugTestCase

from werkzeug import local

class LocalTestCase(WerkzeugTestCase):

    def test_basic_local(self):
        l = local.Local()
        l.foo = 0
        values = []
        def value_setter(idx):
            time.sleep(0.01 * idx)
            l.foo = idx
            time.sleep(0.02)
            values.append(l.foo)
        threads = [Thread(target=value_setter, args=(x,))
                   for x in [1, 2, 3]]
        for thread in threads:
            thread.start()
        time.sleep(0.2)
        assert sorted(values) == [1, 2, 3]

        def delfoo():
            del l.foo
        delfoo()
        self.assert_raises(AttributeError, lambda: l.foo)
        self.assert_raises(AttributeError, delfoo)

        local.release_local(l)

    def test_local_release(self):
        loc = local.Local()
        loc.foo = 42
        local.release_local(loc)
        assert not hasattr(loc, 'foo')

        ls = local.LocalStack()
        ls.push(42)
        local.release_local(ls)
        assert ls.top is None

    def test_local_proxy(self):
        foo = []
        ls = local.LocalProxy(lambda: foo)
        ls.append(42)
        ls.append(23)
        ls[1:] = [1, 2, 3]
        assert foo == [42, 1, 2, 3]
        assert repr(foo) == repr(ls)
        assert foo[0] == 42
        foo += [1]
        assert list(foo) == [42, 1, 2, 3, 1]

    def test_local_proxy_operations_math(self):
        foo = 2
        ls = local.LocalProxy(lambda: foo)
        assert ls + 1 == 3
        assert 1 + ls == 3
        assert ls - 1 == 1
        assert 1 - ls == -1
        assert ls * 1 == 2
        assert 1 * ls == 2
        assert ls / 1 == 2
        assert 1.0 / ls == 0.5
        assert ls // 1.0 == 2.0
        assert 1.0 // ls == 0.0
        assert ls % 2 == 0
        assert 2 % ls == 0

    def test_local_proxy_operations_strings(self):
        _foo = "foo"
        foo = local.LocalProxy(lambda: foo)
        assert

 foo + "bar" == "foobar"
        assert "bar" + foo == "barfoo"

        assert foo * 2 == "foofoo"

        _foo = "foo %s"
        assert foo % ("bar",) == "foo bar"

    def test_local_stack(self):
        ident = local.get_ident()

        ls = local.LocalStack()
        assert ident not in ls._local.__storage__
        assert ls.top is None
        ls.push(42)
        assert ident in ls._local.__storage__
        assert ls.top == 42
        ls.push(23)
        assert ls.top == 23
        ls.pop()
        assert ls.top == 42
        ls.pop()
        assert ls.top is None
        assert ls.pop() is None
        assert ls.pop() is None

        proxy = ls()
        ls.push([1, 2])
        assert proxy == [1, 2]
        ls.push((1, 2))
        assert proxy == (1, 2)
        ls.pop()
        ls.pop()
        assert repr(proxy) == '<LocalProxy unbound>'

        assert ident not in ls._local.__storage__

    def test_local_proxies_with_callables(self):
        foo = 42
        ls = local.LocalProxy(lambda: foo)
        assert ls == 42
        foo = [23]
        ls.append(42)
        assert ls == [23, 42]
        assert foo == [23, 42]

    def test_custom_idents(self):
        ident = 0
        loc = local.Local()
        stack = local.LocalStack()
        mgr = local.LocalManager([loc, stack], ident_func=lambda: ident)

        loc.foo = 42
        stack.push({'foo': 42})
        ident = 1
        loc.foo = 23
        stack.push({'foo': 23})
        ident = 0
        assert loc.foo == 42
        assert stack.top['foo'] == 42
        stack.pop()
        assert stack.top is None
        ident = 1
        assert loc.foo == 23
        assert stack.top['foo'] == 23
        stack.pop()
        assert stack.top is None

def suite():
    suite = unittest.TestSuite()
    suite.addTest(unittest.makeSuite(LocalTestCase))
    return suite


# -*- coding: utf-8 -*-
"""
    werkzeug.wsgi test
    ~~~~~~~~~~~~~~~~~~

    Tests the WSGI utilities.

    :copyright: (c) 2010 by the Werkzeug Team, see AUTHORS for more details.
    :license: BSD, see LICENSE for more details.
"""
from os import path
from cStringIO import StringIO

from nose.tools import assert_raises

from werkzeug import Client, create_environ, BaseResponse, run_wsgi_app
from werkzeug.exceptions import BadRequest

from werkzeug.wsgi import SharedDataMiddleware, get_host, responder, \
     LimitedStream, pop_path_info, peek_path_info, extract_path_info

def test_shareddatamiddleware_get_file_loader():
    """Shared middleware file loader lookup"""
    app = SharedDataMiddleware(None, {})
    assert callable(app.get_file_loader('foo'))

def test_shared_data_middleware():
    """Shared data middleware"""
    def null_application(environ, start_response):
        start_response('404 NOT FOUND', [('Content-Type', 'text/plain')])
        yield 'NOT FOUND'
    app = SharedDataMiddleware(null_application, {
        '/':        path.join(path.dirname(__file__), 'res'),
        '/sources': path.join(path.dirname(__file__), 'res'),
        '/pkg':     ('werkzeug.debug', 'shared')
    })

    for p in '/test.txt', '/sources/test.txt':
        app_iter, status, headers = run_wsgi_app(app, create_environ(p))
        assert status == '200 OK'
        assert ''.join(app_iter).strip() == 'FOUND'

    app_iter, status, headers = run_wsgi_app(app, create_environ('/pkg/body.tmpl'))
    contents = ''.join(app_iter)
    assert 'Werkzeug Debugger' in contents

    app_iter, status, headers = run_wsgi_app(app, create_environ('/missing'))
    assert status == '404 NOT FOUND'
    assert ''.join(app_iter).strip() == 'NOT FOUND'

def test_get_host():
    """Host lookup"""
    env = {'HTTP_X_FORWARDED_HOST': 'example.org',
           'SERVER_NAME': 'bullshit', 'HOST_NAME': 'ignore me dammit'}
    assert get_host(env) == 'example.org'
    assert get_host(create_environ('/', 'http://example.org')) \
        == 'example.org'

def test_responder():
    """Responder decorator"""
    def foo(environ, start_response):
        return BaseResponse('Test')
    client = Client(responder(foo), BaseResponse)
    response = client.get('/')
    assert response.status_code == 200
    assert response.data == 'Test'

def test_pop_path_info():
    """Test path info popping in the utils"""
    original_env = {'SCRIPT_NAME': '/foo', 'PATH_INFO': '/a/b///c'}

    # regular path info popping
    def assert_tuple(script_name, path_info):
        assert env.get('SCRIPT_NAME') == script_name
        assert env.get('PATH_INFO') == path_info
    env = original_env.copy()
    pop = lambda: pop_path_info(env)

    assert_tuple('/foo', '/a/b///c')
    assert pop() == 'a'
    assert_tuple('/foo/a', '/b///c')
    assert pop() == 'b'
    assert_tuple('/foo/a/b', '///c')
    assert pop() == 'c'
    assert_tuple('/foo/a/b///c', '')
    assert pop() is None

def test_peek_path_info():
    """Test path info peeking in wrappers and utils"""
    env = {'SCRIPT_NAME': '/foo', 'PATH_INFO': '/aaa/b///c'}

    assert peek_path_info(env) == 'aaa'
    assert peek_path_info(env) == 'aaa'

class RaisingLimitedStream(LimitedStream):

    def on_exhausted(self):
        raise BadRequest('input stream exhausted')

def test_limited_stream():
    """Test the LimitedStream"""
    io = StringIO('123456')
    stream = RaisingLimitedStream(io, 3)
    assert stream.read() == '123'
    assert_raises(BadRequest, stream.read)

    io = StringIO('123456')
    stream = RaisingLimitedStream(io, 3)
    assert stream.read(1) == '1'
    assert stream.read(1) == '2'
    assert stream.read(1) == '3'
    assert_raises(BadRequest, stream.read)

    io = StringIO('123456\nabcdefg')
    stream = LimitedStream(io, 9)
    assert stream.readline() == '123456\n'
    assert stream.readline() == 'ab'

    io = StringIO('123456\nabcdefg')
    stream = LimitedStream(io, 9)
    assert stream.readlines() == ['123456\n', 'ab']

    io = StringIO('123456\nabcdefg')
    stream = LimitedStream(io, 9)
    assert stream.readlines(2) == ['12']
    assert stream.readlines(2) == ['34']
    assert stream.readlines() == ['56\n', 'ab']

    io = StringIO('123456\nabcdefg')
    stream = LimitedStream(io, 9)
    assert stream.readline(100) == '123456\n'

    io = StringIO('123456\nabcdefg')
    stream = LimitedStream(io, 9)
    assert stream.readlines(100) == ['123456\n', 'ab']

    io = StringIO('123456')
    stream = LimitedStream(io, 3)
    assert stream.read(1) == '1'
    assert stream.read(1) == '2'
    assert stream.read() == '3'
    assert stream.read() == ''

def test_path_info_extraction():
    """PATH INFO extraction feature"""
    x = extract_path_info('http://example.com/app', '/app/hello')
    assert x == u'/hello'
    x = extract_path_info('http://example.com/app',
                          'https://example.com/app/hello')
    assert x == u'/hello'
    x = extract_path_info('http://example.com/app/',
                          'https://example.com/app/hello')
    assert x == u'/hello'
    x = extract_path_info('http://example.com/app/',
                          'https://example.com/app')
    assert x == u'/'
    x = extract_path_info(u'http://☃.net/', u'/fööbär')
    assert x == u'/fööbär'
    x = extract_path_info(u'http://☃.net/x', u'http://☃.net/x/fööbär')
    assert x == u'/fööbär'

    env = create_environ(u'/fööbär', u'http://☃.net/x/')
    x = extract_path_info(env, u'http://☃.net/x/fööbär')
    assert x == u'/fööbär'

    x = extract_path_info('http://example.com/app/',
                          'https://example.com/a/hello')
    assert x is None
    x = extract_path_info('http://example.com/app/',
                          'https://example.com/app/hello',
                          collapse_http_schemes=False)
    assert x is None

def test_get_host_fallback():
    """Test non Host header server name guessing"""
    assert get_host({
        'SERVER_NAME':      'foobar.example.com',
        'wsgi.url_scheme':  'http',
        'SERVER_PORT':      '80'
    }) == 'foobar.example.com'
    assert get_host({
        'SERVER_NAME':      'foobar.example.com',
        'wsgi.url_scheme':  'http',
        'SERVER_PORT':      '81'
    }) == 'foobar.example.com:81'

def test_multi_part_line_breaks():
    test_stream = StringIO('abcdef\r\nghijkl\r\nmnopqrstuvwxyz\r\nABCDEFGHIJK')
    lines = list(make_line_iter(test_stream, limit=1024, buffer_size=16))
    asse

rt lines == ['abcdef\r\n', 'ghijkl\r\n', 'mnopqrstuvwxyz\r\n', 'ABCDEFGHIJK']

    test_stream = StringIO('abc\r\nThis line is broken by the buffer length.\r\nFoo bar baz')
    lines = list(make_line_iter(test_stream, limit=1024, buffer_size=24))

assert lines == ['abc\r\n', 'This line is broken by the buffer length.\r\n', 'Foo bar baz']


# -*- coding: utf-8 -*-
"""
    werkzeug.testsuite.security
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~

    Tests the security helpers.

    :copyright: (c) 2013 by Armin Ronacher.
    :license: BSD, see LICENSE for more details.
"""
import os
import unittest

from werkzeug.testsuite import WerkzeugTestCase

from werkzeug.security import check_password_hash, generate_password_hash, \
     safe_join

class SecurityTestCase(WerkzeugTestCase):

    def test_password_hashing(self):
        hash1 = generate_password_hash('default')
        hash2 = generate_password_hash(u'default', method='sha1')
        assert hash1 != hash2
        assert check_password_hash(hash1, 'default')
        assert check_password_hash(hash2, 'default')
        assert hash1.startswith('sha1$')
        assert hash2.startswith('sha1$')

        fakehash = generate_password_hash('default', method='plain')
        assert fakehash == 'plain$$default'
        assert check_password_hash(fakehash, 'default')

        mhash = generate_password_hash(u'default', method='md5')
        assert mhash.startswith('md5$')
        assert check_password_hash(mhash, 'default')

        legacy = 'md5$$c21f969b5f03d33d43e04f8f136e7682'
        assert check_password_hash(legacy, 'default')

        legacy = u'md5$$c21f969b5f03d33d43e04f8f136e7682'
        assert check_password_hash(legacy, 'default')

    def test_safe_join(self):
        assert safe_join('foo', 'bar/baz') == os.path.join('foo', 'bar/baz')
        assert safe_join('foo', '../bar/baz') is None
        if os.name == 'nt':
            assert safe_join('foo', 'foo\\bar') is None

    def test_pbkdf2(self):
        def check(data, salt, iterations, keylen, expected):
            rv = pbkdf2_hex(data, salt, iterations, keylen)
            self.assert_equal(rv, expected)

        # From RFC 6070
        check('password', 'salt', 1, 20,
              '0c60c80f961f0e71f3a9b524af6012062fe037a6')
        check('password', 'salt', 2, 20,
              'ea6c014dc72d6f8ccd1ed92ace1d41f0d8de8957')
        check('password', 'salt', 4096, 20,
              '4b007901b765489abead49d926f721d065a429c1')
        check('passwordPASSWORDpassword', 'saltSALTsaltSALTsaltSALTsaltSALTsalt',
              4096, 25, '3d2eec4fe41c849b80c8d83662c0e44a8b291a964cf2f07038')
        check('pass\x00word', 'sa\x00lt', 4096, 16,
              '56fa6aa75548099dcc37d7f03425e0c3')
        # This one is from the RFC but it just takes for ages
        ##check('password', 'salt',

16777216, 20,
        ## 'eefe3d61cd4da4e4e9945b3d6ba2158c2634e984')

        # From Crypt-PBKDF2
        check('password', 'ATHENA.MIT.EDUraeburn', 1, 16,
              'cdedb5281bb2f801565a1122b2563515')
        check('password', 'ATHENA.MIT.EDUraeburn', 1, 32,
              'cdedb5281bb2f801565a1122b25635150ad1f7a04bb9f3a333ecc0e2e1f70837')
        check('password', 'ATHENA.MIT.EDUraeburn', 2, 16,
              '01dbee7f4a9e243e988b62c73cda935d')

        check('password', 'ATHENA.MIT.EDUraeburn', 2, 32,
              '01dbee7f4a9e243e988b62c73cda935da05378b93244ec8f48a99e61ad799d86')
        check('password', 'ATHENA.MIT.EDUraeburn', 1200, 32,
              '5c08eb61fdf71e4e4ec3cf6ba1f5512ba7e52ddbc5e5142f708a31e2e62b1e13')
        check('X' * 64, 'pass phrase equals block size', 1200, 32,
              '139c30c0966bc32ba55fdbf212530ac9c5ec59f1a452f5cc9ad940fea0598ed1')
        check('X' * 65, 'pass phrase exceeds block size', 1200, 32,
              '9ccad6d468770cd51b10e6a68721be611a8b4d282601db3b36be9246915ec82a')

def suite():
    suite = unittest.TestSuite()
    suite.addTest(unittest.makeSuite(SecurityTestCase))
    return suite


#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
    Manage SimpleWiki
    ~~~~~~~~~~~~~~~~~

    This script provides some basic commands to debug and test SimpleWiki.

    :copyright: (c) 2009 by the Werkzeug Team, see AUTHORS for more details.
    :license: BSD, see LICENSE for more details.
"""
import os
from werkzeug import script

def make_wiki():
    """Helper function that creates a new wiki instance."""
    from simplewiki import SimpleWiki
    database_uri = os.environ.get('SIMPLEWIKI_DATABASE_URI')
    return SimpleWiki(database_uri or 'sqlite:////tmp/simplewiki.db')

def shell_init_func():
    """
    Called on shell initialization.  Adds useful stuff to the namespace.
    """
    from simplewiki import database
    wiki = make_wiki()
    wiki.bind_to_context()
    return {
        'wiki':     wiki,
        'db':       database
    }

action_runserver = script.make_runserver(make_wiki, use_reloader=True)
action_shell = script.make_shell(shell_init_func)

def action_initdb():
    """Initialize the database"""
    make_wiki().init_database()

@cl

i.command()
@click.option('-h', '--hostname', type=str, default='localhost', help="localhost")
@click.option('-p', '--port', type=int, default=5000, help="5000")

@click.option('--no-reloader', is_flag=True, default=False)
@click.option('--debugger', is_flag=True)
@click.option('--no-evalex', is_flag=True, default=False)
@click.option('--threaded', is_flag=True)
@click.option('--processes', type=int, default=1, help="1")
def runserver(hostname, port, no_reloader, debugger, no_evalex, threaded, processes):
    """Start a new development server."""
    app = make_wiki()
    reloader = not no_reloader
    evalex = not no_evalex
    run_simple(hostname, port, app,
               use_reloader=reloader, use_debugger=debugger,
               use_evalex=evalex, threaded=threaded, processes=processes)

@cli.command()
@click.option('--no-ipython', is_flag=True, default=False)
def shell(no_ipython):
    """Start a new interactive python session."""
    banner = 'Interactive Werkzeug Shell'
    namespace = make_shell()
    if not no_ipython:
        try:
            try:
                from IPython.frontend.terminal.embed import InteractiveShellEmbed
                sh = InteractiveShellEmbed.instance(banner1=banner)
            except ImportError:
                from IPython.Shell import IPShellEmbed
                sh = IPShellEmbed(banner=banner)
        except ImportError:
            pass
        else:
            sh(local_ns=namespace)
            return
    from code import interact
    interact(banner, local=namespace)

if __name__ == '__main__':
    script.run()


import typing as t

import pytest

from werkzeug.sansio.utils import get_host

@pytest.mark.parametrize(
    ("scheme", "host_header", "server", "expected"),
    [
        ("http", "spam", None, "spam"),
        ("http", "spam:80", None, "spam"),
        ("https", "spam", None, "spam"),
        ("https", "spam:443", None, "spam"),
        ("http", "spam:8080", None, "spam:8080"),
        ("ws", "spam", None, "spam"),
        ("ws", "spam:80", None, "spam"),
        ("wss", "spam", None, "spam"),
        ("wss", "spam:443", None, "spam"),
        ("http", None, ("spam", 80), "spam"),
        ("http", None, ("spam", 8080), "spam:8080"),
        ("http", None, ("unix/socket", None), "unix/socket"),
        ("http", "spam", ("eggs", 80), "spam"),
    ],
)
def test_get_host(
    scheme: str,
    host_header: t.Optional[str],
    server: t.Optional[t.Tuple[str, t.Optional[int]]],
    expected: str,
) -> None:
    assert get_host(scheme, host_header, server) == expected

@pytest.mark.parametrize(
    ("http_content_length", "http_transfer_encoding", "expected"),
    [
        ("2", None, 2),

def test_get_content_length(
    http_content_length: str | None,
    http_transfer_encoding: str | None,
    expected: int | None,
) -> None:
    assert get_content_length(http_content_length, http_transfer_encoding) == expected


# -*- coding: utf-8 -*-
"""
    werkzeug.debug.repr
    ~~~~~~~~~~~~~~~~~~~

    This module implements object representations for debugging purposes.
    Unlike the default repr these reprs expose a lot more information and
    produce HTML instead of ASCII.

    Together with the CSS and JavaScript files of the debugger this gives
    a colorful and more compact output.

    :copyright: Copyright 2008 by Armin Ronacher.
    :license: BSD.
"""
import sys
import re
from traceback import format_exception_only
try:
    from collections import deque
except ImportError:
    deque = None
from cgi import escape
try:
    set
except NameError:
    from sets import Set as set, ImmutableSet as frozenset

RegexType = type(re.compile(''))

def debug_repr(obj):
    """Creates a debug repr of an object as HTML unicode string."""
    return DebugReprGenerator().repr(obj)

def _add_subclass_info(inner, obj, base):
    if isinstance(base, tuple):
        for base in base:
            if type(obj) is base:
                return inner
    elif type(obj) is base:
        return inner
    module = ''
    if obj.__class__.__module__ not in ('__builtin__', 'exceptions'):
        module = '%s.' % obj.__class__.__module__
    return '%s%s(%s)' % (module, obj.__class__.__name__, inner)

class DebugReprGenerator(object):

    def __init__(self):
        self._stack = []

    def _sequence_repr_maker(left, right, base=object(), limit=8):
        def proxy(self, obj, recursive):
            if recursive:
                return _add_subclass_info(left + '...' + right, obj, base)
            buf = [left]
            have_extended_section = False
            for idx, item in enumerate(obj):
                if idx:
                    buf.append(', ')
                if idx == limit:
                    buf.append('')
                    have_extended_section = True
                buf.append(self.repr(item))
            if have_extended_section:
                buf.append('')
            buf.append(right)
            return _add_subclass_info(u''.join(buf), obj, base)
        return proxy

    list_repr = _sequence_repr_maker('[', ']', list)
    tuple_repr = _sequence_repr_maker('(', ')', tuple)
    set_repr = _sequence_repr_maker('set([', '])', set)
    frozenset_repr = _sequence_repr_maker('frozenset([', '])', frozenset)
    if deque is not None:
        deque_repr = _sequence_repr_maker('collections.'
                                          'deque([', '])', deque)
    del _sequence_repr_maker

    def regex_repr(self, obj):
        pattern = repr(obj.pattern).decode('string-escape', 'ignore')
        if pattern[:1] == 'u':
            pattern = 'ur' + pattern[1:]
        else:
            pattern = 'r' + pattern
        return u're.compile(%s)' % pattern

    def string_repr(self, obj, limit=70):
        buf = ['']
        escaped = escape(obj)
        a = repr(escaped[:limit])
        b = repr(escaped[limit:])
        if isinstance(obj, unicode):
            buf.append('u')
            a = a[1:]
            b = b[1:]
        if b != "''":
            buf.extend((a[:-1], '', b[1:], ''))
        else:
            buf.append(a)
        buf.append('')
        return _add_subclass_info(u''.join(buf), obj, (str, unicode))

    def dict_repr(self, d, recursive, limit=5):
        if recursive:
            return _add_subclass_info(u'{...}', d, dict)
        buf = ['{']
        have_extended_section = False
        for idx, (key, value) in enumerate(d.iteritems()):
            if idx:
                buf.append(', ')
            if idx == limit - 1:
                buf.append('')
                have_extended_section = True
            buf.append('%s: '
                       '%s' %
                       (self.repr(key), self.repr(value)))
        if have_extended_section:
            buf.append('')
        buf.append('}')
        return _add_subclass_info(u''.join(buf), d, dict)

    def object_repr(self, obj):
        return u'%s' % \
               escape(repr(obj).decode('utf-8', 'replace'))

    def dispatch_repr(self, obj, recursive):
        if isinstance(obj, (int, long, float, complex)):
            return u'%r' % obj
        if isinstance(obj, basestring):
            return self.string_repr(obj)
        if isinstance(obj, RegexType):
            return self.regex_repr(obj)
        if isinstance(obj, list):
            return self.list_repr(obj, recursive)
        if isinstance(obj, tuple):
            return self.tuple_repr(obj, recursive)
        if isinstance(obj, set):
            return self.set_repr(obj, recursive)
        if isinstance(obj, frozenset):
            return self.frozenset_repr(obj, recursive)
        if isinstance(obj, dict):
            return self.dict_repr(obj, recursive)
        if deque is not None and isinstance(obj, deque):
            return self.deque_repr(obj, recursive)
        return self.object_repr(obj)

    def fallback_repr(self):
        try:
            info = ''.join(format_exception_only(*sys.exc_info()[:2]))
        except:
            info = '?'
        return u'<broken repr (%s)>' \
               u'' % escape(info.decode('utf-8', 'ignore').strip())

    def repr(self, obj):
        recursive = False
        for item in self._stack:
            if item is obj:
                recursive = True
                break
        self._stack.append(obj)
        try:
            try:
                return self.dispatch_repr(obj, recursive)
            except:
                return self.fallback_repr()
        finally:
            self._stack.pop()

    def dump_object(self, obj):
        attributes = []
        for key in dir(obj):
            try:

attributes.append((key, self.repr(getattr(obj, key))))
            except:
                pass

        title = 'Details for ' + object.__repr__(obj)[1:-1]
        return render_template('dump_object.html', attributes=attributes,
                               title=title, repr=self.repr(obj))

    def dump_locals(self, d):
        attributes = [(key, self.repr(value)) for key, value in d.items()]
        return render_template('dump_object.html', attributes=attributes,
                               title='Local variables in frame', repr=None)